Skip to content

The agent that grows with you

fix(tools): scope Docker reuse to immutable config

ahamSelb829f2af8c07
diff --git a/tests/tools/test_docker_environment.py b/tests/tools/test_docker_environment.py
index e0940edb6b9..4b0950328ee 100644
--- a/tests/tools/test_docker_environment.py
+++ b/tests/tools/test_docker_environment.py
@@ -1,5 +1,7 @@
import logging
import os
+import re
+from io import StringIO
import subprocess
import pytest
@@ -558,6 +560,37 @@ def test_label_sanitizer_rejects_invalid_characters():
assert len(docker_env._sanitize_label_value(long_value)) == 63
+def test_reuse_environment_fingerprint_tracks_immutable_configuration():
+ """Containers with different images, mounts, or Hermes homes must not
+ share the label used for cross-process reuse."""
+ base = docker_env._reuse_environment_fingerprint(
+ image="python:3.11",
+ mount_args=["-v", "volume-a:/workspace"],
+ hermes_home="/profiles/alpha",
+ )
+
+ assert base == docker_env._reuse_environment_fingerprint(
+ image="python:3.11",
+ mount_args=["-v", "volume-a:/workspace"],
+ hermes_home="/profiles/alpha",
+ )
+ assert base != docker_env._reuse_environment_fingerprint(
+ image="python:3.12",
+ mount_args=["-v", "volume-a:/workspace"],
+ hermes_home="/profiles/alpha",
+ )
+ assert base != docker_env._reuse_environment_fingerprint(
+ image="python:3.11",
+ mount_args=["-v", "volume-b:/workspace"],
+ hermes_home="/profiles/alpha",
+ )
+ assert base != docker_env._reuse_environment_fingerprint(
+ image="python:3.11",
+ mount_args=["-v", "volume-a:/workspace"],
+ hermes_home="/profiles/beta",
+ )
+
+
def test_run_command_sanitizes_unsafe_task_id(monkeypatch):
"""A task_id containing characters Docker rejects in label values must be
sanitized before reaching ``docker run --label``; otherwise the daemon
@@ -678,22 +711,90 @@ def test_sandbox_dir_name_never_resolves_to_the_sandbox_root():
assert not (set(name) & set(':/\\')), name
+def test_labels_attribute_populated_after_init(monkeypatch):
+ """``self._labels`` must be set to the same key/value pairs that went onto
+ docker run, so subsequent reuse / reaper paths can match without re-running
+ the sanitizer or re-importing the profile module."""
+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")
+ monkeypatch.setattr(docker_env, "_get_active_profile_name", lambda: "default")
+ _mock_subprocess_run(monkeypatch)
+ env = _make_dummy_env(task_id="abc")
-def test_shared_container_key_replaces_profile_identity(monkeypatch):
+ labels = dict(env._labels)
+ environment_label = labels.pop("hermes-environment")
+ assert labels == {
+ "hermes-agent": "1",
+ "hermes-task-id": "abc",
+ "hermes-profile": "default",
+ "hermes-egress": "off",
+ }
+ assert re.fullmatch(r"[0-9a-f]{24}", environment_label)
+
+
[email protected]("changed_setting", ["image", "volumes", "hermes_home"])
+def test_reuse_probe_filters_on_environment_fingerprint(monkeypatch, tmp_path, changed_setting):
+ """Reuse and recovery must select the requested configuration, not stale mounts."""
+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")
+ monkeypatch.setattr(docker_env, "_get_active_profile_name", lambda: "default")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "alpha"))
+ # Keep the auto-mounted skills directory present from the first startup.
+ for name in ("alpha", "beta"):
+ (tmp_path / name / "skills").mkdir(parents=True)
+ calls = _mock_subprocess_run(monkeypatch)
+
+ def reuse_filters():
+ return tuple(
+ arg for cmd, _ in calls if isinstance(cmd, list) and cmd[1] == "ps"
+ for arg in cmd if arg.startswith("label=")
+ )
+
+ config = {"image": "python:3.11", "volumes": ["volume-a:/workspace"]}
+ _make_dummy_env(**config)
+ original_filters = reuse_filters()
+ assert original_filters
+ calls.clear()
+ _make_dummy_env(**config)
+ assert reuse_filters() == original_filters
+
+ if changed_setting == "hermes_home":
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "beta"))
+ else:
+ config[changed_setting] = {"image": "python:3.12", "volumes": ["volume-b:/workspace"]}[changed_setting]
+ calls.clear()
+ env = _make_dummy_env(**config)
+ changed_filters = reuse_filters()
+ assert changed_filters != original_filters
+ assert f"label=hermes-environment={env._labels['hermes-environment']}" in changed_filters
+ assert set(f.removeprefix("label=") for f in changed_filters) <= _labels_in_run_args(_run_args_from_calls(calls))
+
+ calls.clear()
+ assert env._recreate_container()
+ assert reuse_filters() == changed_filters
+
+
+def test_shared_container_key_replaces_profile_identity(monkeypatch, tmp_path):
"""Trusted profiles using the same explicit key share the reuse label."""
monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")
monkeypatch.setattr(docker_env, "_get_active_profile_name", lambda: "research")
_mock_subprocess_run(monkeypatch)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "research"))
a = _make_dummy_env(task_id="abc", shared_container_key="team/workspace")
- b = _make_dummy_env(task_id="abc", shared_container_key="team/workspace")
+ monkeypatch.setattr(docker_env, "_get_active_profile_name", lambda: "coding")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "coding"))
+ b = _make_dummy_env(
+ task_id="abc", shared_container_key="team/workspace",
+ image="python:3.12", volumes=["team-volume:/workspace"],
+ )
# Deterministic across processes/profiles, not the profile label, and
# digest-suffixed (label sanitization alone is lossy).
assert a._labels["hermes-profile"] == b._labels["hermes-profile"]
assert a._labels["hermes-profile"] != "research"
assert a._labels["hermes-profile"].startswith("team_workspace-")
+ # Explicit sharing retains the first creator's immutable settings.
+ assert a._labels == b._labels
def test_distinct_shared_keys_never_collide(monkeypatch):
diff --git a/tools/environments/docker.py b/tools/environments/docker.py
index 1cfd06de414..d5896a80f1e 100644
--- a/tools/environments/docker.py
+++ b/tools/environments/docker.py
@@ -21,6 +21,7 @@ import uuid
from pathlib import Path
from typing import Optional
+from hermes_constants import get_hermes_home
from tools.environments.base import BaseEnvironment, EnvironmentConnectionError, _SHELL_ENV_NAME_RE
from tools.terminal_tool_config import (
_host_path_key, _is_windows_drive_path, cwd_follows_host_mount,
@@ -45,6 +46,7 @@ _DOCKER_SEARCH_PATHS = [
_docker_executable: Optional[str] = None # resolved once, cached
_ENV_VAR_NAME_RE = _SHELL_ENV_NAME_RE
+_ENVIRONMENT_LABEL_KEY = "hermes-environment"
def _normalize_forward_env_names(forward_env: list[str] | None) -> list[str]:
@@ -125,6 +127,19 @@ def _container_identity(shared_key: str = "") -> str:
return f"{_sanitize_label_value(shared_key)[:50]}-{digest}"
+def _reuse_environment_fingerprint(*, image: str, mount_args: list[str], hermes_home: str) -> str:
+ """Hash immutable configuration so reuse cannot silently attach to stale mounts.
+
+ Hash requested values rather than exposing profile paths and volume sources in labels.
+ Keep mount order: later arguments can override earlier mount destinations.
+ """
+ normalized_home = os.path.normcase(os.path.abspath(os.path.expanduser(hermes_home)))
+ payload = json.dumps(
+ {"image": image, "mount_args": mount_args, "hermes_home": normalized_home},
+ sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
+
+
def reap_orphan_containers(
*, max_age_seconds: int = 600, profile_filter: str | None = None, docker_exe: str | None = None,
) -> int:
@@ -684,6 +699,12 @@ class DockerEnvironment(BaseEnvironment):
"hermes-task-id": task_label,
"hermes-profile": profile_name,
_EGRESS_LABEL_KEY: egress_label}
+ # Explicit sharing opts into the first creator's settings. Otherwise,
+ # changed image/mount/home configuration must start a fresh container.
+ if not shared_container_key:
+ self._labels[_ENVIRONMENT_LABEL_KEY] = _reuse_environment_fingerprint(
+ image=image, mount_args=[*writable_args, *volume_args],
+ hermes_home=str(get_hermes_home()))
# Saved for container recreation on "No such container" recovery.
self._image = image
self._image_pinned = image_pinned
@@ -1159,7 +1180,8 @@ class DockerEnvironment(BaseEnvironment):
def _find_reusable_container(
self, task_label: str, profile_label: str, egress_label: str) -> Optional[tuple[str, str]]:
"""``(container_id, state)`` of an existing container labeled for this task/profile/
- egress posture, or ``None`` on miss or any failure. The egress posture is a label
+ egress posture and immutable environment, or ``None`` on miss or any failure.
+ Explicit shared keys opt out of the environment filter. The egress posture is a label
FILTER for every posture, "off" included: a container built with egress on must not be
reused after ``hermes egress disable`` (baked-in proxy env and CA mounts), and every
container this class creates carries the label. The ``{{.Label "key"}}`` template
@@ -1169,6 +1191,8 @@ class DockerEnvironment(BaseEnvironment):
"--filter", f"label=hermes-task-id={task_label}",
"--filter", f"label=hermes-profile={profile_label}",
"--filter", f"label={_EGRESS_LABEL_KEY}={egress_label}"]
+ if environment_label := self._labels.get(_ENVIRONMENT_LABEL_KEY):
+ filters.extend(["--filter", f"label={_ENVIRONMENT_LABEL_KEY}={environment_label}"])
result = _docker_query(
[self._docker_exe, "ps", "-a", *filters, "--format", "{{.ID}}\t{{.State}}"], timeout=10,
fail="docker ps probe failed: %s — will start a fresh container",
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index a2061da1de1..41339b38e97 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -403,14 +403,17 @@ terminal:
#### Container lifecycle
-Every Hermes-managed container is tagged with three labels so subsequent processes (and the orphan reaper) can identify it:
+Hermes-managed containers carry labels so subsequent processes (and the orphan reaper) can identify them:
- `hermes-agent=1` — marks it as Hermes-managed
- `hermes-task-id=<sanitized task_id>` — keys the per-task reuse probe
- `hermes-profile=<sanitized profile name>` — scopes reuse and reaping to the active Hermes profile by default; when `docker_shared_container_key` is set, its sanitized value is used instead
+- `hermes-environment=<digest>` — for containers without an explicit shared key, scopes reuse to the requested image, mount arguments, and active `HERMES_HOME`; host paths and volume sources are hashed rather than exposed in this label
On startup, Hermes runs `docker ps --filter label=hermes-task-id=<id> --filter label=hermes-profile=<identity>` and **attaches to the existing container** when it finds one. The identity is the active profile unless `docker_shared_container_key` explicitly opts trusted profiles into a common value. If the container is `exited` (e.g. after a Docker daemon restart), it's `docker start`'d and reused — filesystem state and any installed packages survive, but in-container background processes do not.
+Without an explicit shared key, the reuse probe also requires a matching `hermes-environment` label. Changing the image, mount arguments, or `HERMES_HOME` starts a fresh container instead of silently using another configuration. Containers created before this label was introduced do not match, so the first session after upgrading starts a fresh container; existing running containers are not removed.
+
When a Hermes process exits — `/quit`, closing a TUI session, gateway shutdown, even SIGKILL — the cleanup path is a **no-op for the container in default mode**. The container keeps running. The next Hermes process attaches to it in milliseconds via the label probe. This is the behavior the "one long-lived container shared across sessions" contract requires: it's the only way background processes (npm watchers, dev servers, long-running pytest) survive across sessions.
**The container is only torn down (stopped and `docker rm -f`'d) in these cases:**