Skip to content

fix(tools): give the agent its own scratch directory instead of the user's repo - #3907

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/fix-3734-scratch-dir
Sep 23, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/fix-3734-scratch-dir

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Coding tasks left the user's repository dirty: the agent had nowhere else to put a quick test runner or an intermediate file, because the system temp dir is outside its allowed paths (30 of 30 write_file errors in a 168-run benchmark were /tmp refusals). Each agent that can write files now gets its own scratch directory, named in its prompt and deleted when the agent closes. The rest of the temp dir stays denied, and any tool that refuses a temp path now says where to write instead. Secret-file and blocked-file checks still apply inside the scratch directory.

Fixes #3734

  • python -m pytest tests/unit/test_scratch_dir.py tests/unit/test_chat_agent_integration.py -k scratch: the scratch dir is writable, readable and runnable; /tmp/other is denied and the refusal names the scratch dir, including from edit_file, search_code and the shell working-directory check; .env/id_rsa/*.pem are still refused inside it; the chat profile gets no scratch dir; the dir is removed on cleanup
  • python -m pytest tests/unit/test_file_access_scope.py tests/unit/test_file_write_guardrails.py tests/unit/test_security_edge_cases.py tests/unit/test_file_search_scope.py tests/unit/test_file_tools.py: existing guardrails unchanged
  • Prompt goldens (test_profilespec_characterization) and budget tests unchanged. The prompt assertions match; the tool-set assertions fail the same way on an unmodified origin/main checkout (pre-existing), so this stays unticked
  • Eval gate: runs in the self-hosted CI job once the branch is pushed to amd/gaia (adds one prompt line)
🔍 Technical details
  • PathValidator.set_scratch_dir() grants exactly that directory. scratch_hint() adds the scratch dir to every "not in allowed paths" refusal for a path under the system temp dir: validate_read/validate_write, execute_python_file, the five file-IO tools that build their own refusal, and run_shell_command's working-directory check.
  • ChatAgent creates the dir with tempfile.mkdtemp(prefix="gaia-scratch-") (mode 0700) after tool registration, and only when a file-creating tool (write_file, write_python_file, write_markdown_file) is registered. It removes the dir in its existing __del__, which GaiaAgent.close() also calls. There is no new lifecycle hook.
  • search_roots() skips the scratch dir. On macOS it nests deeper than most repos, so it would otherwise outrank the project as the primary file-search root.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes security Security-sensitive changes agents labels Sep 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Coding tasks used to leave scratch files in the user's repo because the agent had nowhere else to write. Each agent now gets its own private scratch folder, the prompt tells it to use that folder, the folder is deleted when the agent closes, and a refused temp path now says where to write instead. The design is tight: the rest of the system temp directory stays off-limits, the grant is never written to the machine-wide approvals file, and secret/blocked-file protection still applies inside the scratch folder.

One thing to land before merge: this changes the system prompt, and the project rule is that a prompt change needs an agent eval run compared against the baseline. The PR itself marks that as pending, and every test-plan box is still unchecked — worth ticking off what has actually been run.

The suggestions below are all small: the "write here instead" hint only reaches some of the refusal messages (file edits and shell working-directory refusals still give the bare "access denied"); the new prompt line is added even for the lean chat mode, which has no file-writing tools at all; and the cleanup step is less forgiving of unexpected errors than every other step around it.

Real-world evidence

No evidence-bundle.md was produced for this PR, so nothing was captured by the automated stage. I exercised the changed surface directly in the review environment (no inference needed — these are the tool-level paths the fix touches):

scratch_dir: /tmp/.../gaia-scratch-1xf7sdqw
-- write into scratch --
{"status": "success", "file_path": ".../gaia-scratch-1xf7sdqw/run_tests.py", "size_bytes": 12}
-- write into /tmp (outside scratch) --
{"status": "error", "error": "Access denied: '/tmp/gaia-outside/run_tests.py' is not in allowed
 paths. The system temp directory is off-limits; put temporary files in your scratch directory
 instead: /tmp/.../gaia-scratch-1xf7sdqw"}
-- read back from scratch --
{"status": "success", "content": "print('hi')\n"}
-- execute denial outside scratch --
{"status": "error", "error": "Access denied: /tmp/gaia-outside/run_tests.py. The system temp
 directory is off-limits; put temporary files in your scratch directory instead: /tmp/..."}
-- prompt tail --
Scratch directory for temporary files: /tmp/.../gaia-scratch-1xf7sdqw — put throwaway scripts
and intermediate files here, never in the user's project.
-- cleanup --
scratch removed: dir deleted, attr=None

Test suites from the PR's test plan: tests/unit/test_scratch_dir.py 13 passed; tests/unit/test_chat_agent_integration.py 29 passed; the guardrail suites 298 passed (one unrelated failure from a missing fastapi in this environment). The agent eval is the one gate still outstanding — the verdict rests on static review plus the tool-level run above for LLM behaviour.

🔍 Technical details

🟡 Important

Prompt change has no eval run yet. _get_system_prompt() now appends a scratch-directory line for every profile (hub/agents/chat/python/gaia_agent_chat/agent.py:1121). CLAUDE.md requires gaia eval agent against the committed baseline for any change to _get_system_prompt() before merge; the PR marks it "pending on the combined branch". Not a code defect — just the gate that has to be green. Same for the four unchecked test-plan boxes: test_scratch_dir.py, test_chat_agent_integration.py, and the guardrail suites all pass (see evidence above), so those can be ticked.

🟢 Minor

1. The scratch hint reaches only two of the refusal paths. validate_read/validate_write and execute_python_file carry scratch_hint(), but several tools build the "is not in allowed paths" string themselves and bypass it — file_io_tools.py:486 (edit_python_file), :626 (search_code), :984 (edit_file), :1120 (update_gaia_md), :1222 (replace_function), and shell_tools.py:868,876 (run_command working directory). Verified live:

edit_file /tmp/gaia-outside/x.py  → "Access denied: /tmp/gaia-outside/x.py is not in allowed paths"
run_shell_command cwd=/tmp        → "Access denied: /tmp is not in allowed paths"

One example, applied at file_io_tools.py:984:

                        reason = (
                            f"Access denied: {path} is not in allowed paths."
                            f"{path_validator.scratch_hint(str(path))}"
                        )

2. The prompt line goes to profiles with no write tools. Confirmed: prompt_profile="chat" renders the scratch line while its tool registry has zero write/edit tools (doc does have write_file, so gate on tools rather than on profile name). Costs ~25 tokens on the leanest profile and points it at a capability it doesn't have. Consider emitting the line only when a file-writing tool is registered — and skipping mkdtemp in that case too, so a pure-chat session doesn't create a directory it can never use.

3. Two spellings of the same directory (agent.py:260). The agent keeps the raw mkdtemp() path while set_scratch_dir() stores the resolved one, so on macOS the prompt says /var/folders/… and the denial hint says /private/var/folders/…. Functionally equivalent (_normalize_macos_symlinks handles it), but the model sees two strings for one directory.

        self.path_validator.set_scratch_dir(tempfile.mkdtemp(prefix="gaia-scratch-"))
        self.scratch_dir: Optional[Path] = self.path_validator.scratch_dir

4. Cleanup is narrower than its neighbours (agent.py:2463). Every other step in __del__ uses except Exception as e: logger.error(...); the new block catches only FileNotFoundError/OSError. At interpreter shutdown shutil can already be None, and the resulting AttributeError escapes — out of __del__, and out of GaiaAgent.close() for callers that use it. Matching the surrounding pattern also covers the stray-directory case: on SIGKILL nothing runs at all, so gaia-scratch-* dirs accumulate under the temp dir until the OS sweeps it — a startup sweep of orphaned gaia-scratch-* would close that off if it's worth the code.

Strengths

  • The security invariants actually hold. Secret names/extensions are still refused inside the scratch dir (covered by test), a symlink out of the scratch dir still resolves and gets denied by the containment check, and set_scratch_dir() deliberately writes to allowed_paths in memory only — it never touches _save_persisted_path, so a per-process temp dir can't leak into ~/.gaia/cache/allowed_paths.json.
  • The search_roots() exclusion is the non-obvious part done right. Without it a deep /private/var/folders/... path would have outranked the project as the primary file-search root, and the regression would have shown up as bad search results, not as an error.
  • Tests cover the negative cases, not just the happy path — other temp paths denied, denial text outside temp not mentioning the scratch dir, missing dir refused with allowed_paths left untouched, and the search-root ordering.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The scratch-directory feature is a clean, well-scoped fix: throwaway scripts no longer land in the user's project, secrets and blocked-file checks still apply inside the scratch dir, the LLM gets a useful hint on denials, and the scratch dir is excluded from search roots. Tests cover grants, denials, hints, secret protection, and cleanup. GaiaAgent.close() correctly delegates to ChatAgent.__del__(), so the lifecycle doc is accurate.

Two small things worth tidying before the next push:

🟢 The scratch fixture in test_scratch_dir.py tears down with path.iterdir() + child.unlink(), which throws IsADirectoryError if any test creates a subdirectory inside the scratch path. Use shutil.rmtree(path) instead — the same function already used in the production cleanup path.

🟢 The import tempfile in the docs/sdk/security.mdx code block appears mid-snippet after the validate_write call, rather than at the top with from gaia.security import PathValidator. Move it to the top of the block.

🔍 Technical details

Fixture teardown (tests/unit/test_scratch_dir.py:14-20):

# current — fragile against subdirectories
for child in path.iterdir():
    child.unlink()
path.rmdir()

# suggested
import shutil
shutil.rmtree(path)

Docs import order (docs/sdk/security.mdx:14-36):
Move import tempfile to the top of the code block alongside from gaia.security import PathValidator.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Every tool that refuses a temp path now points the model at the scratch directory, and an agent that can't write files (the chat profile) no longer gets a scratch directory or a prompt line about one. Branch is merged with current main; the eval runs in the self-hosted CI job once a maintainer pushes the branch to amd/gaia.

Skipped: the startup sweep of leftover gaia-scratch-* folders. It can't tell a crashed agent's folder from one a live agent is using right now, so it would need owner tracking to be safe.

🔍 Technical details

Commits: 5a06c00c (merge of origin/main; CHANGELOG conflict resolved by keeping both entries), fc31a4cf (review fixes).

  • Fixture teardown: now shutil.rmtree(path). (fc31a4cf)
  • import tempfile in security.mdx: moved to the top of the block. (fc31a4cf)
  • Hint on the other refusal paths: scratch_hint() is appended at each self-built refusal: edit_python_file, search_code, edit_file, update_gaia_md, replace_function, and the path_validator branch of run_shell_command's working-directory check. The existing method is the shared helper, so no new API. New tests cover edit_file, search_code and the shell cwd. (fc31a4cf)
  • Prompt line and mkdtemp on tool-less profiles: the dir is created after super().__init__(), only when write_file/write_python_file/write_markdown_file is in _tools_registry. The cached prompt is dropped at that point so it picks up the line. Tested: chat gets no dir, no grant and no prompt line (run against a cleared global registry, because chat never snapshots and would otherwise see earlier agents' tools). (fc31a4cf)
  • Two spellings: self.scratch_dir = self.path_validator.scratch_dir, and a test asserts they match. (fc31a4cf)
  • Cleanup catch: except Exception with logger.error, matching the neighbouring steps. FileNotFoundError still just clears the attribute, since a missing dir is already the end state. (fc31a4cf)
  • Orphan sweep: not done. gaia-scratch-* under the temp dir can belong to live agents in the Agent UI, daemon sidecars, or other TUI sessions. Deleting them on startup would pull a dir out from under a running agent, and doing it safely needs PID/lock bookkeeping.
  • Eval: not run here. Needs the self-hosted CI job; that box stays unticked.
  • Test plan: re-ran boxes 1–2 (-k scratch: 27 passed; guardrail suites: 317 passed, 7 skipped) and ticked them. Box 3 stays unticked: test_profilespec_characterization prompt assertions match, but its tool-set assertions (15 rows) and test_tool_loader_token_budget (4) fail identically on an unmodified origin/main checkout. test_chat_system_prompt_budget and test_prompt_size_budget pass.
  • Also run: test_file_io_confinement, test_file_io_directory_path_errors, test_shell_*, test_memory_error_staleness, hub/agents/chat/python/tests (584 passed total). hub/agents/gaia/python/tests: 338 passed. The 3 failures there (test_full_tool_bundles ×2, test_manifest_tools_count_matches_real_registry) fail the same way on origin/main in this environment.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Added a commit: the scratch directory now has the same path every session for a given project. The random per-process name was written into the system prompt, so no two sessions ever shared a cached prompt prefix; measured on the benchmark, the only difference between two processes' system prompts was that line. The path is derived from user and project, created private, and a planted symlink or a directory owned by someone else is refused for a fresh private one (test included).

@github-actions

Copy link
Copy Markdown
Contributor

🟡 The security.mdx doc example teaches the pattern this PR was designed to fix — a developer following it would get a new random scratch directory every session, defeating the prompt-caching benefit that stable_scratch_dir was introduced to provide.

The example shows tempfile.mkdtemp(prefix="gaia-scratch-") (random, leaks across sessions) where it should show stable_scratch_dir(Path.cwd()) or note that stable_scratch_dir is the recommended helper when prompt-cache stability matters.

🔍 Technical details

docs/sdk/security.mdx (new block, ~line 34):

# current (teaches random-per-session pattern):
session.set_scratch_dir(tempfile.mkdtemp(prefix="gaia-scratch-"))

# should be (matches the implementation and the fix rationale):
from gaia.security import stable_scratch_dir
session.set_scratch_dir(str(stable_scratch_dir(Path.cwd())))

stable_scratch_dir is already exported from gaia.security and imported in the agent, so it's part of the public API. The doc can either swap the example or add a note explaining that stable_scratch_dir is the preferred helper when session-to-session prompt-prefix stability matters (LLM backend caching). Without it, a reader implementing their own agent will reproduce the old behaviour this PR explicitly fixed.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Refreshed this branch against current main, which had rewritten the same access-denied branch this PR edits. The scratch-directory hint survives the update — a denied working_directory still tells the caller where it is allowed to write.

One thing for the author: the new test_a_hijacked_path_is_not_used fails on Windows because creating a symlink needs SeCreateSymbolicLinkPrivilege, which an ordinary developer account does not have. It needs a skip guard or it will fail for every Windows contributor. Everything else passes.

🔍 Technical details

Only src/gaia/agents/tools/shell_tools.py conflicted. main collapsed the duplicated path_validator / _is_path_allowed branch into a single _path_allowed() helper; this branch had instead extended the old inline form with path_validator.scratch_hint(...). Resolved by keeping main's helper and re-applying the hint on top of it, so both changes are present.

Existing assertions match on "not in allowed paths" as a substring, so the trailing . before the hint is safe, and scratch_hint() returns "" when no scratch dir is set.

pytest tests/unit on the merge result: 222 passed, 15 skipped, 1 failed — the failure is test_scratch_dir.py::TestScratchDirIsTheSameEverySession::test_a_hijacked_path_is_not_used with OSError: [WinError 1314] from expected.symlink_to(tmp_path).

Merged, not rebased — no commit on this branch was rewritten.

Kalin Ovtcharov and others added 5 commits September 23, 2026 02:24
…ser's repo

Coding tasks left throwaway test runners and intermediate files in the user's repository: the system temp dir is outside the allowed paths, so write_file and execute_python_file refused it and the project root was the only writable place the agent knew.

Each ChatAgent (and so GaiaAgent) now creates a private mkdtemp scratch directory, grants exactly that directory in its PathValidator, names it in one system-prompt line, and removes it in the existing cleanup path. The rest of the temp dir stays denied; refusals for temp paths now name the scratch directory. Secret and blocked-file checks still apply inside it, and file search skips it so it never outranks the project as the primary search root.

Fixes amd#3734
…y refusal

The "write here instead" hint now reaches edit_file, edit_python_file,
replace_function, search_code, update_gaia_md and the shell working-directory
check, not just write/read and execute_python_file. An agent with no
file-creating tool (the chat profile) no longer gets a scratch directory or
the prompt line pointing at one. The prompt and the refusal hint now spell the
directory the same way, and cleanup logs any failure instead of letting it
escape close().
The session scratch dir lives in the system temp dir by design, so an empty
temp dir is no longer the invariant; no gaia-run-* snippet left behind is.
…session

The scratch directory was created with a random name per process, and its
path is written into the system prompt. So every session's system prompt
differed by that one line, and a backend's cached prompt prefix never matched
across sessions - on a local model, across every TUI or sidecar restart. The
name is now derived from the user and the project. A predictable name under
a shared temp directory is created private, and one that exists but is not a
directory this user owns is refused, loudly, for a fresh private one.
The SHA-1 derives a stable directory name from owner + project path; it
guards nothing, and ownership is enforced by the lstat check below. Bandit
B324 is HIGH-severity and blocks the gate. Matches context7_cache.py.
@kovtcharov-amd
kovtcharov-amd force-pushed the claude/fix-3734-scratch-dir branch from 2787c0b to c8fcfd2 Compare September 23, 2026 09:26
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 23, 2026
Merged via the queue into amd:main with commit d338119 Sep 23, 2026
41 checks passed
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.

fix(tools): scratch files land in the user's repository because /tmp is denied

2 participants