Skip to content

The agent that grows with you

refactor: single build_subprocess_env() factory for all child-process spawns (profile + secret-scrub single owner)

teknium13d48f893da3d
diff --git a/agent/secret_sources/bitwarden.py b/agent/secret_sources/bitwarden.py
index 2d993f396c2..7e71f0f7fd5 100644
--- a/agent/secret_sources/bitwarden.py
+++ b/agent/secret_sources/bitwarden.py
@@ -667,7 +667,10 @@ def _run_bws_list(
bws: Path, access_token: str, project_id: str, server_url: str = ""
) -> Tuple[Dict[str, str], List[str]]:
cmd = [str(bws), "secret", "list", project_id, "--output", "json"]
- env = os.environ.copy()
+ # bws child intentionally receives the access token; exact preservation
+ # (BWS_SERVER_URL manual overrides etc. must survive untouched).
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
env["BWS_ACCESS_TOKEN"] = access_token
# Make sure we're not echoing telemetry / colour codes into json.
env.setdefault("NO_COLOR", "1")
diff --git a/agent/secret_sources/command.py b/agent/secret_sources/command.py
index d3a9afb81c2..9bce311ba90 100644
--- a/agent/secret_sources/command.py
+++ b/agent/secret_sources/command.py
@@ -179,7 +179,10 @@ def _run_helper(
)
return None
- env = os.environ.copy()
+ # User-configured secret-helper command: runs with the user's full shell
+ # env by design (it may need any credential to resolve the secret).
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
env["HERMES_SECRET_KEY"] = secret_key
try:
diff --git a/cli.py b/cli.py
index 1a7ac47d720..e2044dc1163 100644
--- a/cli.py
+++ b/cli.py
@@ -10003,8 +10003,8 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
# Sanitize env to prevent credential leakage —
# quick commands run in the CLI process which
# has all API keys in os.environ.
- from tools.environments.local import _sanitize_subprocess_env
- sanitized_env = _sanitize_subprocess_env(os.environ.copy())
+ from tools.environments.local import build_subprocess_env
+ sanitized_env = build_subprocess_env()
from hermes_cli._subprocess_compat import windows_hide_flags
result = subprocess.run(
exec_cmd, shell=True, capture_output=True,
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 2d8b63d35b6..9b597aed82d 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -2284,7 +2284,7 @@ def _run_job_script(
argv = [python_exe, str(path)]
try:
- from tools.environments.local import _sanitize_subprocess_env
+ from tools.environments.local import build_subprocess_env
popen_kwargs = {}
if sys.platform == "win32":
@@ -2293,7 +2293,7 @@ def _run_job_script(
"encoding": "utf-8",
"errors": "replace",
}
- env = _sanitize_subprocess_env(os.environ.copy())
+ env = build_subprocess_env()
env.update(env_overlay)
# Use the job's workdir as the subprocess cwd when configured,
# otherwise default to the scripts-dir parent (back-compat).
diff --git a/gateway/platforms/webhook_filters.py b/gateway/platforms/webhook_filters.py
index 30198c6e52d..881effdf85a 100644
--- a/gateway/platforms/webhook_filters.py
+++ b/gateway/platforms/webhook_filters.py
@@ -245,7 +245,7 @@ class WebhookRouteProcessor:
argv = [sys.executable, str(path)]
try:
- from tools.environments.local import _sanitize_subprocess_env
+ from tools.environments.local import build_subprocess_env
popen_kwargs = {"creationflags": 0x08000000} if sys.platform == "win32" else {}
result = subprocess.run(
@@ -255,7 +255,7 @@ class WebhookRouteProcessor:
text=True, encoding="utf-8", errors="replace",
timeout=self.script_timeout_seconds,
cwd=str(path.parent),
- env=_sanitize_subprocess_env(os.environ.copy()),
+ env=build_subprocess_env(),
**popen_kwargs,
)
except subprocess.TimeoutExpired:
diff --git a/gateway/run.py b/gateway/run.py
index c0ea379bf40..8ebac1d942a 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -7323,7 +7323,8 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
)
"""
).strip()
- watcher_env = os.environ.copy()
+ from tools.environments.local import build_subprocess_env
+ watcher_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
# This watcher is intentionally outside the running gateway. If it
# inherits the gateway marker, `hermes gateway restart` refuses to
# run as a self-restart loop guard and the gateway stays stopped.
@@ -7412,7 +7413,8 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# _HERMES_GATEWAY=1 from us, and the CLI's self-restart loop guard
# refuses to run when that marker is set — silently (DEVNULL), so the
# gateway stops and never comes back.
- watcher_env = os.environ.copy()
+ from tools.environments.local import build_subprocess_env
+ watcher_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
watcher_env.pop("_HERMES_GATEWAY", None)
setsid_bin = shutil.which("setsid")
if setsid_bin:
@@ -12455,8 +12457,8 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# Sanitize env to prevent credential leakage —
# quick commands run in the gateway process which
# has all API keys in os.environ.
- from tools.environments.local import _sanitize_subprocess_env
- sanitized_env = _sanitize_subprocess_env(os.environ.copy())
+ from tools.environments.local import build_subprocess_env
+ sanitized_env = build_subprocess_env()
proc = await asyncio.create_subprocess_shell(
exec_cmd,
stdout=asyncio.subprocess.PIPE,
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index ca7e87d0ce1..2a74fe0bbad 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2258,7 +2258,10 @@ def _launch_tui(
import tempfile
- env = os.environ.copy()
+ # TUI child is a hermes process: propagate the profile-home contract via
+ # the single factory; keep secrets (the TUI/agent needs provider creds).
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
try:
from hermes_cli.config import apply_terminal_config_to_env
apply_terminal_config_to_env(env=env)
@@ -2352,7 +2355,8 @@ def _launch_tui(
_tokens.append(f"--max-old-space-size={_resolve_tui_heap_mb()}")
env["NODE_OPTIONS"] = " ".join(_tokens)
# HERMES_TUI_RESUME is an internal hand-off from the Python wrapper to the
- # Ink app. Because we start from os.environ.copy(), an exported/stale value
+ # Ink app. Because we start from a full os.environ snapshot (via
+ # build_subprocess_env), an exported/stale value
# in the user's shell would otherwise make a plain `hermes --tui` try to
# resume a non-existent session and leave the UI at "error: session not
# found" with no live session. Only forward a resume id that argparse
@@ -15144,7 +15148,10 @@ def cmd_dashboard(args):
reexec_argv.append("--insecure")
if getattr(args, "skip_build", False):
reexec_argv.append("--skip-build")
- env = os.environ.copy()
+ from tools.environments.local import build_subprocess_env
+ # Exact env preservation: HERMES_HOME is explicitly pinned to the
+ # machine root below — the factory must not re-inject a profile home.
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
# Pin the child to the machine ROOT, not the launching profile's
# HERMES_HOME. We must resolve the root explicitly instead of just
# dropping HERMES_HOME: in the Docker layout the machine root is
diff --git a/hermes_cli/onepassword_secrets_cli.py b/hermes_cli/onepassword_secrets_cli.py
index 8b17c3e1eb3..68be4f953ae 100644
--- a/hermes_cli/onepassword_secrets_cli.py
+++ b/hermes_cli/onepassword_secrets_cli.py
@@ -510,7 +510,10 @@ def _op_whoami(
cmd = [str(binary), "whoami"]
if account:
cmd += ["--account", account]
- env = os.environ.copy()
+ # 1Password CLI child: intentionally receives the service-account token —
+ # no scrub, no HOME rewrite (op stores auth state under the real home).
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
env.setdefault("NO_COLOR", "1")
if token_value:
env["OP_SERVICE_ACCOUNT_TOKEN"] = token_value
diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.py
index d1ff4260cc8..cf4a4e60a75 100644
--- a/hermes_cli/pty_bridge.py
+++ b/hermes_cli/pty_bridge.py
@@ -143,7 +143,14 @@ class PtyBridge:
# simple terminal probes like `tput cols` fail before winsize reads.
# Preserve explicit caller overrides, but backfill a sensible default
# when TERM is missing or blank.
- spawn_env = (os.environ.copy() if env is None else env.copy())
+ # env=None fallback: callers own env policy (process_registry already
+ # sanitizes). Build via the factory with exact preservation so the
+ # site stays findable without changing inherited content.
+ from tools.environments.local import build_subprocess_env
+ spawn_env = (
+ build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
+ if env is None else env.copy()
+ )
if not spawn_env.get("TERM"):
spawn_env["TERM"] = "xterm-256color"
proc = ptyprocess.PtyProcess.spawn( # type: ignore[union-attr]
diff --git a/hermes_cli/secrets_cli.py b/hermes_cli/secrets_cli.py
index 53f5d5b4d1d..2ae7f4f55dc 100644
--- a/hermes_cli/secrets_cli.py
+++ b/hermes_cli/secrets_cli.py
@@ -608,7 +608,10 @@ def _list_projects(
binary: Path, token: str, console: Console, *, server_url: str = ""
) -> Optional[List[dict]]:
"""Call ``bws project list`` and return the parsed list, or None on failure."""
- env = os.environ.copy()
+ # Secret-manager CLI child: intentionally receives tokens — no scrub,
+ # no HOME rewrite (bws stores state under the real user home).
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
env["BWS_ACCESS_TOKEN"] = token
env.setdefault("NO_COLOR", "1")
if server_url:
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index f2d4ea11930..97632b98651 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -5950,7 +5950,10 @@ def _trim_setup_output(value: Optional[str], limit: int = 4000) -> str:
def _memory_provider_setup_env() -> Dict[str, str]:
- env = os.environ.copy()
+ # External package-manager child (npm/uv/pip): exact env preservation —
+ # scrubbing or HOME rewriting could break user tool auth/config.
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
home = Path.home()
extra_bins = [
home / ".brv-cli" / "bin",
@@ -17763,7 +17766,11 @@ def _resolve_chat_argv(
profile_dir = _resolve_profile_dir(requested)
argv, cwd = _make_tui_argv(PROJECT_ROOT / "ui-tui", tui_dev=False)
- env = os.environ.copy()
+ # Hermes TUI child: build via the single spawn-env factory (profile-home
+ # contract applied; secrets kept — the spawned agent needs provider creds).
+ # An explicit profile scope below still overrides HERMES_HOME afterwards.
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
try:
from hermes_cli.config import apply_terminal_config_to_env
apply_terminal_config_to_env(env=env)
diff --git a/hermes_cli/win_pty_bridge.py b/hermes_cli/win_pty_bridge.py
index fe8ca1acb04..e9bc6ba541b 100644
--- a/hermes_cli/win_pty_bridge.py
+++ b/hermes_cli/win_pty_bridge.py
@@ -88,7 +88,12 @@ class WinPtyBridge:
"pywinpty is not installed. Install with: pip install pywinpty"
)
raise PtyUnavailableError("ConPTY is unavailable on this platform.")
- spawn_env = (os.environ.copy() if env is None else dict(env))
+ # See pty_bridge.py: exact-preservation factory for the env=None fallback.
+ from tools.environments.local import build_subprocess_env
+ spawn_env = (
+ build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
+ if env is None else dict(env)
+ )
if not spawn_env.get("TERM"):
spawn_env["TERM"] = "xterm-256color"
# pywinpty mirrors ptyprocess: dimensions=(rows, cols).
diff --git a/tests/agent/test_subprocess_env_guard.py b/tests/agent/test_subprocess_env_guard.py
new file mode 100644
index 00000000000..2b79e2dbdb4
--- /dev/null
+++ b/tests/agent/test_subprocess_env_guard.py
@@ -0,0 +1,108 @@
+"""Lint guard: no new raw ``os.environ.copy()`` spawn-env sites.
+
+Every child-process env in the codebase must be built through
+``tools.environments.local.build_subprocess_env`` (or its sibling
+``hermes_subprocess_env`` / ``_sanitize_subprocess_env``, which the factory
+wraps) so profile-home propagation and secret-scrubbing have a single owner.
+History: ~11 commits over 6 months each fixed one more spawn site that missed
+``HERMES_HOME`` or secret-scrub propagation.
+
+This test greps the source tree for ``os.environ.copy()`` appearing within
+``PROXIMITY_LINES`` lines of a spawn call (``Popen`` / ``subprocess.run`` /
+``create_subprocess*`` / ``PtyProcess.spawn`` / ``execvpe``) and asserts every
+hit is in the explicit allowlist below. If you are adding a new spawn site:
+
+* use ``build_subprocess_env(...)`` — with ``scrub_secrets=False,
+ inherit_profile_home=False`` if you need today's exact-inherit behavior; or
+* consciously add the file to ``ALLOWED_RAW_SPAWN_ENV_FILES`` with a comment
+ explaining why the factory cannot be used.
+"""
+
+import re
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+# Directories that make up the shipped source tree.
+SCAN_DIRS = ("agent", "hermes_cli", "tools", "gateway", "cron", "tui_gateway")
+SCAN_ROOT_FILES = ("cli.py", "hermes_constants.py")
+
+# How many lines around an `os.environ.copy()` we look for a spawn call.
+PROXIMITY_LINES = 20
+
+SPAWN_RE = re.compile(
+ r"\bPopen\b|\bsubprocess\.run\b|\bcreate_subprocess|\bPtyProcess\.spawn\b"
+ r"|\bexecvpe\b|\bptyprocess\.PtyProcess\b|\bspawn\("
+)
+COPY_RE = re.compile(r"\bos\.environ\.copy\(\)")
+
+# ---------------------------------------------------------------------------
+# ALLOWLIST — intentionally-raw sites. Each entry is a relative posix path.
+# Adding to this list is a conscious decision: document WHY inline here.
+# ---------------------------------------------------------------------------
+ALLOWED_RAW_SPAWN_ENV_FILES = {
+ # THE owner module: _sanitize_subprocess_env / hermes_subprocess_env /
+ # build_subprocess_env legitimately snapshot os.environ — everything else
+ # delegates to them.
+ "tools/environments/local.py",
+}
+
+
+def _iter_source_files():
+ for d in SCAN_DIRS:
+ root = REPO_ROOT / d
+ if root.is_dir():
+ yield from root.rglob("*.py")
+ for f in SCAN_ROOT_FILES:
+ p = REPO_ROOT / f
+ if p.is_file():
+ yield p
+
+
+def _raw_spawn_env_sites():
+ """Return [(relpath, lineno)] of os.environ.copy() near a spawn call."""
+ sites = []
+ for path in _iter_source_files():
+ rel = path.relative_to(REPO_ROOT).as_posix()
+ try:
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
+ except OSError:
+ continue
+ for i, line in enumerate(lines):
+ stripped = line.lstrip()
+ if stripped.startswith("#"):
+ continue # comments referencing the old pattern are fine
+ if not COPY_RE.search(line.split("#", 1)[0]):
+ continue
+ lo = max(0, i - PROXIMITY_LINES)
+ hi = min(len(lines), i + PROXIMITY_LINES + 1)
+ window = "\n".join(lines[lo:hi])
+ if SPAWN_RE.search(window):
+ sites.append((rel, i + 1))
+ return sites
+
+
+def test_no_new_raw_environ_copy_spawn_sites():
+ sites = _raw_spawn_env_sites()
+ offenders = [
+ f"{rel}:{lineno}"
+ for rel, lineno in sites
+ if rel not in ALLOWED_RAW_SPAWN_ENV_FILES
+ ]
+ assert not offenders, (
+ "New raw os.environ.copy() spawn-env site(s) found:\n "
+ + "\n ".join(offenders)
+ + "\nUse tools.environments.local.build_subprocess_env() instead "
+ "(scrub_secrets=False, inherit_profile_home=False preserves exact "
+ "legacy behavior), or consciously extend "
+ "ALLOWED_RAW_SPAWN_ENV_FILES in this test with a justification."
+ )
+
+
+def test_allowlist_entries_still_exist():
+ """Prune the allowlist when files are removed/renamed."""
+ for rel in ALLOWED_RAW_SPAWN_ENV_FILES:
+ assert (REPO_ROOT / rel).is_file(), (
+ f"Allowlist entry {rel} no longer exists — remove it from "
+ "ALLOWED_RAW_SPAWN_ENV_FILES."
+ )
diff --git a/tests/tools/test_build_subprocess_env.py b/tests/tools/test_build_subprocess_env.py
new file mode 100644
index 00000000000..ecb228c5662
--- /dev/null
+++ b/tests/tools/test_build_subprocess_env.py
@@ -0,0 +1,136 @@
+"""Tests for tools.environments.local.build_subprocess_env — the single
+factory for child-process environments (profile-home + secret-scrub owner).
+"""
+
+import os
+import subprocess
+import sys
+
+import pytest
+
+from tools.environments.local import build_subprocess_env
+
+
+# ---------------------------------------------------------------------------
+# Unit: scrub path delegates to _sanitize_subprocess_env semantics
+# ---------------------------------------------------------------------------
+
+def test_scrub_on_strips_provider_key(monkeypatch):
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-secret")
+ env = build_subprocess_env()
+ assert "ANTHROPIC_API_KEY" not in env
+
+
+def test_scrub_on_strips_dynamic_internal_secret(monkeypatch):
+ monkeypatch.setenv("AUXILIARY_VISION_API_KEY", "sk-aux")
+ monkeypatch.setenv("GATEWAY_RELAY_FOO_TOKEN", "tok")
+ env = build_subprocess_env()
+ assert "AUXILIARY_VISION_API_KEY" not in env
+ assert "GATEWAY_RELAY_FOO_TOKEN" not in env
+
+
+def test_scrub_on_strips_venv_markers(monkeypatch):
+ monkeypatch.setenv("VIRTUAL_ENV", "/some/venv")
+ env = build_subprocess_env()
+ assert "VIRTUAL_ENV" not in env
+
+
+def test_scrub_on_forwards_extra_like_sanitize_extra_env(monkeypatch):
+ env = build_subprocess_env(extra={"MY_HARMLESS_VAR": "1"})
+ assert env.get("MY_HARMLESS_VAR") == "1"
+ # extra still goes through the blocklist on the scrub path
+ env2 = build_subprocess_env(extra={"ANTHROPIC_API_KEY": "sk"})
+ assert "ANTHROPIC_API_KEY" not in env2
+
+
+def test_scrub_on_matches_sanitize_exactly(monkeypatch):
+ """build_subprocess_env(scrub_secrets=True) must equal
+ _sanitize_subprocess_env(os.environ.copy()) — single owner, zero drift."""
+ from tools.environments.local import _sanitize_subprocess_env
+
+ monkeypatch.setenv("OPENAI_API_KEEP_TEST", "x")
+ assert build_subprocess_env() == _sanitize_subprocess_env(os.environ.copy())
+
+
+# ---------------------------------------------------------------------------
+# Unit: no-scrub path preserves content exactly
+# ---------------------------------------------------------------------------
+
+def test_no_scrub_no_home_is_exact_environ_copy(monkeypatch):
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-secret")
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
+ assert env == os.environ.copy()
+ assert env is not os.environ # detached copy
+
+
+def test_no_scrub_explicit_base_preserved(monkeypatch):
+ base = {"PATH": "/bin", "ANTHROPIC_API_KEY": "sk"}
+ env = build_subprocess_env(base, scrub_secrets=False, inherit_profile_home=False)
+ assert env == base
+ assert env is not base
+
+
+def test_extra_wins_last_on_no_scrub_path():
+ base = {"HERMES_HOME": "/old"}
+ env = build_subprocess_env(
+ base, scrub_secrets=False, inherit_profile_home=False,
+ extra={"HERMES_HOME": "/new"},
+ )
+ assert env["HERMES_HOME"] == "/new"
+
+
+def test_no_scrub_inherit_profile_home_bridges_context_override(tmp_path):
+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override
+
+ token = set_hermes_home_override(str(tmp_path))
+ try:
+ env = build_subprocess_env(
+ {"PATH": "/bin"}, scrub_secrets=False, inherit_profile_home=True
+ )
+ finally:
+ reset_hermes_home_override(token)
+ assert env["HERMES_HOME"] == str(tmp_path)
+
+
+# ---------------------------------------------------------------------------
+# E2E: real subprocess sees the factory's contract
+# ---------------------------------------------------------------------------
+
+def test_e2e_child_sees_hermes_home_and_no_planted_secret(tmp_path, monkeypatch):
+ """A real child spawned with a factory-built env must see HERMES_HOME
+ propagated and (with scrub on) a planted provider-style key absent."""
+ hermes_home = tmp_path / "hermes-home"
+ hermes_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-FAKE-planted")
+ monkeypatch.setenv("AUXILIARY_FAKE_API_KEY", "sk-FAKE-aux")
+
+ env = build_subprocess_env() # scrub on (default)
+
+ code = (
+ "import os, json; "
+ "print(json.dumps({'home': os.environ.get('HERMES_HOME'), "
+ "'k1': 'ANTHROPIC_API_KEY' in os.environ, "
+ "'k2': 'AUXILIARY_FAKE_API_KEY' in os.environ}))"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", code],
+ env=env, capture_output=True, text=True, timeout=60, check=True,
+ )
+ import json
+
+ result = json.loads(out.stdout)
+ assert result["home"] == str(hermes_home)
+ assert result["k1"] is False
+ assert result["k2"] is False
+
+
+def test_e2e_no_scrub_child_keeps_planted_secret(tmp_path, monkeypatch):
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-FAKE-planted")
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
+ out = subprocess.run(
+ [sys.executable, "-c",
+ "import os; print(os.environ.get('ANTHROPIC_API_KEY', ''))"],
+ env=env, capture_output=True, text=True, timeout=60, check=True,
+ )
+ assert out.stdout.strip() == "sk-FAKE-planted"
diff --git a/tools/checkpoint_manager.py b/tools/checkpoint_manager.py
index a1993187ff6..df3666f134b 100644
--- a/tools/checkpoint_manager.py
+++ b/tools/checkpoint_manager.py
@@ -258,7 +258,10 @@ def _git_env(
``store/indexes/<hash>`` so projects don't race on a shared index.
"""
normalized_working_dir = _normalize_path(working_dir)
- env = os.environ.copy()
+ # git child with hand-isolated config env; exact preservation — a HOME
+ # rewrite would change which ~/.gitconfig the isolation vars are hiding.
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
env["GIT_DIR"] = str(store)
env["GIT_WORK_TREE"] = str(normalized_working_dir)
env.pop("GIT_NAMESPACE", None)
@@ -442,7 +445,8 @@ def _init_store(store: Path, working_dir: str) -> Optional[str]:
# ``git init --bare`` rejects GIT_WORK_TREE, so we can't use _run_git
# here (which always sets GIT_DIR + GIT_WORK_TREE). Use a raw
# subprocess with just the config-isolation env vars.
- init_env = os.environ.copy()
+ from tools.environments.local import build_subprocess_env
+ init_env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
init_env["GIT_CONFIG_GLOBAL"] = os.devnull
init_env["GIT_CONFIG_SYSTEM"] = os.devnull
init_env["GIT_CONFIG_NOSYSTEM"] = "1"
diff --git a/tools/environments/local.py b/tools/environments/local.py
index 673d8a3345e..77cd33d5cf5 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -11,6 +11,7 @@ import subprocess
import sys
import tempfile
import time
+from collections.abc import Mapping
from pathlib import Path
from tools.environments.base import BaseEnvironment, _pipe_stdin
@@ -638,6 +639,69 @@ def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, str
return env
+def build_subprocess_env(
+ base: "Mapping[str, str] | None" = None,
+ *,
+ inherit_profile_home: bool = True,
+ scrub_secrets: bool = True,
+ extra: "Mapping[str, str] | None" = None,
+) -> dict[str, str]:
+ """Single factory for building a child-process environment.
+
+ Every spawn site in the codebase should build its env through this
+ function (or :func:`hermes_subprocess_env` for the model-driving-CLI
+ surface) instead of copying ``os.environ`` directly, so profile-home
+ propagation (``HERMES_HOME`` / subprocess ``HOME`` contract) and the
+ Hermes secret-scrub policy have a single owner. History: ~11 separate
+ commits each fixed one more spawn site that missed profile-HOME or
+ secret-scrub propagation; this factory is the fix for the class.
+
+ Parameters:
+
+ * ``base`` — starting environment. ``None`` (default) snapshots
+ ``os.environ``. Pass an explicit mapping to build on a caller-prepared
+ env instead.
+ * ``scrub_secrets=True`` (default) — delegate to
+ :func:`_sanitize_subprocess_env`, the long-standing owner of the scrub
+ list (provider blocklist + ``_is_hermes_internal_secret`` dynamic
+ patterns + kanban/venv-marker/session-context guards) **and** of
+ ``HERMES_HOME`` / subprocess-HOME propagation. On this path profile
+ home propagation is inherent — ``inherit_profile_home`` is ignored
+ (always applied), exactly matching today's sanitize semantics.
+ * ``scrub_secrets=False`` — preserve the base env content byte-for-byte
+ (no key is removed). Use for children that intentionally receive
+ secrets (git credential flows, ``bws``/``op`` secret CLIs) or where
+ scrubbing could change behavior. The site is still a win: it becomes
+ grep-able and future-fixable.
+ * ``inherit_profile_home`` — on the non-scrub path, when True, bridge the
+ context-local Hermes home override into ``HERMES_HOME`` and apply the
+ subprocess HOME contract (``hermes_constants.apply_subprocess_home_env``).
+ Pass False to keep the inherited env untouched (exact legacy
+ ``os.environ.copy()`` behavior).
+ * ``extra`` — applied **last** on the non-scrub path so explicit caller
+ overrides (e.g. a session-scoped ``HERMES_HOME``) always win. On the
+ scrub path it is forwarded as ``_sanitize_subprocess_env``'s
+ ``extra_env`` (same force-prefix / blocklist handling as today).
+ """
+ if scrub_secrets:
+ # _sanitize_subprocess_env already performs HERMES_HOME override
+ # bridging + apply_subprocess_home_env unconditionally; delegating
+ # wholesale keeps one owner and zero drift.
+ return _sanitize_subprocess_env(
+ dict(base) if base is not None else os.environ.copy(),
+ dict(extra) if extra else None,
+ )
+
+ env: dict[str, str] = dict(base) if base is not None else os.environ.copy()
+ if inherit_profile_home:
+ _inject_context_hermes_home(env)
+ from hermes_constants import apply_subprocess_home_env
+ apply_subprocess_home_env(env)
+ if extra:
+ env.update(extra)
+ return env
+
+
def _find_bash() -> str:
"""Find bash for command execution."""
if not _IS_WINDOWS:
diff --git a/tools/environments/singularity.py b/tools/environments/singularity.py
index 169937096bd..0ea92c43b7e 100644
--- a/tools/environments/singularity.py
+++ b/tools/environments/singularity.py
@@ -129,7 +129,10 @@ def _get_or_build_sif(image: str, executable: str = "apptainer") -> str:
tmp_dir = cache_dir / "tmp"
tmp_dir.mkdir(parents=True, exist_ok=True)
- env = os.environ.copy()
+ # apptainer/singularity build: external tool, may need registry
+ # credentials from the user env — exact preservation.
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
env["APPTAINER_TMPDIR"] = str(tmp_dir)
env["APPTAINER_CACHEDIR"] = str(cache_dir)
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 31d2c32ee82..ec194525f1b 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -342,12 +342,18 @@ class _SlashWorker:
# slash_worker runs the Hermes agent → needs provider credentials.
# Tier-1 secrets (gateway/GitHub/infra) are still stripped (#29157).
- env = hermes_subprocess_env(inherit_credentials=True)
- if profile_home:
- # Global-remote / multi-profile sessions: the worker must resolve
- # config/skills/state against the session's profile home, not the
- # gateway's launch HERMES_HOME (#40677).
- env["HERMES_HOME"] = str(profile_home)
+ # Global-remote / multi-profile sessions: the worker must resolve
+ # config/skills/state against the session's profile home, not the
+ # gateway's launch HERMES_HOME (#40677). The override goes through the
+ # build_subprocess_env factory's `extra` (applied last, always wins)
+ # instead of a hand-rolled env["HERMES_HOME"] assignment.
+ from tools.environments.local import build_subprocess_env
+ env = build_subprocess_env(
+ hermes_subprocess_env(inherit_credentials=True),
+ scrub_secrets=False,
+ inherit_profile_home=False, # base already carries the HOME contract
+ extra={"HERMES_HOME": str(profile_home)} if profile_home else None,
+ )
# start_new_session=True detaches the slash worker into its own
# process group / session. Without this, the worker inherits the
@@ -15752,8 +15758,8 @@ def _(rid, params: dict) -> dict:
# Sanitize env to prevent credential leakage —
# quick commands run in the TUI server process which
# has all API keys in os.environ.
- from tools.environments.local import _sanitize_subprocess_env
- sanitized_env = _sanitize_subprocess_env(os.environ.copy())
+ from tools.environments.local import build_subprocess_env
+ sanitized_env = build_subprocess_env()
from hermes_cli._subprocess_compat import windows_hide_flags
r = subprocess.run(