The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(checkpoints): do not feed container paths into host checkpoint storage
Sora-bluesky10ee9819f9f9
diff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex bcb75960c8c..515629469e0 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -74,12 +74,23 @@ def _record_persisted_path_for_stub(agent, tool_call_id: str, function_result) -logger.debug("persisted-path record for result stub failed: %s", exc)+def _checkpoint_container_backend(effective_task_id: str) -> Optional[str]:+ """Return the task's backend name when its file paths belong to a container."""+ from tools.file_tools_paths import container_backend_for_task++ return container_backend_for_task(effective_task_id or "default")++def _ensure_file_checkpoint(agent, function_name: str, function_args: dict, effective_task_id: str) -> None:"""Checkpoint the same workspace path that the file tool will mutate, resolved the wayfile tools do (against the task's live cwd, which differs from the process cwd in Docker)."""file_path = function_args.get("path", "")if not file_path:return+ backend = _checkpoint_container_backend(effective_task_id)+ if backend is not None:+ agent._checkpoint_mgr.note_unsupported_backend(backend)+ returnfrom agent.file_safety import is_nt_namespace_pathfrom tools.file_tools_paths import _resolve_path_for_task@@ -980,9 +991,13 @@ def _begin_tool_execution(agent, ref: _ToolCallRef, display_index: int | None) -elif function_name == "terminal":command = function_args.get("command", "")if _is_destructive_command(command):- from agent.runtime_cwd import scope_terminal_cwd- cwd = function_args.get("workdir") or scope_terminal_cwd() or os.getcwd()- agent._checkpoint_mgr.ensure_checkpoint(cwd, f"before terminal: {command[:60]}")+ backend = _checkpoint_container_backend(effective_task_id)+ if backend is not None:+ agent._checkpoint_mgr.note_unsupported_backend(backend)+ else:+ from agent.runtime_cwd import scope_terminal_cwd+ cwd = function_args.get("workdir") or scope_terminal_cwd() or os.getcwd()+ agent._checkpoint_mgr.ensure_checkpoint(cwd, f"before terminal: {command[:60]}")def _emit_tool_complete_and_risk(agent, ref: _ToolCallRef, result, risk_metadata, blocked: bool) -> None:diff --git a/agent/turn_explainers.py b/agent/turn_explainers.pyindex f81faf5c25d..44021620559 100644--- a/agent/turn_explainers.py+++ b/agent/turn_explainers.py@@ -253,9 +253,17 @@ class TurnExplainersMixin:# Hermes-authored content from later user hand-edits.mgr = getattr(self, "_checkpoint_mgr", None)if mgr is not None and getattr(mgr, "enabled", False):- for _p in landed_paths:+ backend = None+ with suppress(Exception):+ from agent.tool_executor import _checkpoint_container_backend+ backend = _checkpoint_container_backend(task_id or "default")+ if backend is not None:with suppress(Exception):- mgr.record_agent_write(_p)+ mgr.note_unsupported_backend(backend)+ else:+ for _p in landed_paths:+ with suppress(Exception):+ mgr.record_agent_write(_p)if is_error and not landed:# Keep the FIRST error per path unless a later success replaces it.preview = _extract_error_preview(result)diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 1569d9268fd..263555085c8 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -632,6 +632,12 @@ class CLICommandsMixin:# --all / --force: classic full restore, overwriting user edits too.restore_all = any(a.lower() in ("--all", "--force") for a in args)args = [a for a in args if a.lower() not in ("--all", "--force")]+ if reason := mgr.unsupported_backend_reason(): # CLI: no session key, the "default" container+ # Container-backed session: any host checkpoint listed here belongs to another tree,+ # so diff/restore are refused; the list stays visible for local administration.+ print(f" {reason}")+ if args:+ returnif not args:# No checkpoints for this dir → cross-project view (writes may sit under the session cwd).checkpoints = mgr.list_checkpoints(cwd)diff --git a/tests/agent/test_tool_executor_checkpoint_paths.py b/tests/agent/test_tool_executor_checkpoint_paths.pyindex 46c28fc3745..343e2e787dc 100644--- a/tests/agent/test_tool_executor_checkpoint_paths.py+++ b/tests/agent/test_tool_executor_checkpoint_paths.py@@ -1,9 +1,36 @@-"""Behavioral coverage for file-tool checkpoint path resolution."""+"""Behavioral coverage for checkpoint path resolution across terminal backends."""+import json+import osfrom types import SimpleNamespace-from agent.tool_executor import _ensure_file_checkpoint+import pytest++from agent.tool_executor import _ToolCallRef, _begin_tool_execution, _ensure_file_checkpoint+from agent.turn_explainers import TurnExplainersMixinfrom tools.checkpoint_manager import CheckpointManager+from tools.terminal_tool import _active_environments, _env_lock+++def manager(tmp_path, monkeypatch):+ monkeypatch.setattr(+ "tools.checkpoint_manager.CHECKPOINT_BASE", tmp_path / "checkpoints"+ )+ return CheckpointManager(enabled=True)+++def container_task_id(monkeypatch):+ class FakeDockerEnvironment:+ pass++ task_id = "container-checkpoint-task"+ with _env_lock:+ monkeypatch.setitem(_active_environments, task_id, FakeDockerEnvironment())+ yield task_id+ with _env_lock:+ _active_environments.pop(task_id, None)def test_relative_file_checkpoint_uses_task_workspace(tmp_path, monkeypatch):@@ -38,3 +65,202 @@ def test_relative_file_checkpoint_uses_task_workspace(tmp_path, monkeypatch):assert manager.list_checkpoints(str(workspace_cwd))assert manager.list_checkpoints(str(process_cwd)) == []+++def _assert_container_skipped(manager):+ assert manager.list_all_checkpoints() == []+ assert manager.unsupported_backend == "docker"+ assert "docker" in manager.unsupported_backend_reason()+++def test_container_backend_file_checkpoint_is_not_taken_on_missing_host_path(+ manager, container_task_id,+):+ agent = SimpleNamespace(_checkpoint_mgr=manager)+ _ensure_file_checkpoint(+ agent, "write_file", {"path": "/workspace/project/a.txt"}, container_task_id+ )+ _assert_container_skipped(manager)++[email protected](os.name == "nt", reason="POSIX absolute container path")+def test_container_backend_file_checkpoint_does_not_snapshot_a_colliding_host_tree(+ tmp_path, manager, container_task_id,+):+ host_dir = tmp_path / "workspace" / "project"+ host_dir.mkdir(parents=True)+ (host_dir / "pyproject.toml").write_text("[project]\n", encoding="utf-8")+ (host_dir / "a.txt").write_text("host content\n", encoding="utf-8")+ _ensure_file_checkpoint(+ SimpleNamespace(_checkpoint_mgr=manager),+ "write_file",+ {"path": str(host_dir / "a.txt")},+ container_task_id,+ )+ assert manager.list_checkpoints(str(host_dir)) == []+ _assert_container_skipped(manager)+++def test_container_backend_destructive_terminal_checkpoint_is_not_taken(+ tmp_path, monkeypatch, manager, container_task_id,+):+ # Pin the host cwd the branch would snapshot on main to a small tree, not the test process cwd.+ host_cwd = tmp_path / "host-cwd"+ host_cwd.mkdir()+ (host_cwd / "keep.txt").write_text("host", encoding="utf-8")+ monkeypatch.setenv("TERMINAL_CWD", str(host_cwd))+ agent = SimpleNamespace(+ quiet_mode=True,+ tool_progress_callback=None,+ tool_start_callback=None,+ _checkpoint_mgr=manager,+ _touch_activity=lambda *_: None,+ )+ ref = _ToolCallRef(+ "terminal",+ {"command": "rm -f /workspace/project/a.txt"},+ container_task_id,+ "call-1",+ [],+ )+ _begin_tool_execution(agent, ref, None)+ _assert_container_skipped(manager)+++def test_container_backend_post_write_ledger_is_not_recorded(+ tmp_path, manager, container_task_id,+):+ # A real host file at the container path's spelling: on main the ledger loop hashes it+ # on the host and persists an entry, which is exactly the false attribution to prevent.+ host_file = tmp_path / "workspace" / "project" / "a.txt"+ host_file.parent.mkdir(parents=True)+ host_file.write_text("after\n", encoding="utf-8")+ path = str(host_file)+ agent = SimpleNamespace(+ _turn_failed_file_mutations={},+ _turn_file_mutation_paths=set(),+ _checkpoint_mgr=manager,+ )+ TurnExplainersMixin._record_file_mutation_result(+ agent,+ "write_file",+ {"path": path, "content": "after\n"},+ json.dumps({"bytes_written": 6, "resolved_path": path}),+ False,+ task_id=container_task_id,+ )+ assert not (tmp_path / "checkpoints" / "store" / "ledgers").exists()+ _assert_container_skipped(manager)+++def test_local_backend_behaviour_unchanged(tmp_path, monkeypatch, manager):+ workspace = tmp_path / "local-project"+ workspace.mkdir()+ (workspace / "pyproject.toml").write_text("[project]\n", encoding="utf-8")+ (workspace / "existing.txt").write_text("before\n", encoding="utf-8")+ monkeypatch.setenv("TERMINAL_ENV", "local")+ monkeypatch.setenv("TERMINAL_CWD", str(workspace))+ _ensure_file_checkpoint(+ SimpleNamespace(_checkpoint_mgr=manager),+ "write_file",+ {"path": "new.txt"},+ "local-checkpoint-task",+ )+ assert manager.list_checkpoints(str(workspace))+++def test_container_session_rollback_restore_is_refused(tmp_path, monkeypatch, manager, container_task_id, capsys):+ """A host checkpoint that predates the container session must not be restored from it."""+ from hermes_cli.cli_commands_mixin import CLICommandsMixin++ host_dir = tmp_path / "workspace" / "project"+ host_dir.mkdir(parents=True)+ (host_dir / "a.txt").write_text("before\n", encoding="utf-8")+ monkeypatch.setenv("TERMINAL_ENV", "docker") # the configured backend, as the product bridges it+ monkeypatch.setenv("TERMINAL_CWD", str(host_dir))+ manager.ensure_checkpoint(str(host_dir), "earlier local session")+ assert manager.list_checkpoints(str(host_dir))+ # Fresh session: no mutation has been observed, so only the backend classification can refuse.++ def refuse(*_args, **_kwargs):+ raise AssertionError("host restore reached from a container-backed session")++ cli = SimpleNamespace(+ _checkpoint_manager=lambda _lines: manager,+ _resolve_checkpoint_ref=lambda ref, cps: cps[int(ref) - 1]["hash"],+ _rollback_restore=refuse,+ _rollback_diff=refuse,+ )+ for command in ("/rollback 1 --all", "/rollback diff 1"):+ CLICommandsMixin._handle_rollback_command(cli, command)+ assert "docker" in capsys.readouterr().out+ assert len(manager.list_checkpoints(str(host_dir))) == 1 # no pre-rollback snapshot either+++def test_container_session_rpc_restore_is_refused(tmp_path, monkeypatch, manager, container_task_id):+ import threading++ from tui_gateway import server++ host_dir = tmp_path / "workspace" / "project"+ host_dir.mkdir(parents=True)+ (host_dir / "a.txt").write_text("before\n", encoding="utf-8")+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ manager.ensure_checkpoint(str(host_dir), "earlier local session")+ session = {+ "agent": SimpleNamespace(_checkpoint_mgr=manager), "cwd": str(host_dir), "running": False,+ "session_key": "container-key", "history": [], "history_lock": threading.Lock(), "history_version": 0,+ }+ monkeypatch.setitem(server._sessions, "container-sid", session)+ resp = server.handle_request(+ {"id": "1", "method": "rollback.restore", "params": {"session_id": "container-sid", "hash": "1"}}+ )+ assert resp["result"]["success"] is False+ assert "docker" in resp["result"]["error"]+ assert len(manager.list_checkpoints(str(host_dir))) == 1+++def test_local_session_rollback_restore_still_dispatches(tmp_path, monkeypatch, manager, capsys):+ """The other direction: a local session with a host checkpoint restores as before."""+ import threading++ from hermes_cli.cli_commands_mixin import CLICommandsMixin+ from tui_gateway import server++ host_dir = tmp_path / "local-project"+ host_dir.mkdir()+ (host_dir / "a.txt").write_text("before", encoding="utf-8")+ monkeypatch.setenv("TERMINAL_ENV", "local")+ monkeypatch.setenv("TERMINAL_CWD", str(host_dir))+ manager.ensure_checkpoint(str(host_dir), "earlier local session")++ calls = []+ cli = SimpleNamespace(+ _checkpoint_manager=lambda _lines: manager,+ _resolve_checkpoint_ref=lambda ref, cps: cps[int(ref) - 1]["hash"],+ _rollback_restore=lambda *args: calls.append(args),+ )+ CLICommandsMixin._handle_rollback_command(cli, "/rollback 1 --all")+ assert len(calls) == 1 and "Checkpoints are not taken" not in capsys.readouterr().out++ session = {+ "agent": SimpleNamespace(_checkpoint_mgr=manager), "cwd": str(host_dir), "running": False,+ "session_key": "local-key", "history": [], "history_lock": threading.Lock(), "history_version": 0,+ }+ monkeypatch.setitem(server._sessions, "local-sid", session)+ resp = server.handle_request(+ {"id": "1", "method": "rollback.restore", "params": {"session_id": "local-sid", "hash": "1"}}+ )+ assert resp["result"]["success"] is True++ # A persistent docker container of the launch profile already occupies the "default" registry+ # slot; this local session must still be classified by its own key, not by that cached env.+ class FakeDockerEnvironment:+ pass++ with _env_lock:+ monkeypatch.setitem(_active_environments, "default", FakeDockerEnvironment())+ resp = server.handle_request(+ {"id": "2", "method": "rollback.restore", "params": {"session_id": "local-sid", "hash": "1"}}+ )+ assert resp["result"]["success"] is Truediff --git a/tools/checkpoint_manager.py b/tools/checkpoint_manager.pyindex 2875148b2d2..f6a4a8a157c 100644--- a/tools/checkpoint_manager.py+++ b/tools/checkpoint_manager.py@@ -603,11 +603,40 @@ class CheckpointManager:max(1, int(max_snapshots)), max(0, int(max_total_size_mb)), max(0, int(max_file_size_mb)))self._checkpointed_dirs: Set[str] = set()self._git_available: Optional[bool] = None # lazy probe+ self.unsupported_backend: Optional[str] = Nonedef new_turn(self) -> None:"""Reset per-turn dedup. Call at the start of each agent iteration."""self._checkpointed_dirs.clear()+ def note_unsupported_backend(self, backend: str) -> None:+ """Remember the first backend whose paths cannot be checkpointed. Never raises."""+ try:+ if self.unsupported_backend is None:+ self.unsupported_backend = backend+ logger.debug("Checkpoints skipped for container backend: %s", backend)+ except Exception:+ pass++ def unsupported_backend_reason(self, task_id: str = "default") -> Optional[str]:+ """Explain why host checkpoints are off limits for a container-backed session.++ Classifies the task's backend directly so /rollback is refused before the first+ mutation is observed; the recorded backend, when set, is the same answer."""+ backend = self.unsupported_backend+ if backend is None:+ try:+ from tools.file_tools_paths import container_backend_for_task+ backend = container_backend_for_task(task_id)+ except Exception:+ backend = None+ if backend is None:+ return None+ return (+ f"Checkpoints are not taken for terminal.backend={backend}: "+ "file paths belong to the container, not this host."+ )+# --- public API ---def record_agent_write(self, file_path: str) -> None:diff --git a/tools/file_tools_paths.py b/tools/file_tools_paths.pyindex e1cde504270..45bc5ad434f 100644--- a/tools/file_tools_paths.py+++ b/tools/file_tools_paths.py@@ -72,6 +72,11 @@ def _uses_container_paths(task_id: str = "default") -> bool:return env_type in _CONTAINER_PATH_BACKENDS_FALLBACK+def container_backend_for_task(task_id: str = "default") -> str | None:+ """The task's backend name when its file paths belong to a container, else None."""+ return _terminal_env_type_for_task(task_id) if _uses_container_paths(task_id) else None++def _normalize_without_host_deref(path: str | Path | PurePosixPath) -> PurePosixPath:"""Normalize path syntax without following host symlinks: container paths aremeaningful inside the sandbox, and a host-side ``/workspace`` symlink must not rewrite them."""diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex cd54fedb552..4c1e6480fc0 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -966,6 +966,20 @@ def _(rid, params: dict, session) -> dict:return _err(rid, 4009, busy_message("rollback restore"))def go(mgr, cwd):+ # Container-backed session: the host checkpoints listed are not this session's tree. Classify+ # with the identity and scopes a turn binds (prompt_turn.py): the session key is the tool-call+ # task id, the session context drives the terminal registry lookup, and the profile scope+ # supplies the terminal policy; otherwise a cached launch-profile environment or the launch+ # config would answer for another profile's session.+ task_id = session.get("session_key") or "default"+ tokens = _set_session_context(task_id, cwd=cwd)+ try:+ with _session_profile_runtime_scope(session):+ reason = getattr(mgr, "unsupported_backend_reason", lambda *_: None)(task_id)+ finally:+ _clear_session_context(tokens)+ if reason:+ return {"success": False, "error": reason}result = mgr.restore(cwd, _resolve_checkpoint_hash(mgr, cwd, target), file_path=file_path or None)if result.get("success") and not file_path:removed = 0diff --git a/website/docs/user-guide/checkpoints-and-rollback.md b/website/docs/user-guide/checkpoints-and-rollback.mdindex a0433750fdd..512157bd1e1 100644--- a/website/docs/user-guide/checkpoints-and-rollback.md+++ b/website/docs/user-guide/checkpoints-and-rollback.md@@ -234,6 +234,10 @@ Restore just one file from a checkpoint without affecting the rest of the direct## Safety and Performance Guards+### Container Backends++With a container terminal backend (`docker`, `singularity`, `modal`, `daytona`, `vercel_sandbox`, or a container plugin), file paths belong to the sandbox rather than the host. Hermes therefore does not take checkpoints or record the agent-write ledger for those paths, and `/rollback` explains the limitation; local and SSH backends are unaffected.+- **Git availability** — if `git` is not found on `PATH`, checkpoints are transparently disabled.- **Directory scope** — Hermes skips overly broad directories (root `/`, home `$HOME`).- **Repository size** — directories with more than 50,000 files are skipped.