Skip to content

The agent that grows with you

fix(tools): surface a bad working directory on every file-tool read path (#98723)

teknium110433003ec49
diff --git a/tests/tools/test_file_operations_edge_cases.py b/tests/tools/test_file_operations_edge_cases.py
index 566be82799d..2a389ef2f0a 100644
--- a/tests/tools/test_file_operations_edge_cases.py
+++ b/tests/tools/test_file_operations_edge_cases.py
@@ -9,6 +9,7 @@ import pytest
from unittest.mock import MagicMock, patch
from tests.tools.file_ops_fakes import READ_SENTINEL_RE, compound_read_output
+from tools.file_operations_common import ExecuteResult
from tools.file_operations import ShellFileOperations
from tools.file_operations_search import _parse_search_context_line
@@ -235,11 +236,12 @@ class TestPaginationBounds:
def fake_exec(command, *args, **kwargs):
commands.append(command)
+ # Real result type: a MagicMock's auto-attribute ``cwd_error`` is truthy.
if command.startswith("test -e"):
- return MagicMock(exit_code=0, stdout="exists")
+ return ExecuteResult(exit_code=0, stdout="exists")
if "--files" in command:
- return MagicMock(exit_code=0, stdout="a.py\n")
- return MagicMock(exit_code=0, stdout="")
+ return ExecuteResult(exit_code=0, stdout="a.py\n")
+ return ExecuteResult(exit_code=0, stdout="")
with patch.object(ops, "_has_command", side_effect=lambda cmd: cmd == "rg"), \
patch.object(ops, "_exec", side_effect=fake_exec):
diff --git a/tests/tools/test_file_ops_cwd_tracking.py b/tests/tools/test_file_ops_cwd_tracking.py
index ef5c41bd0af..759ce92f0ed 100644
--- a/tests/tools/test_file_ops_cwd_tracking.py
+++ b/tests/tools/test_file_ops_cwd_tracking.py
@@ -17,6 +17,7 @@ Fix: _exec() now prefers the LIVE ``env.cwd`` over the init-time
from __future__ import annotations
+import pytest
from tools.file_operations import ShellFileOperations
@@ -58,6 +59,24 @@ class _FakeEnv:
}
+class _WrapperEnv:
+ """Backend whose command wrapper does ``builtin cd -- <cwd> || exit 126`` (the
+ real terminal backends' shape), so a bad cwd kills every command before it runs."""
+
+ def __init__(self, cwd, env_type=None):
+ self.cwd = cwd
+ if env_type:
+ self.env_type = env_type
+
+ 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, encoding="utf-8",
+ input=kwargs.get("stdin_data"))
+ return {"output": proc.stdout + proc.stderr, "returncode": proc.returncode}
+
+
class TestShellFileOpsCwdTracking:
"""_exec() must use live env.cwd, not the init-time cached cwd."""
@@ -66,8 +85,8 @@ class TestShellFileOpsCwdTracking:
dir_b = tmp_path / "b"
dir_a.mkdir()
dir_b.mkdir()
- (dir_a / "target.txt").write_text("content-a\n")
- (dir_b / "target.txt").write_text("content-b\n")
+ (dir_a / "target.txt").write_text("content-a\n", encoding="utf-8")
+ (dir_b / "target.txt").write_text("content-b\n", encoding="utf-8")
env = _FakeEnv(start_cwd=str(dir_a))
ops = ShellFileOperations(env, cwd=str(dir_a))
@@ -91,7 +110,7 @@ class TestShellFileOpsCwdTracking:
"""Backends without a cwd attribute still work via init-time cwd."""
dir_a = tmp_path / "fixed"
dir_a.mkdir()
- (dir_a / "target.txt").write_text("fixed-content\n")
+ (dir_a / "target.txt").write_text("fixed-content\n", encoding="utf-8")
class _NoCwdEnv:
def execute(self, command, cwd=None, **kwargs):
@@ -112,19 +131,7 @@ class TestShellFileOpsCwdTracking:
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())
+ ops = ShellFileOperations(_WrapperEnv(host_cwd))
result = ops.write_file(str(tmp_path / "probe.py"), "print('hi')\n")
assert result.error is not None
@@ -132,6 +139,35 @@ class TestShellFileOpsCwdTracking:
assert "No such file or directory" in result.error # the shell's own line is kept
assert not (tmp_path / "probe.py").exists()
+ @pytest.mark.parametrize("op", ["read_file", "read_file_raw", "read_file_bytes", "patch", "search"])
+ def test_wrapper_cd_failure_is_reported_as_such_on_every_read_path(self, tmp_path, op):
+ """#98723: a wrapper-level failure must be reported as what it is on the
+ paths that do NOT embed stdout (stat-probe reads, patch pre-image, search),
+ never as 'environment unavailable' / 'file not found' / 'rg or find missing';
+ and no ``_has_command`` verdict may be cached from a probe that never ran."""
+ target = tmp_path / "t.txt"
+ target.write_text("hello\n", encoding="utf-8")
+ ops = ShellFileOperations(_WrapperEnv("/Users/nobody/ws"))
+ result = {
+ "read_file": lambda: ops.read_file(str(target)),
+ "read_file_raw": lambda: ops.read_file_raw(str(target)),
+ "read_file_bytes": lambda: ops.read_file_bytes(str(target)),
+ "patch": lambda: ops.patch_replace(str(target), "hello", "bye"),
+ "search": lambda: ops.search("t*", str(tmp_path), target="files"),
+ }[op]()
+ assert "/Users/nobody/ws" in result.error and "No such file or directory" in result.error
+ assert "unavailable" not in result.error and "requires" not in result.error
+ assert ops._has_command("find") is False
+ assert ops._command_cache == {} # a later valid cwd must re-probe
+
+ def test_container_hint_only_for_container_backends(self, tmp_path):
+ """The in-container path hint misdirects on local/ssh backends (the cwd may
+ be an explicit arg, a session ``cd`` or a deleted directory)."""
+ local = ShellFileOperations(_WrapperEnv("/nope/local", env_type="local")).read_file_raw("/x")
+ docker = ShellFileOperations(_WrapperEnv("/nope/docker", env_type="docker")).read_file_raw("/x")
+ assert "/workspace" not in local.error
+ assert "/workspace" in docker.error
+
def test_patch_returns_success_only_when_file_actually_written(self, tmp_path):
"""Safety rail: patch_replace success must reflect the real file state.
@@ -142,7 +178,7 @@ class TestShellFileOpsCwdTracking:
this test catches it.
"""
target = tmp_path / "file.txt"
- target.write_text("old content\n")
+ target.write_text("old content\n", encoding="utf-8")
env = _FakeEnv(start_cwd=str(tmp_path))
ops = ShellFileOperations(env, cwd=str(tmp_path))
@@ -150,6 +186,6 @@ class TestShellFileOpsCwdTracking:
result = ops.patch_replace(str(target), "old content\n", "new content\n")
assert result.success is True
assert result.error is None
- assert target.read_text() == "new content\n", (
+ assert target.read_text(encoding="utf-8") == "new content\n", (
"patch_replace claimed success but file wasn't written correctly"
)
diff --git a/tests/tools/test_live_env_cwd_override_sanitize.py b/tests/tools/test_live_env_cwd_override_sanitize.py
index 507990aaa9a..14637a04f68 100644
--- a/tests/tools/test_live_env_cwd_override_sanitize.py
+++ b/tests/tools/test_live_env_cwd_override_sanitize.py
@@ -62,3 +62,21 @@ def test_live_env_cwd_write_is_sanitized_for_container_backends(
# 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") == override
+
+
+def test_real_builders_tag_env_type_and_record_host_cwd(tmp_path):
+ """The sanitizer reads ``env_type``/``host_cwd`` off the live instance, so the
+ producers must actually set them: ``_create_environment`` tags the backend and
+ ``DockerEnvironment._mount_args`` records the host dir bound at /workspace."""
+ import os
+
+ from tools.environments.docker import DockerEnvironment
+ from tools.terminal_tool_backends import _create_environment
+
+ assert _create_environment("local", image="", cwd=str(tmp_path), timeout=5).env_type == "local"
+ docker = object.__new__(DockerEnvironment) # _mount_args needs no docker daemon
+ docker._persistent = False
+ DockerEnvironment._mount_args(docker, [], str(tmp_path), True, "t")
+ assert docker.host_cwd == os.path.abspath(str(tmp_path))
+ DockerEnvironment._mount_args(docker, [], str(tmp_path / "gone"), True, "t")
+ assert docker.host_cwd is None
diff --git a/tools/file_operations.py b/tools/file_operations.py
index f733d02dedb..379f5dda115 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -206,15 +206,20 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
# 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.
+ cwd_error = ""
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()}")
+ from tools.terminal_tool_config import _is_container_backend
+ env_type = getattr(self.env, "env_type", None)
+ hint = ("; for container backends use a path inside the container, e.g. /workspace"
+ if env_type and _is_container_backend(env_type) else "")
+ cwd_error = output = (
+ f"working directory {effective_cwd!r} does not exist on the active terminal "
+ f"backend (check terminal.cwd or the session cwd{hint}). {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=output, exit_code=exit_code)
+ return ExecuteResult(stdout=output, exit_code=exit_code, cwd_error=cwd_error)
def _has_command(self, cmd: str) -> bool:
"""Check if a command exists in the environment (cached); rg goes through
@@ -223,6 +228,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
return self._resolve_command(cmd) is not None
if cmd not in self._command_cache:
result = self._exec(f"command -v {cmd} >/dev/null 2>&1 && echo 'yes'")
+ if result.cwd_error: # the probe never ran: no verdict to cache
+ return False
self._command_cache[cmd] = result.stdout.strip() == 'yes'
return self._command_cache[cmd]
@@ -452,7 +459,9 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
def _probe_regular_file(self, path: str) -> tuple[int, str]:
"""Byte size of a REGULAR file: ``(file_size, status)`` with status ``"ok"``,
- ``"missing"``, ``"not_regular"`` or ``"bad_size"`` (unparseable ``wc``).
+ ``"missing"``, ``"not_regular"``, ``"bad_size"`` (unparseable ``wc``),
+ ``"env_unavailable"``, or the named working-directory error when the exec
+ wrapper itself failed (``_env_unavailable_error`` surfaces it verbatim).
``wc -c <`` on a writer-less FIFO/socket//dev/zero blocks forever and a
name-based blocklist can't cover a FIFO (a file TYPE at any path); ``[ -f ]``
is a stat (symlinks followed) so it answers without touching content."""
@@ -470,13 +479,15 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
if stat_output == NOT_REGULAR_SENTINEL:
return 0, "not_regular"
if stat_result.exit_code != 0:
- return 0, "env_unavailable"
+ return 0, stat_result.cwd_error or "env_unavailable"
try:
return int(stat_output), "ok"
except ValueError:
return 0, "bad_size"
- def _env_unavailable_error(self, path: str) -> ReadResult:
+ def _env_unavailable_error(self, path: str, status: str = "env_unavailable") -> ReadResult:
+ if status != "env_unavailable":
+ return ReadResult(error=status)
return ReadResult(error=(f"Terminal environment unavailable: could not stat {path} "
"(the sandbox may still be starting or was removed). Retry shortly."))
@@ -837,8 +848,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
return self._read_file_missing(path, offset, limit)
if status == "not_regular":
return self._not_regular_error(path)
- if status == "env_unavailable":
- return self._env_unavailable_error(path)
+ if status not in ("ok", "bad_size"):
+ return self._env_unavailable_error(path, status)
if self._is_image(path): # never inlined — redirect to the vision tool
return self._image_redirect_result(file_size)
is_binary, sample_bytes = self._detect_binary(path)
@@ -997,8 +1008,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
return self._suggest_similar_files(path)
if status == "not_regular":
return self._not_regular_error(path)
- if status == "env_unavailable":
- return self._env_unavailable_error(path)
+ if status not in ("ok", "bad_size"):
+ return self._env_unavailable_error(path, status)
if self._is_image(path):
return ReadResult(is_image=True, is_binary=True, file_size=file_size)
is_binary, sample_bytes = self._detect_binary(path)
@@ -1020,8 +1031,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
return ReadResult(error=f"File not found: {path}")
if status == "not_regular":
return self._not_regular_error(path)
- if status == "env_unavailable":
- return self._env_unavailable_error(path)
+ if status not in ("ok", "bad_size"):
+ return self._env_unavailable_error(path, status)
if status == "bad_size":
return ReadResult(error=f"Could not determine file size: {path}")
if max_bytes is not None and file_size > max_bytes:
@@ -1340,7 +1351,7 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
return PatchResult(error=denied)
read_result = self._cat(path)
if read_result.exit_code != 0:
- return PatchResult(error=f"Failed to read file: {path}")
+ return PatchResult(error=read_result.cwd_error or f"Failed to read file: {path}")
# Match and diff on BOM-stripped content (a phantom U+FEFF defeats an exact
# first-line match); the raw read becomes write_file's pre_content.
raw_content = read_result.stdout
@@ -1394,7 +1405,10 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
error=(f"Invalid file search order {order!r}; expected "
"'discovery' or 'modified'."))
path = self._expand_path(path)
- exists_probe = self._path_exists_probe(path)
+ probe = self._path_exists_probe(path)
+ exists_probe = probe.stdout
+ if probe.cwd_error:
+ return SearchResult(error=probe.cwd_error)
if "exists" not in exists_probe and "not_found" not in exists_probe:
return SearchResult(error=(f"Terminal environment unavailable: could not stat {path} "
"(the sandbox may still be starting or was removed). Retry shortly."))
diff --git a/tools/file_operations_common.py b/tools/file_operations_common.py
index b15c0d36cf1..55882a8d27e 100644
--- a/tools/file_operations_common.py
+++ b/tools/file_operations_common.py
@@ -175,6 +175,10 @@ class ExecuteResult:
"""Result from executing a shell command."""
stdout: str = ""
exit_code: int = 0
+ # Set when the backend's own ``builtin cd -- <cwd> || exit 126`` wrapper failed:
+ # the command never ran, so the verdict is about the working directory, not
+ # the requested path (callers must neither cache it nor blame the path).
+ cwd_error: str = ""
# ---------------------------------------------------------------------------
diff --git a/tools/file_operations_search.py b/tools/file_operations_search.py
index c97fe6ace17..5d4232c8e39 100644
--- a/tools/file_operations_search.py
+++ b/tools/file_operations_search.py
@@ -471,12 +471,13 @@ class SearchMixin:
out.extend(["--glob", self._escape_shell_arg(f"!{item}/**")])
return out
- def _path_exists_probe(self, path: str) -> str:
- """Stdout of the existence probe: contains "exists" or "not_found"."""
+ def _path_exists_probe(self, path: str) -> ExecuteResult:
+ """Existence probe; stdout contains "exists" or "not_found" (or the probe's
+ ``cwd_error`` when the exec wrapper itself failed)."""
if self._native_read_enabled():
full = path if os.path.isabs(path) else os.path.join(getattr(self.env, "cwd", None) or self.cwd, path)
- return "exists" if os.path.exists(full) else "not_found"
- return self._exec(f"test -e {self._escape_shell_arg(path)} && echo exists || echo not_found").stdout
+ return ExecuteResult(stdout="exists" if os.path.exists(full) else "not_found")
+ return self._exec(f"test -e {self._escape_shell_arg(path)} && echo exists || echo not_found")
def _dispatch_search(self, pattern: str, path: str, target: str,
file_glob: Optional[str], limit: int, offset: int,
@@ -519,7 +520,7 @@ class SearchMixin:
existing, missing = [], []
for p in parts:
expanded = self._expand_path(p)
- (existing if "exists" in self._path_exists_probe(expanded) else missing).append(expanded)
+ (existing if "exists" in self._path_exists_probe(expanded).stdout else missing).append(expanded)
if not existing:
return None
if target == "files":