Skip to content

The agent that grows with you

fix(file-ops): fence the byte-exact read so backend stdout noise is not decoded

John Paul Soliva5bcb236457ce
diff --git a/tests/tools/test_file_operations.py b/tests/tools/test_file_operations.py
index 8302ee059ce..e9d54fac4b4 100644
--- a/tests/tools/test_file_operations.py
+++ b/tests/tools/test_file_operations.py
@@ -421,6 +421,17 @@ class TestShellFileOpsWriteDenied:
assert "Failed to move" in result.error
+
+def _fenced_base64_reply(command: str, payload: bytes, rc: int = 0) -> str:
+ """The reply shape ``_read_exact_bytes`` asks for: its per-call sentinel around the base64
+ payload, then the read's exit status. Mirrors what the real shell emits, so a double stays
+ honest about the fence the transport relies on."""
+ import base64 as _b64
+ import re as _re
+ sentinel = _re.search(r"__HERMES_RB_[0-9a-f]+__", command).group(0)
+ body = _b64.b64encode(payload).decode() if rc == 0 else ""
+ return f"{sentinel}\n{body}\n{sentinel}\n{rc}\n"
+
class TestPatchReplacePostWriteVerification:
"""Tests for the post-write verification added in patch_replace.
@@ -436,10 +447,11 @@ class TestPatchReplacePostWriteVerification:
def side_effect(command, **kwargs):
# the byte-exact read (base64 over the transport) — both the initial read and the verify read
- if command.startswith("base64 < "):
+ if "base64 < " in command:
for path in file_contents:
if path in command:
- return {"output": base64.b64encode(file_contents[path].encode()).decode(), "returncode": 0}
+ return {"output": _fenced_base64_reply(command, file_contents[path].encode()),
+ "returncode": 0}
return {"output": "", "returncode": 1}
# mkdir for parent dir
if command.startswith("mkdir "):
@@ -474,11 +486,11 @@ class TestPatchReplacePostWriteVerification:
if stdin_data is not None: # write (atomic temp-file + mv script)
state["content"] = stdin_data
return {"output": "", "returncode": 0}
- if command.startswith("base64 < "): # byte-exact read
+ if "base64 < " in command: # byte-exact read
call_count["read"] += 1
# First read (initial fetch) succeeds; second read (verify) fails
if call_count["read"] == 1:
- return {"output": base64.b64encode(state["content"].encode()).decode(), "returncode": 0}
+ return {"output": _fenced_base64_reply(command, state["content"].encode()), "returncode": 0}
return {"output": "", "returncode": 1}
if command.startswith("mkdir "):
return {"output": "", "returncode": 0}
diff --git a/tests/tools/test_file_write_safety.py b/tests/tools/test_file_write_safety.py
index c1cfdab0919..297ca447e09 100644
--- a/tests/tools/test_file_write_safety.py
+++ b/tests/tools/test_file_write_safety.py
@@ -412,6 +412,32 @@ class TestBomHandling:
lints = res.lint.values() if mode == "v4a" else [res.lint]
assert [lint["status"] for lint in lints] == ["ok"], res.lint
+ def test_byte_exact_read_fences_backend_stdout_noise(self, tmp_path: Path, monkeypatch):
+ # The edit paths write this read straight back, so noise in the backend's merged stdout must
+ # never reach the decode. "TERM" is four base64 characters: unfenced it decodes to b"LDL" and
+ # lands at the head of the file. Remote backends announce things on connect, so the local
+ # native fast path is off here and the base64 transport is what runs.
+ from tools.environments.local import LocalEnvironment
+ from tools.file_operations import ShellFileOperations
+ monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0")
+
+ class NoisyEnv(LocalEnvironment):
+ def execute(self, command, *args, **kwargs):
+ result = super().execute(command, *args, **kwargs)
+ if isinstance(result, dict):
+ result = dict(result)
+ result["output"] = "TERM\n" + (result.get("output") or "")
+ return result
+
+ target = tmp_path / "conf.txt"
+ original = b"HEADER\nVERSION=1\n"
+ target.write_bytes(original)
+ ops = ShellFileOperations(NoisyEnv(cwd=str(tmp_path)), cwd=str(tmp_path))
+
+ assert ops._read_exact_bytes(str(target)) == (original, None)
+ ops.patch_replace(str(target), "VERSION=1", "VERSION=2")
+ assert target.read_bytes() == original.replace(b"VERSION=1", b"VERSION=2")
+
class TestProtectedInstructionFiles:
"""Writes to agent-instruction files ALWAYS require approval.
diff --git a/tools/file_operations.py b/tools/file_operations.py
index 240cb4f7ab0..4c1cbcd9cfd 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -149,6 +149,7 @@ MISSING_SENTINEL = "__hermes_missing__"
_READ_SENTINEL_PREFIX = "__HERMES_RF_"
_WRITE_SENTINEL_PREFIX = "__HERMES_WF_"
+_BYTES_SENTINEL_PREFIX = "__HERMES_RB_"
def _new_sentinel(prefix: str) -> str:
@@ -281,12 +282,34 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
return fh.read(), None
except OSError:
pass # missing/unreadable: the shell read below reports it the usual way
- result = self._exec(f"base64 < {self._escape_shell_arg(path)}")
- if result.exit_code != 0:
- return None, result
- data = self._decode_base64_sample(result.stdout)
+ # Fenced like the compound read probe, and for the same reason: a backend whose merged
+ # stdout carries login-shell noise (a remote shell announcing TERM, a banner) would
+ # otherwise have it whitespace-joined onto the payload and decoded INTO the file's bytes,
+ # which the edit paths then write back. Noise outside the fence is dropped; noise inside
+ # it fails base64 validation instead, because the sentinel is not in the base64 alphabet.
+ sentinel = _new_sentinel(_BYTES_SENTINEL_PREFIX)
+ mark = f"echo {sentinel}"
+ result = self._exec(f"{mark}; base64 < {self._escape_shell_arg(path)}; __hb=$?; {mark}; echo $__hb")
+ segments = _split_segments(result.stdout or "", sentinel)
+ garbled = ExecuteResult(stdout=f"{path}: the backend returned a garbled byte-exact read", exit_code=1)
+ if len(segments) != 3:
+ # No fenced reply: the command never ran as written (a wrapper ``cd`` failed, the backend
+ # refused it). Hand the backend's own text back so the caller reports what it said.
+ return None, result if result.exit_code != 0 else garbled
+ status = _strip_terminal_fence_leaks(segments[2]).split()
+ try:
+ read_rc = int(status[0])
+ except (IndexError, ValueError):
+ return None, garbled
+ if read_rc != 0:
+ # stderr is merged into the fenced segment, so that segment holds base64's own diagnostic
+ # ("No such file or directory", "Permission denied"): keep it for the caller's message.
+ return None, ExecuteResult(
+ stdout=_strip_terminal_fence_leaks(segments[1]).strip() or f"{path}: exit {read_rc}",
+ exit_code=read_rc)
+ data = self._decode_base64_sample(segments[1])
if data is None: # stray output in the payload: refuse rather than guess (never echo it back)
- return None, ExecuteResult(stdout=f"{path}: the backend returned a garbled byte-exact read", exit_code=1)
+ return None, garbled
return data, None
@staticmethod