Skip to content

fix(tools): run scripts from the project root so tests can import the project - #3902

Merged
kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:claude/fix-3890-read-dir-exec-cwd
Sep 25, 2026
Merged

kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:claude/fix-3890-read-dir-exec-cwd

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Asking the agent to run a project's test file used to fail before any test ran. execute_python_file ran every script from the script's own folder, so tests/test_dates.py doing from toybox import dates died with ModuleNotFoundError: No module named 'toybox': the project root was neither the working directory nor on the import path. Now a script inside the agent's project directory runs from that directory, with it on PYTHONPATH, so project tests import the project the way they do under pytest. A script outside the project still runs from its own folder.

Found in the same 168-run Fireworks benchmark as #3890. Models made the identical failing call over and over, and in two runs the loop guard ended a task that was already finished.

The directory half of #3890 (read_file on a folder) is left to #3891.

🔍 Technical details
  • The project directory comes from resolve_project_root: the config's project_root, then GAIA_PROJECT_ROOT, then the nearest code repository at or above the working directory, never the home directory. The flagship defers to its project map's cached root, so the map and a script's working directory always name the same tree. With no project, a script runs from its own folder with the environment untouched. An existing PYTHONPATH is kept, after the project root.
  • Only flat-layout projects become importable; a src/ layout would need src/ on the path.
  • The sandbox check (is_path_allowed) and existence check are unchanged and still run first.
  • One behavior change: a project script that opens files by a path relative to its own folder now resolves them against the project root. The tool docstring says where scripts run, so the model can see this.
  • The docstring is part of the LLM-visible tool schema. No agent eval was run for this PR.
  • fix(agents): name a directory instead of leaking a raw errno from file tools #3891 fixes FileIOToolsMixin.read_file but not FileSearchToolsMixin.read_file in file_tools.py, which the chat profiles also register and which still hits the raw errno.

Test plan

  • pytest tests/unit/test_execute_python_file_cwd.py (9 passed): a temp project's tests/test_x.py doing from pkg import mod runs through the registered tool with return code 0 and cwd = project root, also when launched from tests/. Also covers the no-project case, a bad GAIA_PROJECT_ROOT, PYTHONPATH preservation, and a real GaiaAgent whose script cwd follows its project map after a chdir.
  • Related suites pass: tests/unit/test_chat_agent_integration.py, tests/unit/agents/test_tool_arg_coercion.py, tests/unit/agents/test_confirmation_required_tools.py, tests/unit/test_starter_skills.py, the prompt-budget tests, hub/agents/chat/python/tests (265 passed, 15 skipped)
  • gaia chat in a project with a tests/ folder: ask it to run one test file and confirm the imports resolve

… project

execute_python_file ran every script from the script's own folder, so a
project test such as tests/test_dates.py failed with ModuleNotFoundError
for the project's own package. In the Fireworks benchmark that produced
repeated identical failures, and twice the loop guard ended a run whose
task was already done.

A script under the agent's project directory (config project_root, else
the working directory) now runs from that directory with it prepended to
PYTHONPATH. Scripts outside it still run from their own folder. The
sandbox and existence checks are unchanged.
@github-actions github-actions Bot added the tests Test changes label Sep 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

Good catch and a real fix — running a project's test file from the project root with the root importable is exactly right, and the unit test reproduces the original ModuleNotFoundError honestly. The problem is how the project root is decided: the PR invents its own rule instead of using the resolver GAIA already has, and that rule misbehaves in the two most common places users actually launch the agent.

Blocking issues

  1. The fix doesn't fire when the agent is started inside a subfolder of the project. "Project root" here just means "wherever the agent was launched." Start the agent from a project's tests/ folder and asking it to run a test file still fails to import the project — the exact bug this PR set out to kill. GAIA already has a resolver that walks up to the real repository root and honours the project-root environment override; use it rather than a second, weaker rule.

  2. When there is no project, the new rule regresses scripts that used to work. The flagship agent's normal scope is the user's home directory, so "launched from home" is the ordinary case, not an edge one. A script that previously ran from its own folder now runs from home, so any file it opens by a relative path is looked for in the wrong place — and putting home on the import path lets a stray file sitting there quietly stand in for a real library when the script imports it. The existing resolver deliberately refuses to call home a project; when there's no project, keep the old behaviour of running the script from its own folder.

  3. No agent eval was run, and the change edits a tool docstring. The description says so plainly, which is appreciated — but tool docstrings are part of what the model sees, and the project rule is that those changes get an eval run against the committed baseline before merge. Please run it for the relevant category and post the comparison.

Real-world evidence

N/A — no evidence bundle was produced for this run, and this review lane has no pytest installed, so I could not execute the new test myself. The PR's own test plan leaves the one end-to-end item (gaia chat running a test file in a real project) unchecked; that's the item that would have surfaced blocking issues 1 and 2, so please tick it before merge rather than relying on the unit test alone.

🔍 Technical details

🟡 Important

1. project_root resolution duplicates — and weakens — resolve_project_root() (hub/agents/chat/python/gaia_agent_chat/agent.py:1504)

p, getattr(self.config, "project_root", None) or os.getcwd()

src/gaia/agents/base/project_map.py:451 already owns this question, and GaiaAgent composes ProjectMapMixin, which exposes it cached as _project_map_root() (project_map.py:661). The canonical resolver does three things this line doesn't:

  • honours GAIA_PROJECT_ROOT
  • ascends from cwd to the nearest enclosing repository (_MAX_ASCEND levels) — so launching from myproj/tests/ still yields myproj/
  • returns None rather than the home directory (project_map.py:478), which is the guard issue 2 is missing

Note GaiaAgentConfig.project_root defaults to None and its own comment says None "resolves through GAIA_PROJECT_ROOT, then the working directory or the nearest repository above it" — the raw getattr reads the field before that resolution, so the documented contract isn't honoured.

2. os.getcwd() fallback regresses non-project runs (agent.py:1504, helper at agent.py:86)

GaiaAgentConfig.allowed_paths defaults to [str(Path.home())] (hub/agents/gaia/python/gaia_agent/agent.py:209), so launching from $HOME is the documented normal case. With cwd = $HOME:

  • cwd for the child becomes $HOME, so a script doing open("data.csv") relative to its own folder breaks — the PR description acknowledges the relative-path change, but frames it as scoped to "a project script"; here it hits every script.
  • PYTHONPATH=$HOME is injected, and PYTHONPATH entries precede the stdlib in sys.path, so a stray ~/types.py / ~/email.py shadows a real module in the child process.

Combined fix for both — treat "no project" as the old behaviour:

                run_dir, env = python_script_run_context(
                    p,
                    self._project_map_root()
                    if hasattr(self, "_project_map_root")
                    else resolve_project_root(
                        getattr(self.config, "project_root", None)
                    ),
                )

with the helper taking Optional[os.PathLike | str] and returning (script.parent, dict(os.environ)) when it is None. Two extra cases worth a test: project_dir=None, and cwd inside a subdirectory of the project.

(resolve_project_root raises ValueError on a configured path that isn't a directory — that's the intended fail-loud behaviour, but confirm it surfaces as a tool error dict rather than escaping the tool call.)

3. Missing eval run for an LLM-visible surface (agent.py:1469-1473)

CLAUDE.md lists "tool docstrings, or the JSON tool schema sent to Lemonade" among the changes that require gaia eval agent against the committed baseline before merge. The description states none was run. Claude access from a Claude Code session comes from the subscription, so an unset ANTHROPIC_API_KEY isn't a blocker here.

🟢 Minor

  • python_script_run_context is module-level and therefore public in the gaia_agent_chat package surface, but isn't in __all__ or referenced anywhere outside the one call site and the test. Either keep it private (_python_script_run_context) or note the intent — the test can import an underscore name fine.
  • The test's tool-registry save/restore around ChatAgent(config) is careful, but it leaks if ChatAgent.__init__ raises before saved is taken — saved = dict(_TOOL_REGISTRY) is already first, so this is fine as written; worth keeping that ordering if the fixture grows.

Strengths

  • The test file leads with why the bug existed (the loop-guard retry storm) rather than restating the assertions, and covers the helper directly as well as through the registered tool — including PYTHONPATH preservation and the outside-project path.
  • The PR description is honest about the one behaviour change (relative paths now resolving against the project root) and about the skipped eval, instead of quietly shipping both.
  • The fix is correctly ordered behind the existing sandbox (is_path_allowed) and existence checks, so it doesn't widen what the tool can reach.

…does

Running a project's test file from a subfolder still failed to import the
project, and running any script from a home directory quietly changed what
it could see.

execute_python_file had its own project-root rule — config value, else the
working directory — so starting the agent in myproj/tests/ never found
myproj/, the exact case the fix targeted. It now calls the canonical
resolve_project_root(), which honours GAIA_PROJECT_ROOT, ascends to the
nearest enclosing repository, and answers None outside a project.

None restores the old behaviour exactly: the script runs from its own
folder with the environment untouched. That matters because allowed_paths
defaults to the home directory, so the previous cwd fallback made $HOME the
working directory and put it on PYTHONPATH, breaking relative reads next to
the script and letting a stray ~/email.py shadow a stdlib module.

A bad GAIA_PROJECT_ROOT now surfaces as a tool error dict instead of
escaping the tool call.
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

execute_python_file used to run every script from its own folder, so a test file doing from mypackage import thing always failed with ModuleNotFoundError. This PR fixes that: scripts inside the detected project root now run from that root with it prepended to PYTHONPATH, while standalone scripts and any run without a project retain the old behaviour unchanged.

The implementation is well-decomposed: _python_script_run_context is a pure module-level helper (easy to unit-test in isolation), and _script_project_root correctly defers to ProjectMapMixin._project_map_root when a GaiaAgent is in use, so the script's cwd and the project map never disagree about which tree they mean.

Tests cover all the meaningful cases: happy path from both the project root and a subdirectory, the no-project fallback, a misconfigured GAIA_PROJECT_ROOT (returned as a structured tool error, not a crash), and direct unit tests of the helper. No substantive gaps.

One nit (🟢): src-layout projects (packages under src/) won't gain importability from this change — the project root is prepended, not src/. That's a deliberate non-goal for now (such projects use pytest via the shell tool), but a comment in _python_script_run_context or the docstring noting the flat-layout assumption would help the next reader.

🔍 Technical details

hub/agents/chat/python/gaia_agent_chat/agent.py:17-38 — the helper correctly prepends the project root to PYTHONPATH and returns the project as the cwd. For a src-layout project (src/mypkg/), import mypkg would still fail because src/ is not on the path. Adding a note in the docstring ("flat-layout projects only; src-layout projects need src/ which this function does not add") would save the next contributor from having to rediscover this.

agent.py:1048-1057 — _script_project_root checks hasattr(self, "_project_map_root") at runtime to detect ProjectMapMixin. The pattern is correct (GaiaAgent has it, bare ChatAgent does not), but the tests only exercise the ChatAgent path. Not a bug, since _project_map_root is already exercised by its own tests, but a GaiaAgent-based fixture in this file would close the loop completely.

A script run by the flagship now has a test proving it runs in the project
the project map describes, even after the process changes directory. The
run-context helper also notes that only flat-layout projects become
importable, since a src/ layout needs src/ on the path.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Both follow-ups are in. The helper's docstring now says only flat-layout projects become importable. A new test covers the flagship path: its scripts run in the project the project map describes, even after the process changes directory.

🔍 Technical details

All changes are in 0e75567.

Review item Outcome
🟢 src/-layout note Added to _python_script_run_context's docstring: a src/ layout needs src/ on the path, which this does not add. The LLM-visible execute_python_file docstring is unchanged.
🟢 GaiaAgent-based fixture Added TestTheFlagshipFollowsItsProjectMap. It builds a real GaiaAgent from project/tests with memory and auto-indexing off, checks _project_map_root() is the project, then chdirs to a directory with no project and runs the test file. It must still run from the project root and import pkg. Disabling the _project_map_root branch in _script_project_root makes it fail, so it covers the mixin path rather than duplicating the ChatAgent tests.

Tests: test_execute_python_file_cwd.py 9 passed. With the chat-agent integration, tool-arg coercion, confirmation-gate, starter-skill and hub/agents/chat/python/tests suites: 262 passed, 15 skipped. The branch merges cleanly into current main, and the same suites pass on that trial merge.

The first review's eval request still stands, because the tool docstring changed. It runs in the self-hosted CI job once a maintainer pushes this branch to amd/gaia; it can't run on this machine. The live gaia chat box stays unticked.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Refreshed this branch against current main so it can merge again — the branch had fallen far enough behind that GitHub could no longer compute a merge.

The update was a clean merge: nothing was resolved by hand, and no commit on this branch was rewritten. CI now runs against an up-to-date base.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into amd:main with commit ffe2acd Sep 25, 2026
28 of 29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants