Repository navigation
feat(tools): refuse to edit a file the agent hasn't read - #4029
Conversation
|
Verdict: Request changes — two small things, both fixable in one pass. This makes the agent read a file before it can change it, which is the right fix for the blind-patch behaviour the benchmark caught. The implementation is careful: the refusal lands before the approval prompt, it survives full-access mode, and creating a file still needs no read. Two things to settle before merge:
Neither is a design objection. The rest reads as a solid, well-tested change. Real-world evidenceN/A — no evidence bundle was produced for this PR, and this review lane has no pytest available, so I could not run the suite myself. The PR description reports the new 467-line test file passing (33 of its cases failing before the change), the wider unit suite showing no new failures, and a no-LLM 🔍 Technical details🟡 ImportantThe mixin's system prompt contradicts the new rule (
The agent eval was not run (CLAUDE.md → "Run agent evals when changing LLM-affecting code paths") Eight tool docstrings gained a new clause, the edit tools gained a new 🟢 MinorPreflight is skipped when the call has no arguments (
The spec doesn't record the cross-mixin asymmetry. The PR body notes that Strengths
|
|
Merge-order note: #3992 adds |
Every write_file and edit_file left name.<timestamp>.bak beside the edited file and nothing removed it, so every repository the agent touched ended up littered with backups. The backup is still made; it now goes under the validator's state directory (~/.gaia/cache/backups, beside the audit log that records it) at the original's absolute path, e.g. ~/.gaia/cache/backups/Users/me/repo/src/app.py.20260918_101500.bak. ".bak" stays last (amd#3747). A drive letter or UNC share becomes one folder name. Only a filesystem error now skips the backup, with a warning naming both paths; any other exception propagates instead of being swallowed. The file tools only report backup_path, so none of their callers changed. - Backups are made by one function, backup_file, used with or without a validator, so no edit tool (edit_python_file and replace_function included) writes a backup into the user's tree. - Only the five newest backups of each file are kept; older ones are removed when a new one lands. - The backups directory and every directory below it is owner-only. - edit_python_file reports backup_created from whether a backup was made. - Tests that edit files now use a temporary home, so the suite no longer writes backups into the developer's real ~/.gaia.
Benchmark runs caught the flagship patching files it had never read in full, from grep snippets or guesses, and one refactor silently widened behaviour. Every file-changing tool now refuses an existing file the agent hasn't read, or one whose mtime or size changed since that read, before anything is written. The rule rests on what the read tools returned, not on prompt wording, as with Claude Code's Edit and Write. - The record is per agent instance and lasts for its lifetime. read_file (full, paged or line-range, in all three file mixins) adds a file, as do creating it and editing it successfully. - Guarded: edit_file and write_file in both mixins, plus edit_python_file, write_python_file, write_markdown_file, replace_function and update_gaia_md. Creating a file needs no read. - Refusals are marked not executed, and a new @tool(preflight=...) hook runs the same check before the confirmation prompt, so nobody is asked to approve an edit that is about to be refused. Paths outside the allowed set get the usual scope refusal, so the check can't reveal whether a file exists there. Full-access mode is still subject to the check. - The per-agent record replaces the process-wide content-hash tracker, which let a file nobody had read through and shared one ledger across agents. It also fixes replace_function never re-recording the file, which got the next edit rejected as stale. - Existing tests that edited files without reading them now read first. - Narrowed two bare except blocks in the touched modules to the errors they handle, and made them log.
3404b1f to
fc1fbce
Compare
# Conflicts: # src/gaia/agents/tools/filesystem_tools.py
|
The broken-link failure here was the checker, not the doc — so I re-ran the job instead of editing anything.
🔍 Technical details
No doc edit was made, deliberately — inventing a change to green a flaky check would have hidden the real behaviour. |
The file-editing prompt still ended with "do not re-read a file whose content you already hold — edit it directly." With read-before-edit enforced, a model holding content from a search hit or a shell `cat` followed that sentence straight into a guaranteed refusal and spent a turn recovering. It now says what the tools actually require. The starter skill and the tool docstrings already did; this line was the last one out of step. Co-Authored-By: Claude Opus 5 <[email protected]>
main's amd#3656 added a content-hash stale-write guard to the very tools this branch re-implements. `FileReadRecord` already refuses both cases amd#3656 cared about — a file changed on disk since the read, and (unlike amd#3656) one never read at all — so the hash ledger goes and the read record stays. Two things amd#3656 contributed that the auto-merge would have dropped: - **The denied-write audit entries.** Every refusal now logs `audit_write(..., "denied", <error_type>)` the way the stale guard did, so a refused overwrite is still visible in the audit trail. Covered by TestRefusalIsAudited. - **Nothing else.** `tests/unit/agents/test_file_write_state.py` is deleted: it pins the old contract, including `test_unread_existing_file_still_writes`, which is exactly the behaviour this branch removes. Three call sites in file_io_tools.py and file_tools.py auto-merged main's `check_file_state` block in *alongside* the branch's `reads.refusal(...)` without conflicting — duplicate guards that only the import error surfaced. Docs: the "Concurrent file changes" section still described `stale: true` and content hashes, neither of which this branch returns; it now points at "Read before edit". Same for the file-search mixin's cross-reference.
|
The prompt contradiction was already fixed on this branch. What wasn't: main landed a second stale-write guard (#3656) in exactly the tools this PR re-implements, and merging it in produced two guards running back to back in three places — without a single conflict marker. Only the import error made it visible. Your Two real bugs fixed while here — a divide-by-zero this PR's own exception-narrowing introduced, and a hole in the "refused before anyone is asked to approve" guarantee for zero-argument calls. 🔍 Technical detailsThe duplicate guards.
One honest difference: #3656 detected change by content hash, this does it by
Zero-argument preflight. Docs. The "Concurrent file changes" section still described Tests: 1772 passed, 59 skipped across One for you rather than me: commit |
# Conflicts: # docs/spec/file-io-tools-mixin.mdx # docs/spec/file-search-mixin.mdx # src/gaia/agents/tools/file_io_tools.py
The merge combined this PR's read-before-edit fact with main's compacted phrasing, landing 49 chars over the 400-char budget.
…#4314) Before: when the backup failed (full disk, or a cache directory GAIA can't write), the overwrite went ahead anyway. The tool result looked exactly like a backed-up write, even though the Agent UI auto-approves overwrites because it expects a backup. After: the write is refused, the file is left unchanged, and the error names the cause and the fix. Backup names also carry microseconds now, so two edits in the same second keep two backups instead of one overwriting the other. Overlaps with amd#4029, which edits nearby lines in `file_io_tools.py` but doesn't change backup behaviour. Whichever merges second needs a small rebase. ## Test plan - [x] `pytest tests/unit/test_file_write_guardrails.py tests/unit/test_security_edge_cases.py -q` → 166 passed, 7 skipped. 4 new tests fail on `main`: a failed backup raises, `write_file` refuses (tested in both file-tool mixins), and two same-second backups don't collide. - [x] Neighbouring file-tool suites (16 files, including `test_file_tools.py`, `test_file_io_confinement.py`, and `agents/test_file_write_state.py`) → 716 passed, 7 skipped - [x] black, isort, and flake8 on the changed files; pylint on `security.py` (exit 0) - [ ] `gaia eval agent`: a failed backup now returns a different tool result to the model Fixes amd#4232 --------- Co-authored-by: Kalin Ovtcharov <[email protected]> Co-authored-by: Kalin Ovtcharov <[email protected]>
Before this change, nothing stopped the flagship agent from patching a file it had never opened, working from a search snippet or a guess. Now it has to read a file before it can change it, and read it again if the file changed on disk since, as Claude Code requires. (A correction: some of the benchmark judge's "edited without reading" notes that motivated this came from a bug in the benchmark's transcript reader, which dropped reads made several-per-step. In the latest 14-task run the guard never had to fire. It's a safety rule, not a measured quality fix.) An edit that would be refused is refused before anyone is asked to approve it, and the rule still applies with confirmations bypassed.
Test plan
python -m pytest tests/unit/agents/test_read_before_edit.py: 62 new tests, 33 of them failed before the change and all pass after itpython -m pytest tests/unit hub/agents/gaia/python/tests hub/agents/chat/python/tests: the same 27 environment failures asmainon the test machine, and no new onesGaiaAgentwith no LLM, driven through its tool dispatch: an unread edit is refused with no prompt, a partial read unlocks the file, a second edit needs no re-read, a change on disk is refused, a new file needs no read, and a read by another agent instance unlocks nothinggaia eval agent --category tool_selectionshows no regression against the baseline (not run here: this changes what the edit tools return and adds a clause to their docstrings)🔍 Technical details
edit_fileandwrite_filein bothfile_io_toolsandfile_tools, plusedit_python_file,write_python_file,write_markdown_file,replace_functionandupdate_gaia_md. Write tools are only checked when the target file already exists. The flagship registers thefile_io_toolsversions ofread_file,write_fileandedit_file;ChatAgentstrips the rest from itsfullprofile, but they are guarded for other hosts too.read_filein all three mixins, including paged and line-range reads (filesystem_toolsalso counts its CSV and JSON views, but not PDF, image, binary or metadata views). Creating a file with a write tool or editing it successfully also unlocks it. A shellcat, a grep hit or aget_file_infopreview does not.FileReadRecordinfile_edit.pymaps resolved path to(mtime_ns, size). It is attached lazily to the agent instance, so each agent has its own. Read tools take the stamp before reading. It replaces the process-wideFileStateTracker, whose content-hash ledger let unread files through and was shared by every agent. As a side effect,replace_functionnow records the file after writing it. It never did before, so the next edit after it was rejected as stale.@tool(preflight=...)kwarg is stored on the registry entry, andAgent._policy_refusalruns it beforeconfirm_tool_execution. The tool body runs the same check again, because the file can change while a prompt waits. The preflight skips paths outside the allowed set or on the write blocklist, so the tool's own scope error answers instead, and an existence check outside the sandbox isn't possible.auto_approve_gated_toolsorGAIA_AUTO_APPROVE_TOOLS, and it is covered by a test. Refusals carryexecuted: False.test_file_write_guardrails,test_replace_function_spans,test_write_display_contractandtest_file_edit_semanticsedited files they had never read, so they now read them first.test_file_edit_semanticsstaleness tests are rewritten for mtime/size (the old ones asserted hash fields and "an unread file is not blocked").test_parse_error_recoverynow scripts aread_filestep before the edit.test_tool_decoratorexpects the new kwarg.edit_filestill needs an exact match, butwrite_filewould overwrite. Clearing the record per turn would be stricter.cpp/include/gaia/file_tools.h) still lets an agent edit a file it never read, so the two trees now differ. The spec says so.