Skip to content

fix(agents): keep run_python's scratch dir alive and stop system package installs - #5475

Merged
kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:kalin/run-python-cwd
Oct 23, 2026
Merged

kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:kalin/run-python-cwd

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

In a long-running Agent UI session, run_python started failing with "The directory name is invalid". The agent had Full access, so it then installed openpyxl into the user's system Python to get around the broken tool. This PR fixes both problems.

run_python lost its working folder. Every chat on a project shares one scratch folder, and each chat deleted that folder when it shut down. In a long-lived sidecar, one chat's cleanup removed the folder while another chat was still using it.

  • The scratch folder is now deleted only when the last chat using it in this process shuts down.
  • It is re-created before every Python run, in case a temp cleaner or another GAIA process deleted it. The shell session gets the same repair.
  • If the project folder is gone, the run falls back to the scratch folder and the result says so.
  • If Python still can't start, the error names the missing folder and tells the agent not to install packages or switch interpreters. The failure doesn't count toward the turn's failure limit.

Agents could change the user's system packages. Full access swaps the per-command shell policy for a developer set that includes python and npm. That made python -m pip install, npm install -g and similar commands run with no checks. The existing pip/npm rules that refuse installs outside the project never ran.

  • Under Full access these commands are now refused. The agent is told to give the user the exact command or use a virtual environment inside the project.
  • Without Full access they need a one-time approval, with a risk line saying the change affects other programs. "Always" is not offered.
  • Installs into a virtual environment (GAIA's own included), with --target/--prefix, or into a project's node_modules are unaffected.
🔍 Technical details
  • Root cause, part 1: stable_scratch_dir() gives the same path to every agent with the same anchor (the sidecar's cwd when there is no project), and ChatAgent.__del__ called shutil.rmtree on it. A garbage-collected agent for an old chat deleted the folder under a live one, and Popen(cwd=...) then raised WinError 267.
  • gaia.security: new acquire_scratch_dir / release_scratch_dir (per-process refcount) and ensure_scratch_dir (re-creates the folder; refuses a link, a file or a folder owned by another user). ChatAgent._live_scratch_dir switches to a fresh mkdtemp folder if the path can't be re-created.
  • TurnScopeGuard: results marked transient: True don't move the failure streak or record a failed call.
  • ShellToolsMixin._live_session_cwd: re-creates the session folder if it is the scratch folder; otherwise resets the session to its start folder and adds a note to the result.
  • New module gaia.agents.tools.package_installs. _line_verdict applies it before the full-access early return, so the pre-prompt gate and the executor give the same answer.
  • Docs: docs/guides/gaia.mdx (shell and run_python paragraph) and docs/plans/security-model.mdx §4.5.
  • The unrestricted fixture in test_shell_adaptive_timeouts.py now also disables the install check. That test is about timeouts, and its pip install -e . case depended on this machine's pip.

Test plan

  • tests/unit/test_scratch_dir_lifecycle.py (new): scratch folder deleted between two run_python calls; two chats sharing one sidecar, where the first chat's cleanup keeps the folder and the second chat's removes it; missing project folder; start failure is transient; breaker ignores transient failures; shell session folder repair.
  • tests/unit/test_system_package_installs.py (new): what counts as a system install; full access refuses before the prompt and in the executor; installs into a venv and normal developer commands are unaffected; ask mode never offers "always".
  • tests/unit/test_shell_*.py, test_scratch_dir.py, agents/test_turn_scope*.py, test_run_python_untracked.py: pass.
  • Known failures that also fail on main in this environment: test_run_python_tool.py::test_a_pytest_run_attaches_its_check[*] (a pytest plugin crashes in the child process) and hub/agents/gaia/.../test_manifest_tools_count_matches_real_registry.
  • CI

Every chat on a project shares one scratch path, and an agent's cleanup
deleted it, so in a long-lived sidecar one chat's teardown left another
chat's run_python failing with WinError 267 for the rest of the session.

- Hold the scratch dir with a per-process count; only the last holder
  deletes it.
- Re-create it before each run_python spawn (temp cleaners and other
  processes can still remove it); fall back to it with a note when the
  project folder is gone; execute_python_file falls back to the script's
  folder.
- A missing working folder is marked transient, so the turn-scope breaker
  does not count it, and the error tells the agent not to install packages
  or switch interpreters.
Full access swaps the per-binary shell policy for a developer set that
names python and npm, so 'python -m pip install x' and 'npm install -g x'
changed the user's system environment unasked; an agent did this to work
around a broken run_python.

- Detect installs outside a virtual environment or the project (pip into a
  Python with no pyvenv.cfg, --user, uv --system, uv tool, pipx, conda
  without -p, npm/pnpm -g, yarn global, OS package managers), including
  inside cmd /c and powershell -Command bodies.
- Under full access they are refused with guidance; otherwise they are a
  one-time approval with a risk note, never 'always'.
- The shell session's folder is re-created when it is the scratch dir and
  reset to the start folder, with a note, when it was deleted.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes security Security-sensitive changes agents labels Oct 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

The diagnosis is right and most of the fix holds: the scratch folder is re-created before every run, start failures say what went wrong without counting as a failed call, and full access no longer lets an agent pip install into the user's system Python. One gap undercuts the headline fix, and one leaves a hole in the install guard.

  • The "last chat deletes it" protection doesn't work on macOS, or on Windows when the temp path uses a short RUNNER~1-style name. The cleanup compares two spellings of the same folder (as handed out vs. fully resolved), so on those machines they never match and the first chat to close deletes the shared folder anyway. The re-create-before-run repair stops the WinError 267 crash, but the other chat still loses whatever it had in the folder, and a run can lose its folder while it is running. Linux CI can't catch this because /tmp isn't a symlink there. Compare the resolved paths, or drop the comparison.
  • The install guard skips the check when the target is the Python GAIA itself runs from. GAIA's own environment is exempt even when it isn't a virtual environment. If GAIA was pip-installed into the system Python, python -m pip install openpyxl under full access still changes the system Python with no prompt, which is the exact incident this PR is meant to stop. Only exempt GAIA's environment when it really is a venv.

Real-world evidence

N/A: no evidence bundle was produced for this run. The verdict rests on static review and the PR's unit tests. Neither the shell/run_python behaviour in a live Agent UI session nor the full-access refusal was exercised here.

🔍 Technical details

🟡 The refcount guard is bypassed when the temp path isn't canonical (hub/agents/chat/python/gaia_agent_chat/agent.py:3156)
held comes from stable_scratch_dir(), i.e. Path(tempfile.gettempdir()) / ..., which is abspath-normalised only. self.scratch_dir comes from PathValidator.set_scratch_dir, which stores Path(path).resolve() (src/gaia/security.py:1093). On macOS (/var/folders/... → /private/var/folders/...) and on Windows with an 8.3 TEMP, scratch_dir == held is False. The non-last holder then falls through to shutil.rmtree(scratch_dir). _live_scratch_dir already clears _scratch_held when it switches folders, so the equality check isn't needed:

            if not release_scratch_dir(held):

A test that acquires through a symlinked temp dir (monkeypatch tempfile.gettempdir to a symlink) would pin this on Linux CI.

🟡 GAIA's own non-venv Python is exempt (src/gaia/agents/tools/package_installs.py:128)
root == sys.prefix returns None even when sys.prefix == sys.base_prefix, meaning GAIA itself is installed into a system Python.

    if sys.prefix != sys.base_prefix and os.path.normcase(str(root)) == os.path.normcase(
        os.path.abspath(sys.prefix)
    ):
        return None  # GAIA's own virtual environment

🟡 No live evidence for the user-facing tool change. The rubric expects a run showing the behaviour on the real surface: a full-access run_shell_command refusal and a run_python recovery after the scratch folder is deleted, via gaia chat --ui or the Agent UI MCP. Underlying-route evidence with the screenshot deferred to the strix-halo lane is enough.

🟢 The pre-flight check now has side effects (src/gaia/agents/tools/shell_tools.py:3304). _system_install_block → _call_cwd → _live_session_cwd can re-create the scratch folder or reset the session and set _shell_cwd_note during policy_refusal_for_call, before the user has approved anything. Reading self.shell_session.cwd directly there would keep the check read-only.

🟢 Weak assertion (tests/unit/test_system_package_installs.py:220). test_system_pip_install_is_never_an_always accepts either TIER_CONFIRM_ONCE or TIER_REFUSE, so it would still pass if ask mode started refusing outright. Pin the tier this environment actually produces.

Strengths

  • transient failures are kept out of both the streak and failed_calls, so a repaired environment doesn't trip the breaker. The breaker test covers both directions.
  • package_installs handles the important ways in: wrappers (timeout, env), cmd /c / powershell -Command bodies, a per-step cd before resolving the interpreter, and --target/--prefix. The refusal is checked both before the prompt and in the executor.
  • Start-failure messages tell the model explicitly not to install packages or switch interpreters, which addresses the behaviour behind the incident as well as the bug.

# Conflicts:
#	hub/agents/chat/python/gaia_agent_chat/agent.py
…paths

The first chat to close still deleted the shared scratch folder wherever the
temp path is not canonical (macOS /var -> /private/var, Windows 8.3 names),
because cleanup compared the path as handed out with the resolved one. The
held path alone now decides.

- The system-install pre-check reads the session folder instead of
  repairing it, so nothing changes before the user approves.
- The new lifecycle tests run in the chat-agent lane, where the chat wheel
  is installed, and the cleanup test gets its own anchor so agents other
  tests leave alive do not hold its folder.
- The ask-mode install test pins the one-time tier it actually gets.
@github-actions github-actions Bot added the devops DevOps/infrastructure changes label Oct 23, 2026
If GAIA was pip-installed into the system Python, an install through that
interpreter changed the system Python under full access with no prompt, which
is the case this guard exists to stop.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Both points are fixed now. Cleanup decides on the held path alone, so the first chat to close no longer deletes the shared folder when the temp path isn't canonical (533fcb6). GAIA's own Python is only exempt from the install guard when it's a virtual environment, so a GAIA installed into the system Python no longer gets a free pip install under full access. There are tests for both cases (latest commit). The pre-check is read-only again, and the ask-mode test pins the one-time tier.

# Conflicts:
#	src/gaia/agents/tools/shell_tools.py
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 23, 2026
Merged via the queue into amd:main with commit a66ec2a Oct 23, 2026
41 of 42 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/run-python-cwd branch October 23, 2026 12:13
kovtcharov-amd added a commit to tylerbea/gaia that referenced this pull request Oct 30, 2026
…reach (amd#5653)

Of the last 150 bug fixes, 147 shipped a regression test, yet CI caught
only about 7 of those bugs before users or RC testing did. Each test
guards the one call site that broke, and the next site with the same
flaw ships untested. Meanwhile every PR ran all ~27k unit tests on three
operating systems, even for a docs edit, and most main-branch runs were
cancelled before they finished. This PR guards the recurring bug shapes
everywhere, fixes a real bug the new tests found, and makes a PR run
only the tests it can affect.

- **Guards for the shapes behind most recent fixes.** A ratchet counts
subprocess and HTTP calls with no timeout, kill-by-image-name, and
`except Exception` bodies that only pass or return a placeholder.
Existing sites are grandfathered, new ones fail CI, and fixing one
lowers the count.
- **Folder grants were lost when several GAIA processes saved at once.**
A four-process test lost 96–98 of 100: the read-modify-write had no
lock, and a torn read "rebuilt" the file from empty. It is now locked
and atomic. Six runtime calls that could hang forever now time out, with
actionable errors.
- **PRs run only the reachable tests.** `util/select_tests.py` combines
a nightly per-test coverage map with static rules for what coverage
can't see. Windows and macOS run the OS-touching subset of that. The
median PR runs about a quarter of the suite. On ~1,150 recent commits,
it selected every bug fix's own regression test from the fix's source
changes alone.
- **Full coverage moves to main and nightly.** Every push to main runs
the full suite on Linux and now finishes instead of being cancelled. The
nightly run covers all three operating systems and rebuilds the map. The
frozen flagship binary also builds on packaging PRs and weekly, not only
at an RC.
- **Duplicates trimmed.** The email unit lane no longer re-runs ~90
files `test_unit.yml` already covers, and the warning-only C++
benchmarks run on main instead of every PR.

Also unbreaks main's TUI build: amd#5464 documented the desktop app's
`gaia` shim in backticks, and the TUI doc check only exempted it before
a space, so every PR's TUI checks went red. The shim is the Python
CLI's, so the exemption now accepts any punctuation after it.

Trade-offs to know: a Windows- or macOS-only bug outside the OS-touching
subset surfaces at the nightly run, not on the PR, and PRs no longer
upload partial coverage to Codecov. To run the full suite on a branch,
dispatch `test_unit.yml` on it.

## Test plan
- [x] `pytest tests/unit/test_select_tests.py
tests/unit/test_process_safety_ratchet.py
tests/unit/test_allowed_paths_concurrency.py`: 26 + 33 + 1 passed; the
concurrency test fails on the old code (96–98 of 100 grants lost)
- [x] Full `tests/unit` locally: 27,501 passed; 26 failures that fail
identically on main in this environment (PATH-installed `gaia`, real
wheel installs)
- [x] `python util/lint.py --all` passes, including the lane-coverage,
path-coverage, trigger and ancestor-skip checks
- [x] Selector replayed over ~1,150 recent commits with a map built from
a real `--cov-context=test` run
- [ ] After merge: the first nightly run saves `unit-test-map-*`, and
the next PR's "Select unit tests" summary reports a map-based selection

<details>
<summary>🔍 Technical details</summary>

- Static rules: module-level imports (transitive); every import and
module-naming string in tests and tooling (transitive); filename strings
and directory scans (one hop); nested `conftest.py`; top-level fixtures
by requested name, through fixture chains; autouse isolation fixtures
(one hop); CLIs run with `python -m`, whose lazy imports coverage can't
see. A package `__init__` reaches everything below it when it changes,
but the walk never continues through one.
- Full-run triggers: any `conftest.py`, packaging or pytest config, the
selector or `test_unit.yml`, and any deleted or renamed file (`git diff
--no-renames`). So does a selection over 70% of the suite.
- With no map (a cache miss), function-level imports are followed too
and the job summary says so; a map over 3 days old raises a warning.
- A push diffs against the last commit a successful main run tested, so
merges whose runs were dropped while pending still reach Windows and
macOS. The event name is in the concurrency group, so a push can't drop
the nightly.
- Known blind spot, documented in `docs/reference/dev.mdx`: code behind
a cache or shared fixture is credited in coverage only to the first test
that ran it.
- Open PRs touching the same files (amd#5453, amd#5417, amd#5511, amd#5600, amd#5475,
amd#5542, amd#5558) test-merge cleanly against this branch; none gains a
conflict from it.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: v <v@x>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents devops DevOps/infrastructure changes 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