The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
merge: connector UI e2e v2 into bundled onboarding (rebuilt)
ethernetcc01ae9d44a0
diff --cc apps/desktop/electron/main.tsindex 069c62caeec,986e556b63b..ea8858f49c4--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -212,10 -207,9 +212,10 @@@ importwriteBufferToFile} 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,17 @@@ import} from './managed-ssh-update'import { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc'import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'+import {+ oauthGuardMayHardFail,+ oauthSessionIsLive,+ oauthTicketFailureAuthMessage,+ resolveGatedDownloadAuth,+ resolveJsonBody,+ resolveOauthRestAuth,+ resolveReadinessProbeAuth+} from './native-auth-decisions'+ import { fetchLocalMedia } from './media-range'+ import { createNativeAccessTokenCoordinator, NativeAuthChangedError } from './native-access-token'-import { oauthSessionIsLive, resolveJsonBody, resolveReadinessProbeAuth } from './native-auth-decisions'import {nativeRefreshUrl,type NativeTokenSet,@@@ -814,8 -908,10 +816,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()+// One launch decision must reach both the renderer and every backend spawn.+const GUEST_ONBOARDING: boolean = guestOnboardingEnabled()+ const SKIP_INTRO = skipIntroEnabled()const BOOT_FAKE_STEP_MS = (() => {const raw = Number.parseInt(String(process.env.HERMES_DESKTOP_BOOT_FAKE_STEP_MS || ''), 10)@@@ -1268,14 -1367,11 +1271,11 @@@ protocol.registerSchemesAsPrivileged(function registerMediaProtocol() {const handler = createMediaProtocolHandler({- ensureRemoteBearer: baseUrl => ensureNativeAccessToken(baseUrl),+ ensureRemoteBearer: baseUrl => ensureNativeAccessToken(baseUrl).catch(() => null),- fetchLocal: (resolvedPath, headers, method) =>- electronNet.fetch(pathToFileURL(resolvedPath).toString(), {- bypassCustomProtocolHandlers: true,- credentials: 'omit',- headers,- method- }),+ // 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]).+ fetchLocal: fetchLocalMedia,fetchRemote: (url, headers, method) =>electronNet.fetch(url, {bypassCustomProtocolHandlers: true,@@@ -16791,20 -17151,16 +16791,21 @@@ ipcMain.on('hermes:translucency:supportevent.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/src/app/settings/local-models-settings.tsxindex 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 ?? nullconst 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.tsindex f2f7b750d75,84192c2450b..ccdad4dd70a--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@@ -336,10 -349,16 +336,13 @@@ declare globalglassSupported?: 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?: booleansetTranslucency?: (payload: TranslucencyState) => voidsetKeepAwake?: (on: boolean) => voidsetDisableF12?: (blocked: boolean) => voiddiff --cc apps/desktop/src/i18n/en.tsindex 978121062a2,b63c79aeb9a..de6a7f01660--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@@ -32,12 -26,12 +32,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 -1312,15 +1289,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',diff --cc apps/desktop/src/i18n/ja.tsindex 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.tsindex 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.tsindex 7ac4d7b0219,b2e1eefb3e0..0e0e0456717--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@@ -32,12 -26,12 +32,11 @@@ export const zh: Translations =ownerMissing: '请重新打开此对话以管理连接。',search: '查找应用',empty: '没有匹配的应用',- continue: '在对话中继续',- continueBusy: '等待当前操作完成',- continueFailed: '无法继续,请重试。',disclaimer: '连接为可选操作。请仅授权你希望 Hermes 使用的应用。',+ connectTitle: app => `连接 ${app}?`,+ describe: app => `Hermes 会在浏览器中登录 ${app},读取任何内容前都会先询问。`,execution: '连接器工具'},-sessionImport: {title: '从其他应用继续',subtitle: '将对话导入 Hermes,接着上次的进度继续。',@@@ -1479,15 -1500,15 +1478,18 @@@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: '使用',diff --cc gateway/hooks.pyindex 027dcf90236,58efd7e6b0b..38b3750b05a--- a/gateway/hooks.py+++ b/gateway/hooks.py@@@ -15,9 -16,10 +16,10 @@@ import threadinfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional-import yaml+import hermes_yaml as yamlfrom hermes_cli.config import get_hermes_home+ from hermes_constants import hermes_home_keyHOOKS_DIR = get_hermes_home() / "hooks"diff --cc gateway/sticker_cache.pyindex bdf7f4b7449,fee46acb69f..57af88dacd2--- a/gateway/sticker_cache.py+++ b/gateway/sticker_cache.py@@@ -21,13 -30,10 +30,13 @@@ 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():+ try:- return json.loads(CACHE_PATH.read_text(encoding="utf-8-sig"))++ return json.loads(_resolve_cache_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.pyindex 74aa6cf3c14,d8ba7e8639b..aa877094ce9--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@@ -6102,9 -6043,11 +6117,11 @@@ def _cmd_install(args)managed_error("install gateway service")returnforce = 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.pyindex 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.pyindex 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 installgateway_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.pyindex 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 POSTsynchronously 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 plugins/memory/hindsight/__init__.pyindex 4b61ed9cf63,381b43c657a..d150f410def--- a/plugins/memory/hindsight/__init__.py+++ b/plugins/memory/hindsight/__init__.py@@@ -34,10 -34,10 +34,11 @@@ from tools.registry import tool_errofrom .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_daemonfrom .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,32 @@@ class HindsightMemoryProvider(MemoryProself._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.++ # Fail-closed on key material: when this process holds no key (no secret++ # scope on this thread) but the file does, a rewrite would destroy the++ # only key copy the daemon subprocess can read. Skip the write AND the++ # restart: bringing the daemon back up now would boot it keyless, which++ # is the exact outage this guards against. The client kwargs above++ # already carry whatever key WAS available.+ changed = _load_simple_env(_embedded_profile_env_path(cfg)) != _build_embedded_profile_env(cfg)++ if changed and not _may_rewrite_profile_env(cfg):++ logger.warning(++ "Hindsight profile env for %r holds an LLM API key this process cannot see "++ "(no secret scope); leaving the file untouched so the daemon keeps its key.",++ profile)++ changed = False+ if changed:+ _materialize_embedded_profile_env(cfg)+ 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.pyindex 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 ResolvedCommentRuleclass _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_mtimeexcept 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() -> setdef _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-readdef _mutate_pairing(user_open_id: str, add: bool) -> bool:diff --cc scripts/release.pyindex 419d71678fc,5a07abf88a5..c3877a9fd41--- a/scripts/release.py+++ b/scripts/release.py@@@ -2369,46 -2219,71 +2369,100 @@@ 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 [+ 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")++ 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")++ 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")+++ 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()]+def resolve_author(name: str, email: str) -> str:"""Resolve a git author to a GitHub @mention."""diff --cc tests/test_packaging_build_guard.pyindex 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.pyindex 1e0cfd73e8c,bfd52a1036a..47bfa8b1518--- a/tests/test_profile_isolation_runtime.py+++ b/tests/test_profile_isolation_runtime.py@@@ -109,9 -108,96 +109,96 @@@ class TestRichSentStorePathResolutionb_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.pyindex 8cccda656bf,9afb4948a74..97692761a23--- a/tests/tools/test_env_passthrough.py+++ b/tests/tools/test_env_passthrough.py@@@ -44,9 -44,9 +44,9 @@@ class TestConfigPassthroughdef 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/checkpoint_manager.pyindex eb76d268190,6df3db1c721..af813285fe7--- a/tools/checkpoint_manager.py+++ b/tools/checkpoint_manager.py@@@ -66,107 -30,59 +66,116 @@@ from utils import env_inlogger = 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 = 2000DEFAULT_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 CheckpointManagerdigest = _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 Falsedef 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 resultsdef 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)- if not (store / "HEAD").exists():+ store = _store_path()+ if not _store_has_head(store):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"] = Truereturn 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]] = Noneif 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) / relif 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 resultdef 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 directoriesif _dir_file_count(working_dir) > _MAX_FILES:logger.debug("Checkpoint skipped: >%d files in %s", _MAX_FILES, working_dir)return False@@@ -1609,307 -977,141 +1618,332 @@@ def _workdir_is_observably_goneif 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 Falseelif 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 _int_or_none(value) -> Optional[int]:- return value if isinstance(value, int) and not isinstance(value, bool) else None+def _dir_has_any_entry(directory: Path) -> bool:+ """True when ``directory`` contains at least one entry.+ 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+- _sweep(entries(), result, lambda child, reason: _rmtree_counted(- child, result, f"deleted_{reason}", "Failed to prune checkpoint repo %s: %s", child.name))+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)+ # --- 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-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():+ 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)++ # --- 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 ""if not dir_hash:continue- gone = delete_orphans and (not workdir or _workdir_is_observably_gone(- workdir, parent_dev=_int_or_none(meta.get("workdir_parent_dev")),- parent_ino=_int_or_none(meta.get("workdir_parent_ino"))))- yield (dir_hash, gone, orphan_allowlist is None or dir_hash in orphan_allowlist,- lambda m=meta: cutoff > 0 and 0 < float(m.get("last_touch", 0) or 0) < cutoff)+ result["scanned"] += 1+ reason = None+ parent_dev = meta.get("workdir_parent_dev")+ parent_ino = meta.get("workdir_parent_ino")+ if not isinstance(parent_dev, int) or isinstance(parent_dev, bool):+ parent_dev = None+ if not isinstance(parent_ino, int) or isinstance(parent_ino, bool):+ parent_ino = None+ if (+ delete_orphans+ and (+ not workdir+ or _workdir_is_observably_gone(+ workdir,+ parent_dev=parent_dev,+ parent_ino=parent_ino,+ )+ )+ and (orphan_allowlist is None or dir_hash in orphan_allowlist)+ ):+ reason = "orphan"+ elif retention_days > 0:+ last_touch = float(meta.get("last_touch", 0) or 0)+ if last_touch > 0 and last_touch < cutoff:+ reason = "stale"+ if reason is None:+ continue+ ref = _ref_name(dir_hash)+ if not _delete_ref(store, ref):+ result["errors"] += 1+ return result+ # Drop per-project index and metadata.+ try:+ idx = _index_path(store, dir_hash)+ if idx.exists():+ idx.unlink()+ except OSError:+ pass+ try:+ mp = _project_meta_path(store, dir_hash)+ if mp.exists():+ mp.unlink()+ except OSError:+ pass+ if reason == "orphan":+ result["deleted_orphan"] += 1+ else:+ result["deleted_stale"] += 1- def delete(dir_hash: str, reason: str) -> None:- _delete_ref(store, _ref_name(dir_hash))- _unlink_quiet(_index_path(store, dir_hash))- _unlink_quiet(_project_meta_path(store, dir_hash))- result[f"deleted_{reason}"] += 1+ from tools.checkpoint_pruning import Pruner, PruneError- _sweep(entries(), result, delete)+ pruner = Pruner(_run_git, store, str(base), _GIT_TIMEOUT, _dir_size_bytes, _REFS_PREFIX)+ try:+ pruner.reclaim()+ if not pruner.enforce_size(max_total_size_mb * 1024 * 1024):+ result["errors"] += 1+ logger.warning("Checkpoint store remains over its size cap; minimum history retained")+ except (PruneError, OSError) as exc:+ result["errors"] += 1+ logger.warning("Checkpoint pruning stopped: %s", exc)+ size_after = _dir_size_bytes(base)+ delta = size_before - size_after+ result["bytes_freed"] = max(result["bytes_freed"], delta)+ 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. Never raises. Deleted when+ ``delete_orphans`` and the workdir is observably gone, OR last touch predates ``retention_days``+ (``<= 0`` disables). ``orphan_allowlist`` (v2 ``_hash`` strings and/or pre-v2 repo paths as+ ``str``) binds orphan deletion to exactly what a ``store_status()`` preview showed — a project+ orphaned after the preview is skipped; ``None`` deletes every current orphan (``--force``,+ unattended). ``max_total_size_mb > 0`` drops the oldest commit per project until the store fits."""+ base = checkpoint_base or _resolve_checkpoint_base()+ result = _empty_prune_result()+ if not base.exists():+ return result+ size_before = _dir_size_bytes(base)+ cutoff = time.time() - retention_days * 86400 if retention_days > 0 else 0.0+ _prune_legacy_archives(base, cutoff, result)+ _prune_pre_v2_repos(base, cutoff, delete_orphans, orphan_allowlist, result)+ store = _store_path(base)+ if _store_has_head(store):+ _prune_v2_projects(store, cutoff, delete_orphans, orphan_allowlist, result)+ _gc_store(store, str(base))+ if max_total_size_mb > 0:+ _shrink_store_to_cap(store, str(base), max_total_size_mb * _MB)+ _gc_store(store, str(base))++ result["bytes_freed"] = max(result["bytes_freed"], size_before - _dir_size_bytes(base))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_NAMEnow = 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 +1966,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 +2054,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 +2083,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 outdiff --cc tools/process_registry_checkpoint.pyindex 4fe4e288b0f,74c9f22fffb..3cdf1f129a4--- 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 0try:- 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 0recovered = 0diff --cc tui_gateway/methods_tools.pyindex 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) -> dicton_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')}")