Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into ethie/pm-clean

ethernet84f59e2064d7
diff --cc apps/desktop/electron/main.ts
index 069c62caeec,986e556b63b..e5f8b07c954
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -212,10 -207,9 +212,10 @@@ import
writeBufferToFile
} from './gateway-file-download'
import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'
+import { resolveGatewayVersion } from './gateway-version'
import { probeGatewayWebSocket } from './gateway-ws-probe'
import { registerGitIpc } from './git-ipc'
- import { desktopBackendSpawnEnv, guestOnboardingEnabled } from './guest-onboarding'
+ import { desktopBackendSpawnEnv, guestOnboardingEnabled, skipIntroEnabled } from './guest-onboarding'
import { readAndConsumeHandoffResult } from './handoff-result'
import {
ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,
@@@ -270,15 -262,9 +270,16 @@@ import
} from './managed-ssh-update'
import { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc'
import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'
+ import { fetchLocalMedia } from './media-range'
-import { createNativeAccessTokenCoordinator, NativeAuthChangedError } from './native-access-token'
-import { oauthSessionIsLive, resolveJsonBody, resolveReadinessProbeAuth } from './native-auth-decisions'
+import {
+ oauthGuardMayHardFail,
+ oauthSessionIsLive,
+ oauthTicketFailureAuthMessage,
+ resolveGatedDownloadAuth,
+ resolveJsonBody,
+ resolveOauthRestAuth,
+ resolveReadinessProbeAuth
+} from './native-auth-decisions'
import {
nativeRefreshUrl,
type NativeTokenSet,
@@@ -814,8 -908,10 +815,9 @@@ const BOOT_FAKE_ERROR = process.env.HER
// nobody to answer a modal, so the active-work confirmation would hang the
// caller instead of letting the process exit. Force quits set this.
const SKIP_QUIT_CONFIRM = process.env.HERMES_DESKTOP_SKIP_QUIT_CONFIRM === '1'
-// Nous free tier gate, decided ONCE here and stamped onto every backend spawn
-// (desktopBackendSpawnEnv) and the renderer (hermes:launch-flags).
-const GUEST_ONBOARDING = guestOnboardingEnabled()
-const SKIP_INTRO = skipIntroEnabled()
+// One launch decision must reach both the renderer and every backend spawn.
+const GUEST_ONBOARDING: boolean = guestOnboardingEnabled()
++const SKIP_INTRO: boolean = skipIntroEnabled()
const BOOT_FAKE_STEP_MS = (() => {
const raw = Number.parseInt(String(process.env.HERMES_DESKTOP_BOOT_FAKE_STEP_MS || ''), 10)
@@@ -1266,16 -1365,13 +1268,12 @@@ protocol.registerSchemesAsPrivileged(
}
])
--function registerMediaProtocol() {
-- const handler = createMediaProtocolHandler({
- ensureRemoteBearer: baseUrl => ensureNativeAccessToken(baseUrl).catch(() => null),
- fetchLocal: (resolvedPath, headers, method) =>
- electronNet.fetch(pathToFileURL(resolvedPath).toString(), {
- bypassCustomProtocolHandlers: true,
- credentials: 'omit',
- headers,
- method
- }),
- ensureRemoteBearer: baseUrl => ensureNativeAccessToken(baseUrl),
- // Answer local files ourselves: Electron's file:// loader ignores Range and
- // returns the whole body as 200 without Accept-Ranges, which makes <video>
- // unseekable (seekable=[0,0]).
++function registerMediaProtocol(): void {
++ const handler: ReturnType<typeof createMediaProtocolHandler> = createMediaProtocolHandler({
++ ensureRemoteBearer: (baseUrl: string): Promise<string | null> =>
++ ensureNativeAccessToken(baseUrl).catch((): null => null),
++ // Electron's file:// loader ignores Range, which prevents video seeking.
+ fetchLocal: fetchLocalMedia,
fetchRemote: (url, headers, method) =>
electronNet.fetch(url, {
bypassCustomProtocolHandlers: true,
@@@ -16791,20 -17151,16 +16789,21 @@@ ipcMain.on('hermes:translucency:support
event.returnValue = { glass: GLASS_SUPPORTED, translucency: TRANSLUCENCY_SUPPORTED }
})
-// Launch-flag facts the renderer needs before first paint (same sendSync
-// pattern as translucency). `--local` gates every local-models GUI surface;
-// it arrives from `hermes desktop --local` or directly on Hermes.exe (a
-// shortcut edit), and survives self-relaunches because collectRelaunchArgs
-// only strips internal flags.
-ipcMain.on('hermes:launch-flags', event => {
+// Feature-flag facts the renderer needs before first paint (same sendSync
+// pattern as translucency). Resolved in feature-flags.ts from the launch
+// argv and the artifact's channel: `--local` (from `hermes desktop --local`
+// or directly on Hermes.exe, a shortcut edit) gates the local-models GUI on
+// stable builds, and canary builds get the same surfaces by default. Launch
+// flags survive self-relaunches because collectRelaunchArgs only strips
+// internal flags.
+ipcMain.on('hermes:feature-flags', (event: IpcMainEvent): void => {
event.returnValue = {
- localModels: process.argv.includes('--local') || process.platform === 'win32' || process.platform === 'darwin',
+ ...resolveFeatureFlags({
+ argv: process.argv,
+ canary: resolveUpdaterChannelFromStamp() === 'canary'
+ }),
- guestOnboarding: GUEST_ONBOARDING
+ guestOnboarding: GUEST_ONBOARDING,
+ skipIntro: SKIP_INTRO
}
})
diff --cc apps/desktop/electron/preload-flags.test.ts
index 4d31802ee07,00000000000..58f5922ed15
mode 100644,000000..100644
--- a/apps/desktop/electron/preload-flags.test.ts
+++ b/apps/desktop/electron/preload-flags.test.ts
@@@ -1,36 -1,0 +1,36 @@@
+import { expect, it, vi } from 'vitest'
+
+const host = vi.hoisted(() => ({
+ exposeInMainWorld: vi.fn(),
+ send: vi.fn<(channel: string, line: string) => void>(),
+ sendSync: vi.fn((channel: string): unknown => channel === 'hermes:feature-flags'
- ? { localModels: true, guestOnboarding: true }
++ ? { localModels: true, guestOnboarding: true, skipIntro: true }
+ : {})
+}))
+
+vi.mock('electron', () => ({
+ contextBridge: { exposeInMainWorld: host.exposeInMainWorld },
+ ipcRenderer: { send: host.send, sendSync: host.sendSync },
+ webFrame: {},
+ webUtils: {}
+}))
+
+it('publishes the feature flags answered by main before the renderer starts', async (): Promise<void> => {
+ await import('./preload')
+ const registration = host.exposeInMainWorld.mock.calls.find(([name]): boolean => name === 'hermesDesktop')
+
+ expect(registration).toBeDefined()
- expect(registration![1]).toMatchObject({ localModelsEnabled: true, guestOnboardingEnabled: true })
++ expect(registration![1]).toMatchObject({ localModelsEnabled: true, guestOnboardingEnabled: true, skipIntro: true })
+ expect(host.sendSync).toHaveBeenCalledWith('hermes:feature-flags')
+})
+
+it('forwards full renderer error lines through the exposed bridge', async (): Promise<void> => {
+ await import('./preload')
+ const registration = host.exposeInMainWorld.mock.calls.find(([name]): boolean => name === 'hermesDesktop')
+ const bridge = registration?.[1] as { logLine?: (line: string) => void } | undefined
+ const line: string = '[renderer error:main] Prompt failed: database is locked\n at saveSession (session.ts:12)'
+
+ expect(bridge?.logLine).toBeTypeOf('function')
+ bridge?.logLine?.(line)
+ expect(host.send).toHaveBeenCalledExactlyOnceWith('hermes:logs:renderer-line', line)
+})
diff --cc apps/desktop/electron/preload.ts
index a14c7b827fd,c5b29478f14..60cf0d5b671
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@@ -10,7 -10,7 +10,7 @@@ import { contextBridge, ipcRenderer, we
const translucencySupport = ipcRenderer.sendSync('hermes:translucency:support')
const hudWindowing = ipcRenderer.sendSync('hermes:hud:windowing')
const hudNativeDrag = hudWindowing?.nativeDrag === true
- const launchFlags: { localModels?: boolean; guestOnboarding?: boolean } | undefined = ipcRenderer.sendSync('hermes:feature-flags')
-const launchFlags = ipcRenderer.sendSync('hermes:launch-flags')
++const launchFlags: { localModels?: boolean; guestOnboarding?: boolean; skipIntro?: boolean } | undefined = ipcRenderer.sendSync('hermes:feature-flags')
contextBridge.exposeInMainWorld('hermesDesktop', {
glassSupported: translucencySupport?.glass === true,
diff --cc apps/desktop/src/app/settings/local-models-settings.test.tsx
index 86607c81453,b176091a1e5..bf84f1869aa
--- a/apps/desktop/src/app/settings/local-models-settings.test.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.test.tsx
@@@ -1,9 -1,9 +1,9 @@@
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
--import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
++import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'
import { I18nProvider } from '@/i18n'
-import { $localRuntimeJobs } from '@/store/local-runtime-jobs'
+import { $localRuntimeJobs, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'
import type { LocalCatalogModel, LocalHardware, LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'
import { LocalModelsSettings } from './local-models-settings'
@@@ -115,24 -113,12 +115,24 @@@ function renderPane()
// The fresh-machine states these tests exercise now lead with the
// quickstart card; the full pane (runtime rows, model list, browser)
- // is one 'Configure…' click away. Render and click through.
- async function renderFullPane() {
- const result = renderPane()
+ // is one 'Let me choose' click away. Render and click through.
-async function renderFullPane() {
- const result = renderPane()
- const configure = await screen.findByRole('button', { name: /let me choose/i })
++async function renderFullPane(): Promise<ReturnType<typeof renderPane>> {
++ const result: ReturnType<typeof renderPane> = renderPane()
+
+ // Wait for status to load: the pane either shows the setup card (click
+ // through to the full pane) or, when an active runtime/model job routes
+ // straight to the full pane, the runtime section directly.
- await waitFor(() => {
++ await waitFor((): void => {
+ expect(
- Boolean(screen.queryByRole('button', { name: /configure/i })) || screen.queryAllByText(/this machine/i).length > 0
++ Boolean(screen.queryByRole('button', { name: /let me choose/i })) || screen.queryAllByText(/this machine/i).length > 0
+ ).toBe(true)
+ })
+
- const configure = screen.queryByRole('button', { name: /configure/i })
++ const configure: HTMLElement | null = screen.queryByRole('button', { name: /let me choose/i })
- fireEvent.click(configure)
+ if (configure) {
+ fireEvent.click(configure)
+ }
return result
}
@@@ -433,6 -415,47 +435,51 @@@ describe('quickstart', () =>
})
describe('BrowseSection', () => {
- it('keeps manual spill selection and HF browsing available without an automatic recommendation', async () => {
- const stagedId = 'Spilled-Model-Q4_K_M'
++ it('keeps manual spill selection and HF browsing available without an automatic recommendation', async (): Promise<void> => {
++ const stagedId: string = 'Spilled-Model-Q4_K_M'
+ mocked.getLocalModelsStatus.mockResolvedValue({ ...BASE_STATUS, runtime_installed: true })
+ mocked.getLocalCatalog.mockResolvedValue({ models: [SPILLED_MODEL] })
+ renderPane()
+
+ await screen.findByText('Spilled Model')
+ expect(screen.getByText('No automatic recommendation for this machine')).toBeTruthy()
+ expect(screen.getByText('Uses system RAM')).toBeTruthy()
+ expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()
+
+ // Attach the browser-only scroll method to the real search container,
+ // so a missing or misdirected click handler cannot satisfy the assertion.
- const search = screen.getByPlaceholderText(/search models/i)
- const browse = search.closest('#local-model-browse')
++ const search: HTMLElement = screen.getByPlaceholderText(/search models/i)
++ const browse: Element | null = search.closest('#local-model-browse')
+ expect(browse).not.toBeNull()
- const scroll = vi.fn()
++ const scroll: Mock<(options?: boolean | ScrollIntoViewOptions) => void> = vi.fn()
+ Object.defineProperty(browse, 'scrollIntoView', { configurable: true, value: scroll })
+ fireEvent.click(screen.getByRole('button', { name: /browse models/i }))
+ expect(scroll).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' })
+ expect(mocked.downloadLocalModel).not.toHaveBeenCalled()
+
+ // The backend reports the completed download on refresh. Use must send
+ // the staged variant id, not the catalog family id or an automatic pick.
+ mocked.downloadLocalModel.mockResolvedValue({ already_downloaded: true, job_id: null })
+ mocked.getLocalModelsStatus.mockResolvedValue({
+ ...BASE_STATUS,
+ runtime_installed: true,
+ models: [{ id: stagedId, size_bytes: SPILLED_MODEL.size_bytes, size_label: SPILLED_MODEL.size_label }]
+ })
+ mocked.getLocalCatalog.mockResolvedValue({
+ models: [{ ...SPILLED_MODEL, downloaded: true, downloaded_model_id: stagedId }]
+ })
+ fireEvent.click(screen.getByRole('button', { name: /download ·/i }))
- await waitFor(() => expect(mocked.downloadLocalModel).toHaveBeenCalledWith(SPILLED_MODEL.id))
++ await waitFor((): void => {
++ expect(mocked.downloadLocalModel).toHaveBeenCalledWith(SPILLED_MODEL.id)
++ })
+ mocked.activateLocalModel.mockResolvedValue({ job_id: 'explicit-spill' })
+ fireEvent.click(await screen.findByRole('button', { name: /^use$/i }))
- await waitFor(() => expect(mocked.activateLocalModel).toHaveBeenCalledWith(stagedId))
++ await waitFor((): void => {
++ expect(mocked.activateLocalModel).toHaveBeenCalledWith(stagedId)
++ })
+ expect(mocked.quickstartLocalModels).not.toHaveBeenCalled()
+ })
+
it('searches HF after a pause and shows fit-priced files on demand', async () => {
vi.useFakeTimers()
diff --cc apps/desktop/src/app/settings/local-models-settings.tsx
index 89953a13201,865e7c75615..bda53c933e4
--- a/apps/desktop/src/app/settings/local-models-settings.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.tsx
@@@ -299,16 -304,12 +299,19 @@@ export function LocalModelsSettings()
const qJob = runningQuickstart ?? null
const needsSetup = !status.runtime_installed || status.models.length === 0
- const heroModel = catalog.find(c => c.recommended && c.fits) ?? catalog.find(c => c.fits) ?? null
+ // The setup hero is reserved for an automatic recommendation. A
+ // spilled model remains visible below, but setup must not silently choose it.
+ const heroModel = catalog.find(c => c.recommended && c.fits) ?? null
+ const hasRecommendation = catalog.some(c => c.recommended)
- if (qJob || (needsSetup && !configure && heroModel)) {
+ // An active runtime install/update or model download needs the FULL pane
+ // (its row lives there with its controls) — the setup hero must not hide
+ // it on a remount.
+ const otherActiveJob = jobs.some(
+ j => (j.kind === 'runtime-install' || j.kind === 'model-download') && isActiveStatus(j.status)
+ )
+
+ if ((qJob || (needsSetup && !configure && heroModel)) && !otherActiveJob) {
// Stage rail derived from the job phase: engine -> model -> finish.
const phase = qJob?.phase ?? ''
@@@ -1012,128 -1003,126 +1033,130 @@@ function BrowseSection({ onChanged }:
icon={Search}
title={copy.browseTitle}
>
- <p className="text-[0.75rem] text-muted-foreground">{copy.browseHint}</p>
-
- <div className="relative">
- <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
- <input
- className="w-full rounded-md border border-(--ui-border) bg-transparent py-1.5 pl-8 pr-3 text-[0.8rem] outline-none placeholder:text-muted-foreground focus:border-primary"
- onChange={e => setQuery(e.target.value)}
- placeholder={copy.browsePlaceholder}
- value={query}
- />
- </div>
+ <div id="local-model-browse">
+ <p className="text-[0.75rem] text-muted-foreground">{copy.browseHint}</p>
+
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <input
+ className="w-full rounded-md border border-(--ui-border) bg-transparent py-1.5 pl-8 pr-3 text-[0.8rem] outline-none placeholder:text-muted-foreground focus:border-primary"
+ onChange={e => setQuery(e.target.value)}
+ placeholder={copy.browsePlaceholder}
+ value={query}
+ />
+ </div>
- {searching && (
- <p className="flex items-center gap-2 text-[0.75rem] text-muted-foreground">
- <Loader2 className="size-3 animate-spin" />
- {copy.browseSearching}
- </p>
- )}
-
- {error && <p className="text-[0.75rem] text-destructive">{error}</p>}
-
- <div className="grid gap-1">
- {hits.map(hit => (
- <div key={hit.repo}>
- <ListRow
- action={
- <Button onClick={() => openFiles(hit.repo)} size="sm" variant="ghost">
- {openRepo === hit.repo ? copy.browseRefresh : copy.browseShowFiles}
- </Button>
- }
- description={
- <span>
- {Intl.NumberFormat().format(hit.downloads)} {copy.browseDownloads}
- {' · '}
- {Intl.NumberFormat().format(hit.likes)} {copy.browseLikes}
- {hit.gated ? ` · ${copy.browseGated}` : ''}
- </span>
- }
- title={<span className="font-mono text-[0.8rem]">{hit.repo}</span>}
- />
-
- {openRepo === hit.repo && (
- <div className="ml-4 grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-1.5 border-l border-(--ui-border) py-1 pl-3">
- {listing && (
- <p className="col-span-full flex items-center gap-2 py-1 text-[0.75rem] text-muted-foreground">
- <Loader2 className="size-3 animate-spin" />
- {copy.browseListing}
- </p>
- )}
+ {searching && (
+ <p className="flex items-center gap-2 text-[0.75rem] text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ {copy.browseSearching}
+ </p>
+ )}
- {!listing && files.length === 0 && (
- <p className="col-span-full py-1 text-[0.75rem] text-muted-foreground">{copy.browseNoGguf}</p>
- )}
+ {error && <p className="text-[0.75rem] text-destructive">{error}</p>}
- {files.map(group => {
- const dJob = runningDownloadFor(jobs, browsedModelId(group))
+ <div className="grid gap-1">
+ {hits.map(hit => (
+ <div key={hit.repo}>
+ <ListRow
+ action={
+ <Button onClick={() => openFiles(hit.repo)} size="sm" variant="ghost">
+ {openRepo === hit.repo ? copy.browseRefresh : copy.browseShowFiles}
+ </Button>
+ }
+ description={
+ <span>
+ {Intl.NumberFormat().format(hit.downloads)} {copy.browseDownloads}
+ {' · '}
+ {Intl.NumberFormat().format(hit.likes)} {copy.browseLikes}
+ {hit.gated ? ` · ${copy.browseGated}` : ''}
+ </span>
+ }
+ title={<span className="font-mono text-[0.8rem]">{hit.repo}</span>}
+ />
- return (
- <div
- className={cn(
- 'flex flex-col gap-1 rounded-md border border-(--ui-border) px-2.5 py-1.5',
- group.fit === 'too-big' && 'opacity-45'
- )}
- key={group.label}
- >
- <span className="flex w-full items-center justify-between gap-2">
- <span className="truncate font-mono text-[0.75rem]">
- {group.label}
- {group.paths.length > 1 ? ` ×${group.paths.length}` : ''}
+ {openRepo === hit.repo && (
+ <div className="ml-4 grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-1.5 border-l border-(--ui-border) py-1 pl-3">
+ {listing && (
+ <p className="col-span-full flex items-center gap-2 py-1 text-[0.75rem] text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ {copy.browseListing}
+ </p>
+ )}
+
+ {!listing && files.length === 0 && (
+ <p className="col-span-full py-1 text-[0.75rem] text-muted-foreground">{copy.browseNoGguf}</p>
+ )}
+
+ {files.map(group => {
+ const dJob = runningDownloadFor(jobs, browsedModelId(group))
+
+ return (
+ <div
+ className={cn(
+ 'flex flex-col gap-1 rounded-md border border-(--ui-border) px-2.5 py-1.5',
+ group.fit === 'too-big' && 'opacity-45'
+ )}
+ key={group.label}
+ >
+ <span className="flex w-full items-center justify-between gap-2">
+ <span className="truncate font-mono text-[0.75rem]">
+ {group.label}
+ {group.paths.length > 1 ? ` ×${group.paths.length}` : ''}
+ </span>
+
+ <Button
+ aria-label={copy.browseDownloadAria.replace('{name}', group.label)}
+ className="h-6 shrink-0 px-2"
+ disabled={group.fit === 'too-big' || Boolean(dJob)}
+ onClick={() => startBrowsedDownload(hit.repo, group)}
+ size="sm"
+ variant="ghost"
+ >
+ {dJob ? <Loader2 className="size-3.5 animate-spin" /> : <Download className="size-3.5" />}
+ </Button>
</span>
- <Button
- aria-label={copy.browseDownloadAria.replace('{name}', group.label)}
- className="h-6 shrink-0 px-2"
- disabled={group.fit === 'too-big' || Boolean(dJob)}
- onClick={() => startBrowsedDownload(hit.repo, group)}
- size="sm"
- variant="ghost"
- >
- {dJob ? <Loader2 className="size-3.5 animate-spin" /> : <Download className="size-3.5" />}
- </Button>
- </span>
-
- {dJob ? (
- <>
- <ProgressBar paused={dJob.status === 'paused'} percent={dJob.percent} />
-
- <span className="text-[0.68rem] text-muted-foreground">
- {dJob.status === 'paused'
- ? copy.downloadPausedLabel
- : !dJob.done_bytes && dJob.detail
- ? dJob.detail
- : copy.downloadProgress(gbLabel(dJob.done_bytes), gbLabel(dJob.total_bytes))}
- </span>
+ {dJob ? (
+ <>
- <ProgressBar percent={dJob.percent} />
++ <ProgressBar paused={dJob.status === 'paused'} percent={dJob.percent} />
- <LocalModelDownloadActions job={dJob} />
- </>
- ) : (
- <span className="flex items-center justify-between gap-2">
- <Pill tone={fitTone(group.fit)}>
- <Cpu className="mr-1 size-3" />
- {group.fit === 'fits-gpu'
- ? copy.pillFitsGpu
- : group.fit === 'needs-ram'
- ? copy.pillUsesRam
- : group.fit === 'too-big'
- ? copy.pillTooBig
- : copy.browseFitUnknown}
- </Pill>
+ <span className="text-[0.68rem] text-muted-foreground">
- {!dJob.done_bytes && dJob.detail
- ? dJob.detail
- : copy.downloadProgress(gbLabel(dJob.done_bytes), gbLabel(dJob.total_bytes))}
++ {dJob.status === 'paused'
++ ? copy.downloadPausedLabel
++ : !dJob.done_bytes && dJob.detail
++ ? dJob.detail
++ : copy.downloadProgress(gbLabel(dJob.done_bytes), gbLabel(dJob.total_bytes))}
+ </span>
++
++ <LocalModelDownloadActions job={dJob} />
+ </>
+ ) : (
+ <span className="flex items-center justify-between gap-2">
+ <Pill tone={fitTone(group.fit)}>
+ <Cpu className="mr-1 size-3" />
+ {group.fit === 'fits-gpu'
+ ? copy.pillFitsGpu
+ : group.fit === 'needs-ram'
+ ? copy.pillUsesRam
+ : group.fit === 'too-big'
+ ? copy.pillTooBig
+ : copy.browseFitUnknown}
+ </Pill>
- <span className="shrink-0 text-[0.7rem] text-muted-foreground">
- {gbLabel(group.total_bytes)}
+ <span className="shrink-0 text-[0.7rem] text-muted-foreground">
+ {gbLabel(group.total_bytes)}
+ </span>
</span>
- </span>
- )}
- </div>
- )
- })}
- </div>
- )}
- </div>
- ))}
+ )}
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
</div>
</SettingsSection>
)
diff --cc apps/desktop/src/global.d.ts
index f2f7b750d75,84192c2450b..ccdad4dd70a
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@@ -336,10 -349,16 +336,13 @@@ declare global
glassSupported?: boolean
/** Main-process fact: this OS can do any translucency at all (not Linux). */
translucencySupported?: boolean
- /** Launch flag: the app was started with --local, enabling the
- * local-models GUI surfaces. Absent/false = every local surface hides. */
+ /** Feature flag: the local-models UI is enabled. */
localModelsEnabled?: boolean
- /** Launch flag: the Nous free tier is on for this launch
- * (HERMES_GUEST_ONBOARDING=1 or --guest-onboarding). Read-only fact the
- * main process also stamps onto every backend it spawns. */
+ /** Launch flag shared with every backend the app starts. */
guestOnboardingEnabled?: boolean
+ /** Launch flag: skip the first-run film (HERMES_SKIP_INTRO=1 or
+ * --skip-intro) so a fresh HERMES_HOME lands on the guided chat. */
+ skipIntro?: boolean
setTranslucency?: (payload: TranslucencyState) => void
setKeepAwake?: (on: boolean) => void
setDisableF12?: (blocked: boolean) => void
diff --cc apps/desktop/src/i18n/en.ts
index 978121062a2,ad7bf69067d..3fbf10020c5
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -32,12 -32,12 +38,11 @@@ export const en: Translations =
ownerMissing: 'Reopen this conversation to manage its connections.',
search: 'Find an app',
empty: 'No matching apps',
- continue: 'Continue in chat',
- continueBusy: 'Waiting for this turn to finish',
- continueFailed: 'Could not continue. Try again.',
disclaimer: 'Connecting is optional. Only authorize the apps you want Hermes to use.',
+ connectTitle: app => `Connect ${app}?`,
+ describe: app => `Hermes signs in to ${app} in your browser and asks before reading anything there.`,
execution: 'Connector tools'
},
-
sessionImport: {
title: 'Continue from another app',
subtitle: 'Bring a conversation into Hermes and pick up where you left off.',
@@@ -1290,15 -1322,15 +1299,18 @@@
'speed-gated-quality':
'A higher-quality model fits this machine but would respond too slowly on its memory bandwidth — this is the best model that stays fast.',
'fastest-resident':
- 'No model reaches full speed on this hardware; this one comes closest while running entirely in GPU memory.',
- 'least-painful-spilled': 'No model fits entirely in GPU memory here — this one runs best from system RAM.'
+ 'No model reaches full speed on this hardware; this one comes closest while running entirely in GPU memory.'
} as Record<string, string>,
+ noRecommendationTitle: 'No automatic recommendation for this machine',
+ noRecommendationDetail:
+ 'Automatic setup requires a curated model that fits entirely in GPU or unified memory. You can still choose a model below or browse more models.',
+ noRecommendationAction: 'Browse models',
downloaded: 'Downloaded',
downloadAction: size => `Download · ${size}`,
- downloadProgress: (done, total) => `Downloading ${done} of ${total}`,
+ downloadProgress: (done, total) => `${done} of ${total}`,
+ downloadPausedLabel: 'Paused',
+ downloadPauseAction: 'Pause',
+ downloadResumeAction: 'Resume',
downloadDoneToast: model => `${model} is ready.`,
installDoneToast: 'Local runtime installed and ready.',
quickstartTitle: 'Run a model on this machine',
@@@ -3344,50 -3171,19 +3163,60 @@@
notAvailable: 'Update not available for this backend.',
failed: 'Backend update failed.',
noReturn: 'Backend didn’t come back online. The update may not have completed — check the backend host.'
- }
+ },
+ // Update-status overlay + version-details (mechanism-aware update UI).
+ appName: 'Hermes',
+ version: (value: string) => `Version ${value}`,
+ versionUnavailable: 'Version unavailable',
+ checkNow: 'Check now',
+ seeWhatsNew: "See what's new",
+ releaseNotes: 'Release notes',
+ onLatest: "You're on the latest version.",
+ installing: 'An update is currently installing.',
+ cantReach: "We couldn't reach the update server.",
+ tapCheck: 'Tap "Check now" to look for updates.',
+ updateReady: count => `A new update is ready (${count} change${count === 1 ? '' : 's'} included).`,
+ updateReadyUnknown: 'A new update is ready.',
+ availableBodyRelease: tag => `Version ${tag} is ready to install.`,
+ lastChecked: age => `Last checked ${age}`,
+ never: 'never',
+ justNow: 'just now',
+ minAgo: count => `${count} min ago`,
+ hoursAgo: count => `${count}h ago`,
+ daysAgo: count => `${count}d ago`,
+ justNowSuffix: ' · just now',
+ bundleOutOfSync: 'App build out of date',
+ bundleOutOfSyncDesc:
+ 'The Hermes runtime was updated, but the desktop app itself is still an older build. Update it to pick up the latest fixes.',
+ bundleOutOfSyncAction: 'Get the installer',
+ checkingShort: 'Checking…',
+ releaseAvailable: tag => `Version ${tag} is available.`,
+ versionDetailsTitle: 'Version details',
+ versionDetailsBody:
+ 'This install is managed outside the app. Update it the same way you installed it.',
+ versionDetailsVersion: 'Version',
+ versionDetailsCommit: 'Commit',
+ versionDetailsBuildOrigin: 'Build Origin',
+ versionDetailsDistribution: 'Distribution',
+ versionDetailsDistributionDesktop: 'Desktop app (MSIX)',
+ versionDetailsDistributionStore: 'Microsoft Store',
+ versionDetailsRuntime: 'Runtime',
+ versionDetailsRuntimeEmbedded: 'Embedded runtime',
+ versionDetailsRuntimeExternal: 'External (uses the machine runtime)',
+ versionDetailsInstallId: 'Install ID',
+ versionDetailsUncommittedChanges: 'uncommitted changes'
},
+ handoffTour: {
+ profileTitle: 'Your first task runs on the default profile',
+ profileText:
+ 'This rail switches profiles. The one lit up now is default, where the task session lives. The other one is the setup profile, where the welcome chat lives.',
+ sessionsTitle: 'Each profile keeps its own sessions',
+ sessionsText:
+ 'This list belongs to the default profile. New session starts one on whichever profile is selected. Switch profiles on the rail and the list changes with it.',
+ stayTitle: 'Hermes is one click away',
+ stayText: 'Switch to the setup profile and open Welcome to Hermes whenever you want a hand. It stays there.'
+ },
guidedGreeting: {
line: "Hey, come on in. I'm Hermes. Give me two minutes to set the place up around you, then we'll put me to work on something you actually want done.\n\nFirst though, what should I call you?",
nameSuggestion: (name: string) => `(I can also just call you ${name}, if you prefer.)`
diff --cc apps/desktop/src/i18n/ja.ts
index b2f4acae0ea,ed6e365eec3..41d5758365c
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@@ -1156,16 -1182,16 +1156,19 @@@ export const ja = defineLocale(
'speed-gated-quality':
'より高品質なモデルもこのマシンに載りますが、メモリ帯域の制約で応答が遅くなります — これは速度を保てる最良のモデルです。',
'fastest-resident':
- 'このハードウェアでフルスピードに達するモデルはありません。GPU メモリ内で動くものの中で最速です。',
- 'least-painful-spilled':
- 'GPU メモリに完全に収まるモデルはありません — システム RAM からの実行で最も快適なモデルです。'
+ 'このハードウェアでフルスピードに達するモデルはありません。GPU メモリ内で動くものの中で最速です。'
} as Record<string, string>,
+ noRecommendationTitle: 'このマシン向けの自動推奨モデルはありません',
+ noRecommendationDetail:
+ '自動セットアップには、GPU メモリまたはユニファイドメモリに完全に収まる厳選モデルが必要です。下の一覧から選ぶか、ほかのモデルを探すこともできます。',
+ noRecommendationAction: 'モデルを探す',
+ quickstartConfigure: '自分で選ぶ',
downloaded: 'ダウンロード済み',
downloadAction: size => `ダウンロード · ${size}`,
- downloadProgress: (done, total) => `ダウンロード中 ${done} / ${total}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
+ downloadPausedLabel: '一時停止中',
+ downloadPauseAction: '一時停止',
+ downloadResumeAction: '再開',
downloadDoneToast: model => `${model} の準備ができました。`,
installDoneToast: 'ローカルランタイムのインストールが完了しました。',
useAction: '使用する',
diff --cc apps/desktop/src/i18n/zh-hant.ts
index 27039d145e9,5ac6be0ecb4..51c111817f2
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@@ -1109,15 -1135,16 +1109,19 @@@ export const zhHant = defineLocale(
'best-quality-resident': '在完全駐留 GPU 且保持全速的模型中品質最高。推薦會在品質與該硬體的預計速度之間權衡。',
'speed-gated-quality':
'有更高品質的模型可以裝入這台機器,但受記憶體頻寬限制回應會太慢——這是保持流暢的最佳模型。',
- 'fastest-resident': '沒有模型能在該硬體上達到全速;這是完全駐留 GPU 記憶體中最快的一個。',
- 'least-painful-spilled': '沒有模型能完全裝入 GPU 記憶體——這是從系統記憶體執行表現最好的一個。'
+ 'fastest-resident': '沒有模型能在該硬體上達到全速;這是完全駐留 GPU 記憶體中最快的一個。'
} as Record<string, string>,
+ noRecommendationTitle: '此裝置暫無自動推薦模型',
+ noRecommendationDetail:
+ '自動設定需要一個可完全放入 GPU 記憶體或統一記憶體的精選模型。你仍可在下方自行選擇,或瀏覽更多模型。',
+ noRecommendationAction: '瀏覽模型',
+ quickstartConfigure: '讓我選擇',
downloaded: '已下載',
downloadAction: size => `下載 · ${size}`,
- downloadProgress: (done, total) => `正在下載 ${done} / ${total}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
+ downloadPausedLabel: '已暫停',
+ downloadPauseAction: '暫停',
+ downloadResumeAction: '繼續',
downloadDoneToast: model => `${model} 已就緒。`,
installDoneToast: '本地執行環境已安裝就緒。',
useAction: '使用',
diff --cc apps/desktop/src/i18n/zh.ts
index 7ac4d7b0219,fcce24b1871..eb34ed08a56
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@@ -1,14 -1,8 +1,14 @@@
import { defineFieldCopy } from '@/app/settings/field-copy'
- import type { Translations } from './types'
+ import { defineLocale } from './define-locale'
- export const zh: Translations = {
+ export const zh = defineLocale({
+ externalOpenFailed: {
+ title: '无法打开此链接',
+ message: '没有注册用于打开此地址的浏览器。请复制链接并手动打开。',
+ copyUrl: '复制链接',
+ close: '关闭'
+ },
connectors: {
title: '连接你的应用',
connect: '连接',
@@@ -32,12 -26,12 +32,11 @@@
ownerMissing: '请重新打开此对话以管理连接。',
search: '查找应用',
empty: '没有匹配的应用',
- continue: '在对话中继续',
- continueBusy: '等待当前操作完成',
- continueFailed: '无法继续,请重试。',
disclaimer: '连接为可选操作。请仅授权你希望 Hermes 使用的应用。',
+ connectTitle: app => `连接 ${app}?`,
+ describe: app => `Hermes 会在浏览器中登录 ${app},读取任何内容前都会先询问。`,
execution: '连接器工具'
},
-
sessionImport: {
title: '从其他应用继续',
subtitle: '将对话导入 Hermes,接着上次的进度继续。',
@@@ -1463,7 -1499,7 +1477,6 @@@
`一键完成所有设置:本地引擎、${model}(需下载 ${size}),并设为新会话的默认模型。数据不会离开这台电脑。`,
quickstartDetailReady: model => `一键将 ${model} 设为新会话的默认模型。所有内容都在本机运行。`,
quickstartAction: '为我设置',
- quickstartConfigure: '自定义…',
- quickstartConfigure: '让我选择',
quickstartDoneToast: model => `${model} 已就绪——新会话将在本机运行。`,
quickstartFailed: '本地模型设置失败',
quickstartStageEngine: '引擎',
@@@ -1479,15 -1515,15 +1492,14 @@@
recommendedReason: {
'best-quality-resident': '在完全驻留 GPU 且保持全速的模型中质量最高。推荐会在质量与该硬件的预计速度之间权衡。',
'speed-gated-quality': '有更高质量的模型可以装入这台机器,但受内存带宽限制响应会太慢——这是保持流畅的最佳模型。',
- 'fastest-resident': '没有模型能在该硬件上达到全速;这是完全驻留 GPU 内存中最快的一个。',
- 'least-painful-spilled': '没有模型能完全装入 GPU 内存——这是从系统内存运行表现最好的一个。'
+ 'fastest-resident': '没有模型能在该硬件上达到全速;这是完全驻留 GPU 内存中最快的一个。'
} as Record<string, string>,
- noRecommendationTitle: '此设备暂无自动推荐模型',
- noRecommendationDetail:
- '自动设置需要一个可完全放入显存或统一内存的精选模型。你仍可在下方自行选择,或浏览更多模型。',
- noRecommendationAction: '浏览模型',
downloaded: '已下载',
downloadAction: size => `下载 · ${size}`,
- downloadProgress: (done, total) => `正在下载 ${done} / ${total}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
+ downloadPausedLabel: '已暂停',
+ downloadPauseAction: '暂停',
+ downloadResumeAction: '继续',
downloadDoneToast: model => `${model} 已就绪。`,
installDoneToast: '本地运行时已安装就绪。',
useAction: '使用',
@@@ -1553,6 -1589,6 +1565,11 @@@
deleteAction: '删除模型',
deleteConfirm: model => `从磁盘删除 ${model}?`,
deleted: model => `已删除 ${model}。`,
++ quickstartConfigure: '让我选择',
++ noRecommendationTitle: '此设备暂无自动推荐模型',
++ noRecommendationDetail:
++ '自动设置需要一个可完全放入显存或统一内存的精选模型。你仍可在下方自行选择,或浏览更多模型。',
++ noRecommendationAction: '浏览模型',
deleteFailed: '删除失败'
},
providers: {
diff --cc gateway/hooks.py
index 027dcf90236,58efd7e6b0b..38b3750b05a
--- a/gateway/hooks.py
+++ b/gateway/hooks.py
@@@ -15,9 -16,10 +16,10 @@@ import threadin
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
-import yaml
+import hermes_yaml as yaml
from hermes_cli.config import get_hermes_home
+ from hermes_constants import hermes_home_key
HOOKS_DIR = get_hermes_home() / "hooks"
diff --cc gateway/sticker_cache.py
index bdf7f4b7449,fee46acb69f..30cfb47bba5
--- a/gateway/sticker_cache.py
+++ b/gateway/sticker_cache.py
@@@ -21,13 -30,10 +30,14 @@@ STICKER_VISION_PROMPT =
def _load_cache() -> dict:
- try:
- return json.loads(_resolve_cache_path().read_text(encoding="utf-8"))
- except (FileNotFoundError, json.JSONDecodeError, OSError):
- return {}
+ """Load the sticker cache from disk (utf-8-sig: BOM-tolerant read fix)."""
- if CACHE_PATH.exists():
++ path = _resolve_cache_path()
++ if path.exists():
+ try:
- return json.loads(CACHE_PATH.read_text(encoding="utf-8-sig"))
++ return json.loads(path.read_text(encoding="utf-8-sig"))
+ except (json.JSONDecodeError, OSError): # OSError covers FileNotFoundError
+ return {}
+ return {}
def _save_cache(cache: dict) -> None:
diff --cc hermes_cli/gateway.py
index 74aa6cf3c14,2032d427db9..2c4382a2664
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@@ -6102,9 -6036,11 +6110,11 @@@ def _cmd_install(args)
managed_error("install gateway service")
return
force = getattr(args, "force", False)
+ # `--force` doubles as the reinstall flag here; a served profile's unit would only ever exit 78.
+ _guard_named_profile_under_multiplexer(force=force)
system = getattr(args, "system", False)
run_as_user = getattr(args, "run_as_user", None)
- if is_termux():
+ if _service_mgmt_blocked():
_no_backend_exit("install", "termux")
backend = _service_backend()
if backend == "systemd":
diff --cc hermes_cli/status.py
index 81bcb99b926,07386ef37f9..e07454f122f
--- a/hermes_cli/status.py
+++ b/hermes_cli/status.py
@@@ -224,8 -232,13 +231,10 @@@ def _render_gateway(ctx)
_kv("Manager:", snapshot.manager)
if snapshot.gateway_pids:
_kv("PID(s):", _format_gateway_pids(snapshot.gateway_pids))
+ if snapshot.running and (served := multiplexer_served_secondaries()):
+ _kv("Serves:", ", ".join(served))
if snapshot.has_process_service_mismatch:
_kv("Service:", "installed but not managing the current running gateway")
- elif _is_termux() and not snapshot.gateway_pids:
- _kv("Start with:", "hermes gateway")
- _kv("Note:", "Android may stop background jobs when Termux is suspended")
elif snapshot.service_installed and not snapshot.service_running:
_kv("Service:", "installed but stopped")
except Exception:
diff --cc hermes_cli/subcommands/gateway.py
index 659651b9213,c135f803016..c04ccb44291
--- a/hermes_cli/subcommands/gateway.py
+++ b/hermes_cli/subcommands/gateway.py
@@@ -105,10 -94,10 +114,11 @@@ def build_gateway_parser
_add_system_flag(gateway_status)
_add_compat_platform_flag(gateway_status)
+ # gateway install
gateway_install = gateway_subparsers.add_parser(
"install", help="Install gateway as a systemd/launchd background service")
- _flag(gateway_install, "--force", help="Force reinstall")
+ _flag(gateway_install, "--force",
+ help="Force reinstall, and install even when the default multiplexer already serves this profile")
_flag(gateway_install, "--system",
help="Install as a Linux system-level service (starts at boot)")
gateway_install.add_argument("--run-as-user", dest="run_as_user",
diff --cc hermes_cli/web_routers/local_models.py
index 87666af3e0d,9ccbce01ba3..cd5ecf67194
--- a/hermes_cli/web_routers/local_models.py
+++ b/hermes_cli/web_routers/local_models.py
@@@ -667,10 -707,11 +667,13 @@@ async def local_models_delete(model_id
# ── quickstart: one click from nothing to a working default ──
+
+
def _quickstart_target(body: QuickstartBody, budget):
- """(entry, variant) to set up: explicit id, else this machine's recommendation, else the first servable entry."""
+ """Resolve an explicit model, or start with the machine's automatic recommendation.
+
+ With no recommendation, require an explicit choice before starting setup.
+ """
if body.model_id:
candidates = [_entry_or_404(body.model_id)]
else:
@@@ -685,10 -731,10 +693,10 @@@
@router.post("/api/local-models/quickstart")
-async def local_models_quickstart(body: QuickstartBody):
+def local_models_quickstart(body: QuickstartBody):
"""One job: install the runtime (if missing), download this machine's build of the recommended model (if
- missing), make it the default. Each leg is the same code the individual routes run, so 'Configure' and
- quickstart can never disagree. Preflight rejects (no servable entry, engine too old) fail the POST
+ missing), make it the default. Each leg uses the same code as the individual setup routes.
+ Preflight rejects (no automatic recommendation or no servable choice) fail the POST
synchronously so the button can explain itself; everything slow runs in the job with phase/byte progress."""
entry, variant = _quickstart_target(body, hardware.probe_budget(planning=True))
tag, backend = _runtime_target()
diff --cc package-lock.json
index f678fc0baf6,eaf154d4507..85c06169b2e
--- a/package-lock.json
+++ b/package-lock.json
@@@ -35,7 -31,7 +35,7 @@@
},
"apps/bootstrap-installer": {
"name": "@hermes/bootstrap-installer",
-- "version": "0.0.1",
++ "version": "0.21.1",
"dependencies": {
"@nous-research/ui": "0.18.2",
"@tailwindcss/typography": "0.5.20",
diff --cc plugins/memory/hindsight/__init__.py
index 4b61ed9cf63,381b43c657a..2abdacdeaf9
--- a/plugins/memory/hindsight/__init__.py
+++ b/plugins/memory/hindsight/__init__.py
@@@ -34,10 -34,10 +34,11 @@@ from tools.registry import tool_erro
from .embedded import (
_RETRIABLE_CONNECTION_MARKERS, _build_embedded_profile_env,
- _check_local_runtime, _embedded_llm_api_key, _embedded_profile_env_path,
- _export_port_health_grace_timeout, _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,
+ _check_local_runtime, _embedded_profile_env_path,
+ _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,
+ _may_rewrite_profile_env,
)
+from .embedded_runtime import ensure_daemon_and_url as _start_sideenv_daemon
from .settings import (
_DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_RETAIN_SOURCE,
_DEFAULT_TIMEOUT, _HINDSIGHT_GLYPH, _MIN_CLIENT_VERSION, _MIN_VERSION_FOR_UPDATE_MODE_APPEND,
@@@ -228,33 -235,17 +229,36 @@@ REFLECT_SCHEMA =
def _load_config() -> dict:
- """$HERMES_HOME/hindsight/config.json (profile-scoped), else ~/.hindsight/config.json
- (legacy, shared), else environment variables."""
- for path in (get_hermes_home() / "hindsight" / "config.json", Path.home() / ".hindsight" / "config.json"):
- if path.exists():
- with contextlib.suppress(Exception):
- return json.loads(path.read_text(encoding="utf-8"))
+ """Load config from profile-scoped path, legacy path, or env vars.
+
+ Resolution order:
+ 1. $HERMES_HOME/hindsight/config.json (profile-scoped)
+ 2. ~/.hindsight/config.json (legacy, shared)
+ 3. Environment variables
+ """
+ from pathlib import Path
+
+ # Profile-scoped path (preferred)
+ profile_path = get_hermes_home() / "hindsight" / "config.json"
+ if profile_path.exists():
+ try:
+ return json.loads(profile_path.read_text(encoding="utf-8-sig"))
+ except Exception:
+ pass
+
+ # Legacy shared path (backward compat)
+ legacy_path = Path.home() / ".hindsight" / "config.json"
+ if legacy_path.exists():
+ try:
+ return json.loads(legacy_path.read_text(encoding="utf-8-sig"))
+ except Exception:
+ pass
+
+ # Mode, bank (the data partition), endpoint and retain shaping are per-profile .env values like
+ # the key beside them: read through the secret scope so a multiplexed secondary never inherits
+ # the default profile's bank/mode. Tuning knobs (timeouts, budget) stay process-global.
return {
- "mode": os.environ.get("HINDSIGHT_MODE", "cloud"),
+ "mode": get_secret("HINDSIGHT_MODE", "") or "cloud",
"apiKey": get_secret("HINDSIGHT_API_KEY", ""),
"timeout": _parse_int_setting(os.environ.get("HINDSIGHT_TIMEOUT"), _DEFAULT_TIMEOUT),
"idle_timeout": _parse_int_setting(os.environ.get("HINDSIGHT_IDLE_TIMEOUT"), _DEFAULT_IDLE_TIMEOUT),
@@@ -474,20 -465,12 +478,28 @@@ class HindsightMemoryProvider(MemoryPro
self._idle_timeout = self._int_setting(
"idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT, env_default=self._idle_timeout,
)
- kwargs = dict(profile=cfg.get("profile", "hermes"), llm_provider=llm_provider,
- llm_api_key=_embedded_llm_api_key(cfg), llm_model=cfg.get("llm_model", ""),
- idle_timeout=self._idle_timeout)
- if self._llm_base_url:
- kwargs["llm_base_url"] = self._llm_base_url
- return HindsightEmbedded(**kwargs)
+ # Starts (or reuses) the side-env daemon; the URL comes from the side env's
+ # own ProfileManager/get_url, never a hardcoded port.
+ changed = _load_simple_env(_embedded_profile_env_path(cfg)) != _build_embedded_profile_env(cfg)
+ if changed:
- _materialize_embedded_profile_env(cfg)
++ if _may_rewrite_profile_env(cfg):
++ _materialize_embedded_profile_env(cfg)
++ else:
++ # A scopeless worker must neither erase a persisted key nor stop
++ # the daemon that still uses it. The side-env manager reuses it.
++ logger.warning(
++ "Hindsight profile env for %r holds an LLM API key this process cannot see; "
++ "leaving the file and running daemon untouched.", profile)
++ changed = False
+ url = _start_sideenv_daemon(cfg, restart=changed)
+ self._api_url = url
+ _ensure_client_dependency()
+ from hindsight_client import Hindsight
+ kwargs = {"base_url": url, "timeout": float(self._timeout or _DEFAULT_TIMEOUT)}
+ if self._api_key:
+ kwargs["api_key"] = self._api_key
+ logger.info("Hindsight embedded: HTTP client ready (profile=%s, url=%s)", profile, url)
+ return Hindsight(**kwargs)
def _new_cloud_client(self):
_ensure_client_dependency()
diff --cc plugins/platforms/feishu/feishu_comment_rules.py
index 13261c153c8,27fa01fbcb8..73ea6e172a5
--- a/plugins/platforms/feishu/feishu_comment_rules.py
+++ b/plugins/platforms/feishu/feishu_comment_rules.py
@@@ -51,31 -61,40 +61,40 @@@ class ResolvedCommentRule
class _MtimeCache:
- """Mtime-based JSON file cache: ``stat()`` per access, re-read only on change."""
+ """Mtime-based JSON file cache: ``stat()`` per access, re-read only on change. ``path`` is a
+ ``Path`` or a zero-arg callable resolving one; state is keyed per resolved path so profiles
+ routed through one multiplexed process never share a slot."""
+
+ def __init__(self, path: Path | Callable[[], Path]):
+ self._resolve = path if callable(path) else (lambda: path)
+ self._entries: Dict[Path, tuple[float, dict]] = {}
- def __init__(self, path: Path):
- self._path, self._mtime, self._data = path, 0.0, None
+ def invalidate(self) -> None:
+ self._entries.pop(self._resolve(), None)
def load(self) -> dict:
+ path = self._resolve()
try:
- mtime = self._path.stat().st_mtime
+ mtime = path.stat().st_mtime
except FileNotFoundError:
- self._mtime, self._data = 0.0, {}
+ self._entries.pop(path, None)
return {}
- if mtime == self._mtime and self._data is not None:
- return self._data
+ cached = self._entries.get(path)
+ if cached is not None and cached[0] == mtime:
+ return cached[1]
try:
- with open(self._path, "r", encoding="utf-8-sig") as f:
- with open(path, "r", encoding="utf-8") as f:
++ with open(path, "r", encoding="utf-8-sig") as f:
data = json.load(f)
except (json.JSONDecodeError, OSError):
- logger.warning("[Feishu-Rules] Failed to read %s, using empty config", self._path)
+ logger.warning("[Feishu-Rules] Failed to read %s, using empty config", path)
data = {}
- self._mtime, self._data = mtime, (data if isinstance(data, dict) else {})
- return self._data
+ data = data if isinstance(data, dict) else {}
+ self._entries[path] = (mtime, data)
+ return data
- _rules_cache = _MtimeCache(RULES_FILE)
- _pairing_cache = _MtimeCache(PAIRING_FILE)
+ _rules_cache = _MtimeCache(_rules_file)
+ _pairing_cache = _MtimeCache(_pairing_file)
def _parse_frozenset(raw: Any) -> Optional[frozenset]:
@@@ -137,11 -156,12 +156,12 @@@ def _load_pairing_approved() -> set
def _save_pairing(data: dict) -> None:
- PAIRING_FILE.parent.mkdir(parents=True, exist_ok=True)
- with open(PAIRING_FILE.with_suffix(".tmp"), "w", encoding="utf-8") as f: # windows-footgun: ok (write/append mode, not a read)
+ pairing_file = _pairing_file()
+ pairing_file.parent.mkdir(parents=True, exist_ok=True)
- with open(pairing_file.with_suffix(".tmp"), "w", encoding="utf-8") as f:
++ with open(pairing_file.with_suffix(".tmp"), "w", encoding="utf-8") as f: # windows-footgun: ok (write/append mode, not a read)
json.dump(data, f, indent=2, ensure_ascii=False)
- PAIRING_FILE.with_suffix(".tmp").replace(PAIRING_FILE)
- _pairing_cache._mtime, _pairing_cache._data = 0.0, None # invalidate so the next load re-reads
+ pairing_file.with_suffix(".tmp").replace(pairing_file)
+ _pairing_cache.invalidate() # same-second rewrite can keep the mtime; force the next load to re-read
def _mutate_pairing(user_open_id: str, add: bool) -> bool:
diff --cc scripts/release.py
index 419d71678fc,5a07abf88a5..a3bd3a1007f
--- a/scripts/release.py
+++ b/scripts/release.py
@@@ -2369,46 -2219,71 +2369,92 @@@ def update_version_files(semver: str, c
# Python package version. The desktop About panel reads the live Hermes
# version at runtime, but app.getVersion()/packaging metadata still come
# from this field, so it must track pyproject to avoid drift.
- desktop_pkg = REPO_ROOT / "apps" / "desktop" / "package.json"
- if desktop_pkg.exists():
- pkg_text = desktop_pkg.read_text(encoding="utf-8")
- pkg_text = re.sub(
- r'("version"\s*:\s*)"[^"]+"',
- rf'\g<1>"{semver}"',
- pkg_text,
- count=1,
- )
- desktop_pkg.write_text(pkg_text, encoding="utf-8")
+ pkg_text = DESKTOP_PKG_FILE.read_text(encoding="utf-8-sig")
+ pkg_text = re.sub(
+ r'("version"\s*:\s*)"[^"]+"',
+ rf'\g<1>"{semver}"',
+ pkg_text,
+ count=1,
+ )
+ DESKTOP_PKG_FILE.write_text(pkg_text, encoding="utf-8")
+
+ # npm mirrors each workspace package's version into the root lockfile.
+ # Update the apps/desktop entry so `npm ci`/`npm install` do not see the
+ # lockfile as out of date and rewrite it (or fail in CI) after a bump.
+ lock_text = PKG_LOCK_FILE.read_text(encoding="utf-8-sig")
+ lock_text = re.sub(
+ r'("apps/desktop"\s*:\s*\{\s*"name"\s*:\s*"[^"]+"\s*,\s*"version"\s*:\s*)"[^"]+"',
+ rf'\g<1>"{semver}"',
+ lock_text,
+ count=1,
+ )
+ PKG_LOCK_FILE.write_text(lock_text, encoding="utf-8")
+
+ # uv.lock records the editable root package's version from pyproject.
+ # Update it in place so a post-release `uv sync`/`uv lock` is a no-op.
+ uv_text = UV_LOCK_FILE.read_text(encoding="utf-8-sig")
+ uv_text = re.sub(
+ r'(name = "hermes-agent"\nversion = )"[^"]+"',
+ rf'\g<1>"{semver}"',
+ uv_text,
+ count=1,
+ )
+ UV_LOCK_FILE.write_text(uv_text, encoding="utf-8")
+
- return [
++ updated = [
+ str(VERSION_FILE),
+ str(PYPROJECT_FILE),
+ str(DESKTOP_PKG_FILE),
+ str(PKG_LOCK_FILE),
+ str(UV_LOCK_FILE),
+ ]
+ # Keep the bootstrap installer (Hermes-Setup.dmg CFBundleShortVersionString)
+ # in lockstep with the Python package version. Tauri reads `version` from
+ # package.json + tauri.conf.json; a hardcoded 0.0.1 ships in the DMG.
+ installer_pkg = REPO_ROOT / "apps" / "bootstrap-installer" / "package.json"
+ if installer_pkg.exists():
+ pkg_text = installer_pkg.read_text(encoding="utf-8")
+ pkg_text = re.sub(
+ r'("version"\s*:\s*)"[^"]+"',
+ rf'\g<1>"{semver}"',
+ pkg_text,
+ count=1,
+ )
+ installer_pkg.write_text(pkg_text, encoding="utf-8")
++ updated.append(str(installer_pkg))
+
+ installer_tauri = (
+ REPO_ROOT / "apps" / "bootstrap-installer" / "src-tauri" / "tauri.conf.json"
+ )
+ if installer_tauri.exists():
+ pkg_text = installer_tauri.read_text(encoding="utf-8")
+ pkg_text = re.sub(
+ r'("version"\s*:\s*)"[^"]+"',
+ rf'\g<1>"{semver}"',
+ pkg_text,
+ count=1,
+ )
+ installer_tauri.write_text(pkg_text, encoding="utf-8")
++ updated.append(str(installer_tauri))
+
+ installer_cargo = (
+ REPO_ROOT / "apps" / "bootstrap-installer" / "src-tauri" / "Cargo.toml"
+ )
+ if installer_cargo.exists():
+ cargo_text = installer_cargo.read_text(encoding="utf-8")
+ cargo_text = re.sub(
+ r'^version\s*=\s*"[^"]+"',
+ f'version = "{semver}"',
+ cargo_text,
+ count=1,
+ flags=re.MULTILINE,
+ )
+ installer_cargo.write_text(cargo_text, encoding="utf-8")
++ updated.append(str(installer_cargo))
+
-
-def version_files_to_stage() -> list[str]:
- """Return version-bearing files that exist and should be `git add`ed after a bump."""
- candidates = [
- VERSION_FILE,
- PYPROJECT_FILE,
- REPO_ROOT / "apps" / "desktop" / "package.json",
- REPO_ROOT / "apps" / "bootstrap-installer" / "package.json",
- REPO_ROOT / "apps" / "bootstrap-installer" / "src-tauri" / "tauri.conf.json",
- REPO_ROOT / "apps" / "bootstrap-installer" / "src-tauri" / "Cargo.toml",
- ]
- return [str(path) for path in candidates if path.exists()]
++ return updated
+
def resolve_author(name: str, email: str) -> str:
"""Resolve a git author to a GitHub @mention."""
diff --cc tests/scripts/test_release_bootstrap_installer_version.py
index 00000000000,a6e4ab25e51..48e45245999
mode 000000,100644..100644
--- a/tests/scripts/test_release_bootstrap_installer_version.py
+++ b/tests/scripts/test_release_bootstrap_installer_version.py
@@@ -1,0 -1,144 +1,153 @@@
+ """release.py must stamp bootstrap-installer versions with the release semver.
+
+ Tauri CFBundleShortVersionString is read from
+ apps/bootstrap-installer/src-tauri/tauri.conf.json (and the sibling
+ package.json). Those files were hardcoded 0.0.1 and omitted from
+ update_version_files / the --publish --bump git add list, so Hermes-Setup.dmg
+ always shipped 0.0.1. Same class as the desktop stamp (#68783 / PR #68796).
+ """
+
+ from __future__ import annotations
+
+ import importlib.util
+ import json
+ from pathlib import Path
+
+ SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "release.py"
+
+
+ def _load():
+ spec = importlib.util.spec_from_file_location(
+ "release_bootstrap_installer_version", SCRIPT
+ )
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+ release = _load()
+
+
+ def _json_version(path: Path) -> str:
+ return json.loads(path.read_text(encoding="utf-8"))["version"]
+
+
+ def _patch_repo(tmp_path, monkeypatch, *, with_installer: bool = True):
+ repo = tmp_path
+ init_py = repo / "hermes_cli" / "__init__.py"
+ init_py.parent.mkdir(parents=True)
+ init_py.write_text(
+ '__version__ = "0.0.1"\n__release_date__ = "2026.1.1"\n',
+ encoding="utf-8",
+ )
+ pyproject = repo / "pyproject.toml"
+ pyproject.write_text('version = "0.0.1"\n', encoding="utf-8")
+
+ desktop_pkg = repo / "apps" / "desktop" / "package.json"
+ desktop_pkg.parent.mkdir(parents=True)
+ desktop_pkg.write_text('{"version":"0.0.1"}\n', encoding="utf-8")
+
++ package_lock = repo / "package-lock.json"
++ package_lock.write_text('{"packages":{"apps/desktop":{"name":"hermes","version":"0.0.1"}}}\n', encoding="utf-8")
++ uv_lock = repo / "uv.lock"
++ uv_lock.write_text('[[package]]\nname = "hermes-agent"\nversion = "0.0.1"\n', encoding="utf-8")
++
+ installer_pkg = repo / "apps" / "bootstrap-installer" / "package.json"
+ tauri_conf = (
+ repo / "apps" / "bootstrap-installer" / "src-tauri" / "tauri.conf.json"
+ )
+ cargo_toml = repo / "apps" / "bootstrap-installer" / "src-tauri" / "Cargo.toml"
+ if with_installer:
+ tauri_conf.parent.mkdir(parents=True)
+ installer_pkg.write_text(
+ '{"name":"x","version":"0.0.1"}\n', encoding="utf-8"
+ )
+ tauri_conf.write_text(
+ '{"productName":"Hermes","version":"0.0.1"}\n', encoding="utf-8"
+ )
+ cargo_toml.write_text('[package]\nversion = "0.0.1"\n', encoding="utf-8")
+
+ monkeypatch.setattr(release, "REPO_ROOT", repo)
+ monkeypatch.setattr(release, "VERSION_FILE", init_py)
+ monkeypatch.setattr(release, "PYPROJECT_FILE", pyproject)
++ monkeypatch.setattr(release, "DESKTOP_PKG_FILE", desktop_pkg)
++ monkeypatch.setattr(release, "PKG_LOCK_FILE", package_lock)
++ monkeypatch.setattr(release, "UV_LOCK_FILE", uv_lock)
++ monkeypatch.setattr(release, "git", lambda *args: "0")
+ return {
+ "repo": repo,
+ "init_py": init_py,
+ "pyproject": pyproject,
+ "desktop_pkg": desktop_pkg,
+ "installer_pkg": installer_pkg,
+ "tauri_conf": tauri_conf,
+ "cargo_toml": cargo_toml,
+ }
+
+
+ def test_update_version_files_stamps_bootstrap_installer(tmp_path, monkeypatch):
+ paths = _patch_repo(tmp_path, monkeypatch)
+
+ release.update_version_files("0.21.1", "2026.9.10")
+
+ assert _json_version(paths["installer_pkg"]) == "0.21.1"
+ assert _json_version(paths["tauri_conf"]) == "0.21.1"
+ assert 'version = "0.21.1"' in paths["cargo_toml"].read_text(encoding="utf-8")
+
+ # CONTROL: existing desktop / Python stamps still happen.
+ assert _json_version(paths["desktop_pkg"]) == "0.21.1"
+ assert 'version = "0.21.1"' in paths["pyproject"].read_text(encoding="utf-8")
+ init_text = paths["init_py"].read_text(encoding="utf-8")
+ assert '__version__ = "0.21.1"' in init_text
+ assert '__release_date__ = "2026.9.10"' in init_text
+
+
+ def test_update_version_files_skips_missing_installer_dir(tmp_path, monkeypatch):
+ paths = _patch_repo(tmp_path, monkeypatch, with_installer=False)
+
+ release.update_version_files("0.21.1", "2026.9.10")
+
+ assert not paths["installer_pkg"].exists()
+ assert not paths["tauri_conf"].exists()
+ assert _json_version(paths["desktop_pkg"]) == "0.21.1"
+ assert 'version = "0.21.1"' in paths["pyproject"].read_text(encoding="utf-8")
+ assert '__version__ = "0.21.1"' in paths["init_py"].read_text(encoding="utf-8")
+
+
+ def test_update_version_files_does_not_invent_version_keys(tmp_path, monkeypatch):
+ paths = _patch_repo(tmp_path, monkeypatch)
+ original = '{"name":"x","productName":"Hermes"}\n'
+ paths["installer_pkg"].write_text(original, encoding="utf-8")
+ paths["tauri_conf"].write_text(original, encoding="utf-8")
+
+ release.update_version_files("0.21.1", "2026.9.10")
+
+ assert paths["installer_pkg"].read_text(encoding="utf-8") == original
+ assert paths["tauri_conf"].read_text(encoding="utf-8") == original
+ assert _json_version(paths["desktop_pkg"]) == "0.21.1"
+
+
-def test_version_files_to_stage_includes_installer_when_present(tmp_path, monkeypatch):
++def test_updated_files_include_installer_when_present(tmp_path, monkeypatch):
+ paths = _patch_repo(tmp_path, monkeypatch)
+
- staged = release.version_files_to_stage()
++ staged = release.update_version_files("0.21.1", "2026.9.10")
+
+ assert str(paths["init_py"]) in staged
+ assert str(paths["pyproject"]) in staged
+ assert str(paths["desktop_pkg"]) in staged
+ assert str(paths["installer_pkg"]) in staged
+ assert str(paths["tauri_conf"]) in staged
+ assert str(paths["cargo_toml"]) in staged
+
+
-def test_version_files_to_stage_omits_missing_installer(tmp_path, monkeypatch):
++def test_updated_files_omit_missing_installer(tmp_path, monkeypatch):
+ paths = _patch_repo(tmp_path, monkeypatch, with_installer=False)
+
- staged = release.version_files_to_stage()
++ staged = release.update_version_files("0.21.1", "2026.9.10")
+
+ assert str(paths["installer_pkg"]) not in staged
+ assert str(paths["tauri_conf"]) not in staged
+ assert str(paths["cargo_toml"]) not in staged
+ assert str(paths["desktop_pkg"]) in staged
+ assert str(paths["init_py"]) in staged
+ assert str(paths["pyproject"]) in staged
diff --cc tests/test_packaging_build_guard.py
index 68538edd45a,0b169f76ed8..c4bc3a80bfd
--- a/tests/test_packaging_build_guard.py
+++ b/tests/test_packaging_build_guard.py
@@@ -98,39 -93,4 +93,39 @@@ def test_artifact_build_allows_explicit
}
missing = sorted(expected - shipped)
- assert not missing, f"{kind} omits runtime modules or bundled data: {missing}"
+ assert not missing, f"{kind} omits bundled plugin manifests: {missing}"
+
+
+def test_wheel_ships_pm_package_and_lock_json(tmp_path):
+ """The pm/ package manager must survive a sealed wheel build.
+
+ pm is a flat package listed in [tool.setuptools.packages.find] include,
+ and pm/lock.json is its runtime pin table (uv/python/tool versions +
+ sha256s) declared via [tool.setuptools.package-data]. If either drops
+ out of the wheel, installed Hermes has no package manager at all --
+ exercise the real PEP 517 build path rather than reading TOML source.
+ """
+ result = _build_artifact("wheel", tmp_path, nix_build=True)
+
+ assert result.returncode == 0, result.stderr
+ artifacts = list(tmp_path.glob("hermes_agent-*.whl"))
+ assert artifacts
+
+ with zipfile.ZipFile(artifacts[0]) as wheel:
+ shipped = set(wheel.namelist())
+
+ missing = sorted({"pm/__init__.py", "pm/lock.json", "pm/artifact-mirror.json"} - shipped)
+ assert not missing, f"wheel omits pm package files: {missing}"
+
+ installed = tmp_path / "installed"
+ with zipfile.ZipFile(artifacts[0]) as wheel:
+ wheel.extractall(installed)
+ check = subprocess.run(
+ [sys.executable, "-I", "-S", "-c",
+ "import sys; sys.path.insert(0, sys.argv[1]); "
+ "from pm.artifact_mirror import mirror_url; print(mirror_url('0' * 64))", str(installed)],
+ cwd=tmp_path, text=True, capture_output=True, timeout=30,
+ )
+ assert check.returncode == 0, check.stderr
+ from pm.artifact_mirror import mirror_url
+ assert check.stdout.strip() == mirror_url("0" * 64)
diff --cc tests/test_profile_isolation_runtime.py
index 1e0cfd73e8c,bfd52a1036a..47bfa8b1518
--- a/tests/test_profile_isolation_runtime.py
+++ b/tests/test_profile_isolation_runtime.py
@@@ -109,9 -108,96 +109,96 @@@ class TestRichSentStorePathResolution
b_seen = _under_override(prof_b, lambda: rss._store_path())
assert b_seen.startswith(str(prof_b))
- assert b_seen.endswith("state/rich_sent_index.json")
+ assert b_seen.endswith(os.path.join("state", "rich_sent_index.json"))
+ class TestGatewayHooksDirResolution:
+ """gateway/hooks.py's HookRegistry must discover hooks from the active
+ profile's directory — otherwise one profile's HookRegistry loads and
+ executes a DIFFERENT profile's hook handlers (arbitrary Python) against
+ its own live event context under the multiplexed gateway."""
+
+ def test_hooks_dir_follows_override(self, two_profiles):
+ prof_a, prof_b = two_profiles
+ import gateway.hooks as gh
+
+ a_seen = _under_override(prof_a, lambda: gh._resolve_hooks_dir())
+ b_seen = _under_override(prof_b, lambda: gh._resolve_hooks_dir())
+
+ assert a_seen == prof_a / "hooks"
+ assert b_seen == prof_b / "hooks"
+ assert a_seen != b_seen
+
+ def test_discover_and_load_uses_active_profile_hooks_dir(self, two_profiles):
+ """End-to-end: a hook that only exists under profile B's hooks dir
+ must not be discovered when profile A's override is active, and vice
+ versa — proving the registry doesn't fall back to a frozen profile."""
+ prof_a, prof_b = two_profiles
+ import gateway.hooks as gh
+
+ b_hook_dir = prof_b / "hooks" / "only-in-b"
+ b_hook_dir.mkdir(parents=True)
+ (b_hook_dir / "HOOK.yaml").write_text(
+ "name: only-in-b\nevents: [\"agent:start\"]\n", encoding="utf-8",
+ )
+ (b_hook_dir / "handler.py").write_text(
+ "async def handle(event_type, context):\n pass\n", encoding="utf-8",
+ )
+
+ def _load_and_names():
+ reg = gh.HookRegistry()
+ reg.discover_and_load()
+ return [h["name"] for h in reg.loaded_hooks]
+
+ a_hooks = _under_override(prof_a, _load_and_names)
+ b_hooks = _under_override(prof_b, _load_and_names)
+
+ assert "only-in-b" not in a_hooks
+ assert "only-in-b" in b_hooks
+
+
+ class TestCheckpointManagerPathResolution:
+ """tools/checkpoint_manager.py's checkpoint store root must honor the
+ active profile — otherwise one profile's CheckpointManager instance can
+ read/write code-edit checkpoints into a different profile's store under
+ the multiplexed gateway."""
+
+ def test_checkpoint_base_follows_override(self, two_profiles):
+ prof_a, prof_b = two_profiles
+ import tools.checkpoint_manager as cm
+
+ a_seen = _under_override(prof_a, lambda: cm._resolve_checkpoint_base())
+ b_seen = _under_override(prof_b, lambda: cm._resolve_checkpoint_base())
+
+ assert a_seen == prof_a / "checkpoints"
+ assert b_seen == prof_b / "checkpoints"
+ assert a_seen != b_seen
+
+ def test_store_path_follows_override(self, two_profiles):
+ prof_a, prof_b = two_profiles
+ import tools.checkpoint_manager as cm
+
+ b_seen = _under_override(prof_b, lambda: cm._store_path())
+ assert b_seen == prof_b / "checkpoints" / "store"
+
+
+ class TestStickerCachePathResolution:
+ """gateway/sticker_cache.py's cache file must honor the active profile —
+ otherwise one profile's Telegram sticker-description cache leaks into a
+ different profile's under the multiplexed gateway."""
+
+ def test_cache_path_follows_override(self, two_profiles):
+ prof_a, prof_b = two_profiles
+ import gateway.sticker_cache as sc
+
+ a_seen = _under_override(prof_a, lambda: sc._resolve_cache_path())
+ b_seen = _under_override(prof_b, lambda: sc._resolve_cache_path())
+
+ assert a_seen == prof_a / "sticker_cache.json"
+ assert b_seen == prof_b / "sticker_cache.json"
+ assert a_seen != b_seen
+
+
# ---------------------------------------------------------------------------
# M2 — thread / executor context propagation
# ---------------------------------------------------------------------------
diff --cc tests/tools/test_env_passthrough.py
index 8cccda656bf,9afb4948a74..97692761a23
--- a/tests/tools/test_env_passthrough.py
+++ b/tests/tools/test_env_passthrough.py
@@@ -44,9 -44,9 +44,9 @@@ class TestConfigPassthrough
def test_reads_from_config(self, tmp_path, monkeypatch):
config = {"terminal": {"env_passthrough": ["MY_CUSTOM_KEY", "ANOTHER_TOKEN"]}}
config_path = tmp_path / "config.yaml"
- config_path.write_text(yaml.dump(config), encoding="utf-8")
+ config_path.write_text(yaml.safe_dump(config), encoding="utf-8")
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- _ep_mod._config_passthrough = None
+ _ep_mod._config_passthrough.clear()
assert is_env_passthrough("MY_CUSTOM_KEY")
assert is_env_passthrough("ANOTHER_TOKEN")
@@@ -56,9 -56,9 +56,9 @@@
def test_union_of_skill_and_config(self, tmp_path, monkeypatch):
config = {"terminal": {"env_passthrough": ["CONFIG_KEY"]}}
config_path = tmp_path / "config.yaml"
- config_path.write_text(yaml.dump(config), encoding="utf-8")
+ config_path.write_text(yaml.safe_dump(config), encoding="utf-8")
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- _ep_mod._config_passthrough = None
+ _ep_mod._config_passthrough.clear()
register_env_passthrough(["SKILL_KEY"])
all_pt = get_all_passthrough()
diff --cc tools/approval.py
index b1606733070,7fb8d43f9d2..ecf9fa4e097
--- a/tools/approval.py
+++ b/tools/approval.py
@@@ -324,6 -350,29 +350,29 @@@ def _persist_choice(session_key: str, c
# --- Config persistence for permanent allowlist ---------------------------------------------------------------------
+ def _read_permanent_allowlist() -> set:
+ """``command_allowlist`` of the active profile's config as a set (empty on malformed input)."""
+ from hermes_cli.config import load_config_readonly
+ config = load_config_readonly()
+ raw = config.get("command_allowlist")
+ legacy = isinstance(raw, str)
+ if legacy:
+ # Old config-set versions serialized list values as scalar strings.
- import yaml
++ import hermes_yaml as yaml
+ try:
+ raw = yaml.safe_load(raw)
+ except yaml.YAMLError:
+ raw = False
+ if raw is None and not legacy:
+ raw = []
+ if not isinstance(raw, list) or any(not isinstance(item, str) for item in raw):
+ logger.warning("Ignoring malformed command_allowlist; configure a list of strings.")
+ return set()
+ if legacy:
+ logger.warning("Recovered legacy string command_allowlist; re-save it as a list of strings.")
+ return set(raw)
+
+
def load_permanent_allowlist() -> set:
"""Load ``command_allowlist`` from config and sync it into the approval state
so is_approved() honors 'always' choices from previous sessions."""
diff --cc tools/checkpoint_manager.py
index eb76d268190,6df3db1c721..7196a3b4577
--- a/tools/checkpoint_manager.py
+++ b/tools/checkpoint_manager.py
@@@ -66,107 -30,59 +66,116 @@@ from utils import env_in
logger = logging.getLogger(__name__)
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
CHECKPOINT_BASE = get_hermes_home() / "checkpoints"
+ _CHECKPOINT_BASE_AT_IMPORT = CHECKPOINT_BASE
+
+
+ def _resolve_checkpoint_base() -> Path:
+ """Active profile's checkpoint root at call time: the patched ``CHECKPOINT_BASE`` when a test
+ changed it, else live profile-scoped HERMES_HOME — under the multiplexed gateway one process
+ serves every profile, so the import-time constant would write every profile's code-edit
+ checkpoints into the launch profile's store."""
+ return CHECKPOINT_BASE if CHECKPOINT_BASE != _CHECKPOINT_BASE_AT_IMPORT else get_hermes_home() / "checkpoints"
-_STORE_DIRNAME, _INDEXES_DIRNAME, _PROJECTS_DIRNAME, _LEDGERS_DIRNAME = "store", "indexes", "projects", "ledgers"
-_REFS_PREFIX, _LEGACY_PREFIX, _PRUNE_MARKER_NAME = "refs/hermes", "legacy-", ".last_prune"
-_LEDGER_MAX_ENTRIES = 2000 # newest agent-write entries retained per project
+# Single shared store directory under CHECKPOINT_BASE.
+_STORE_DIRNAME = "store"
+_REFS_PREFIX = "refs/hermes"
+_INDEXES_DIRNAME = "indexes"
+_PROJECTS_DIRNAME = "projects"
+_LEDGERS_DIRNAME = "ledgers"
+_LEGACY_PREFIX = "legacy-"
+
+# Agent-write ledger cap: newest entries retained per project.
+_LEDGER_MAX_ENTRIES = 2000
DEFAULT_EXCLUDES = [
- "node_modules/", "dist/", "build/", "target/", "out/", ".next/", ".nuxt/", # dependency / build output
- "__pycache__/", "*.pyc", "*.pyo", ".cache/", ".pytest_cache/", ".mypy_cache/", # caches
- ".ruff_cache/", "coverage/", ".coverage",
- ".venv/", "venv/", "env/", # virtualenvs
- ".git/", ".hg/", ".svn/", ".worktrees/", # VCS + worktrees (Hermes convention — don't snapshot siblings)
- "*.so", "*.dylib", "*.dll", "*.o", "*.a", "*.jar", "*.class", "*.exe", "*.obj", # compiled binaries
- "*.mp4", "*.mov", "*.mkv", "*.webm", "*.zip", "*.tar", "*.tar.gz", "*.tgz", # media / large binaries
- "*.7z", "*.rar", "*.iso",
- ".env", ".env.*", ".env.local", ".env.*.local", # secrets
- ".DS_Store", "Thumbs.db", "*.log", # OS junk / logs
+ # Dependency / build output
+ "node_modules/",
+ "dist/",
+ "build/",
+ "target/",
+ "out/",
+ ".next/",
+ ".nuxt/",
+ # Caches
+ "__pycache__/",
+ "*.pyc",
+ "*.pyo",
+ ".cache/",
+ ".pytest_cache/",
+ ".mypy_cache/",
+ ".ruff_cache/",
+ "coverage/",
+ ".coverage",
+ # Virtualenvs
+ ".venv/",
+ "venv/",
+ "env/",
+ # VCS
+ ".git/",
+ ".hg/",
+ ".svn/",
+ # Worktrees (Hermes convention — don't recursively snapshot siblings)
+ ".worktrees/",
+ # Native / compiled binaries
+ "*.so",
+ "*.dylib",
+ "*.dll",
+ "*.o",
+ "*.a",
+ "*.jar",
+ "*.class",
+ "*.exe",
+ "*.obj",
+ # Media / large binaries
+ "*.mp4",
+ "*.mov",
+ "*.mkv",
+ "*.webm",
+ "*.zip",
+ "*.tar",
+ "*.tar.gz",
+ "*.tgz",
+ "*.7z",
+ "*.rar",
+ "*.iso",
+ # Secrets
+ ".env",
+ ".env.*",
+ ".env.local",
+ ".env.*.local",
+ # OS junk
+ ".DS_Store",
+ "Thumbs.db",
+ # Logs
+ "*.log",
]
+# Git subprocess timeout (seconds).
_GIT_TIMEOUT: int = max(10, min(60, env_int("HERMES_CHECKPOINT_TIMEOUT", 30)))
-_MAX_FILES = 50_000 # skip huge directories to avoid slowdowns
-_COMMIT_HASH_RE = re.compile(r'^[0-9a-fA-F]{4,64}$') # short or full SHA-1/SHA-256
-_MB = 1024 * 1024
-# Inherited GIT_* vars that would redirect the shadow store's git calls.
-_GIT_LEAK_VARS = ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_NAMESPACE", "GIT_ALTERNATE_OBJECT_DIRECTORIES")
-# Per-store config: isolated by env vars already, but belt-and-suspenders.
-_STORE_GIT_CONFIG = (("user.email", "hermes@local"), ("user.name", "Hermes Checkpoint"),
- ("commit.gpgsign", "false"), ("tag.gpgSign", "false"), ("gc.auto", "0"))
-_PROJECT_MARKERS = {".git", "pyproject.toml", "package.json", "Cargo.toml", "go.mod", "Makefile", "pom.xml", ".hg", "Gemfile"}
-
-_SHORTSTAT_FIELDS = (("files_changed", r'(\d+) file'), ("insertions", r'(\d+) insertion'),
- ("deletions", r'(\d+) deletion'))
+# Max files to snapshot — skip huge directories to avoid slowdowns.
+_MAX_FILES = 50_000
-def _no_store_result() -> Dict:
- return {"success": False, "error": "No checkpoints exist for this directory"}
+# Valid git commit hash pattern: 4–40 hex chars (short or full SHA-1/SHA-256).
+_COMMIT_HASH_RE = re.compile(r'^[0-9a-fA-F]{4,64}$')
-def _empty_prune_result() -> Dict[str, int]:
- return dict.fromkeys(("scanned", "deleted_orphan", "deleted_stale", "errors", "bytes_freed"), 0)
-
+# ---------------------------------------------------------------------------
+# Input validation helpers
+# ---------------------------------------------------------------------------
def _validate_commit_hash(commit_hash: str) -> Optional[str]:
- """Error string if unsafe as a git revision (a leading '-' would parse as a flag), else None."""
+ """Validate a commit hash to prevent git argument injection.
+
+ Returns an error string if invalid, None if valid.
+ Values starting with '-' would be interpreted as git flags
+ (e.g., '--patch', '-p') instead of revision specifiers.
+ """
if not commit_hash or not commit_hash.strip():
return "Empty commit hash"
if commit_hash.startswith("-"):
@@@ -210,10 -113,13 +219,10 @@@ def _project_hash(working_dir: str) ->
def _store_path(base: Optional[Path] = None) -> Path:
+ """Return the single shared shadow store path."""
- return (base or CHECKPOINT_BASE) / _STORE_DIRNAME
+ return (base or _resolve_checkpoint_base()) / _STORE_DIRNAME
-def _store_has_head(store: Path) -> bool:
- return (store / "HEAD").exists()
-
-
def _index_path(store: Path, dir_hash: str) -> Path:
return store / _INDEXES_DIRNAME / dir_hash
@@@ -805,47 -600,20 +814,47 @@@ class CheckpointManager
digest = _hash_file(path)
if digest is None:
return
- with store_lock(CHECKPOINT_BASE):
- store, dir_hash = _store_path(), _project_hash(self.get_working_dir_for_path(str(path)))
- _save_ledger(store, dir_hash, {**_load_ledger(store, dir_hash), str(path): {"sha256": digest, "ts": time.time()}})
++ with store_lock(_resolve_checkpoint_base()):
+ working_dir = self.get_working_dir_for_path(str(path))
- store = _store_path(CHECKPOINT_BASE)
++ store = _store_path()
+ dir_hash = _project_hash(working_dir)
+ ledger = _load_ledger(store, dir_hash)
+ ledger[str(path)] = {"sha256": digest, "ts": time.time()}
+ _save_ledger(store, dir_hash, ledger)
except Exception as exc:
logger.debug("record_agent_write failed for %s: %s", file_path, exc)
- def safe_restore_plan(self, working_dir: str, commit_hash: str) -> Dict:
- """Classify files changed since ``commit_hash``: ``restore`` = still matching what Hermes
- last wrote (or deleted since); ``skipped`` = user-edited afterwards or never written by
- Hermes. ``ledger_empty`` => no ledger, callers fall back to a full restore."""
- p, err = _locate(working_dir, commit_hash)
- if err:
- return err
+ def _safe_restore_plan(self, working_dir: str, commit_hash: str) -> Dict:
+ """Classify files changed since ``commit_hash`` for a safe restore.
- (ok, names_out, err), = _diff_staged_tree(p, ["diff", "--name-only", "-z", commit_hash, "--cached"])
+ Returns ``{"success", "restore": [rel...], "skipped": [rel...],
+ "error"?}`` where ``restore`` lists files whose current content
+ still matches what Hermes last wrote (per the agent-write ledger)
+ and ``skipped`` lists files the user hand-edited after Hermes'
+ last write or that Hermes never wrote at all.
+ """
+ hash_err = _validate_commit_hash(commit_hash)
+ if hash_err:
+ return {"success": False, "error": hash_err}
+
+ abs_dir = str(_normalize_path(working_dir))
- store = _store_path(CHECKPOINT_BASE)
++ store = _store_path()
+ if not (store / "HEAD").exists():
+ return {"success": False, "error": "No checkpoints exist for this directory"}
+
+ dir_hash = _project_hash(abs_dir)
+ index_file = _index_path(store, dir_hash)
+
+ # Stage the current tree so the name-only diff sees new files too.
+ _run_git(["add", "-A"], store, abs_dir,
+ timeout=_GIT_TIMEOUT * 2, index_file=index_file)
+ ok, names_out, err = _run_git(
+ ["diff", "--name-only", "-z", commit_hash, "--cached"],
+ store, abs_dir, index_file=index_file,
+ )
+ # Reset the index back to the project ref so it doesn't drift.
+ _run_git(["read-tree", _ref_name(dir_hash)], store, abs_dir,
+ index_file=index_file, allowed_returncodes={128})
if not ok:
return {"success": False, "error": f"Could not compute changed files: {err}"}
@@@ -894,129 -639,64 +903,129 @@@
logger.debug("Checkpoints disabled: git not found")
if not self._git_available:
return False
+
abs_dir = str(_normalize_path(working_dir))
- if abs_dir in {"/", str(Path.home())}: # never snapshot root/home
+
+ # Skip root, home, and other overly broad directories
+ if abs_dir in {"/", str(Path.home())}:
logger.debug("Checkpoint skipped: directory too broad (%s)", abs_dir)
return False
+
if abs_dir in self._checkpointed_dirs:
return False
+
self._checkpointed_dirs.add(abs_dir)
+
try:
- return self._take(abs_dir, reason)
+ from tools.checkpoint_pruning import store_lock
+
- with store_lock(CHECKPOINT_BASE):
++ with store_lock(_resolve_checkpoint_base()):
+ return self._take(abs_dir, reason)
except Exception as e:
logger.debug("Checkpoint failed (non-fatal): %s", e)
return False
def list_checkpoints(self, working_dir: str) -> List[Dict]:
"""List available checkpoints for a directory (most recent first)."""
- p = _project_refs(working_dir)
- if not _store_has_head(p.store):
+ abs_dir = str(_normalize_path(working_dir))
- store = _store_path(CHECKPOINT_BASE)
++ store = _store_path()
+
+ if not (store / "HEAD").exists():
+ return []
+
+ ref = _ref_name(_project_hash(abs_dir))
+ ok, stdout, _ = _run_git(
+ ["log", ref, "--format=%H|%h|%aI|%s", "-n", str(self.max_snapshots)],
+ store, abs_dir,
+ allowed_returncodes={128, 129},
+ )
+
+ if not ok or not stdout:
return []
- log = _git_out(["log", p.ref, "--format=%H|%h|%aI|%s", "-n", str(self.max_snapshots)],
- p.store, p.abs_dir, {128, 129})
results: List[Dict] = []
- for line in log.splitlines():
+ for line in stdout.splitlines():
parts = line.split("|", 3)
- if len(parts) != 4:
- continue
- entry = {"hash": parts[0], "short_hash": parts[1], "timestamp": parts[2], "reason": parts[3],
- "files_changed": 0, "insertions": 0, "deletions": 0}
- stat_out = _git_out(["diff", "--shortstat", f"{parts[0]}~1", parts[0]], p.store, p.abs_dir, {128, 129})
- for key, pattern in _SHORTSTAT_FIELDS:
- m = re.search(pattern, stat_out)
- if m:
- entry[key] = int(m.group(1))
- results.append(entry)
+ if len(parts) == 4:
+ entry = {
+ "hash": parts[0],
+ "short_hash": parts[1],
+ "timestamp": parts[2],
+ "reason": parts[3],
+ "files_changed": 0,
+ "insertions": 0,
+ "deletions": 0,
+ }
+ stat_ok, stat_out, _ = _run_git(
+ ["diff", "--shortstat", f"{parts[0]}~1", parts[0]],
+ store, abs_dir,
+ allowed_returncodes={128, 129},
+ )
+ if stat_ok and stat_out:
+ self._parse_shortstat(stat_out, entry)
+ results.append(entry)
return results
def list_all_checkpoints(self) -> List[Dict]:
- """Checkpoints across every registered project (most recent first), each tagged ``workdir``.
+ """List checkpoints across every registered project (most recent first).
- Surgical reapply of PR #10633 by @nightq (#10505) onto the v2 single-store layout: iterate
- ``projects/<hash>.json`` metadata via ``_list_projects`` instead of the pre-v2 per-shadow-dir scan.
- Each entry carries the extra ``workdir`` key so callers can label which project a checkpoint belongs
- to.
+ Surgical reapply of PR #10633 by @nightq (#10505) onto the v2
+ single-store layout: iterate ``projects/<hash>.json`` metadata via
+ ``_list_projects`` instead of the pre-v2 per-shadow-dir scan. Each
+ entry carries the extra ``workdir`` key so callers can label which
+ project a checkpoint belongs to.
"""
- store = _store_path(CHECKPOINT_BASE)
+ store = _store_path()
- if not _store_has_head(store):
+ if not (store / "HEAD").exists():
return []
- results = [{**entry, "workdir": workdir}
- for workdir in (meta.get("workdir") or "" for meta in _list_projects(store)) if workdir
- for entry in self.list_checkpoints(workdir)]
- return sorted(results, key=lambda x: x.get("timestamp", ""), reverse=True)
+ results: List[Dict] = []
+ for meta in _list_projects(store):
+ workdir = meta.get("workdir") or ""
+ if not workdir:
+ continue
+ for entry in self.list_checkpoints(workdir):
+ entry["workdir"] = workdir
+ results.append(entry)
+ results.sort(key=lambda x: x.get("timestamp", ""), reverse=True)
+ return results
+
+ @staticmethod
+ def _parse_shortstat(stat_line: str, entry: Dict) -> None:
+ """Parse git --shortstat output into entry dict."""
+ m = re.search(r'(\d+) file', stat_line)
+ if m:
+ entry["files_changed"] = int(m.group(1))
+ m = re.search(r'(\d+) insertion', stat_line)
+ if m:
+ entry["insertions"] = int(m.group(1))
+ m = re.search(r'(\d+) deletion', stat_line)
+ if m:
+ entry["deletions"] = int(m.group(1))
def diff(self, working_dir: str, commit_hash: str) -> Dict:
"""Show diff between a checkpoint and the current working tree."""
- p, err = _locate(working_dir, commit_hash)
- if err:
- return err
- ok, _ = _commit_exists(p, commit_hash)
+ from tools.checkpoint_pruning import PruneError, store_lock
+
+ try:
- with store_lock(CHECKPOINT_BASE):
++ with store_lock(_resolve_checkpoint_base()):
+ return self._diff(working_dir, commit_hash)
+ except (PruneError, OSError) as exc:
+ return {"success": False, "error": str(exc)}
+
+ def _diff(self, working_dir: str, commit_hash: str) -> Dict:
+ hash_err = _validate_commit_hash(commit_hash)
+ if hash_err:
+ return {"success": False, "error": hash_err}
+
+ abs_dir = str(_normalize_path(working_dir))
- store = _store_path(CHECKPOINT_BASE)
++ store = _store_path()
+
+ if not (store / "HEAD").exists():
+ return {"success": False, "error": "No checkpoints exist for this directory"}
+
+ ok, _, err = _run_git(
+ ["cat-file", "-t", commit_hash], store, abs_dir,
+ )
if not ok:
return {"success": False, "error": f"Checkpoint '{commit_hash}' not found"}
@@@ -1084,214 -722,103 +1093,214 @@@
result["empty"] = True
return result
- def restore(self, working_dir: str, commit_hash: str, file_path: str = None,
- safe: bool = False) -> Dict:
- """Restore files to a checkpoint state. ``safe=True`` (full-directory only) leaves files
- the user hand-edited after Hermes' last write untouched (agent-write ledger); the result
- then gains ``skipped_user_edits``, ``skipped_oversize`` (size cap kept them out of every
- checkpoint) and, only when a delete failed, ``failed_deletes``."""
- p, err = _locate(working_dir, commit_hash, file_path)
- if err:
- return err
- abs_dir = p.abs_dir
- ok, err = _commit_exists(p, commit_hash)
+ def restore(
+ self,
+ working_dir: str,
+ commit_hash: str,
+ file_path: str = None,
+ safe: bool = False,
+ ) -> Dict:
+ """Restore files to a checkpoint state.
+
+ With ``safe=True`` (full-directory restores only), files the user
+ hand-edited after Hermes' last write — per the agent-write ledger —
+ are left untouched, and only Hermes-authored changes are reverted.
+ The result gains ``skipped_user_edits`` listing the preserved paths,
+ ``skipped_oversize`` listing paths kept because the size cap excluded
+ them from every checkpoint, and — only when a delete failed —
+ ``failed_deletes`` listing paths that could not be removed.
+ """
+ from tools.checkpoint_pruning import PruneError, store_lock
+
+ try:
- with store_lock(CHECKPOINT_BASE):
++ with store_lock(_resolve_checkpoint_base()):
+ return self._restore(working_dir, commit_hash, file_path, safe)
+ except (PruneError, OSError) as exc:
+ return {"success": False, "error": str(exc)}
+
+ def _restore(self, working_dir: str, commit_hash: str, file_path: str | None, safe: bool) -> Dict:
+ hash_err = _validate_commit_hash(commit_hash)
+ if hash_err:
+ return {"success": False, "error": hash_err}
+
+ abs_dir = str(_normalize_path(working_dir))
+
+ if file_path:
+ path_err = _validate_file_path(file_path, abs_dir)
+ if path_err:
+ return {"success": False, "error": path_err}
+
- store = _store_path(CHECKPOINT_BASE)
++ store = _store_path()
+
+ if not (store / "HEAD").exists():
+ return {"success": False, "error": "No checkpoints exist for this directory"}
+
+ ok, _, err = _run_git(
+ ["cat-file", "-t", commit_hash], store, abs_dir,
+ )
if not ok:
- return {"success": False, "error": f"Checkpoint '{commit_hash}' not found", "debug": err or None}
+ return {"success": False, "error": f"Checkpoint '{commit_hash}' not found",
+ "debug": err or None}
skipped_user_edits: List[str] = []
+ kept_oversize: List[str] = []
+ failed_deletes: List[str] = []
restore_paths: Optional[List[str]] = None
if safe and not file_path:
- plan = self.safe_restore_plan(abs_dir, commit_hash)
+ plan = self._safe_restore_plan(abs_dir, commit_hash)
if not plan.get("success"):
return {"success": False, "error": plan.get("error", "Safe-restore plan failed")}
- if not plan.get("ledger_empty"): # no agent-write history => classic full restore
- restore_paths, skipped_user_edits = plan["restore"], plan["skipped"]
+ if plan.get("ledger_empty"):
+ # No agent-write history to compare against — fall back to
+ # the classic full restore rather than restoring nothing.
+ restore_paths = None
+ else:
+ restore_paths = plan["restore"]
+ skipped_user_edits = plan["skipped"]
if not restore_paths:
- return _restore_ok(commit_hash, "nothing to restore (all changed files were user-edited)",
- abs_dir, restored_files=[], skipped_user_edits=skipped_user_edits,
- skipped_oversize=[])
+ return {
+ "success": True,
+ "restored_to": commit_hash[:8],
+ "reason": "nothing to restore (all changed files were user-edited)",
+ "directory": abs_dir,
+ "restored_files": [],
+ "skipped_user_edits": skipped_user_edits,
+ "skipped_oversize": [],
+ }
# Take a pre-rollback snapshot so you can undo the undo.
- self._take(abs_dir, f"pre-rollback snapshot (restoring to {commit_hash[:8]})")
+ self._take(abs_dir, f"pre-rollback snapshot (restoring to {commit_hash[:8]})", prune=False)
- targets = _SafeRestoreTargets(checkout=[file_path or "."])
- if restore_paths is not None:
- targets = self._apply_safe_restore_deletes(p, commit_hash, restore_paths)
- if targets.checkout:
- ok, _, err = _run_git(["checkout", commit_hash, "--", *targets.checkout], p.store, abs_dir,
- timeout=_GIT_TIMEOUT * 2, index_file=p.index_file)
- if not ok:
- return {"success": False, "error": f"Restore failed: {err}", "debug": err or None}
-
- reason_out = _git_out(["log", "--format=%s", "-1", commit_hash], p.store, abs_dir) or "unknown"
- result = _restore_ok(commit_hash, reason_out, abs_dir)
- if file_path:
- result["file"] = file_path
- if restore_paths is not None:
- # Report only what was actually acted on: a kept oversize path or a
- # failed unlink left the file in place and must not read as "Restored".
- not_restored = set(targets.kept_oversize) | set(targets.failed_deletes)
- result.update(restored_files=[rel for rel in restore_paths if rel not in not_restored],
- skipped_user_edits=skipped_user_edits, skipped_oversize=targets.kept_oversize)
- if targets.failed_deletes:
- result["failed_deletes"] = targets.failed_deletes
- return result
+ dir_hash = _project_hash(abs_dir)
+ index_file = _index_path(store, dir_hash)
- def _apply_safe_restore_deletes(self, p: _ProjectRefs, commit_hash: str,
- restore_paths: List[str]) -> _SafeRestoreTargets:
- """Split ledger-approved paths into checkout targets and delete the rest. A path absent
- from the checkpoint is Hermes-created (delete to restore) — unless ``max_file_size_mb`` kept
- it out of every checkpoint: no prior copy exists and the ledger can't prove it agent-created
- (hashes, not create-vs-modify), so leaving it costs a stale file, deleting costs the file."""
- targets = _SafeRestoreTargets()
- for rel in restore_paths:
- ok_in_commit, _, _ = _run_git(["cat-file", "-e", f"{commit_hash}:{rel}"],
- p.store, p.abs_dir, allowed_returncodes={1, 128})
- target = Path(p.abs_dir) / rel
- if ok_in_commit:
- targets.checkout.append(rel)
- elif self._exceeds_size_cap(target):
- targets.kept_oversize.append(rel)
- else:
+ if restore_paths is not None:
+ # Split into files present in the checkpoint (checkout) and
+ # Hermes-created files absent from it (delete to restore state).
+ checkout_targets: List[str] = []
+ delete_targets: List[str] = []
+ for rel in restore_paths:
+ ok_in_commit, _, _ = _run_git(
+ ["cat-file", "-e", f"{commit_hash}:{rel}"],
+ store, abs_dir, allowed_returncodes={1, 128},
+ )
+ if ok_in_commit:
+ checkout_targets.append(rel)
+ elif self._exceeds_size_cap(Path(abs_dir) / rel):
+ # Absent from the checkpoint because ``max_file_size_mb``
+ # kept it out (_drop_oversize_from_index), not because
+ # Hermes created it. Deleting it would not restore a prior
+ # state — no checkpoint holds one — it would destroy the
+ # only copy. The ledger records a content hash, not whether
+ # a write created or modified the file, so an oversize path
+ # cannot be proven agent-created; leaving it costs a stale
+ # file, deleting it costs the file.
+ kept_oversize.append(rel)
+ else:
+ delete_targets.append(rel)
+ for rel in delete_targets:
try:
+ target = Path(abs_dir) / rel
if target.is_file() or target.is_symlink():
target.unlink()
except OSError as exc:
- logger.warning("Safe restore: could not remove %s: %s", rel, exc)
- targets.failed_deletes.append(rel)
- return targets
+ logger.warning(
+ "Safe restore: could not remove %s: %s", rel, exc,
+ )
+ failed_deletes.append(rel)
+ if not checkout_targets:
+ ok, stdout, err = True, "", ""
+ else:
+ ok, stdout, err = _run_git(
+ ["checkout", commit_hash, "--", *checkout_targets],
+ store, abs_dir, timeout=_GIT_TIMEOUT * 2,
+ index_file=index_file,
+ )
+ else:
+ ok, stdout, err = _run_git(
+ ["checkout", commit_hash, "--", file_path if file_path else "."],
+ store, abs_dir, timeout=_GIT_TIMEOUT * 2,
+ index_file=index_file,
+ )
+
+ if not ok:
+ return {"success": False, "error": f"Restore failed: {err}",
+ "debug": err or None}
+
+ ok2, reason_out, _ = _run_git(
+ ["log", "--format=%s", "-1", commit_hash], store, abs_dir,
+ )
+ reason = reason_out if ok2 else "unknown"
+
+ result = {
+ "success": True,
+ "restored_to": commit_hash[:8],
+ "reason": reason,
+ "directory": abs_dir,
+ }
+ if file_path:
+ result["file"] = file_path
+ if restore_paths is not None:
+ # Only what was actually acted on. A kept oversize path was not
+ # restored (and a failed unlink left the file in place), and
+ # reporting either as restored is how the data loss above stayed
+ # silent: the user was told "Restored" for a file that had just
+ # been unlinked.
+ not_restored = set(kept_oversize) | set(failed_deletes)
+ result["restored_files"] = [
+ rel for rel in restore_paths if rel not in not_restored
+ ]
+ result["skipped_user_edits"] = skipped_user_edits
+ result["skipped_oversize"] = kept_oversize
+ if failed_deletes:
+ result["failed_deletes"] = failed_deletes
+ # The selected tree was needed until checkout completed. Only now may
+ # the safety snapshot's count/size budget make that tree unreachable.
+ self._prune(store, abs_dir, _ref_name(dir_hash))
+ return result
def get_working_dir_for_path(self, file_path: str) -> str:
- """Resolve a file path to its working directory (nearest project-marker ancestor)."""
+ """Resolve a file path to its working directory for checkpointing."""
path = _normalize_path(file_path)
- candidate = path if path.is_dir() else path.parent
+ if path.is_dir():
+ candidate = path
+ else:
+ candidate = path.parent
+
+ # An explicitly checkpointed root owns its ledger even when an
+ # ancestor carries a project marker. Prefer the nearest owner.
+ roots = [Path(meta["workdir"]) for meta in _list_projects(_store_path()) if meta.get("workdir")]
+ owners = [root for root in roots if candidate.is_relative_to(root)]
+ if owners:
+ return str(max(owners, key=lambda root: len(root.parts)))
+ markers = {".git", "pyproject.toml", "package.json", "Cargo.toml",
+ "go.mod", "Makefile", "pom.xml", ".hg", "Gemfile"}
+ home = Path.home().resolve()
+ broad = {home, *home.parents}
check = candidate
- while check != check.parent:
- if any((check / m).exists() for m in _PROJECT_MARKERS):
+ while check != check.parent and check not in broad:
+ if any((check / m).exists() for m in markers):
return str(check)
check = check.parent
+
return str(candidate)
- # --- internal ---
+ # ------------------------------------------------------------------
+ # Internal
+ # ------------------------------------------------------------------
- def _take(self, working_dir: str, reason: str) -> bool:
+ def _take(self, working_dir: str, reason: str, *, prune: bool = True) -> bool:
"""Take a snapshot. Returns True on success."""
- store = _store_path(CHECKPOINT_BASE)
- p = _project_refs(working_dir)
- err = _init_store(p.store, working_dir)
++ store = _store_path()
+
+ err = _init_store(store, working_dir)
if err:
- return _step_failed("store init", err)
- _touch_project(p.store, working_dir)
+ logger.debug("Checkpoint store init failed: %s", err)
+ return False
+
+ _touch_project(store, working_dir)
+
+ # Quick size guard — don't try to snapshot enormous directories
if _dir_file_count(working_dir) > _MAX_FILES:
logger.debug("Checkpoint skipped: >%d files in %s", _MAX_FILES, working_dir)
return False
@@@ -1609,189 -977,72 +1618,189 @@@ def _workdir_is_observably_gone
if parent_dev is not None and parent_ino is not None:
st = parent.stat()
if (st.st_dev, st.st_ino) != (parent_dev, parent_ino):
+ # A different directory is visible at the parent's path than
+ # the one the project lived in — the volume is detached (its
+ # underlay showing through) or was swapped. Not a deletion.
return False
elif require_parent_identity:
+ # No recorded identity to check against — we cannot tell the
+ # project's real parent from an underlay directory exposed by an
+ # unmount. Unsure never deletes; retention still reclaims.
return False
- with os.scandir(parent) as entries:
- return next(entries, None) is not None or os.path.ismount(parent)
+ if _dir_has_any_entry(parent):
+ return True
+ # Empty parent: only evidence if that directory is a mount point, i.e.
+ # the volume is attached right now and simply does not hold the
+ # project. An empty plain directory is an unmounted mount point as
+ # readily as an emptied project root.
+ return os.path.ismount(parent)
except OSError:
- return False # probe failed (permission, I/O error) — not evidence of deletion
+ # Probe failed (permission, I/O error) — not evidence of deletion.
+ return False
+
+def _dir_has_any_entry(directory: Path) -> bool:
+ """True when ``directory`` contains at least one entry.
-def _int_or_none(value) -> Optional[int]:
- return value if isinstance(value, int) and not isinstance(value, bool) else None
+ Stops after the first entry rather than materializing the listing; a
+ project root can hold a large tree.
+ """
+ with os.scandir(directory) as entries:
+ for _ in entries:
+ return True
+ return False
-def _sweep(entries, result: Dict[str, int], delete) -> None:
- """Shared orphan/stale sweep. ``entries`` yields ``(item, gone, allowed, is_stale)`` where
- ``is_stale`` is a thunk (may do I/O, so only evaluated for non-orphans); "orphan" wins."""
- for item, gone, allowed, is_stale in entries:
- result["scanned"] += 1
- reason = "orphan" if gone and allowed else "stale" if is_stale() else None
- if reason is not None:
- delete(item, reason)
+def prune_checkpoints(
+ retention_days: int = 7,
+ delete_orphans: bool = True,
+ checkpoint_base: Optional[Path] = None,
+ max_total_size_mb: int = 0,
+ orphan_allowlist: Optional[set] = None,
+) -> Dict[str, int]:
+ """Delete stale/orphan checkpoints and reclaim store space.
+ A project entry is deleted when either:
+
+ * ``delete_orphans=True`` and its ``workdir`` no longer exists on disk
+ (the original project was deleted / moved); OR
+ * its ``last_touch`` is older than ``retention_days`` days.
+
+ ``orphan_allowlist``, when not ``None``, restricts orphan deletion to
+ the given identities (v2 project ``_hash`` strings and/or pre-v2 shadow
+ repo paths as ``str``). This lets a caller that showed the user a
+ confirmation preview (built from ``store_status()``) bind the resulting
+ deletion to exactly what was displayed — a project that only becomes
+ orphaned *after* the preview (e.g. its workdir vanishes while the human
+ is answering the prompt) is skipped rather than swept up under the
+ earlier confirmation. Pass ``None`` (the default) to delete every
+ currently-orphaned project, e.g. for ``--force`` or unattended callers
+ that never show a preview.
+
+ Additionally, if ``max_total_size_mb > 0`` and the store exceeds that
+ after orphan/stale pruning, the oldest commit per remaining project is
+ dropped until the store is under the cap.
+
+ Legacy-archive dirs (``legacy-*``) older than ``retention_days`` are
+ also deleted.
+
+ Returns a dict with counts ``{"scanned", "deleted_orphan",
+ "deleted_stale", "errors", "bytes_freed"}``.
+
+ Never raises — maintenance must never block interactive startup.
+ """
- base = checkpoint_base or CHECKPOINT_BASE
++ base = checkpoint_base or _resolve_checkpoint_base()
+ result = {
+ "scanned": 0,
+ "deleted_orphan": 0,
+ "deleted_stale": 0,
+ "errors": 0,
+ "bytes_freed": 0,
+ }
+ if not base.exists():
+ return result
+
+ from tools.checkpoint_pruning import PruneError, store_lock
-def _rmtree_counted(child: Path, result: Dict[str, int], key: str, fail_fmt: str, label) -> None:
- """rmtree ``child``, crediting bytes + ``result[key]``; failures count as ``errors`` when tracked."""
try:
- size = _dir_size_bytes(child)
- shutil.rmtree(child)
- result["bytes_freed"] += size
- result[key] += 1
- except OSError as exc:
- if "errors" in result:
- result["errors"] += 1
- logger.warning(fail_fmt, label, exc)
-
-
-def _prune_legacy_archives(base: Path, cutoff: float, result: Dict[str, int]) -> None:
- """Delete ``legacy-*`` archives whose mtime predates ``cutoff`` (skipped when retention is off)."""
- for child in _legacy_archives(base) if cutoff > 0 else ():
- mtime = _mtime_or_none(child)
- if mtime is not None and mtime < cutoff:
- _rmtree_counted(child, result, "deleted_stale", "Failed to delete legacy archive %s: %s", child)
-
-
-def _prune_pre_v2_repos(base: Path, cutoff: float, delete_orphans: bool,
- orphan_allowlist: Optional[set], result: Dict[str, int]) -> None:
- """Sweep pre-v2 per-project shadow repos exactly as the v1 pruner did (scan shared with
- ``store_status``; the frozen layout has no recorded parent identity, so orphan detection
- uses the structural checks only)."""
- def entries():
- for repo in _pre_v2_shadow_repos(base):
- child = repo["path"]
- gone = delete_orphans and not repo["marker_unreadable"] and (
- repo["workdir"] is None
- or _workdir_is_observably_gone(repo["workdir"], require_parent_identity=False))
- yield (child, gone, orphan_allowlist is None or str(child) in orphan_allowlist,
- lambda c=child: cutoff > 0 and 0 < _newest_mtime(c) < cutoff)
+ with store_lock(base):
+ return _prune_checkpoints(base, result, retention_days, delete_orphans, max_total_size_mb, orphan_allowlist)
+ except (PruneError, OSError) as exc:
+ result["errors"] += 1
+ logger.warning("Checkpoint maintenance stopped: %s", exc)
+ return result
+
+
+def _prune_checkpoints(
+ base: Path, result: Dict[str, int], retention_days: int, delete_orphans: bool,
+ max_total_size_mb: int, orphan_allowlist: Optional[set],
+) -> Dict[str, int]:
+ size_before = _dir_size_bytes(base)
- _sweep(entries(), result, lambda child, reason: _rmtree_counted(
- child, result, f"deleted_{reason}", "Failed to prune checkpoint repo %s: %s", child.name))
+ # --- Legacy pre-v2 per-project shadow repos (kept directly under base) ---
+ # Pre-v2 layout: ``base/<hash>/HEAD`` etc. We treat these exactly as the
+ # v1 pruner did so behaviour is unchanged for anyone still on that layout
+ # or sitting on a mid-migration system.
+ cutoff = 0.0
+ if retention_days > 0:
+ cutoff = time.time() - retention_days * 86400
+ for child in base.iterdir():
+ if not child.is_dir():
+ continue
+ if child.name == _STORE_DIRNAME:
+ continue
+ if child.name.startswith(_LEGACY_PREFIX):
+ # Legacy archive: prune by dir mtime using same retention rule.
+ if retention_days <= 0:
+ continue
+ try:
+ m = child.stat().st_mtime
+ except OSError:
+ continue
+ if m >= cutoff:
+ continue
+ try:
+ size = _dir_size_bytes(child)
+ shutil.rmtree(child)
+ result["bytes_freed"] += size
+ result["deleted_stale"] += 1
+ except OSError as exc:
+ result["errors"] += 1
+ logger.warning("Failed to delete legacy archive %s: %s", child, exc)
+
+ # Pre-v2 per-project shadow repos. Scanned via the same helper
+ # `store_status()` uses for its orphan preview, so a confirmation prompt
+ # built from that preview always matches what gets deleted here.
+ for repo in _pre_v2_shadow_repos(base):
+ child = repo["path"]
+ result["scanned"] += 1
+ reason: Optional[str] = None
+ if (
+ delete_orphans
+ and not repo["marker_unreadable"]
+ and (
+ repo["workdir"] is None
+ # The frozen pre-v2 layout has no metadata channel to carry a
+ # recorded parent identity, so only the structural checks
+ # (parent present + populated / live mount point) apply here.
+ or _workdir_is_observably_gone(
+ repo["workdir"], require_parent_identity=False,
+ )
+ )
+ and (orphan_allowlist is None or str(child) in orphan_allowlist)
+ ):
+ reason = "orphan"
+ if reason is None and retention_days > 0:
+ newest = 0.0
+ try:
+ for p in child.rglob("*"):
+ try:
+ mt = p.stat().st_mtime
+ newest = max(newest, mt)
+ except OSError:
+ continue
+ except OSError:
+ pass
+ if newest > 0 and newest < cutoff:
+ reason = "stale"
+ if reason is None:
+ continue
+ try:
+ size = _dir_size_bytes(child)
+ shutil.rmtree(child)
+ result["bytes_freed"] += size
+ if reason == "orphan":
+ result["deleted_orphan"] += 1
+ else:
+ result["deleted_stale"] += 1
+ except OSError as exc:
+ result["errors"] += 1
+ logger.warning("Failed to prune checkpoint repo %s: %s", child.name, exc)
-def _prune_v2_projects(store: Path, cutoff: float, delete_orphans: bool,
- orphan_allowlist: Optional[set], result: Dict[str, int]) -> None:
- """Drop the ref, index and metadata of orphan/stale projects in the shared store."""
- def entries():
+ # --- v2 shared store: per-project ref pruning via metadata ---
+ store = _store_path(base)
+ if (store / "HEAD").exists():
for meta in _list_projects(store):
dir_hash = meta.get("_hash") or ""
workdir = meta.get("workdir") or ""
@@@ -1865,51 -1091,27 +1874,51 @@@
return result
-def maybe_auto_prune_checkpoints(retention_days: int = 7, min_interval_hours: int = 24, delete_orphans: bool = True,
- checkpoint_base: Optional[Path] = None, max_total_size_mb: int = 0) -> Dict[str, object]:
- """Idempotent wrapper around ``prune_checkpoints`` for startup hooks: writes
- ``CHECKPOINT_BASE/.last_prune`` so calls within ``min_interval_hours`` short-circuit.
- Returns ``{"skipped": bool, "result": prune dict, "error": optional str}``."""
+def maybe_auto_prune_checkpoints(
+ retention_days: int = 7,
+ min_interval_hours: int = 24,
+ delete_orphans: bool = True,
+ checkpoint_base: Optional[Path] = None,
+ max_total_size_mb: int = 0,
+) -> Dict[str, object]:
+ """Idempotent wrapper around ``prune_checkpoints`` for startup hooks.
+
+ Writes ``CHECKPOINT_BASE/.last_prune`` on completion so subsequent
+ calls within ``min_interval_hours`` short-circuit.
+
+ Returns ``{"skipped": bool, "result": prune_checkpoints-dict,
+ "error": optional str}``.
+ """
- base = checkpoint_base or CHECKPOINT_BASE
+ base = checkpoint_base or _resolve_checkpoint_base()
out: Dict[str, object] = {"skipped": False}
+
try:
if not base.exists():
- out["result"] = _empty_prune_result()
+ out["result"] = {
+ "scanned": 0, "deleted_orphan": 0, "deleted_stale": 0,
+ "errors": 0, "bytes_freed": 0,
+ }
return out
+
marker = base / _PRUNE_MARKER_NAME
now = time.time()
- try:
- if marker.exists() and now - float(marker.read_text(encoding="utf-8").strip()) < min_interval_hours * 3600:
- out["skipped"] = True
- return out
- except (OSError, ValueError):
- pass # corrupt marker — treat as no prior run
- result = out["result"] = prune_checkpoints(retention_days=retention_days, delete_orphans=delete_orphans,
- checkpoint_base=base, max_total_size_mb=max_total_size_mb)
+ if marker.exists():
+ try:
+ last_ts = float(marker.read_text(encoding="utf-8-sig").strip())
+ if now - last_ts < min_interval_hours * 3600:
+ out["skipped"] = True
+ return out
+ except (OSError, ValueError):
+ pass # corrupt marker — treat as no prior run
+
+ result = prune_checkpoints(
+ retention_days=retention_days,
+ delete_orphans=delete_orphans,
+ checkpoint_base=base,
+ max_total_size_mb=max_total_size_mb,
+ )
+ out["result"] = result
+
try:
marker.write_text(str(now), encoding="utf-8")
except OSError as exc:
@@@ -1932,35 -1128,15 +1941,35 @@@
return out
+# ---------------------------------------------------------------------------
+# Public helpers for `hermes checkpoints` CLI
+# ---------------------------------------------------------------------------
+
def store_status(checkpoint_base: Optional[Path] = None) -> Dict:
- """Summarise the shadow store: ``{"base", "store_size_bytes", "legacy_size_bytes",
- "total_size_bytes", "project_count", "projects", "pre_v2_projects", "legacy_archives"}``.
- ``pre_v2_projects`` are repos still on the pre-v2 layout, distinct from the migrated
- ``legacy_archives``; an orphan-deletion preview must include both ``projects`` and
- ``pre_v2_projects`` since ``prune_checkpoints`` sweeps both."""
+ """Return a summary of the shadow store.
+
+ ``{"base": path, "store_size_bytes": N, "legacy_size_bytes": N,
+ "total_size_bytes": N, "project_count": N, "projects": [...],
+ "pre_v2_projects": [...], "legacy_archives": [...]}``
+
+ ``pre_v2_projects`` covers shadow repos still on the pre-v2 per-project
+ layout (``base/<hash>/HEAD``) — distinct from ``legacy_archives``, which
+ are already-migrated ``legacy-<ts>/`` dirs. Callers that preview an
+ orphan-deletion sweep must include both ``projects`` and
+ ``pre_v2_projects``, since ``prune_checkpoints`` deletes orphans from
+ both layouts.
+ """
- base = checkpoint_base or CHECKPOINT_BASE
+ base = checkpoint_base or _resolve_checkpoint_base()
- out: Dict = {"base": str(base), "store_size_bytes": 0, "legacy_size_bytes": 0, "total_size_bytes": 0,
- "project_count": 0, "projects": [], "pre_v2_projects": [], "legacy_archives": []}
+ out: Dict = {
+ "base": str(base),
+ "store_size_bytes": 0,
+ "legacy_size_bytes": 0,
+ "total_size_bytes": 0,
+ "project_count": 0,
+ "projects": [],
+ "pre_v2_projects": [],
+ "legacy_archives": [],
+ }
if not base.exists():
return out
@@@ -2020,18 -1161,10 +2029,18 @@@
return out
+def _rmtree_force(path: Path) -> None:
+ from hermes_cli.fs_utils import rmtree_force
+
+ rmtree_force(path)
+
+
def clear_all(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
"""Nuke the entire checkpoint base (store + legacy). Irreversible.
- Returns ``{"bytes_freed": N, "deleted": bool}``."""
+
+ Returns ``{"bytes_freed": N, "deleted": bool}``.
+ """
- base = checkpoint_base or CHECKPOINT_BASE
+ base = checkpoint_base or _resolve_checkpoint_base()
out = {"bytes_freed": 0, "deleted": False}
if not base.exists():
return out
@@@ -2049,11 -1178,8 +2058,11 @@@
def clear_legacy(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
- """Delete all ``legacy-*`` archive directories. Returns ``{"bytes_freed": N, "deleted": count}``."""
+ """Delete all ``legacy-*`` archive directories.
+
+ Returns ``{"bytes_freed": N, "deleted": count}``.
+ """
- base = checkpoint_base or CHECKPOINT_BASE
+ base = checkpoint_base or _resolve_checkpoint_base()
out = {"bytes_freed": 0, "deleted": 0}
if not base.exists():
return out
diff --cc tools/environments/local.py
index 2157254ed02,b9ffb48aa5e..3e82f00d38c
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@@ -368,19 -337,80 +368,42 @@@ def build_subprocess_env
return delegated_child_subprocess_env(env)
+ def strip_launch_profile_env(env: dict, target_home: "str | Path | None" = None) -> dict:
+ """Drop the LAUNCH profile's residue from a child env built for another served profile.
+ ``os.environ`` holds the default profile's ``.env`` and its bridged ``TERMINAL_*`` settings;
+ the secret scrub removes credentials but not settings (``HERMES_MODEL``, ``TERMINAL_ENV``,
+ ``HERMES_LANGUAGE``...), so a standalone ``hermes -p X`` worker and a served one saw different
+ envs. The child re-loads X's own ``.env`` and bridges X's config itself. ``target_home``
+ defaults to the active home override; no-op outside multiplex or when the target IS the
+ launch profile."""
+ from agent.secret_scope import _is_global_env, is_multiplex_active, load_env_file
+ from hermes_constants import get_hermes_home_override, get_process_hermes_home
+ target = target_home or get_hermes_home_override()
+ if not is_multiplex_active() or not target:
+ return env
+ launch_home = get_process_hermes_home()
+ if Path(target).resolve() == launch_home.resolve():
+ return env
+ from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP
+ for key in set(load_env_file(launch_home / ".env")) | set(TERMINAL_CONFIG_ENV_MAP.values()):
+ if not _is_global_env(key) or key.startswith("TERMINAL_"):
+ env.pop(key, None)
+ return env
+
+
-# --- Shell discovery ---
-def _windows_bash_candidates(custom: "str | None") -> list[str]:
- """Ordered bash.exe candidates on Windows: HERMES_GIT_BASH_PATH, our portable Git
- under %LOCALAPPDATA%\\hermes\\git (PortableGit ``bin`` and MinGit ``usr\\bin``),
- known Git-for-Windows dirs, then PATH last — ``shutil.which`` may return WSL's
- bash, which fails silently on Windows paths."""
- getenv = os.environ.get
- lad = getenv("LOCALAPPDATA", "")
- roots = [
- lad and os.path.join(lad, "hermes", "git", "bin"),
- lad and os.path.join(lad, "hermes", "git", "usr", "bin"),
- os.path.join(getenv("ProgramFiles", r"C:\Program Files"), "Git", "bin"),
- os.path.join(getenv("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Git", "bin"),
- lad and os.path.join(lad, "Programs", "Git", "bin"),
- ]
- raw = [custom or "", *(os.path.join(r, "bash.exe") for r in roots if r)]
- candidates = list(dict.fromkeys(c for c in raw if c and os.path.isfile(c)))
- found = shutil.which("bash")
- if found and found not in candidates:
- candidates.append(found)
- return candidates
-
-
def _find_bash() -> str:
- """Find bash for command execution."""
- if not _IS_WINDOWS:
- return (shutil.which("bash")
- or next((p for p in ("/usr/bin/bash", "/bin/bash") if os.path.isfile(p)), None)
- or os.environ.get("SHELL") or "/bin/sh")
- custom = os.environ.get("HERMES_GIT_BASH_PATH")
- candidates = _windows_bash_candidates(custom)
- # First candidate that can actually start wins: a stale HERMES_GIT_BASH_PATH
- # pointing at a broken install must not beat a healthy portable Git.
- for candidate in candidates:
- if _bash_starts(candidate):
- if candidate != custom and custom and os.path.isfile(custom):
- logger.warning(
- "HERMES_GIT_BASH_PATH=%s fails to start; using %s instead", custom, candidate)
- return candidate
- if candidates:
- probe_details = "\n".join(
- detail for c in candidates if (detail := _bash_probe_details_cache.get(c)))
- if _mandatory_aslr_enabled() is True or _looks_like_msys_spawn_failure(probe_details):
- raise RuntimeError(_git_bash_aslr_help(candidates[0], probe_details))
- # Unknown failure class: return the first path so the caller sees the
- # real bash error instead of a less useful "not found".
- return candidates[0]
+ """Resolve the shell Hermes runs commands with. Owned by pm (the store
+ is the authority on bundled bash); this is a thin wrapper over
+ pm.shell() for callers that need a bash binary."""
+ import pm.shell
+
+ bash = pm.shell.bash()
+ if bash:
+ return bash
raise RuntimeError(
- "Git Bash not found. Hermes Agent requires Git for Windows on Windows.\n"
- "Install it from: https://git-scm.com/download/win\n"
- "Or set HERMES_GIT_BASH_PATH to your bash.exe location.")
+ "No shell found. Hermes needs bash (Git for Windows on Windows). "
+ "Run `hermes pm install` or reinstall the bundle."
+ )
_git_bash_bin_dirs_cache: "list[str] | None" = None
diff --cc tools/process_registry_checkpoint.py
index 4fe4e288b0f,a12dfe749c7..04a140b1e29
--- a/tools/process_registry_checkpoint.py
+++ b/tools/process_registry_checkpoint.py
@@@ -51,10 -51,11 +51,11 @@@ class ProcessCheckpointMixin
_CHECKPOINT_DEFAULTS, _WATCHER_ROUTE_KEYS, _stop_systemd_unit,
)
- if not CHECKPOINT_PATH.exists():
+ checkpoint_path = _checkpoint_path()
+ if not checkpoint_path.exists():
return 0
try:
- entries = json.loads(CHECKPOINT_PATH.read_text(encoding="utf-8-sig"))
- entries = json.loads(checkpoint_path.read_text(encoding="utf-8"))
++ entries = json.loads(checkpoint_path.read_text(encoding="utf-8-sig"))
except Exception:
return 0
recovered = 0
diff --cc tui_gateway/methods_tools.py
index cf1d30669d2,f067041883d..44fb5b14972
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@@ -450,14 -444,13 +445,13 @@@ def _(rid, params: dict) -> dict
on_result=lambda r: _ok(rid, {
"blocked": False, "code": r.returncode, "output": (_joined_output(r) or "(no output)")[:48_000]}),
timeout_err=(5016, "cli.exec: timeout"), fail_code=5017,
- env=hermes_subprocess_env(inherit_credentials=True))
+ env=_compat.restore_ambient_pythonpath(hermes_subprocess_env(inherit_credentials=True)))
- @_scoped_rpc("command.resolve", 5012)
+ @_rpc("command.resolve", 5012)
def _(rid, params: dict) -> dict:
- commands = _tools_mod("hermes_cli.commands")
- r = commands.resolve_command(params.get("name", ""))
- if r and commands.command_available(r):
+ r = _tools_mod("hermes_cli.commands").resolve_command(params.get("name", ""))
+ if r:
return _ok(rid, {"canonical": r.name, "description": r.description, "category": r.category})
return _err(rid, 4011, f"unknown command: {params.get('name')}")