Skip to content

The agent that grows with you

fix(tools): a task's own patch keeps its full-file write baseline

Victor Kyriazakos2b3afee3fe0c
diff --git a/tests/tools/test_known_file_write_baseline.py b/tests/tools/test_known_file_write_baseline.py
index 7f493a467a2..3cc10832472 100644
--- a/tests/tools/test_known_file_write_baseline.py
+++ b/tests/tools/test_known_file_write_baseline.py
@@ -1,11 +1,25 @@
-"""A narrower read must not discard unchanged whole-file knowledge."""
+"""Whole-file knowledge survives what does not change it.
+
+A narrower reread of unchanged bytes keeps the write_file baseline, and so does the task's
+own patch of a file it knew in full: ``write_file -> read_file -> patch -> write_file`` used
+to refuse the last write although the same task made the only change. The baseline survives
+the patch exactly when the task held one for the pre-patch bytes and the patch's write is what
+is on disk. A blind patch, a sibling or external writer, or an incomplete paged read stays
+refused.
+"""
import json
import os
+import pytest
+
+from tools import file_operations
from tools.file_tools import clear_file_ops_cache
+from tools.file_tools_read_tracking import reset_file_dedup
from tools.registry import registry
+_BLIND = "Your patch changed this file"
+
def _call(name, path, task_id, **arguments):
result = registry.dispatch(name, {"path": str(path), **arguments}, task_id=task_id)
@@ -74,3 +88,249 @@ def test_partial_read_cannot_refresh_a_changed_full_baseline(tmp_path):
assert path.read_text(encoding="utf-8").startswith("x" * (get_max_line_length() + 10))
finally:
clear_file_ops_cache("clamped")
+
+
+def _dispatch(name, task_id, **arguments):
+ result = registry.dispatch(name, arguments, task_id=task_id)
+ assert isinstance(result, str)
+ return json.loads(result)
+
+
+def _ok(result):
+ assert "error" not in result, result
+ return result
+
+
+def _write(path, task_id, content):
+ return _dispatch("write_file", task_id, path=str(path), content=content)
+
+
+def _read(path, task_id, **paging):
+ return _ok(_dispatch("read_file", task_id, path=str(path), **paging))
+
+
+def _replace(path, task_id, old, new):
+ return _ok(_dispatch("patch", task_id, path=str(path), old_string=old, new_string=new))
+
+
+def _v4a(task_id, *updates):
+ body = "".join(f"*** Update File: {p}\n@@\n-{old}\n+{new}\n" for p, old, new in updates)
+ return _ok(_dispatch("patch", task_id, mode="patch", patch=f"*** Begin Patch\n{body}*** End Patch"))
+
+
+def _blocked(result):
+ assert result.get("stale_write_blocked") is True, result
+ return result["error"]
+
+
+def task(request):
+ task_id = f"own-patch-{request.node.name}"
+ yield task_id
+ clear_file_ops_cache(task_id)
+
+
+def test_own_replace_patch_after_full_read_keeps_the_baseline(tmp_path, task):
+ path = tmp_path / "probe.txt"
+ _ok(_write(path, task, "first=old\nsecond=old\n"))
+ _read(path, task)
+ _replace(path, task, "first=old", "first=new")
+
+ written = _write(path, task, "first=new\nsecond=new\n")
+
+ assert "error" not in written and not written.get("stale_write_blocked"), written
+ assert path.read_text() == "first=new\nsecond=new\n"
+
+
+def test_own_patch_after_own_write_keeps_the_baseline(tmp_path, task):
+ path = tmp_path / "written.txt"
+ _ok(_write(path, task, "a=1\nb=1\n"))
+ _replace(path, task, "a=1", "a=2")
+ _replace(path, task, "b=1", "b=2")
+
+ _ok(_write(path, task, "a=3\nb=3\n"))
+ assert path.read_text() == "a=3\nb=3\n"
+
+
+def test_own_v4a_patch_keeps_the_baseline_for_every_file(tmp_path, task):
+ one, two = tmp_path / "one.txt", tmp_path / "two.txt"
+ for p in (one, two):
+ p.write_text("alpha\nbeta\n")
+ _read(p, task)
+ _v4a(task, (one, "alpha", "ALPHA"))
+ _ok(_write(one, task, "single\n"))
+ assert one.read_text() == "single\n"
+
+ _read(one, task)
+ _v4a(task, (one, "single", "SINGLE"), (two, "alpha", "ALPHA"))
+ for p in (one, two):
+ _ok(_write(p, task, f"replaced {p.name}\n"))
+ assert p.read_text() == f"replaced {p.name}\n"
+
+ # Two operations on one file chain: the second reads what the first wrote.
+ _v4a(task, (one, f"replaced {one.name}", "first"), (one, "first", "second"))
+ assert one.read_text() == "second\n"
+ _ok(_write(one, task, "chained\n"))
+
+ # A file the patch created holds only bytes the task wrote, like write_file creating it.
+ added = tmp_path / "added.txt"
+ _ok(_dispatch("patch", task, mode="patch",
+ patch=f"*** Begin Patch\n*** Add File: {added}\n+created\n*** End Patch"))
+ _ok(_write(added, task, "replaced\n"))
+ assert added.read_text() == "replaced\n"
+
+
+def test_own_patch_keeps_crlf_and_bom_files_writable(tmp_path, task):
+ path = tmp_path / "crlf.txt"
+ path.write_bytes(b"\xef\xbb\xbfone\r\ntwo\r\n")
+ _read(path, task)
+ _replace(path, task, "one", "ONE")
+ assert path.read_bytes() == b"\xef\xbb\xbfONE\r\ntwo\r\n"
+ _ok(_write(path, task, "three\n"))
+
+
+def test_blind_patch_never_gains_a_baseline(tmp_path, task):
+ path = tmp_path / "blind.txt"
+ path.write_text("one\ntwo\nthree\n")
+ _replace(path, task, "one", "ONE")
+
+ error = _blocked(_write(path, task, "x\n"))
+ assert _BLIND in error
+ assert path.read_text() == "ONE\ntwo\nthree\n"
+
+ # A partial view is not full knowledge either.
+ path.write_text("one\ntwo\nthree\n")
+ _read(path, task, offset=1, limit=1)
+ _replace(path, task, "two", "TWO")
+ assert _BLIND in _blocked(_write(path, task, "x\n"))
+ assert path.read_text() == "one\nTWO\nthree\n"
+
+ # Recovery: read every line, then the overwrite lands.
+ _read(path, task)
+ _ok(_write(path, task, "merged\n"))
+ assert path.read_text() == "merged\n"
+
+
+def test_sibling_patch_voids_the_other_task_and_gives_the_patcher_nothing(tmp_path, task):
+ path = tmp_path / "shared.txt"
+ path.write_text("left\nright\n")
+ sibling = f"{task}-sibling"
+ try:
+ _read(path, task)
+ _replace(path, sibling, "right", "RIGHT")
+
+ mine = _blocked(_write(path, task, "mine\n"))
+ assert _BLIND not in mine and sibling in mine
+ assert _BLIND in _blocked(_write(path, sibling, "theirs\n"))
+ assert path.read_text() == "left\nRIGHT\n"
+
+ _read(path, task)
+ _ok(_write(path, task, "mine\n"))
+ _read(path, sibling)
+ _ok(_write(path, sibling, "theirs\n"))
+ assert path.read_text() == "theirs\n"
+ finally:
+ clear_file_ops_cache(sibling)
+
+
[email protected]("preserve_mtime", [False, True], ids=["mtime-moves", "mtime-restored"])
+def test_external_edit_after_own_patch_is_refused(tmp_path, task, preserve_mtime):
+ path = tmp_path / "external.txt"
+ path.write_text("one\ntwo\n")
+ _read(path, task)
+ _replace(path, task, "one", "ONE")
+ stamp = path.stat()
+ path.write_text("ONE\nEXTERNAL\n")
+ if preserve_mtime:
+ os.utime(path, ns=(stamp.st_atime_ns, stamp.st_mtime_ns))
+ else:
+ os.utime(path, ns=(stamp.st_atime_ns, stamp.st_mtime_ns + 1_000_000_000))
+
+ error = _blocked(_write(path, task, "clobber\n"))
+ assert _BLIND not in error
+ assert path.read_text() == "ONE\nEXTERNAL\n"
+
+ _read(path, task)
+ _ok(_write(path, task, "merged\n"))
+ assert path.read_text() == "merged\n"
+
+
+def test_write_landing_after_the_patch_write_gives_no_baseline(tmp_path, task, monkeypatch):
+ path = tmp_path / "raced-after.txt"
+ path.write_text("one\ntwo\n")
+ original = file_operations.ShellFileOperations.patch_replace
+
+ def patch_then_external_write(self, *args, **kwargs):
+ result = original(self, *args, **kwargs)
+ stamp = os.stat(path)
+ path.write_text("ONE\nRACED\n")
+ os.utime(path, ns=(stamp.st_atime_ns, stamp.st_mtime_ns))
+ return result
+
+ _read(path, task)
+ monkeypatch.setattr(file_operations.ShellFileOperations, "patch_replace", patch_then_external_write)
+ _replace(path, task, "one", "ONE")
+ monkeypatch.undo()
+
+ _blocked(_write(path, task, "clobber\n"))
+ assert path.read_text() == "ONE\nRACED\n"
+
+
+def test_write_landing_before_the_patch_read_gives_no_baseline(tmp_path, task, monkeypatch):
+ """The patch applied its delta to bytes the task never saw in full."""
+ path = tmp_path / "raced-before.txt"
+ path.write_text("one\ntwo\n")
+ original = file_operations.ShellFileOperations.patch_replace
+
+ def external_write_then_patch(self, *args, **kwargs):
+ path.write_text("one\nUNSEEN\n")
+ return original(self, *args, **kwargs)
+
+ _read(path, task)
+ monkeypatch.setattr(file_operations.ShellFileOperations, "patch_replace", external_write_then_patch)
+ _replace(path, task, "one", "ONE")
+ monkeypatch.undo()
+ assert path.read_text() == "ONE\nUNSEEN\n"
+
+ _blocked(_write(path, task, "clobber\n"))
+ assert path.read_text() == "ONE\nUNSEEN\n"
+
+
+def test_paged_read_carries_only_when_every_page_was_read(tmp_path, task):
+ content = "".join(f"line {i}\n" for i in range(1, 2501))
+ complete, missing = tmp_path / "complete.txt", tmp_path / "missing.txt"
+ for p in (complete, missing):
+ p.write_text(content)
+ assert _read(p, task).get("truncated")
+ _read(complete, task, offset=2001)
+
+ for p in (complete, missing):
+ _replace(p, task, "line 1\n", "LINE 1\n")
+ _ok(_write(complete, task, "merged\n"))
+ assert complete.read_text() == "merged\n"
+ assert _BLIND in _blocked(_write(missing, task, "merged\n"))
+ assert missing.read_text().startswith("LINE 1\nline 2\n")
+
+
[email protected]("reread", [False, True], ids=["no-reread", "reread"])
+def test_own_patch_after_compaction_keeps_the_baseline(tmp_path, task, reread):
+ path = tmp_path / "compacted.txt"
+ path.write_text("one\ntwo\n")
+ _read(path, task)
+ reset_file_dedup(task)
+ if reread:
+ _read(path, task)
+ _replace(path, task, "one", "ONE")
+ _ok(_write(path, task, "merged\n"))
+ assert path.read_text() == "merged\n"
+
+
+def test_third_patch_failure_hint_requires_a_full_reread_before_write_file(tmp_path, task):
+ path = tmp_path / "anchor.txt"
+ path.write_text("alpha\n")
+ for _ in range(3):
+ failed = _dispatch("patch", task, path=str(path), old_string="missing", new_string="x")
+ hint = failed["_hint"]
+ assert "failure #3" in hint
+ assert "re-read the file in full, then use write_file to replace it" in hint
+ assert "use write_file to replace the entire file" not in hint
diff --git a/tools/file_operations.py b/tools/file_operations.py
index de21a872b92..5c219b35e84 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -1263,7 +1263,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
# Strip a leading BOM (a phantom U+FEFF defeats an exact first-line match);
# write_file re-probes disk and restores it.
raw_content, _ = _strip_bom(data.decode("utf-8", "surrogateescape"))
- return ReadResult(content=raw_content, file_size=file_size)
+ return ReadResult(content=raw_content, file_size=file_size,
+ _content_sha256=hashlib.sha256(data).hexdigest())
def read_file_bytes(self, path: str, max_bytes: Optional[int] = None) -> ReadResult:
"""Read binary-safe bytes (as base64) from any shell-backed environment."""
@@ -1639,7 +1640,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):
success=True, diff=self._unified_diff(content, new_content, path), files_modified=[path],
lint=lint_result.to_dict() if lint_result else None,
# From the internal write_file call, whose baseline was the pre-patch content.
- lsp_diagnostics=write_result.lsp_diagnostics)
+ lsp_diagnostics=write_result.lsp_diagnostics,
+ _writes=[(path, hashlib.sha256(data).hexdigest(), write_result._content_sha256)])
def patch_v4a(self, patch_content: str) -> PatchResult:
"""Apply a V4A format patch (``*** Begin Patch`` / ``*** Update File:`` /
diff --git a/tools/file_operations_common.py b/tools/file_operations_common.py
index a7c4403c1b7..df6a61a96a4 100644
--- a/tools/file_operations_common.py
+++ b/tools/file_operations_common.py
@@ -7,7 +7,7 @@ the model.
import re
from dataclasses import dataclass, field
-from typing import Any, ClassVar, Dict, List, Optional
+from typing import Any, ClassVar, Dict, List, Optional, Tuple
@dataclass
@@ -31,6 +31,8 @@ class ReadResult:
not_found: bool = False
similar_files: List[str] = field(default_factory=list)
_snapshot: Optional[tuple] = None
+ # sha256 of the exact on-disk bytes ``read_file_raw`` decoded (BOM included).
+ _content_sha256: Optional[str] = None
def to_dict(self) -> dict:
return {k: v for k, v in self.__dict__.items() if not k.startswith("_") and v is not None and v != []}
@@ -70,6 +72,10 @@ class PatchResult:
# Success-shaped no-op: the edit was already present, nothing written; ``note`` says why.
no_change: bool = False
note: Optional[str] = None
+ # One ``(path, read_sha256, written_sha256)`` per file write, in order: the sha256 of the
+ # bytes the edit read ("" when it created the file, None when unknown) and of the bytes it
+ # wrote (None when unknown). patch_tool carries a task's full-file baseline across them.
+ _writes: List[Tuple[str, Optional[str], Optional[str]]] = field(default_factory=list)
# Emission order is part of the output contract.
_DICT_FIELDS: ClassVar[tuple] = (
diff --git a/tools/file_tools.py b/tools/file_tools.py
index 56dca8c4986..953cce88db8 100644
--- a/tools/file_tools.py
+++ b/tools/file_tools.py
@@ -35,7 +35,8 @@ from tools.file_tools_write_guards import (
_check_cross_profile_path, _check_protected_instruction_write, _check_sensitive_path,
_is_internal_file_tool_content, _stale_overwrite_blocker, _stale_write_refusal)
from tools.file_tools_read_tracking import (
- _bump_consecutive, _cap_read_tracker_data, _check_file_staleness, _check_not_found_cache,
+ _bump_consecutive, _cap_read_tracker_data, _carry_full_write_baselines, _check_file_staleness,
+ _check_not_found_cache, _known_full_content_sha256,
_file_metadata, _file_version,
_mark_full_write_baseline, _mark_verification_stale, _note_read_coverage, _patch_failure_lock,
_patch_failure_tracker, _read_tracker, _read_tracker_lock, _record_not_found,
@@ -575,6 +576,7 @@ def _record_successful_read(task_data: dict, task_id: str, path: str, resolved_s
complete = complete and not redacted
if complete:
baselines[resolved_str] = version
+ task_data.setdefault("blind_patches", {}).pop(resolved_str, None)
if not complete:
baselines.pop(resolved_str, None)
if not stable or count >= 4:
@@ -913,7 +915,7 @@ def write_file_tool(path: str, content: str, task_id: str = "default",
if _resolved:
result_dict["files_modified"] = [_resolved]
# Own write = current whole-file content: consecutive
- # same-task writes stay unblocked. patch never does this.
+ # same-task writes stay unblocked (patch_tool carries it).
_mark_full_write_baseline(_resolved, task_id, getattr(result, "_content_sha256", None))
_note_edited(task_id, [path], path_to_resolved, session_id)
return json.dumps(result_dict, ensure_ascii=False)
@@ -987,6 +989,9 @@ def patch_tool(mode: str = "replace", path: str = None, old_string: str = None,
_locks.enter_context(file_state.lock_path(_r))
stale_warnings = _edit_warnings(_paths_to_check, _path_to_resolved, task_id)
file_ops = _get_file_ops(task_id)
+ # Whole-file knowledge held BEFORE the patch reads, under the same locks. Like
+ # every baseline check it stats the host path, so a sandbox path carries nothing.
+ _known = _known_full_content_sha256(_path_to_resolved.values(), task_id)
# Hand the shell layer the RESOLVED targets so both layers agree on
# which file is edited even when the shell's cwd differs.
@@ -1017,6 +1022,7 @@ def patch_tool(mode: str = "replace", path: str = None, old_string: str = None,
if len(_resolved_modified) == 1:
result_dict["resolved_path"] = _resolved_modified[0]
_note_edited(task_id, _paths_to_check, _path_to_resolved, session_id)
+ _carry_full_write_baselines(task_id, _known, getattr(result, "_writes", ()), _path_to_resolved)
# Clear failure counters so a future miss starts a fresh count.
_reset_patch_failures(task_id, [_r for _r in _path_to_resolved.values() if _r])
# old_string-not-found hint. Failure escalation is tracked for replace
@@ -1032,9 +1038,9 @@ def patch_tool(mode: str = "replace", path: str = None, old_string: str = None,
"Stop retrying with variations of the same old_string. "
"Either: (1) re-read the file fresh to verify current "
"content, (2) use a longer / more unique old_string with "
- "surrounding context lines, or (3) use write_file to "
- "replace the entire file if the targeted region is hard "
- "to anchor.")
+ "surrounding context lines, or (3) re-read the file in "
+ "full, then use write_file to replace it if the targeted "
+ "region is hard to anchor.")
elif "Did you mean one of these sections?" not in str(result_dict["error"]):
result_dict["_hint"] = (
"old_string not found. Use read_file to verify the current "
diff --git a/tools/file_tools_read_tracking.py b/tools/file_tools_read_tracking.py
index 80dcdb1418d..31981c9d3a2 100644
--- a/tools/file_tools_read_tracking.py
+++ b/tools/file_tools_read_tracking.py
@@ -11,8 +11,10 @@ full content), ``dedup_hits`` (stub-loop breaker), ``read_timestamps``
task has paged through at one file version — contiguous pages that reach the last line
count as a whole-file read), ``full_write_baselines`` (resolved paths whose
whole-file content this task saw via unredacted read_file page(s) or wrote via
-write_file; required before write_file may overwrite an existing file — patch
-never qualifies) and ``not_found`` (short-TTL negative cache). Every
+write_file, or patched from a baseline it already held; required before write_file
+may overwrite an existing file), ``blind_patches`` (resolved path -> sha256 a patch
+of this task wrote without such a baseline, for the refusal wording) and
+``not_found`` (short-TTL negative cache). Every
container is hard-capped (``_cap_read_tracker_data``) so long sessions stay small.
"""
@@ -52,7 +54,8 @@ def _task_data(task_id: str) -> dict:
(search_tool / tests create partial entries). Lock must be held."""
task_data = _read_tracker.setdefault(task_id, {
"last_key": None, "consecutive": 0, "read_history": set()})
- for key in ("dedup", "dedup_hits", "read_timestamps", "read_coverage", "full_write_baselines"):
+ for key in ("dedup", "dedup_hits", "read_timestamps", "read_coverage", "full_write_baselines",
+ "blind_patches"):
task_data.setdefault(key, {})
task_data.setdefault("dedup_generation_reads", set())
return task_data
@@ -90,6 +93,7 @@ def _cap_read_tracker_data(task_data: dict) -> None:
("read_timestamps", _READ_TIMESTAMPS_CAP),
("read_coverage", _READ_TIMESTAMPS_CAP),
("full_write_baselines", _FULL_WRITE_BASELINES_CAP),
+ ("blind_patches", _FULL_WRITE_BASELINES_CAP),
("not_found", _NOT_FOUND_CAP)):
container = task_data.get(key)
if container is not None and len(container) > cap:
@@ -281,6 +285,7 @@ def _mark_full_write_baseline(resolved: str, task_id: str, expected_sha256: str
with _read_tracker_lock:
task_data = _task_data(task_id)
task_data["full_write_baselines"][str(resolved)] = version
+ task_data["blind_patches"].pop(str(resolved), None)
_cap_read_tracker_data(task_data)
@@ -291,6 +296,61 @@ def _has_full_write_baseline(resolved: str, task_id: str) -> bool:
return baseline is not None and _file_version(resolved) == baseline
+def _known_full_content_sha256(resolved_paths, task_id: str) -> dict:
+ """``{resolved: sha256 hex}`` for each path whose recorded full-write baseline still
+ matches the bytes on disk. Call under the per-path locks, before a patch reads."""
+ with _read_tracker_lock:
+ baselines = dict((_read_tracker.get(task_id) or {}).get("full_write_baselines", {}))
+ known = {}
+ for resolved in {str(r) for r in resolved_paths if r}:
+ baseline = baselines.get(resolved)
+ if baseline is not None and _file_version(resolved) == baseline:
+ known[resolved] = baseline[-1].hex()
+ return known
+
+
+def _carry_full_write_baselines(task_id: str, known: dict, writes, path_to_resolved: dict) -> None:
+ """After this task's own successful patch: keep the whole-file baseline of each written
+ path when the task knew the exact bytes the patch read (``known``, from
+ ``_known_full_content_sha256``) or the patch created the file (read sha ``""``). Then
+ the task knows every byte it wrote. ``writes`` is ``PatchResult._writes`` in order, so
+ a second edit of the same path chains from the first. The mark re-hashes the disk and
+ requires the bytes the patch wrote, so a writer landing after the patch leaves no
+ baseline. A write the task could not vouch for is noted in ``blind_patches``."""
+ lookup = {raw: r for raw, r in path_to_resolved.items() if r}
+ lookup.update({r: r for r in lookup.values()})
+ known = dict(known)
+ written: dict = {}
+ for path, read_sha, written_sha in writes:
+ resolved = lookup.get(path)
+ if resolved is None:
+ continue # a backend-side path (sandbox, translated mount): no host baseline
+ vouched = read_sha == "" or (read_sha is not None and read_sha == known.get(resolved))
+ known[resolved] = written_sha if vouched else None
+ written[resolved] = written_sha
+ for resolved, written_sha in written.items():
+ if written_sha is None:
+ continue
+ if known[resolved] is not None:
+ _mark_full_write_baseline(resolved, task_id, written_sha)
+ continue
+ with _read_tracker_lock:
+ task_data = _task_data(task_id)
+ task_data["blind_patches"][resolved] = written_sha
+ _cap_read_tracker_data(task_data)
+
+
+def _is_own_blind_patch(resolved: str, task_id: str) -> bool:
+ """True when the bytes on disk are exactly what this task's own patch wrote without a
+ full-content baseline (a blind patch, or one after a partial view)."""
+ with _read_tracker_lock:
+ written_sha = ((_read_tracker.get(task_id) or {}).get("blind_patches") or {}).get(str(resolved))
+ if written_sha is None:
+ return False
+ version = _file_version(resolved)
+ return version is not None and version[-1].hex() == written_sha
+
+
_READ_COVERAGE_RANGES_CAP = 256
diff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.py
index c6baec10aba..e6f0a2e36d6 100644
--- a/tools/file_tools_write_guards.py
+++ b/tools/file_tools_write_guards.py
@@ -24,7 +24,7 @@ from tools.binary_extensions import (
)
from tools.file_tools_paths import (
_expand_tilde, _resolve_path_for_task, _ssh_path_escapes_home, _terminal_env_type_for_task)
-from tools.file_tools_read_tracking import _has_full_write_baseline, _read_mtime_drifted
+from tools.file_tools_read_tracking import _has_full_write_baseline, _is_own_blind_patch, _read_mtime_drifted
# Prefixes matched after realpath. macOS: /private/var mirrors /var — block the
# sensitive subtrees only; a blanket "/private/var/" refuses every temp-file
@@ -557,9 +557,10 @@ def _stale_overwrite_blocker(filepath: str, resolved: str | None, task_id: str)
Refuses BEFORE any disk mutation (the pre-#65604 warning arrived after the
clobber): a sibling/external/partial-read staleness finding, or an existing
file with no full-content baseline for this task (never read in full, read
- redacted, only patched). Net-new files, files this task fully read (in one
- page or by paging contiguously to the last line) or wrote, unresolvable
- paths and the file-state kill switch all let the write proceed.
+ redacted, only patched without one). Net-new files, files this task fully read
+ (in one page or by paging contiguously to the last line), wrote, or patched
+ from such a baseline, unresolvable paths and the file-state kill switch all
+ let the write proceed.
"""
if file_state.guard_disabled():
return None
@@ -578,9 +579,13 @@ def _stale_overwrite_blocker(filepath: str, resolved: str | None, task_id: str)
return None
if not exists:
return None
+ if _is_own_blind_patch(resolved, task_id):
+ return (
+ "Your patch changed this file without a full view of its current content. Read the current file "
+ "in full before a whole-file overwrite, or continue with targeted patches.")
return (
f"{resolved} exists but this task has not seen its full current content "
- "(never read, only patched, or only a redacted/partial view). Read the "
+ "(never read, patched without a prior full read, or only a redacted/partial view). Read the "
"file — every page of it, if it needs offset/limit — or use patch for a "
"targeted edit; a stale conversation copy must not overwrite the current "
"disk content.")
diff --git a/tools/patch_parser.py b/tools/patch_parser.py
index 8e6ce92ed7b..00bbe221883 100644
--- a/tools/patch_parser.py
+++ b/tools/patch_parser.py
@@ -266,19 +266,22 @@ def _validate_operations(operations: List[PatchOperation], file_ops: Any) -> Lis
return errors
-# Every _apply_* returns (success, diff_or_error, lsp_diagnostics, lint_result).
-ApplyResult = Tuple[bool, str, Optional[str], Optional[dict]]
+# Every _apply_* returns (success, diff_or_error, lsp_diagnostics, lint_result, write): ``write``
+# is the PatchResult._writes entry of a file write, None for Delete/Move and failures.
+ApplyResult = Tuple[bool, str, Optional[str], Optional[dict], Optional[tuple]]
def _fail(error: str) -> ApplyResult:
- return False, error, None, None
+ return False, error, None, None, None
-def _written(result: Any, diff: str) -> ApplyResult:
- """Outcome of a write: its error, else success with LSP/lint propagated from the WriteResult."""
+def _written(result: Any, diff: str, path: str, read_sha256: Optional[str]) -> ApplyResult:
+ """Outcome of a write: its error, else success with LSP/lint propagated from the WriteResult
+ and the ``(path, read_sha256, written_sha256)`` record of the bytes it replaced and wrote."""
if result.error:
return _fail(result.error)
- return True, diff, getattr(result, "lsp_diagnostics", None), getattr(result, "lint", None)
+ write = (path, read_sha256, getattr(result, "_content_sha256", None))
+ return True, diff, getattr(result, "lsp_diagnostics", None), getattr(result, "lint", None), write
def _unified_diff(path: str, old: str, new: Optional[str]) -> str:
@@ -305,10 +308,11 @@ def apply_v4a_operations(operations: List[PatchOperation], file_ops: Any) -> Pat
# V4A bypasses write_file's WriteResult plumbing: LSP diagnostics and lint propagate per file.
lsp_blocks: List[str] = []
lint_results: Dict[str, dict] = {}
+ writes: List[tuple] = []
for op in operations:
handler, verb, bucket = _APPLY_DISPATCH[op.operation]
try:
- ok, payload, lsp, lint = handler(op, file_ops)
+ ok, payload, lsp, lint, write = handler(op, file_ops)
except Exception as e:
ok, payload = None, str(e)
if not ok:
@@ -318,6 +322,8 @@ def apply_v4a_operations(operations: List[PatchOperation], file_ops: Any) -> Pat
is_move = op.operation is OperationType.MOVE
files[bucket].append(f"{op.file_path} -> {op.new_path}" if is_move else op.file_path)
all_diffs.append(payload)
+ if write:
+ writes.append(write)
if lsp:
lsp_blocks.append(lsp)
if lint:
@@ -329,7 +335,7 @@ def apply_v4a_operations(operations: List[PatchOperation], file_ops: Any) -> Pat
+ _bullets(errors)) if errors else None,
diff='\n'.join(all_diffs),
files_modified=files["modified"], files_created=files["created"], files_deleted=files["deleted"],
- lint=lint_results or None, lsp_diagnostics="\n\n".join(lsp_blocks) or None)
+ lint=lint_results or None, lsp_diagnostics="\n\n".join(lsp_blocks) or None, _writes=writes)
def _write_file_accepts_pre_content(file_ops: Any) -> bool:
@@ -358,7 +364,7 @@ def _apply_add(op: PatchOperation, file_ops: Any) -> ApplyResult:
content_lines = [line.content for hunk in op.hunks for line in hunk.lines if line.prefix == '+']
result = file_ops.write_file(op.file_path, '\n'.join(content_lines))
diff = f"--- /dev/null\n+++ b/{op.file_path}\n" + '\n'.join(f"+{line}" for line in content_lines)
- return _written(result, diff)
+ return _written(result, diff, op.file_path, "")
def _apply_delete(op: PatchOperation, file_ops: Any) -> ApplyResult:
@@ -368,7 +374,7 @@ def _apply_delete(op: PatchOperation, file_ops: Any) -> ApplyResult:
return _fail(f"Cannot delete {op.file_path}: file not found")
result = file_ops.delete_file(op.file_path)
diff = _unified_diff(op.file_path, read_result.content, None) or f"# Deleted: {op.file_path}"
- return _fail(result.error) if result.error else (True, diff, None, None)
+ return _fail(result.error) if result.error else (True, diff, None, None, None)
def _apply_move(op: PatchOperation, file_ops: Any) -> ApplyResult:
@@ -381,7 +387,7 @@ def _apply_move(op: PatchOperation, file_ops: Any) -> ApplyResult:
return _fail(f"{op.new_path}: could not confirm the destination is free — {dst.error}")
result = file_ops.move_file(op.file_path, op.new_path)
return _fail(result.error) if result.error else (
- True, f"# Moved: {op.file_path} -> {op.new_path}", None, None)
+ True, f"# Moved: {op.file_path} -> {op.new_path}", None, None, None)
def _insert_addition_only(new_content: str, hunk: Hunk, insert_text: str) -> Tuple[Optional[str], Optional[str]]:
@@ -440,7 +446,8 @@ def _apply_update(op: PatchOperation, file_ops: Any) -> ApplyResult:
# Pass pre_content to skip a redundant re-read inside write_file when supported.
extra = {"pre_content": current_content} if _write_file_accepts_pre_content(file_ops) else {}
write_result = file_ops.write_file(op.file_path, new_content, **extra)
- return _written(write_result, _unified_diff(op.file_path, current_content, new_content))
+ return _written(write_result, _unified_diff(op.file_path, current_content, new_content),
+ op.file_path, getattr(read_result, "_content_sha256", None))
# operation -> (handler, verb for error text, files_* bucket)
diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.md
index e955b9d2c4d..87582903d76 100644
--- a/website/docs/reference/tools-reference.md
+++ b/website/docs/reference/tools-reference.md
@@ -117,7 +117,7 @@ Scoped to the Feishu document-comment handler. Drives comment read/write operati
| `search_files` | Search file contents or find files by name. Use this instead of grep/rg/find/ls in terminal. Ripgrep-backed, faster than shell equivalents. Content search (target='content'): Regex search inside files. Output modes: full matches with line… | — |
| `write_file` | Write content to a file, completely replacing existing content. Use this instead of echo/cat heredoc in terminal. Creates parent directories automatically. OVERWRITES the entire file — use 'patch' for targeted edits. For an existing file, call read_file first: write_file refuses (file untouched) when the task has no current full read/write of the file or the file changed on disk since — on refusal, read_file, merge, retry. Auto-runs syntax checks on .py/.json/.yaml/.toml and other linted languages; only NEW errors introduced by the write are surfaced. | — |
-For local files, a full unredacted read (including all pages of the same file version) or a successful `write_file` supplies a whole-file baseline. Reading a smaller region afterward does not discard that baseline while the bytes remain unchanged. A changed file, an unread file, or a view with hidden/redacted or clamped content still needs a full current read before replacement; `patch` remains available for targeted edits. Writes made through terminal commands or `execute_code` do not establish a `write_file` baseline.
+For local files, a full unredacted read (including all pages of the same file version), a successful `write_file`, or your own `patch` of a file you had read in full supplies a whole-file baseline. Reading a smaller region afterward does not discard that baseline while the bytes remain unchanged. A file changed by another writer, an unread file, a file patched without a full read, or a view with hidden/redacted or clamped content still needs a full current read before replacement; `patch` remains available for targeted edits. Writes made through terminal commands or `execute_code` do not establish a `write_file` baseline.
## `computer_use` toolset