The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(paths): suffix default agent and desktop data directories
ethernet06ef8ce78605
diff --git a/apps/desktop/electron/data-paths.test.ts b/apps/desktop/electron/data-paths.test.tsnew file mode 100644index 00000000000..6aee08bb557--- /dev/null+++ b/apps/desktop/electron/data-paths.test.ts@@ -0,0 +1,78 @@+import assert from 'node:assert/strict'+import os from 'node:os'+import path from 'node:path'++import { afterEach, test, vi } from 'vitest'++import { platformDefaultHermesHome, resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths'+import { controlSocketPath } from './ssh-connection'++afterEach((): void => {+ vi.unstubAllEnvs()+})++test.skipIf(process.platform === 'win32')('local SSH sockets use the suffixed default root', (): void => {+ vi.stubEnv('HERMES_DATA_DIR_SUFFIX', 'magic-test')+ const socket: string = controlSocketPath('user', 'host', 22)++ assert.equal(path.dirname(socket), path.join(platformDefaultHermesHome(os.homedir()), 'desktop-ssh'))+})++test('default data roots append the suffix literally on each platform', (): void => {+ for (const platform of ['linux', 'darwin', 'win32'] as const) {+ const paths: typeof path = platform === 'win32' ? path.win32 : path.posix+ const home: string = platform === 'win32' ? 'C:\\Users\\test' : '/home/test'+ const local: string = paths.join(home, 'AppData', 'Local')+ const userData: string = paths.join(home, 'app-data', 'Hermes')+ const base: string = platform === 'win32' ? paths.join(local, 'hermes') : paths.join(home, '.hermes')++ for (const suffix of ['', '-asdfasdf', 'magic-test', ' spaced ']) {+ const env: NodeJS.ProcessEnv = { LOCALAPPDATA: local, HERMES_DATA_DIR_SUFFIX: suffix }++ assert.equal(platformDefaultHermesHome(home, env, platform), base + suffix)+ assert.equal(resolveDesktopUserData(userData, env), userData + suffix)+ assert.equal(+ resolveDesktopHermesHome({ home, env, platform, directoryExists: (): boolean => false }),+ base + suffix+ )+ }+ }+})++test('explicit homes and userData retain precedence, and suffixed Windows homes never use legacy state', (): void => {+ const home: string = '/home/test'++ const env: NodeJS.ProcessEnv = {+ HERMES_DATA_DIR_SUFFIX: 'magic-test',+ HERMES_HOME: '/explicit/home',+ HERMES_DESKTOP_USER_DATA_DIR: '/explicit/electron'+ }++ assert.equal(resolveDesktopUserData('/default/electron', env), path.resolve(env.HERMES_DESKTOP_USER_DATA_DIR!))+ assert.equal(resolveDesktopHermesHome({ home, env, platform: 'linux' }), env.HERMES_HOME)+ delete env.HERMES_HOME+ assert.equal(resolveDesktopHermesHome({ home, env, platform: 'linux' }), '/explicit/electron/hermes-home')++ const windowsHome: string = 'C:\\Users\\test'+ const windowsEnv: NodeJS.ProcessEnv = { HERMES_DATA_DIR_SUFFIX: 'magic-test' }+ const expected: string = path.win32.join(windowsHome, 'AppData', 'Local', 'hermesmagic-test')++ assert.equal(+ resolveDesktopHermesHome({+ home: windowsHome,+ env: windowsEnv,+ platform: 'win32',+ directoryExists: (): boolean => true+ }),+ expected+ )+ assert.equal(+ resolveDesktopHermesHome({+ home: windowsHome,+ env: windowsEnv,+ platform: 'win32',+ readWindowsHome: (): string => 'C:\\custom'+ }),+ 'C:\\custom'+ )+})diff --git a/apps/desktop/electron/data-paths.ts b/apps/desktop/electron/data-paths.tsnew file mode 100644index 00000000000..7b897770b24--- /dev/null+++ b/apps/desktop/electron/data-paths.ts@@ -0,0 +1,74 @@+import path from 'node:path'++import { normalizeHermesHomeRoot } from './backend-env'++export function platformDefaultHermesHome(+ home: string,+ env: NodeJS.ProcessEnv = process.env,+ platform: NodeJS.Platform = process.platform+): string {+ const suffix: string = env.HERMES_DATA_DIR_SUFFIX || ''++ if (platform === 'win32') {+ const base: string = env.LOCALAPPDATA?.trim() || path.win32.join(home, 'AppData', 'Local')++ return path.win32.join(base, 'hermes') + suffix+ }++ return path.posix.join(home, '.hermes') + suffix+}++export function resolveDesktopUserData(defaultPath: string, env: NodeJS.ProcessEnv = process.env): string {+ return env.HERMES_DESKTOP_USER_DATA_DIR+ ? path.resolve(env.HERMES_DESKTOP_USER_DATA_DIR)+ : defaultPath + (env.HERMES_DATA_DIR_SUFFIX || '')+}++interface HermesHomeOptions {+ home: string+ env?: NodeJS.ProcessEnv+ platform?: NodeJS.Platform+ directoryExists?: (directory: string) => boolean+ readWindowsHome?: () => string | null+}++export function resolveDesktopHermesHome({+ home,+ env = process.env,+ platform = process.platform,+ directoryExists = (): boolean => false,+ readWindowsHome = (): null => null+}: HermesHomeOptions): string {+ const paths: typeof path = platform === 'win32' ? path.win32 : path.posix++ if (env.HERMES_HOME) {+ return normalizeHermesHomeRoot(env.HERMES_HOME, { pathModule: paths })+ }++ // Fresh-install rehearsals must not touch the real Hermes home.+ if (env.HERMES_DESKTOP_USER_DATA_DIR) {+ return paths.join(paths.resolve(env.HERMES_DESKTOP_USER_DATA_DIR), 'hermes-home')+ }++ if (platform === 'win32') {+ // Explorer can retain an old environment after the user runs setx.+ const registryHome: string | null = readWindowsHome()++ if (registryHome) {+ return normalizeHermesHomeRoot(registryHome, { pathModule: paths })+ }+ }++ const defaultHome: string = platformDefaultHermesHome(home, env, platform)++ // Keep the legacy migration for ordinary installs, not isolated suffix runs.+ if (platform === 'win32' && !env.HERMES_DATA_DIR_SUFFIX) {+ const legacy: string = paths.join(home, '.hermes')++ if (!directoryExists(defaultHome) && directoryExists(legacy)) {+ return legacy+ }+ }++ return defaultHome+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex f3a3bb8e7c8..eeeb01e97be 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -51,7 +51,7 @@ import {import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command'import { createBackendConnectionState } from './backend-connection-state'import { BackendDialClaims } from './backend-dial-claim'-import { buildDesktopBackendEnv, normalizeHermesHomeRoot } from './backend-env'+import { buildDesktopBackendEnv } from './backend-env'import {isReauthRequiredError,makeNousCloudBackendDownError,@@ -162,6 +162,7 @@ import {import type { RosterProfileMetadata } from './connection-registry'import { describeCrashReason, installCrashForensics } from './crash-forensics'import { adoptServedDashboardToken } from './dashboard-token'+import { resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths'import { loadOrCreateInstallationId, sshOwnershipId } from './desktop-installation'import { formatDesktopLogLine } from './desktop-log-line'import { resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route'@@ -478,10 +479,10 @@ import { isPackagedInstallPath as isPackagedInstallPathUnderRoots } from './workimport { readWslWindowsClipboardImage } from './wsl-clipboard-image'import { resolvePickerDefaultPath, setActiveGatewayProfile, setWslBridgeProfileState } from './wsl-path-bridge'-const USER_DATA_OVERRIDE = process.env.HERMES_DESKTOP_USER_DATA_DIR+const USER_DATA_OVERRIDE: string | undefined = process.env.HERMES_DESKTOP_USER_DATA_DIR-if (USER_DATA_OVERRIDE) {- const resolvedUserData = path.resolve(USER_DATA_OVERRIDE)+if (USER_DATA_OVERRIDE || process.env.HERMES_DATA_DIR_SUFFIX) {+ const resolvedUserData: string = resolveDesktopUserData(app.getPath('userData'))fs.mkdirSync(resolvedUserData, { recursive: true })app.setPath('userData', resolvedUserData)}@@ -718,61 +719,11 @@ if (INSTALL_STAMP) {)}-// HERMES_HOME — the user-facing root for everything Hermes-related. Mirrors-// scripts/install.ps1's $HermesHome and scripts/install.sh's $HERMES_HOME.-//-// Defaults:-// Windows: %LOCALAPPDATA%\hermes (matches install.ps1)-// macOS / Linux: ~/.hermes (matches install.sh)-//-// Special case for Windows: if the user has a legacy ~/.hermes directory-// (e.g., from a prior pip install or a manual setup) AND no-// %LOCALAPPDATA%\hermes yet, prefer the legacy path so we don't orphan their-// existing config / sessions / .env. New installs go to %LOCALAPPDATA%.-//-// HERMES_DESKTOP_USER_DATA_DIR (used by test:desktop:fresh) puts the sandbox-// HERMES_HOME beneath the throwaway userData dir so a fresh-install run never-// touches the user's real ~/.hermes / %LOCALAPPDATA%\hermes.-function resolveHermesHome() {- if (process.env.HERMES_HOME) {- return normalizeHermesHomeRoot(process.env.HERMES_HOME)- }-- if (USER_DATA_OVERRIDE) {- return path.join(path.resolve(USER_DATA_OVERRIDE), 'hermes-home')- }-- if (IS_WINDOWS) {- // A GUI app launched from Explorer inherits the environment block captured- // at login, so a HERMES_HOME set via `setx` AFTER login is invisible in- // process.env even though the CLI (a fresh shell) sees it. Without this the- // backend silently falls back to %LOCALAPPDATA%\hermes and reports "No- // inference provider configured" despite a valid configured home (#45471).- // Consult the live User-scoped registry value before the default below.- const fromRegistry = readWindowsUserEnvVar('HERMES_HOME')-- if (fromRegistry) {- return normalizeHermesHomeRoot(fromRegistry)- }- }-- if (IS_WINDOWS && process.env.LOCALAPPDATA) {- const localappdata = path.join(process.env.LOCALAPPDATA, 'hermes')- const legacy = path.join(app.getPath('home'), '.hermes')-- // Migrate transparently to LOCALAPPDATA, but honour an existing legacy- // ~/.hermes setup (no LOCALAPPDATA install yet) so users don't lose state.- if (!directoryExists(localappdata) && directoryExists(legacy)) {- return legacy- }-- return localappdata- }-- return path.join(app.getPath('home'), '.hermes')-}--const HERMES_HOME = resolveHermesHome()+const HERMES_HOME: string = resolveDesktopHermesHome({+ home: app.getPath('home'),+ directoryExists,+ readWindowsHome: (): string | null => readWindowsUserEnvVar('HERMES_HOME')+})// The spawned `hermes update` / updater children compose managed-tool env// (node, git, uv) in-process via pm. Electron only prepends the explicitdiff --git a/apps/desktop/electron/ssh-connection.ts b/apps/desktop/electron/ssh-connection.tsindex 9a11a193789..6436be9aa2c 100644--- a/apps/desktop/electron/ssh-connection.ts+++ b/apps/desktop/electron/ssh-connection.ts@@ -36,6 +36,8 @@ import net from 'node:net'import os from 'node:os'import path from 'node:path'+import { platformDefaultHermesHome } from './data-paths'+const DEFAULT_CONNECT_TIMEOUT_MS = 15_000const DEFAULT_EXEC_TIMEOUT_MS = 20_000const DEFAULT_FORWARD_TIMEOUT_MS = 15_000@@ -189,14 +191,14 @@ function controlSocketPath(user, host, port, baseDir?, identity: any = {}) {return path.join(dir, `${id}.sock`)}-function defaultControlDir() {+function defaultControlDir(): string {// POSIX: a SHORT, PER-USER base stays under the socket limit AND avoids a// world-shared /tmp dir (no symlink-hijack surface). Created 0700 in open().if (process.platform === 'win32') {return path.join(os.tmpdir(), 'hermes-desktop-ssh')}- return path.join(os.homedir(), '.hermes', 'desktop-ssh')+ return path.join(platformDefaultHermesHome(os.homedir()), 'desktop-ssh')}// Command construction (pure — the unit tests exercise these directly)diff --git a/hermes_cli/dashboard_procs.py b/hermes_cli/dashboard_procs.pyindex 38a5a99291e..7a4ff2edec9 100644--- a/hermes_cli/dashboard_procs.py+++ b/hermes_cli/dashboard_procs.py@@ -524,9 +524,10 @@ _HEX32 = set("0123456789abcdef")def _hermes_home_dir() -> Path:- """Resolved Hermes home (HERMES_HOME override or ~/.hermes)."""- override = os.environ.get("HERMES_HOME", "").strip()- return Path(override).expanduser() if override else Path.home() / ".hermes"+ """Process home for backend ownership records, independent of request scope."""+ from hermes_constants import get_process_hermes_home++ return get_process_hermes_home().expanduser()def _is_hex(value: object, length: int) -> bool:diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.pyindex a3d4e86ef3b..be0d2af46a6 100644--- a/hermes_cli/env_loader.py+++ b/hermes_cli/env_loader.py@@ -332,7 +332,9 @@ def load_hermes_dotenv() -> list[Path]:"""Load Hermes env files: ``~/.hermes/.env`` overrides stale shell exports; project ``.env`` is a devfallback that only fills gaps when the user env exists (and overrides shell vars when it does not)."""- home_path = Path(hermes_home or os.getenv("HERMES_HOME", Path.home() / ".hermes"))+ from hermes_constants import get_process_hermes_home++ home_path = Path(hermes_home) if hermes_home else get_process_hermes_home()# Multiplex gateway: while a routed profile-home override is active, copying that profile's .env# into os.environ would expose its credentials to sibling turns and every spawned child. Unscopeddiff --git a/hermes_constants.py b/hermes_constants.pyindex c63b124f6ec..d5eb5a47846 100644--- a/hermes_constants.py+++ b/hermes_constants.py@@ -43,12 +43,13 @@ def get_hermes_home_override() -> str | None:def _get_platform_default_hermes_home() -> Path:- """Return the platform-native default Hermes home path."""+ """Return the platform default with the literal data-directory suffix."""+ suffix = os.environ.get("HERMES_DATA_DIR_SUFFIX", "")if sys.platform == "win32":local_appdata = os.environ.get("LOCALAPPDATA", "").strip()base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"- return base / "hermes"- return Path.home() / ".hermes"+ return base / ("hermes" + suffix)+ return Path.home() / (".hermes" + suffix)def _warn_profile_fallback_once() -> None:diff --git a/hermes_startup_watchdog.py b/hermes_startup_watchdog.pyindex 3bfb34ebd52..660b8366d3a 100644--- a/hermes_startup_watchdog.py+++ b/hermes_startup_watchdog.py@@ -99,15 +99,10 @@ _handle: Optional["StartupWatchdogHandle"] = Nonedef _process_hermes_home() -> Path:- """HERMES_HOME for diagnostic files — stdlib-only replica of the hermes_constants default."""- val = os.environ.get("HERMES_HOME", "").strip()- if val:- return Path(val)- if sys.platform == "win32":- local_appdata = os.environ.get("LOCALAPPDATA", "").strip()- base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"- return base / "hermes"- return Path.home() / ".hermes"+ """Use the stdlib-only process resolver before application startup."""+ from hermes_constants import get_process_hermes_home++ return get_process_hermes_home()def get_startup_watchdog_dump_path(home: Optional[Path] = None) -> Path:diff --git a/tests/test_data_dir_suffix.py b/tests/test_data_dir_suffix.pynew file mode 100644index 00000000000..4f75f94f132--- /dev/null+++ b/tests/test_data_dir_suffix.py@@ -0,0 +1,94 @@+"""Default-root isolation through the real Python resolution chain."""++import json+import os+from pathlib import Path+import subprocess+import sys++import pytest++[email protected]("linux", "macos", "windows")[email protected]("suffix", ["", "-asdfasdf", "magic-test", " spaced "])+def test_suffix_scopes_default_home_and_profiles(tmp_path, suffix):+ env = dict(os.environ)+ env.pop("HERMES_HOME", None)+ env.update(+ HOME=str(tmp_path), USERPROFILE=str(tmp_path),+ LOCALAPPDATA=str(tmp_path / "AppData" / "Local"),+ HERMES_DATA_DIR_SUFFIX=suffix,+ )+ script = """+import json+import os+from pathlib import Path+from hermes_constants import get_hermes_home, get_process_hermes_home, get_default_hermes_root+from hermes_cli.profiles import _get_profiles_root, _get_active_profile_path, resolve_profile_env+root = get_default_hermes_root()+profile = root / 'profiles' / 'coder'+profile.mkdir(parents=True)+result = [str(get_hermes_home()), str(get_process_hermes_home()), str(root),+ str(_get_profiles_root()), str(_get_active_profile_path()), resolve_profile_env('coder')]+os.environ['HERMES_HOME'] = str(profile)+result.extend([str(get_hermes_home()), str(get_default_hermes_root())])+os.environ.pop('HERMES_HOME')+os.environ['HERMES_DATA_DIR_SUFFIX'] += '-changed'+result.append(str(get_default_hermes_root()))+print(json.dumps(result))+"""+ result = subprocess.run(+ [sys.executable, "-c", script], env=env,+ cwd=Path(__file__).resolve().parents[1],+ text=True, capture_output=True, check=True,+ )+ base = tmp_path / "AppData" / "Local" / "hermes" if sys.platform == "win32" else tmp_path / ".hermes"+ root = Path(str(base) + suffix)+ profile = root / "profiles" / "coder"+ assert json.loads(result.stdout) == list(map(str, [+ root, root, root, root / "profiles", root / "active_profile", profile,+ profile, root, Path(str(root) + "-changed"),+ ]))++[email protected]("linux", "macos", "windows")+def test_startup_readers_use_the_suffixed_home(tmp_path, monkeypatch):+ from hermes_constants import get_process_hermes_home+ from hermes_cli.dashboard_procs import _hermes_home_dir+ from hermes_cli.env_loader import load_hermes_dotenv+ from hermes_startup_watchdog import get_startup_watchdog_dump_path++ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "AppData" / "Local"))+ monkeypatch.delenv("HERMES_HOME", raising=False)+ monkeypatch.setenv("HERMES_DATA_DIR_SUFFIX", "magic-test")+ monkeypatch.delenv("SUFFIX_TEST_CREDENTIAL", raising=False)+ home = get_process_hermes_home()+ home.mkdir(parents=True)+ (home / ".env").write_text("SUFFIX_TEST_CREDENTIAL=suffixed\n", encoding="utf-8")++ load_hermes_dotenv(project_env=tmp_path / "absent.env", load_external_secrets=False)+ assert os.environ.get("SUFFIX_TEST_CREDENTIAL") == "suffixed"+ assert _hermes_home_dir() == home+ assert get_startup_watchdog_dump_path() == home / "logs" / "gateway-startup-watchdog.log"+++def test_suffix_does_not_change_explicit_or_context_home(tmp_path, monkeypatch):+ from hermes_constants import (+ get_default_hermes_root, get_hermes_home, get_process_hermes_home,+ reset_hermes_home_override, set_hermes_home_override,+ )++ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "AppData" / "Local"))+ explicit = tmp_path / "explicit"+ scoped = tmp_path / "scoped"+ monkeypatch.setenv("HERMES_HOME", str(explicit))+ monkeypatch.setenv("HERMES_DATA_DIR_SUFFIX", "magic-test")+ assert get_hermes_home() == get_process_hermes_home() == get_default_hermes_root() == explicit+ token = set_hermes_home_override(scoped)+ try:+ assert get_hermes_home() == scoped+ assert get_process_hermes_home() == get_default_hermes_root() == explicit+ finally:+ reset_hermes_home_override(token)diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.mdindex d20a9f22e97..104d782b008 100644--- a/website/docs/reference/environment-variables.md+++ b/website/docs/reference/environment-variables.md@@ -124,6 +124,7 @@ Hermes reads environment variables from the process environment and, for user-ma| `HERMES_LOCAL_STT_COMMAND` | Optional local speech-to-text command template. Supports `{input_path}`, `{output_dir}`, `{language}`, and `{model}` placeholders || `HERMES_LOCAL_STT_LANGUAGE` | Default language hint for STT. Used by the `local` (faster-whisper) provider, `HERMES_LOCAL_STT_COMMAND`, the local `whisper` CLI fallback (default: `en`), Groq, and xAI when no per-provider `language` is set in `config.yaml` || `HERMES_HOME` | Select the configuration and user-data home. Defaults to `~/.hermes` on POSIX and `%LOCALAPPDATA%\hermes` on Windows; the official Docker image uses `/opt/data`. Profile/runtime context can select a more specific home. |+| `HERMES_DATA_DIR_SUFFIX` | Append this value literally to the default Hermes home and default Electron `userData` directory. For example, `-asdfasdf` selects `~/.hermes-asdfasdf`, while `magic-test` selects `~/.hermesmagic-test` on POSIX. No separator is added. Named profiles and shared root data stay under the suffixed home. Explicit `HERMES_HOME` and `HERMES_DESKTOP_USER_DATA_DIR` keep their existing precedence and are not suffixed. Set this in the launch environment, before startup, not in `.env` or `config.yaml` inside the home being selected. An unset or empty value keeps the ordinary defaults. || `HERMES_DISABLE_WINDOWS_UTF8` | **Windows only.** Set to `1` to disable the UTF-8 stdio shim (`configure_windows_stdio()`) and fall back to the console's locale code page. Useful for bisecting encoding bugs; rarely the right setting in normal operation || `HERMES_KANBAN_HOME` | Override the shared Hermes root that anchors the kanban board (db + workspaces + worker logs). Falls back to `get_default_hermes_root()` (the parent of any active profile). Useful for tests and unusual deployments || `HERMES_KANBAN_BOARD` | Pin the active kanban board for this process. Takes precedence over `~/.hermes/kanban/current`; the dispatcher injects this into worker subprocess env so workers physically cannot see tasks on other boards. Defaults to `default`. Slug validation: lowercase alphanumerics + hyphens + underscores, 1-64 chars |