Skip to content

feat(tools): refuse to edit a file the agent hasn't read - #4029

Merged
kovtcharov-amd merged 9 commits into
amd:mainfrom
kovtcharov:claude/read-before-edit
Sep 26, 2026
Merged

kovtcharov-amd merged 9 commits into
amd:mainfrom
kovtcharov:claude/read-before-edit

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

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 it
  • python -m pytest tests/unit hub/agents/gaia/python/tests hub/agents/chat/python/tests: the same 27 environment failures as main on the test machine, and no new ones
  • Real GaiaAgent with 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 nothing
  • black, isort, flake8 and pylint pass on the touched files; the doc link and doc code checks pass
  • gaia eval agent --category tool_selection shows no regression against the baseline (not run here: this changes what the edit tools return and adds a clause to their docstrings)
🔍 Technical details
  • Guarded tools: edit_file and write_file in both file_io_tools and file_tools, plus edit_python_file, write_python_file, write_markdown_file, replace_function and update_gaia_md. Write tools are only checked when the target file already exists. The flagship registers the file_io_tools versions of read_file, write_file and edit_file; ChatAgent strips the rest from its full profile, but they are guarded for other hosts too.
  • What unlocks a file: read_file in all three mixins, including paged and line-range reads (filesystem_tools also 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 shell cat, a grep hit or a get_file_info preview does not.
  • The record: FileReadRecord in file_edit.py maps 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-wide FileStateTracker, whose content-hash ledger let unread files through and was shared by every agent. As a side effect, replace_function now records the file after writing it. It never did before, so the next edit after it was rejected as stale.
  • Before the prompt: a new @tool(preflight=...) kwarg is stored on the registry entry, and Agent._policy_refusal runs it before confirm_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.
  • Full access: the check does not depend on auto_approve_gated_tools or GAIA_AUTO_APPROVE_TOOLS, and it is covered by a test. Refusals carry executed: False.
  • Tests I changed: test_file_write_guardrails, test_replace_function_spans, test_write_display_contract and test_file_edit_semantics edited files they had never read, so they now read them first. test_file_edit_semantics staleness tests are rewritten for mtime/size (the old ones asserted hash fields and "an unread file is not blocked"). test_parse_error_recovery now scripts a read_file step before the edit. test_tool_decorator expects the new kwarg.
  • Things to weigh:
    • The record lasts for the agent's lifetime, but GAIA drops tool results from history between turns. A file read in turn 1 can therefore be edited in turn 3 without being in the model's context. edit_file still needs an exact match, but write_file would overwrite. Clearing the record per turn would be stricter.
    • The C++ tracker (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.
    • The file-editing prompt fragment still says "do not re-read a file whose content you already hold". A model that "holds" content from grep will now get one refusal before it reads.
    • Docstring cost for the doc profile's native tool payload goes from 6124 to 6153 tokens (+29). The flagship's CORE set is unchanged at 2780.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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:

  • The agent is still told the opposite. The file-editing instructions the agent receives end with "do not re-read a file whose content you already hold — edit it directly." A model that holds content from a search hit will now follow that sentence straight into a refusal and burn a turn recovering. That one line needs to say "read it with the read tool first."
  • The behaviour eval wasn't run. This changes what eight tools say about themselves and what they return on failure, plus it adds a mandatory extra step to every edit — exactly the surface the repo requires an eval for, and the PR's own test plan leaves that box unchecked. Please run the tool-selection category against the committed baseline and post the comparison.

Neither is a design objection. The rest reads as a solid, well-tested change.

Real-world evidence

N/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 GaiaAgent driven through its tool dispatch; I'm relaying that, not confirming it. The one surface that is explicitly not covered is the agent-behaviour eval, which is the first blocking item above. My verdict rests on static review plus the PR's own reported runs.

🔍 Technical details

🟡 Important

The mixin's system prompt contradicts the new rule (src/gaia/agents/tools/file_io_tools.py:267)

get_file_editing_system_prompt() still ships "Do not re-read a file whose content you already hold — edit it directly." With read-before-edit enforced, "already hold" from search_code, a grep hit, or a shell cat no longer unlocks anything — the model gets one guaranteed refusal per file before it complies. The PR body lists this under "things to weigh"; it's the one surface the model actually reads, and CLAUDE.md's rule that a functional change updates every doc describing it applies to the prompt first. The starter skills (hub/skills/file-ops/SKILL.md:35-37) already say the right thing, so this line is the lone outlier.

            "Read a file with read_file before you change it — the edit tools "
            "refuse a file you have not read, and content from a search hit or "
            "a shell command does not count."

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 error_type surface, and every edit now costs an extra read_file round-trip. That is squarely inside the listed triggers (tool docstrings, the JSON tool schema, tool-call response handling). The PR's test plan marks gaia eval agent --category tool_selection unrun. Please run it and diff against tests/fixtures/eval_baselines/<model>/scorecard_tool_selection.json; the prompt fix above should land first, since it is the thing most likely to move the score.

🟢 Minor

Preflight is skipped when the call has no arguments (src/gaia/agents/base/agent.py:3821). _policy_refusal returns early on falsy tool_args, so update_gaia_md() with all-default arguments prompts the user and then gets refused by the tool body — the one hole in "nobody is asked to approve a call that is going to be refused."

len(sample) can be zero (src/gaia/agents/tools/filesystem_tools.py:982). Narrowing the handler to OSError lets a ZeroDivisionError escape when st_size > 0 but the read returns nothing (concurrent truncation, some pseudo-files). The old bare except fell through to reading it as text; now the outer handler turns it into "Error reading file: division by zero". Guard with if sample:.

The spec doesn't record the cross-mixin asymmetry. The PR body notes that file_io/file_search binary reads unlock a file while filesystem_tools' binary, PDF, image and metadata views don't. docs/spec/file-io-tools-mixin.mdx:249-251 only says "a paged one included". Worth one line so the next reader doesn't have to derive it.

Strengths

  • The refusal runs before the confirmation prompt, and the tool body repeats it. The @tool(preflight=...) hook is the right shape for "validate first, confirm second", and the docstring is explicit that the body must re-check because state can move while a prompt waits. test_full_access_still_refuses_an_unread_edit pins the part that is easiest to regress.
  • The preflight defers to the tool's own scope refusal for out-of-allowlist paths, so the check can't be used to probe whether a file exists outside the sandbox — and there's a test for exactly that (test_a_path_outside_the_sandbox_gets_the_scope_refusal).
  • The test file is parametrized across all eight guarded calls and all three read mixins, so a new file-changing tool that forgets the check fails the suite rather than shipping. Replacing the process-wide FileStateTracker with a per-instance record also removes a real cross-agent leak, and every Python reference to the old tracker is gone (the C++ tree keeps its own, and the spec now says the two differ).

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Merge-order note: #3992 adds TestEditingLeavesTheWorkspaceClean::test_edit_file_leaves_no_new_file_beside_the_original in tests/unit/test_file_write_guardrails.py, which edits app.py without reading it. With this PR it's refused, so whichever of the two merges second needs the test's _tool helper to read an existing target first on the same mixin instance (the file's existing _reading_first does it). One-line change; everything else in the full unit suite is clean with both merged.

Kalin Ovtcharov and others added 3 commits September 21, 2026 04:41
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.
@kovtcharov
kovtcharov force-pushed the claude/read-before-edit branch from 3404b1f to fc1fbce Compare September 21, 2026 11:59
@github-actions github-actions Bot added the security Security-sensitive changes label Sep 21, 2026
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #3992 (edit-backups-outside-tree). Merge after #3992.

# Conflicts:
#	src/gaia/agents/tools/filesystem_tools.py
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

The broken-link failure here was the checker, not the doc — so I re-ran the job instead of editing anything.

https://docs.anthropic.com/claude/prompt-library is alive: it 301-redirects to the platform.claude.com docs and returns 200. Anthropic is mid-migration, so it intermittently serves a 404 that our checker takes at face value.

🔍 Technical details
  • The link lives in docs/plans/image-agent.mdx — a file this PR doesn't touch; it's also present on main.
  • util/check_doc_links.py::check_external_link() returns ('ok', 'HTTP 200') for this URL when run locally.
  • The checker never retries a 404 (by design — "a genuine 404 stays broken on the first attempt"), so a transient one from a migrating host is fatal. That's the gap worth filing separately if this recurs.

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.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

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 FileReadRecord already refuses everything #3656 refused, plus the case #3656 couldn't (a file never read at all), so the hash ledger goes and the read record stays. One thing from #3656 was worth keeping and I kept it: a refused overwrite still writes a denied audit entry.

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 details

The duplicate guards. file_io_tools.py (update_gaia_md, replace_function) and file_tools.py (write_file) each ended up with main's check_file_state(...) block sitting next to this branch's reads.refusal(...). Git merged them as adjacent additions. check_file_state, record_read and record_write are now gone from both files.

tests/unit/agents/test_file_write_state.py is deleted — it pins the old contract, including test_unread_existing_file_still_writes_and_records_state, which is the precise behaviour this branch removes. Its audit-entry coverage is preserved as TestRefusalIsAudited (not_read and changed_since_read both asserted).

One honest difference: #3656 detected change by content hash, this does it by (mtime_ns, size). A rewrite that preserves both would slip past. Nanosecond mtime makes that vanishingly unlikely, but it is not literally the same test.

ZeroDivisionError (filesystem_tools.py). Narrowing except Exception to except OSError was the right call, but it exposed nontext / len(sample) when st_size > 0 and the read returns empty — a pseudo-file, or a truncation racing the read. The old bare except swallowed it; now it surfaced as "Error reading file: division by zero". Guarded with if sample:; regression test confirmed failing without the guard.

Zero-argument preflight. _policy_refusal returned early on falsy tool_args, so update_gaia_md() with all-default arguments was prompted for and then refused by the tool body. The preflight now runs before that guard (it already tolerates missing arguments and defers to the tool). Test confirmed failing without the fix: assert ['update_gaia_md'] == [].

Docs. The "Concurrent file changes" section still described stale: true and content hashes, which this branch does not return; it now points at "Read before edit". Same for the file-search mixin's cross-reference. Added the cross-mixin asymmetry line — filesystem_tools' PDF/image/binary/metadata views don't unlock a file, its text views do.

Tests: 1772 passed, 59 skipped across tests/unit/agents, test_file_write_guardrails, test_replace_function_spans, test_filesystem_tools_mixin, test_tool_decorator. A full tests/unit run reached 99% with zero failures before I cut it short.

One for you rather than me: commit 2e89aca62 carries a Co-Authored-By: Claude Opus 5 trailer, which CLAUDE.md prohibits. I didn't rewrite history to strip it.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Sep 26, 2026
# 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.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…#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]>
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 2ec88e2 Sep 26, 2026
40 of 43 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/read-before-edit branch September 26, 2026 04:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes security Security-sensitive changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants