Skip to content

The agent that grows with you

feat: Hermes-owned scratch dir replaces the system temp dir for every process and child

teknium12dcebe6471b9
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py
index 82c6300f73d..982da2f8e2f 100644
--- a/agent/prompt_builder.py
+++ b/agent/prompt_builder.py
@@ -16,7 +16,7 @@ from pathlib import Path
from typing import Any, Dict, Optional
from hermes_constants import (
- get_hermes_home, get_skills_dir, is_wsl, reset_hermes_home_override, set_hermes_home_override,
+ get_hermes_home, get_scratch_dir, get_skills_dir, is_wsl, reset_hermes_home_override, set_hermes_home_override,
)
from agent.model_metadata import CHARS_PER_TOKEN
@@ -997,6 +997,13 @@ def _local_host_hints() -> list[str]:
host_lines.append(f"Current working directory: {resolve_agent_cwd()}")
except OSError:
pass
+ # The model reaches for the system temp dir by reflex (tmpfs on most Linux hosts, fills RAM);
+ # naming Hermes' scratch dir here is what makes the TMPDIR export a habit rather than a hidden default.
+ try:
+ host_lines.append(f"Scratch directory: {get_scratch_dir()} (TMPDIR points here; write temporary files "
+ "and probes there, never under the system temp dir; entries are pruned after 72h)")
+ except OSError:
+ pass
if not (sys.platform == "win32" and not is_wsl()):
return ["\n".join(host_lines)]
host_lines.append(
diff --git a/hermes_bootstrap.py b/hermes_bootstrap.py
index 313e08a6ac7..e36a662ba1a 100644
--- a/hermes_bootstrap.py
+++ b/hermes_bootstrap.py
@@ -319,8 +319,24 @@ def activate_durable_lazy_target() -> None:
pass # a failed activation just leaves the backend reporting itself unavailable
+def export_scratch_tmp_env() -> None:
+ """Point ``TMPDIR``/``TMP``/``TEMP`` at ``HERMES_HOME/cache/scratch`` unless the user set them.
+
+ System temp is tmpfs on most Linux hosts and containers; Hermes' browser profiles, PTY
+ probes and every ``tempfile`` default a child script makes would eat RAM there. Runs at
+ import so every entry point and every child they spawn inherits it; ``hermes_cli.main``
+ re-runs it after ``--profile`` re-homes the process. Never raises.
+ """
+ try:
+ from hermes_constants import export_scratch_tmp_env as _export
+ _export()
+ except Exception:
+ pass # a missing/unwritable home just leaves the system temp dir in place
+
+
# Apply on import — entry points only need ``import hermes_bootstrap`` first.
apply_windows_utf8_bootstrap()
suppress_platform_ver_console()
activate_durable_lazy_target()
install_happy_eyeballs_socket_connect()
+export_scratch_tmp_env()
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index d577d97e167..eef40064f36 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -3,6 +3,7 @@ Split out of ``hermes_cli/doctor.py``, which re-exports every name so ``hermes_c
from __future__ import annotations
+import os
import subprocess
from pathlib import Path
from hermes_cli.doctor_report import (
@@ -118,6 +119,7 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:
for subdir_name in ["cron", "sessions", "logs", "skills"] + (["memories"] if memory_on else []):
ensure_dir(f, should_fix, hermes_home / subdir_name, f"{_DHH}/{subdir_name}/ exists",
f"Created {_DHH}/{subdir_name}/", f"{_DHH}/{subdir_name}/ not found")
+ _check_scratch_dir(hermes_home, _DHH)
# SOUL.md persona file
soul_path = hermes_home / "SOUL.md"
if soul_path.exists():
@@ -149,6 +151,18 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:
check_info(f"{fname} not created yet (will be created when the agent first writes a memory)")
+def _check_scratch_dir(hermes_home: Path, _DHH: str) -> None:
+ """Report the scratch dir (TMPDIR target) and its size; a user-set TMPDIR elsewhere is shown, not judged."""
+ from hermes_constants import (
+ SCRATCH_DIR_MARKER_ENV, SCRATCH_MAX_AGE_HOURS, get_scratch_dir, scratch_dir_usage_bytes)
+ scratch = get_scratch_dir(hermes_home, prune=False)
+ size = _human_bytes(scratch_dir_usage_bytes(scratch))
+ check_ok(f"{_DHH}/cache/scratch/ is the scratch dir (TMPDIR; {size}, pruned after {SCRATCH_MAX_AGE_HOURS}h)")
+ tmpdir = os.environ.get("TMPDIR", "")
+ if tmpdir and tmpdir != os.environ.get(SCRATCH_DIR_MARKER_ENV, ""):
+ check_info(f"TMPDIR={tmpdir} is set by you or the OS, so Hermes leaves it alone")
+
+
def _session_count(state_db_path: Path):
import sqlite3
# mode=ro: doctor is a reader; a writable open of a gateway-held WAL DB is the second-writer class (#103339).
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 1abdabc92fe..564ae1b782b 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -626,6 +626,14 @@ def _apply_profile_override() -> None:
_apply_profile_override()
+# ``-p``/active_profile re-homed the process after hermes_bootstrap ran: re-point the temp vars
+# at THIS home's scratch dir (a user-set TMPDIR is still left alone).
+try:
+ from hermes_constants import export_scratch_tmp_env as _export_scratch_tmp_env
+
+ _export_scratch_tmp_env()
+except Exception:
+ pass # an unwritable home leaves the system temp dir in place; never block startup
# Windows launcher self-heal — the ``hermes`` command is a COPY of the venv
# console script staged into the managed bin dir (outside the checkout, since
diff --git a/hermes_constants.py b/hermes_constants.py
index d0536b6f927..0fc075adb65 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -9,6 +9,7 @@ import re
import shutil
import stat
import sys
+from collections.abc import MutableMapping
from contextvars import ContextVar, Token
from pathlib import Path
@@ -953,14 +954,136 @@ def get_subprocess_home(env: dict[str, str] | None = None) -> str | None:
return None
-def apply_subprocess_home_env(env: dict[str, str]) -> None:
- """Apply Hermes' subprocess HOME contract to *env* in-place."""
+def apply_subprocess_home_env(env: MutableMapping[str, str]) -> None:
+ """Apply Hermes' subprocess HOME contract to *env* in-place: ``HOME``/``HERMES_REAL_HOME``
+ per the home mode, and the temp vars re-pointed at ``env["HERMES_HOME"]``'s scratch dir."""
real_home = get_real_home(env)
if real_home:
env["HERMES_REAL_HOME"] = real_home
home = get_subprocess_home(env)
if home:
env["HOME"] = home
+ apply_scratch_tmp_env(env)
+
+
+# --- Scratch dir: Hermes' own temp space, never the system /tmp ---
+# System temp is tmpfs on most Linux distros and containers, so browser profiles, PTY probes,
+# download spools and every ``tempfile.mkdtemp()`` a Hermes-launched script performs eat RAM
+# and vanish on reboot. ``HERMES_HOME/cache/scratch`` is real storage with a fixed retention.
+SCRATCH_TMP_ENV_VARS = ("TMPDIR", "TMP", "TEMP")
+SCRATCH_DIR_MARKER_ENV = "HERMES_SCRATCH_DIR"
+SCRATCH_MAX_AGE_HOURS = 72
+_SCRATCH_PRUNE_STAMP = ".last_prune"
+_SCRATCH_PRUNE_INTERVAL_SECONDS = 3600
+_scratch_pruned_once = False
+
+
+def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Path:
+ """``<home>/cache/scratch`` (created, owner-only); *home* defaults to the active Hermes home.
+
+ Every Hermes process and child gets ``TMPDIR``/``TMP``/``TEMP`` pointed here at boot (see
+ :func:`export_scratch_tmp_env`), so ``tempfile`` defaults land here without call sites
+ knowing. Entries older than ``SCRATCH_MAX_AGE_HOURS`` are pruned at most once per process
+ and once per hour across processes (stamp file), so a fan-out of children stays cheap.
+ """
+ base = Path(home) if home is not None else get_hermes_home()
+ scratch = base / "cache" / "scratch"
+ try:
+ scratch.mkdir(parents=True, exist_ok=True)
+ if sys.platform != "win32":
+ os.chmod(scratch, 0o700)
+ except OSError:
+ pass
+ if prune:
+ _prune_scratch_dir_once(scratch)
+ return scratch
+
+
+def prune_scratch_dir(scratch: Path | None = None, max_age_hours: float = SCRATCH_MAX_AGE_HOURS) -> int:
+ """Delete top-level scratch entries untouched for *max_age_hours*; return the count removed."""
+ import time
+ root = scratch if scratch is not None else get_scratch_dir(prune=False)
+ cutoff = time.time() - max_age_hours * 3600
+ removed = 0
+ try:
+ entries = list(root.iterdir())
+ except OSError:
+ return 0
+ for entry in entries:
+ if entry.name == _SCRATCH_PRUNE_STAMP:
+ continue
+ try:
+ if entry.lstat().st_mtime >= cutoff:
+ continue
+ if entry.is_dir() and not entry.is_symlink():
+ shutil.rmtree(entry, ignore_errors=True)
+ else:
+ entry.unlink()
+ removed += 1
+ except OSError:
+ continue
+ return removed
+
+
+def _prune_scratch_dir_once(scratch: Path) -> None:
+ global _scratch_pruned_once
+ if _scratch_pruned_once:
+ return
+ _scratch_pruned_once = True
+ import time
+ stamp = scratch / _SCRATCH_PRUNE_STAMP
+ try:
+ if time.time() - stamp.stat().st_mtime < _SCRATCH_PRUNE_INTERVAL_SECONDS:
+ return
+ except OSError:
+ pass
+ with contextlib.suppress(Exception):
+ stamp.touch()
+ prune_scratch_dir(scratch)
+
+
+def scratch_dir_usage_bytes(scratch: Path | None = None) -> int:
+ """Total bytes under the scratch dir (for ``hermes doctor``); 0 when unreadable."""
+ root = scratch if scratch is not None else get_scratch_dir(prune=False)
+ total = 0
+ for dirpath, _dirnames, filenames in os.walk(root, onerror=lambda _e: None):
+ for name in filenames:
+ with contextlib.suppress(OSError):
+ total += os.lstat(os.path.join(dirpath, name)).st_size
+ return total
+
+
+def apply_scratch_tmp_env(env: MutableMapping[str, str]) -> bool:
+ """Point ``TMPDIR``/``TMP``/``TEMP`` in *env* at the scratch dir of ``env["HERMES_HOME"]``.
+
+ A temp var the user (or the OS: macOS ``/var/folders``, Windows ``%TEMP%``) set is
+ respected and nothing changes. A value Hermes itself exported earlier — recognisable
+ because it equals ``HERMES_SCRATCH_DIR`` — is re-derived, so a child running under another
+ profile's home gets that home's scratch dir rather than its parent's. Returns True when
+ the vars were (re)written.
+ """
+ ours = env.get(SCRATCH_DIR_MARKER_ENV, "")
+ for key in SCRATCH_TMP_ENV_VARS:
+ value = env.get(key, "").strip()
+ if value and value != ours:
+ return False
+ home = env.get("HERMES_HOME", "").strip()
+ scratch = str(get_scratch_dir(_expand_hermes_home(home) if home else get_process_hermes_home()))
+ for key in SCRATCH_TMP_ENV_VARS:
+ env[key] = scratch
+ env[SCRATCH_DIR_MARKER_ENV] = scratch
+ return True
+
+
+def export_scratch_tmp_env() -> bool:
+ """Boot hook: apply :func:`apply_scratch_tmp_env` to this process and reset ``tempfile``'s
+ cached default so ``tempfile.gettempdir()`` follows. Call again after anything that
+ re-homes the process (``--profile`` resolution); a user-set temp var is never overridden."""
+ changed = apply_scratch_tmp_env(os.environ)
+ if changed:
+ import tempfile
+ tempfile.tempdir = None
+ return changed
VALID_REASONING_EFFORTS = ("minimal", "low", "medium", "high", "xhigh", "max", "ultra")
diff --git a/tests/test_scratch_dir.py b/tests/test_scratch_dir.py
new file mode 100644
index 00000000000..ee033a8e57d
--- /dev/null
+++ b/tests/test_scratch_dir.py
@@ -0,0 +1,54 @@
+"""Scratch dir contract: TMPDIR/TMP/TEMP follow HERMES_HOME/cache/scratch unless the user set them."""
+
+import os
+import subprocess
+import sys
+import time
+
+from hermes_constants import apply_scratch_tmp_env, get_scratch_dir, prune_scratch_dir
+
+
+def test_scratch_env_follows_home_and_respects_user_tmpdir(tmp_path):
+ """Unset temp vars → scratch of env HERMES_HOME; a Hermes-exported value re-derives for a routed
+ home; a user/OS-set value (macOS ``/var/folders``, ``%TEMP%``) is never touched."""
+ home_a, home_b = tmp_path / "a", tmp_path / "b"
+ env = {"HERMES_HOME": str(home_a)}
+ assert apply_scratch_tmp_env(env) is True
+ scratch_a = str(home_a / "cache" / "scratch")
+ assert env["TMPDIR"] == env["TMP"] == env["TEMP"] == env["HERMES_SCRATCH_DIR"] == scratch_a
+ assert os.path.isdir(scratch_a)
+
+ env["HERMES_HOME"] = str(home_b) # child served under another profile's home
+ assert apply_scratch_tmp_env(env) is True
+ assert env["TMPDIR"] == str(home_b / "cache" / "scratch")
+
+ user_env = {"HERMES_HOME": str(home_a), "TMPDIR": "/var/folders/zz"}
+ assert apply_scratch_tmp_env(user_env) is False
+ assert user_env["TMPDIR"] == "/var/folders/zz" and "HERMES_SCRATCH_DIR" not in user_env
+ assert "TMP" not in user_env # a partially user-set triple is left exactly as found
+
+
+def test_bootstrap_import_exports_scratch_to_process_and_children(tmp_path):
+ """``import hermes_bootstrap`` alone makes ``tempfile`` (this process AND a child) land in scratch."""
+ env = {k: v for k, v in os.environ.items() if k not in ("TMPDIR", "TMP", "TEMP", "HERMES_SCRATCH_DIR")}
+ env["HERMES_HOME"] = str(tmp_path)
+ code = ("import tempfile, os, subprocess, sys; import hermes_bootstrap; "
+ "print(tempfile.gettempdir()); "
+ "print(subprocess.run([sys.executable, '-c', 'import tempfile;print(tempfile.gettempdir())'],"
+ " capture_output=True, text=True).stdout.strip())")
+ out = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, text=True,
+ cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))), check=True)
+ expected = str(tmp_path / "cache" / "scratch")
+ assert out.stdout.split() == [expected, expected]
+
+
+def test_prune_removes_only_stale_top_level_entries(tmp_path):
+ scratch = get_scratch_dir(tmp_path, prune=False)
+ stale, fresh = scratch / "stale", scratch / "fresh.txt"
+ stale.mkdir()
+ (stale / "f").write_text("x", encoding="utf-8")
+ fresh.write_text("y", encoding="utf-8")
+ ancient = time.time() - 100 * 3600
+ os.utime(stale, (ancient, ancient))
+ assert prune_scratch_dir(scratch) == 1
+ assert not stale.exists() and fresh.exists()
diff --git a/tools/code_execution_env.py b/tools/code_execution_env.py
index 6dd3eb0b4d1..34d90c36c43 100644
--- a/tools/code_execution_env.py
+++ b/tools/code_execution_env.py
@@ -116,7 +116,7 @@ def _scrub_child_env(source_env, is_passthrough=None, is_windows=None):
def _build_child_env(*, rpc_endpoint: str, rpc_token: str, tmpdir: str,
child_python: str) -> Dict[str, str]:
"""Build the scrubbed child environment both execution paths share."""
- from hermes_constants import apply_subprocess_home_env, get_hermes_home_override
+ from hermes_constants import apply_scratch_tmp_env, apply_subprocess_home_env, get_hermes_home_override
child_env = _scrub_child_env(os.environ)
child_env["HERMES_RPC_SOCKET"] = rpc_endpoint
child_env["HERMES_RPC_TOKEN"] = rpc_token
@@ -144,6 +144,7 @@ def _build_child_env(*, rpc_endpoint: str, rpc_token: str, tmpdir: str,
_home_override = get_hermes_home_override()
if _home_override:
child_env["HERMES_HOME"] = _home_override
+ apply_scratch_tmp_env(child_env) # TMPDIR follows the routed home, like HOME does
# PYTHONPATH: the staging dir (hermes_tools.py) must always be importable even when project
# mode changes CWD. Hermes's root is added ONLY when the child runs in Hermes's Python env —
# exposing Hermes's site-packages to an external interpreter can mix incompatible compiled
diff --git a/tools/environments/local.py b/tools/environments/local.py
index d165ce61077..a83e256d8d5 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -375,11 +375,12 @@ def served_profile_child_env(
``hermes_subprocess_env`` snapshot."""
from agent.secret_scope import (
UnscopedSecretError, build_profile_secret_scope, current_secret_scope, is_multiplex_active)
- from hermes_constants import get_hermes_home_override
+ from hermes_constants import apply_scratch_tmp_env, get_hermes_home_override
env = dict(base) if base is not None else hermes_subprocess_env(inherit_credentials=inherit_credentials)
target = str(target_home or get_hermes_home_override() or "")
if target:
env["HERMES_HOME"] = target
+ apply_scratch_tmp_env(env) # TMPDIR follows the served home, like HOME does
if _is_routed_home(target):
strip_launch_profile_env(env, target)
_scrub_credentials(env, inherit_credentials=False)
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index c869f941e8d..37885be6f8f 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -242,6 +242,16 @@ swept hourly by gateway housekeeping and once per process on CLI-only
installs. Set `temp_dir` to an existing absolute path to redirect session
temp anywhere else; user-set paths are never auto-pruned.
+Independently of `terminal.temp_dir`, every Hermes process (CLI, TUI, gateway, Desktop
+backend, cron) and every child it launches gets `TMPDIR`, `TMP` and `TEMP` pointed at
+**`~/.hermes/cache/scratch`** (per profile) at startup, so `tempfile.mkdtemp()`,
+`mktemp`, browser profiles and probe scripts all land on real storage instead of a
+RAM-backed system temp dir. The system prompt names this directory as the scratch
+directory. Hermes only sets these when they are not already set — a `TMPDIR` exported
+by you or by the OS (macOS `/var/folders`, Windows `%TEMP%`) is left alone. Entries
+older than 72 hours are pruned at startup (at most once per hour). `hermes doctor`
+reports the directory and its size.
+
`desktop.font_family` sets the font for chat and the rest of the Hermes Desktop interface (the terminal pane has its own key above). Give it one installed family name (for example, `OpenDyslexic` or `Atkinson Hyperlegible`) or a CSS font stack; Hermes keeps the active theme's own stack behind it so CJK and emoji glyphs still resolve, and an empty value uses the theme's font. Edit it in **Settings → Appearance → Chat Font**.
`terminal.font_family` controls the embedded terminal in Hermes Desktop. It accepts either one locally installed family name (for example, `MesloLGS NF`) or a CSS font stack. Hermes appends its bundled JetBrains Mono stack as a fallback, and an empty value keeps the default. You can edit the same profile-scoped setting in **Settings → Appearance → Terminal Font**; no Google Fonts download or system-font permission is required.