The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(docker): keep per-process temp mounts out of the reuse fingerprint
Brooklyn Nicholson80aab939c8b8
diff --git a/tests/tools/test_docker_environment.py b/tests/tools/test_docker_environment.pyindex 4b0950328ee..991f5604659 100644--- a/tests/tools/test_docker_environment.py+++ b/tests/tools/test_docker_environment.py@@ -3,6 +3,7 @@ import osimport refrom io import StringIOimport subprocess+import tempfileimport pytest@@ -591,6 +592,37 @@ def test_reuse_environment_fingerprint_tracks_immutable_configuration():)+def test_reuse_environment_fingerprint_ignores_volatile_temp_mounts(tmp_path, monkeypatch):+ """A mount whose host source is a per-process tempdir must not churn the+ reuse label: symlinked skills trees are served from a fresh mkdtemp copy+ every process (``_safe_skills_path``), so hashing that path made the+ label differ across processes and container reuse never matched."""+ temp_root = tmp_path / "tmp"+ temp_root.mkdir()+ monkeypatch.setattr(docker_env.tempfile, "gettempdir", lambda: str(temp_root))+ stable_source = str(tmp_path / "data")+ process_a = docker_env._reuse_environment_fingerprint(+ image="python:3.11",+ mount_args=["-v", f"{temp_root}/hermes-skills-safe-a1b2c3:/root/.hermes/skills:ro",+ "-v", f"{stable_source}:/data:ro"],+ hermes_home="/profiles/alpha",+ )+ process_b = docker_env._reuse_environment_fingerprint(+ image="python:3.11",+ mount_args=["-v", f"{temp_root}/hermes-skills-safe-d4e5f6:/root/.hermes/skills:ro",+ "-v", f"{stable_source}:/data:ro"],+ hermes_home="/profiles/alpha",+ )+ assert process_a == process_b+ # A real mount change still forces a fresh container.+ assert process_a != docker_env._reuse_environment_fingerprint(+ image="python:3.11",+ mount_args=["-v", f"{temp_root}/hermes-skills-safe-a1b2c3:/root/.hermes/skills:ro",+ "-v", f"{tmp_path}/other-data:/data:ro"],+ hermes_home="/profiles/alpha",+ )++def test_run_command_sanitizes_unsafe_task_id(monkeypatch):"""A task_id containing characters Docker rejects in label values must besanitized before reaching ``docker run --label``; otherwise the daemon@@ -711,6 +743,41 @@ def test_sandbox_dir_name_never_resolves_to_the_sandbox_root():assert not (set(name) & set(':/\\')), name[email protected]_symlinks+def test_symlinked_skills_tree_reuses_container_across_processes(monkeypatch, tmp_path):+ """A symlink under ``skills/`` makes the skills mount a fresh mkdtemp copy per+ process (and even per DockerEnvironment construction — ``_safe_skills_path``+ rmtree+mkdtemps on every call). The reuse label must stay stable anyway, or+ the persistent container is never reused and users silently lose the+ installed packages / filesystem state of their long-lived sandbox."""+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ monkeypatch.setattr(docker_env, "_get_active_profile_name", lambda: "default")+ hermes_home = tmp_path / "alpha"+ skills_dir = hermes_home / "skills"+ (skills_dir / "some-skill").mkdir(parents=True)+ (skills_dir / "some-skill" / "SKILL.md").write_text("# skill")+ (skills_dir / "link").symlink_to(tmp_path / "outside") # forces the safe-copy path+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ _mock_subprocess_run(monkeypatch)++ config = {"image": "python:3.11", "volumes": ["volume-a:/workspace"]}+ first = _make_dummy_env(**config)+ second = _make_dummy_env(**config)+ assert first._labels["hermes-environment"] == second._labels["hermes-environment"]+ # The safe copy really is per-construction volatile: proof the stability above+ # comes from canonicalization, not from the mount happening to be stable.+ mounts = []+ for entry in docker_env._readonly_skill_mount_args():+ if entry not in ("-v",) and ":/root/.hermes/skills" in entry:+ mounts.append(entry)+ assert mounts, "expected a skills mount from the symlink-safe copy"++ # A real (non-tempdir) mount change must still start a fresh container.+ changed = dict(config, volumes=["volume-b:/workspace"])+ third = _make_dummy_env(**changed)+ assert third._labels["hermes-environment"] != first._labels["hermes-environment"]++def test_labels_attribute_populated_after_init(monkeypatch):"""``self._labels`` must be set to the same key/value pairs that went ontodocker run, so subsequent reuse / reaper paths can match without re-runningdiff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex d5896a80f1e..aec68cd58a7 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -15,6 +15,7 @@ import shleximport shutilimport subprocessimport sys+import tempfileimport threadingimport timeimport uuid@@ -127,15 +128,48 @@ def _container_identity(shared_key: str = "") -> str:return f"{_sanitize_label_value(shared_key)[:50]}-{digest}"+def _is_volatile_mount_spec(spec: str) -> bool:+ """True when *spec* is a ``host:container[:mode]`` mount whose host source is a+ per-process tempdir (a ``mkdtemp`` under the system temp), so its path is random+ per process and must not be hashed into the reuse label.++ The known source is the symlink-safe skills copy from+ ``credential_files._safe_skills_path``: any symlink under ``skills/`` makes it a+ fresh ``mkdtemp`` per process. Stable host paths — including a symlink-free+ skills dir, which mounts directly — never sit under the process tempdir.+ """+ if spec in ("-v", "--mount") or ":" not in spec:+ return False # the flag element itself, or a non-bind arg (tmpfs modes etc.)+ parsed = _split_volume_spec(spec)+ source = parsed[0] if parsed is not None else spec.split(":", 1)[0]+ if _is_windows_drive_path(source):+ return False # drive-letter hosts can never be the POSIX process tempdir+ try:+ temp_root = os.path.realpath(tempfile.gettempdir())+ source_abs = os.path.realpath(os.path.abspath(os.path.expanduser(source)))+ return source_abs == temp_root or source_abs.startswith(temp_root + os.sep)+ except OSError: # unreadable source — treat as stable, fail the safe way+ return False++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.+ Per-process tempdir-sourced mounts (the symlink-safe skills copy) have their volatile+ host path replaced by a stable placeholder: the path is random per process, so hashing+ it made the label differ across processes and cross-process container reuse never+ matched for users with any symlink under ``skills/``. The container path stays in the+ hash, so moving where that mount lands still forces a fresh container."""normalized_home = os.path.normcase(os.path.abspath(os.path.expanduser(hermes_home)))+ canonical_mounts = [+ (f"<volatile-tempdir-mount>:{spec.split(':', 1)[1]}"+ if _is_volatile_mount_spec(spec) else spec)+ for spec in mount_args]payload = json.dumps(- {"image": image, "mount_args": mount_args, "hermes_home": normalized_home},+ {"image": image, "mount_args": canonical_mounts, "hermes_home": normalized_home},sort_keys=True, separators=(",", ":"))return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 41339b38e97..49663af2983 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -408,7 +408,7 @@ Hermes-managed containers carry labels so subsequent processes (and the orphan r- `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+- `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. Per-process tempdir-sourced mounts (the symlink-safe skills copy) are hashed by their stable container path, not the random host tempdir, so they don't defeat reuseOn 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.