The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): file tools name an invalid terminal.cwd; trim live-env cwd tests to invariants
teknium1e85e5addf445
diff --git a/tests/tools/test_file_ops_cwd_tracking.py b/tests/tools/test_file_ops_cwd_tracking.pyindex 53ea596b771..ef5c41bd0af 100644--- a/tests/tools/test_file_ops_cwd_tracking.py+++ b/tests/tools/test_file_ops_cwd_tracking.py@@ -106,6 +106,32 @@ class TestShellFileOpsCwdTracking:assert result.exit_code == 0assert "fixed-content" in result.stdout+ def test_wrapper_cd_failure_names_the_invalid_working_directory(self, tmp_path):+ """When the backend's own ``builtin cd -- <cwd> || exit 126`` fails (a+ host ``terminal.cwd`` inside a container, #113894) the surfaced error+ must name the working directory / ``terminal.cwd`` problem, not just+ the raw ``cd:`` line that reads like a fault at the requested path."""+ host_cwd = r"C:\Users\rashi\OneDrive\Documents\ai_workspace"++ class _WrapperEnv:+ cwd = host_cwd++ def execute(self, command, cwd=None, **kwargs):+ import shlex+ import subprocess+ script = f"builtin cd -- {shlex.quote(cwd)} || exit 126\n{command}"+ proc = subprocess.run(["bash", "-c", script], capture_output=True, text=True,+ input=kwargs.get("stdin_data"))+ return {"output": proc.stdout + proc.stderr, "returncode": proc.returncode}++ ops = ShellFileOperations(_WrapperEnv())+ result = ops.write_file(str(tmp_path / "probe.py"), "print('hi')\n")++ assert result.error is not None+ assert "terminal.cwd" in result.error and host_cwd in result.error+ assert "No such file or directory" in result.error # the shell's own line is kept+ assert not (tmp_path / "probe.py").exists()+def test_patch_returns_success_only_when_file_actually_written(self, tmp_path):"""Safety rail: patch_replace success must reflect the real file state.diff --git a/tests/tools/test_live_env_cwd_override_sanitize.py b/tests/tools/test_live_env_cwd_override_sanitize.pyindex 800a63151bd..507990aaa9a 100644--- a/tests/tools/test_live_env_cwd_override_sanitize.py+++ b/tests/tools/test_live_env_cwd_override_sanitize.py@@ -1,4 +1,4 @@-"""Regression tests for cwd-override sanitization on LIVE cached envs.+"""Invariants for cwd overrides written into LIVE cached envs (#113894, #98723).``register_task_env_overrides`` applies a ``cwd`` override to the cached liveenvironment directly. On container backends a raw host path (a desktop/TUI@@ -6,8 +6,6 @@ session registering its workspace) can never be the in-sandbox workdir: everyfile-tools ``_exec`` wrapper does ``builtin cd -- <env.cwd> || exit 126``, so ahost cwd poisoned all later file operations with an unrelated ``cd:`` errorwhile terminal commands kept working (their per-command resolver sanitizes).-These tests pin the live-env write so a host cwd is either remapped to the-in-container view of the same mounted directory or not applied at all."""import pytest@@ -34,94 +32,33 @@ def _clean_state(monkeypatch):monkeypatch.setattr(tt, "_container_aliases", {})-class TestLiveEnvCwdSanitized:- def test_windows_host_cwd_not_applied_to_docker_env(self):- # The reported bug: a desktop session registers its Windows workspace,- # env.cwd becomes C:\... and every file op dies on `cd: C:\...`.- env = _FakeEnv("docker", "/workspace")- tt._active_environments["default"] = env- tt.register_task_env_overrides(- "default", {"cwd": r"C:\Users\rashi\ai_workspace"}- )- assert env.cwd == "/workspace"-- def test_posix_host_cwd_not_applied_to_docker_env(self):- env = _FakeEnv("docker", "/root")- tt._active_environments["default"] = env- tt.register_task_env_overrides("default", {"cwd": "/Users/me/workspace"})- assert env.cwd == "/root"-- def test_mounted_host_cwd_remaps_to_workspace(self):- # Docker cwd passthrough: the host dir IS mounted at /workspace, so the- # session's directory stays reachable — remap instead of discarding.- env = _FakeEnv("docker", "/workspace", host_cwd="/Users/me/ws")- tt._active_environments["default"] = env- tt.register_task_env_overrides("default", {"cwd": "/Users/me/ws"})- assert env.cwd == "/workspace"-- def test_mounted_windows_host_cwd_remaps_to_workspace(self):- # The exact reported shape: a Windows host cwd with docker cwd- # passthrough mounted at /workspace.- env = _FakeEnv("docker", "/workspace", host_cwd=r"C:\Users\rashi\ai_workspace")- tt._active_environments["default"] = env- tt.register_task_env_overrides(- "default", {"cwd": r"C:\Users\rashi\ai_workspace"}- )- assert env.cwd == "/workspace"-- def test_host_cwd_not_applied_on_singularity(self):- env = _FakeEnv("singularity", "/root")- tt._active_environments["default"] = env- tt.register_task_env_overrides("default", {"cwd": "/Users/me/workspace"})- assert env.cwd == "/root"-- def test_in_container_override_applied_verbatim(self):- env = _FakeEnv("docker", "/root")- tt._active_environments["default"] = env- tt.register_task_env_overrides("default", {"cwd": "/workspace/task42"})- assert env.cwd == "/workspace/task42"-- def test_local_env_applies_override_verbatim(self):- # Non-container backends must keep applying overrides raw: ACP- # session/load project-root switching relies on it.- env = _FakeEnv("local", "/start")- tt._active_environments["default"] = env- tt.register_task_env_overrides("default", {"cwd": "/proj/two"})- assert env.cwd == "/proj/two"-- def test_session_record_keeps_raw_host_path(self):- # The record is the tracking surface for host workspaces; only the- # live-env write is sanitized.- tt.register_task_env_overrides("default", {"cwd": "/Users/me/workspace"})- assert tt.get_session_cwd("default") == "/Users/me/workspace"-- def test_env_found_under_collapsed_container_id(self):- # CWD-only overrides collapse to "default": the env may be cached under- # the collapsed key, not the raw task id.- env = _FakeEnv("docker", "/workspace")- tt._active_environments["default"] = env- tt.register_task_env_overrides(- "sess-abc", {"cwd": r"C:\Users\rashi\ai_workspace"}- )- assert env.cwd == "/workspace"---class TestSanitizerUnit:- def test_none_env_type_returns_cwd(self):- # Env without the backend tag (pre-existing instances, __slots__ plugin- # providers): do not guess, apply verbatim like before the tag existed.- env = _FakeEnv(None, "/root")- assert tt._sanitize_cwd_for_live_env(env, "/any/path") == "/any/path"-- def test_docker_env_mounted_remap(self, monkeypatch):- monkeypatch.setattr("os.path.isdir", lambda p: True)- env = _FakeEnv("docker", "/workspace", host_cwd="/Users/me/ws")- assert tt._sanitize_cwd_for_live_env(env, "/Users/me/ws") == "/workspace"-- def test_docker_env_unmounted_host_path_returns_none(self):- env = _FakeEnv("docker", "/root", host_cwd=None)- assert tt._sanitize_cwd_for_live_env(env, "/Users/me/ws") is None-- def test_relative_cwd_not_applied_to_docker_env(self):- env = _FakeEnv("docker", "/root")- assert tt._sanitize_cwd_for_live_env(env, "relative/dir") is None+WIN_WS = r"C:\Users\rashi\ai_workspace"+++ "env_type, host_cwd, override, expected_live_cwd",+ [+ # Reported shape: docker cwd passthrough, the host dir IS the one mounted+ # at /workspace -> remap to the in-container view of the same directory.+ ("docker", WIN_WS, WIN_WS, "/workspace"),+ # Host path that is not mounted anywhere: leave the live env untouched.+ ("docker", None, WIN_WS, "/root"),+ ("singularity", None, "/Users/me/workspace", "/root"),+ # In-sandbox override (ACP project switch) still applies on a container.+ ("docker", None, "/workspace/task42", "/workspace/task42"),+ # Non-container backends apply the override verbatim.+ ("local", None, "/proj/two", "/proj/two"),+ ],+)+def test_live_env_cwd_write_is_sanitized_for_container_backends(+ env_type, host_cwd, override, expected_live_cwd+):+ env = _FakeEnv(env_type, "/root", host_cwd=host_cwd)+ # CWD-only overrides collapse to "default": the env is cached under the+ # collapsed key, not the raw task id.+ tt._active_environments["default"] = env+ tt.register_task_env_overrides("sess-abc", {"cwd": override})+ assert env.cwd == expected_live_cwd+ # The session record keeps the RAW path: host-side surfaces track the+ # workspace there and its readers already guard container use.+ assert tt.get_session_cwd("sess-abc") == overridediff --git a/tools/file_operations.py b/tools/file_operations.pyindex 97b951c56f2..f733d02dedb 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -201,11 +201,20 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):effective_cwd = cwd or getattr(self.env, 'cwd', None) or self.cwdresult = self.env.execute(command, cwd=effective_cwd, **kwargs)exit_code = result.get("returncode", 0)+ output = result.get("output", "")+ # The command wrapper's own ``builtin cd -- <cwd> || exit 126`` failed: the+ # working directory does not exist on this backend (typically ``terminal.cwd``+ # is a host path and the backend is a container). Name that, or the raw+ # ``cd:`` line reads like a sandbox/mount fault at the requested path.+ if exit_code == 126 and "cd: " in output:+ output = (f"working directory {effective_cwd!r} does not exist on the active "+ f"terminal backend; terminal.cwd is not valid for this backend "+ f"(for docker use a path inside the container, e.g. /workspace). {output.strip()}")# A stdin write failure with a clean child exit is still a failure: the# child never received the input.if result.get("stdin_error") and exit_code == 0:exit_code = 1- return ExecuteResult(stdout=result.get("output", ""), exit_code=exit_code)+ return ExecuteResult(stdout=output, exit_code=exit_code)def _has_command(self, cmd: str) -> bool:"""Check if a command exists in the environment (cached); rg goes throughdiff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex c6ae5ce1989..11aa5062b9d 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -708,6 +708,8 @@ Security tradeoff:Use the opt-in only when you intentionally want the container to work on live host files.+A host path in `terminal.cwd` (for example `C:\Users\me\project` on Windows, or a desktop/TUI session's workspace) never becomes the container's working directory: when it is the directory mounted at `/workspace`, file tools and terminal commands use `/workspace`; otherwise the container keeps its own working directory. If a file tool still cannot enter its working directory, the error names the invalid `terminal.cwd` for the active backend rather than the shell's raw `cd:` line.+### Persistent ShellBy default, each terminal command runs in its own subprocess — working directory, environment variables, and shell variables reset between commands. When **persistent shell** is enabled, a single long-lived bash process is kept alive across `execute()` calls so that state survives between commands.