Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions tests/tools/test_file_staleness.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def test_no_warning_when_file_unchanged(self, mock_ops):

@patch("tools.file_tools._get_file_ops")
def test_warning_when_file_modified_externally(self, mock_ops):
"""Read, then external modify, then write — should warn."""
"""Read, then external modify, then write — should error."""
mock_ops.return_value = _make_fake_ops("original content\n", 18)
read_file_tool(self._tmpfile, task_id="t1")

Expand All @@ -114,8 +114,9 @@ def test_warning_when_file_modified_externally(self, mock_ops):
f.write("someone else changed this\n")

result = json.loads(write_file_tool(self._tmpfile, "new content", task_id="t1"))
self.assertIn("_warning", result)
self.assertIn("modified since you last read", result["_warning"])
self.assertIn("error", result)
self.assertIn("Refusing to write", result["error"])
self.assertIn("modified since you last read", result["error"])

@patch("tools.file_tools._get_file_ops")
def test_no_warning_when_file_never_read(self, mock_ops):
Expand Down Expand Up @@ -186,8 +187,9 @@ def test_relative_path_uses_recorded_session_cwd_for_staleness_tracking(self, mo
finally:
terminal_tool.clear_session_cwd("live_task")

self.assertIn("_warning", result)
self.assertIn("modified since you last read", result["_warning"])
self.assertIn("error", result)
self.assertIn("Refusing to write", result["error"])
self.assertIn("modified since you last read", result["error"])


# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -215,7 +217,7 @@ def tearDown(self):

@patch("tools.file_tools._get_file_ops")
def test_patch_warns_on_stale_file(self, mock_ops):
"""Patch should warn if the target file changed since last read."""
"""Patch should error if the target file changed since last read."""
mock_ops.return_value = _make_fake_ops("original line\n", 15)
read_file_tool(self._tmpfile, task_id="p1")

Expand All @@ -228,8 +230,9 @@ def test_patch_warns_on_stale_file(self, mock_ops):
old_string="original", new_string="patched",
task_id="p1",
))
self.assertIn("_warning", result)
self.assertIn("modified since you last read", result["_warning"])
self.assertIn("error", result)
self.assertIn("Refusing to patch", result["error"])
self.assertIn("modified since you last read", result["error"])

@patch("tools.file_tools._get_file_ops")
def test_patch_no_warning_when_fresh(self, mock_ops):
Expand Down
9 changes: 5 additions & 4 deletions tests/tools/test_file_state_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,11 +238,12 @@ def test_sibling_agent_write_surfaces_warning_through_handler(self):
self.assertNotIn("error", w_b)

w_a = json.loads(write_file_tool(path=p, content="A stale\n", task_id="agentA"))
warn = w_a.get("_warning", "")
self.assertTrue(warn, f"expected warning, got: {w_a}")
err = w_a.get("error", "")
self.assertTrue(err, f"expected error, got: {w_a}")
# The cross-agent message names the sibling task_id.
self.assertIn("agentB", warn)
self.assertIn("sibling", warn.lower())
self.assertIn("Refusing to write", err)
self.assertIn("agentB", err)
self.assertIn("sibling", err.lower())

def test_same_agent_consecutive_writes_no_false_warning(self):
p = self._write_seed("own.txt")
Expand Down
52 changes: 38 additions & 14 deletions tools/file_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1604,11 +1604,14 @@ def write_file_tool(path: str, content: str, task_id: str = "default",

if _resolved is None:
stale_warning = _check_file_staleness(path, task_id)
if stale_warning:
return tool_error(
f"Refusing to write: {stale_warning} "
"Use read_file to get the current content, then retry the write."
)
file_ops = _get_file_ops(task_id)
result = file_ops.write_file(path, content)
result_dict = result.to_dict()
if stale_warning:
result_dict["_warning"] = stale_warning
if not result_dict.get("error"):
_mark_verification_stale(task_id, [path], session_id=session_id)
_update_read_timestamp(path, task_id)
Expand All @@ -1622,15 +1625,23 @@ def write_file_tool(path: str, content: str, task_id: str = "default",
# fire — its message names the sibling subagent.
cross_warning = file_state.check_stale(task_id, _resolved)
stale_warning = _check_file_staleness(path, task_id)
# Block on staleness — refuse to clobber external edits or
# sibling-subagent changes. The caller must re-read first.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only blocks when a tracker entry already exists. _check_file_staleness() returns None for an unread path, so a task can still fully overwrite an existing file without a fresh baseline. Add an existing-file/full-read baseline check here.

staleness_block = cross_warning or stale_warning
if staleness_block:
return tool_error(
f"Refusing to write: {staleness_block} "
"Use read_file to get the current content, then retry the write."
)
# Workspace-divergence warning: relative path resolving outside the
# terminal's cwd (the worktree-cwd bug). Lowest priority of the three.
# terminal's cwd (the worktree-cwd bug). Lowest priority — kept as
# a soft warning because it doesn't risk data loss.
cwd_warning = _path_resolution_warning(path, Path(_resolved), task_id)
file_ops = _get_file_ops(task_id)
result = file_ops.write_file(_resolved, content)
result_dict = result.to_dict()
effective_warning = cross_warning or stale_warning or cwd_warning
if effective_warning:
result_dict["_warning"] = effective_warning
if cwd_warning:
result_dict["_warning"] = cwd_warning
# Always report the ABSOLUTE path actually written, so a wrong-cwd
# mismatch is visible in the response instead of silently routing
# the edit to the wrong checkout.
Expand Down Expand Up @@ -1741,7 +1752,8 @@ def _reject_v4a_traversal(v4a_path: str) -> str | None:

# Collect warnings — cross-agent registry first (names sibling),
# then per-task tracker as a fallback.
stale_warnings: list[str] = []
stale_blocks: list[str] = []
cwd_warnings: list[str] = []
_path_to_resolved: dict[str, str] = {}
for _p in _paths_to_check:
try:
Expand All @@ -1750,13 +1762,25 @@ def _reject_v4a_traversal(v4a_path: str) -> str | None:
_r = None
_path_to_resolved[_p] = _r
_cross = file_state.check_stale(task_id, _r) if _r else None
_sw = _cross or _check_file_staleness(_p, task_id)
if not _sw and _r:
_per_task = _check_file_staleness(_p, task_id)
_staleness = _cross or _per_task
if _staleness:
stale_blocks.append(_staleness)
elif _r:
# Workspace-divergence warning (worktree-cwd bug): relative
# path resolving outside the terminal's cwd.
_sw = _path_resolution_warning(_p, Path(_r), task_id)
if _sw:
stale_warnings.append(_sw)
_cwd = _path_resolution_warning(_p, Path(_r), task_id)
if _cwd:
cwd_warnings.append(_cwd)

# Block on staleness — refuse to apply a patch that would
# clobber external edits or sibling-subagent changes.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This broadens the write_file fix into a hard behavioral change for targeted patches. Current patch staleness is warning-only; please retain that behavior unless the patch semantic change is intentionally approved.

if stale_blocks:
msg = stale_blocks[0] if len(stale_blocks) == 1 else " | ".join(stale_blocks)
return tool_error(
f"Refusing to patch: {msg} "
"Use read_file to get the current content, then retry the patch."
)

file_ops = _get_file_ops(task_id)

Expand All @@ -1780,8 +1804,8 @@ def _reject_v4a_traversal(v4a_path: str) -> str | None:
return tool_error(f"Unknown mode: {mode}")

result_dict = result.to_dict()
if stale_warnings:
result_dict["_warning"] = stale_warnings[0] if len(stale_warnings) == 1 else " | ".join(stale_warnings)
if cwd_warnings:
result_dict["_warning"] = cwd_warnings[0] if len(cwd_warnings) == 1 else " | ".join(cwd_warnings)
# Report the ABSOLUTE path(s) actually patched so a wrong-cwd
# mismatch (e.g. a worktree session editing the main checkout) is
# visible in the response instead of silently landing elsewhere.
Expand Down
Loading