Skip to content

fix(shell): name shell control flow instead of reporting a missing file - #4044

Closed
kovtcharov wants to merge 8 commits into
amd:mainfrom
kovtcharov:claude/name-shell-keywords
Closed

kovtcharov wants to merge 8 commits into
amd:mainfrom
kovtcharov:claude/name-shell-keywords

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Asking the agent to run a shell loop told it the file for was missing:

[Errno 2] No such file or directory: 'for'

That reads as a PATH problem, so the agent goes looking for an install or a broken environment. Commands run directly rather than through a shell, so for is not a binary that happens to be absent — it can never run, whatever the environment. The refusal now says that, and names run_python as the thing that does handle a loop.

Two different agents hit this in a benchmark run and each spent steps on it before giving up.

Test plan

  • pytest tests/unit/test_shell_control_flow_message.py — for, while, if, until, select each named, none reported as a missing file
  • The refusal names run_python
  • find still runs — it begins with fi, so matching is on the whole token, not a prefix
  • All shell suites pass: 642 passed, 3 skipped
  • black / isort / flake8 clean
  • gaia eval agent --category tool_selection shows no regression against the baseline
🔍 Technical details

Adds SHELL_KEYWORDS next to ALLOWED_COMMANDS in src/gaia/agents/tools/shell_tools.py, checked in _validate_command just before the allowlist branch, returning TIER_REFUSE — this is not a permission question, since no approval could make for executable.

case is covered by a separate test rather than the parametrized list: it uses ;;, which the compound-command separator check catches first as an empty command between separators. That refusal is already clear, so the test pins that it stays clear rather than falling through to exec.

@github-actions github-actions Bot added documentation Documentation changes devops DevOps/infrastructure changes llm LLM backend changes cli CLI changes eval Evaluation framework changes tests Test changes security Security-sensitive changes performance Performance-critical changes agents tui Go terminal UI (gaia-tui) sidecar Agent sidecar contract / harness labels Sep 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

The title and description are about one thing — the shell refusal that told the agent the file for was missing — but the branch carries roughly a hundred commits and 14k added lines, including a new session-wide full access mode that turns confirmation prompts off and persists that choice to disk. The shell change itself is good and well tested. The problem is that nobody can review what's actually here from what's written.

What needs to happen before merge:

  • Describe the PR, not the last commit. Group the bundled work into a handful of themes a reviewer can evaluate independently — full access, compound shell commands, the skill-catalog rewrite, agent scratch directories, backups moving out of the working tree, the loop-guard and step-limit answers, read-before-edit, the new wait tool. Right now the permission-bypass feature is invisible in the description, and it's the highest-stakes thing in the diff.

  • Run the agent eval. It's the one unchecked box in the test plan, and the eval jobs are being skipped in CI. This branch rewrites the system prompt's skill section, adds a tool, rewrites the shell tool's docstring, and changes how errors are classified — all four are on the list of changes the project requires an eval for. Green unit tests don't cover any of it.

  • Stop should interrupt a throttled shell command. When the rate limiter kicks in, the shell tool now waits instead of refusing — but it waits in one uninterruptible block of up to a minute. Pressing Stop during that window does nothing and the session just looks hung. The new wait tool in this same PR already solves this by waking up twice a second to check; the shell path should do the same.

Real-world evidence

N/A — no evidence bundle was produced for this run, so the verdict rests on static review alone. That matters more than usual here: /full-access is a TUI surface and a shell-permission change, and neither the TUI banner nor a real run_shell_command chaining a command was exercised anywhere I can see. The eval lane that would have covered the prompt and tool-selection changes is reporting skipping. Please attach a TUI screenshot with full access on, and the eval scorecard diff against the Gemma baseline.

🔍 Technical details

🟡 Important

PR bundles ~100 commits behind a single-commit description

The description documents SHELL_KEYWORDS in src/gaia/agents/tools/shell_tools.py (~30 lines). The branch is +14,240 / −4,532 across 185 files and also lands:

  • Full access: OutputHandler.full_access (src/gaia/agents/base/console.py:213), GaiaConfig.full_access (src/gaia/config.py), tui/internal/ui/preflight/fullaccess.go, and the bypass.go → fullaccess.go rename.
  • A new positive-approval channel: src/gaia/agents/base/approval.py.
  • Compound command lines in the shell tool — && / || / ; / cd / leading NAME=value / 2>&1 / 2>/dev/null, plus a hand-rolled pipeline runner (_run_pipeline).
  • skill_discovery.py + skill_retriever.py deleted and replaced by skill_catalog.py; three test modules and util/skill_retrieval_bench.py removed with them.
  • create_backup relocated to ~/.gaia/cache/backups (src/gaia/security.py), stable_scratch_dir, loop-guard corrections and step-cap closing answers in agent.py, read-before-edit in file_edit.py, WaitToolsMixin, and a new util/check_tool_descriptions.py lint gate.

Per CLAUDE.md's PR-description rules, a PR that genuinely bundles threads should group them — four themes, not sixteen bullets and not one.

Eval not run for LLM-affecting changes

Unchecked test-plan item; rag_quality + context_retention + tool_selection vs Gemma baselines and Flagship agent tasks vs expectations both report skipping on this PR. CLAUDE.md lists four triggers this PR hits:

  • System prompt: CATALOG_HEADER / GROUNDING_RULE in src/gaia/agents/base/skill_catalog.py now sit in the prompt head.
  • Tool registration: sleep (src/gaia/agents/tools/wait_tools.py:41), registered via KNOWN_TOOLS["wait"].
  • Tool docstrings: run_shell_command's description rewritten (shell_tools.py:2143).
  • Error classification: _LOOP_CONNECTION_RE / _LOOP_NOT_PERMITTED_RE and _build_loop_break_summary in agent.py.

_pace_rate_limit blocks up to 60 s without checking for cancellation (src/gaia/agents/tools/shell_tools.py:1503)

cap = getattr(self, "max_rate_limit_wait_seconds", 60.0)
...
time.sleep(wait_time)

WaitToolsMixin._sleep in this same PR naps in _STOP_POLL_SECONDS (0.5 s) slices and calls _wait_interrupted() precisely so console.cancelled / _cancel_event / tool_cancelled() are honoured. The shell path should reuse that loop. Separately, max_rate_limit_wait_seconds exists only as a getattr default and a test attribute — it is never initialised in ShellToolsMixin.__init__ alongside max_commands_per_minute / max_commands_per_10_seconds, so the documented knob isn't discoverable:

        self.max_commands_per_10_seconds = 3
        self.max_rate_limit_wait_seconds = 60.0

🟢 Minor

Unreachable branches after the path-traversal check (shell_tools.py, in run_shell_command)

error = self._path_traversal_refusal(step, step_cwd, granted)
if not error:
    continue
if not _reaches_the_prompt(error):
    return error
if blanket_only:
    return self._blanket_approval_refusal(error)
if not approved:
    return self._unapproved_refusal(error)

_path_traversal_refusal never sets tier, so _reaches_the_prompt(error) is always False and the last four lines can't run. The comment above the block already says path refusals are "refused, never offered" — drop the dead branches so the code says the same thing.

--all check numbering is now off (util/lint.py)

check_tool_descriptions prints no [n/m] prefix, and check_doc_versions still prints [12/12] although it is now the 13th check.

Tier omitted on some refusals in the same function (shell_tools.py, _cd_shape_refusal)

Two branches set "tier": TIER_REFUSE; the third (cd with an environment assignment) omits it, as do _env_refusal, _no_command_refusal, and the unattached-stderr-redirection error. Omission fails closed by design, but three of four siblings relying on that is easy to break later — set it explicitly.

Strengths

  • src/gaia/agents/base/approval.py is the right shape for this problem. A ContextVar ticket set only by Agent._execute_tool, keyed to the tool name and the exact arguments, absent by default, and reset around a single dispatch — so a bare mixin, a unit test, or a nested tool call all read "not approved". Replacing "no blanket-approval flag was set" with positive evidence is what makes the new CONFIRM tier safe.
  • Full access is confined to the user's own file. ~/.gaia/config.json only, JSON boolean only (GaiaConfig._coerce rejects "yes", and readFullAccess treats corrupt or absent as off), banner on every frame, and gaia-agent.yaml / TUI both naming the source. A cloned repo's .env can't switch off someone's prompts.
  • Classifying before the grant check in _validate_command closes a real ordering hole: a REFUSE-tier invocation like gh auth token is now refused on what it does rather than falling through to the weaker confirmation prompt when the binary happens to be ungranted.
  • Ten new shell test modules covering pipelines, connectors, stderr redirection, env assignments, approval paths and rate pacing — the compound-command work is the best-tested part of the diff.

Kalin Ovtcharov and others added 8 commits September 21, 2026 04:14
On macOS and Linux every piped shell command returned wrong output with
status "success". The validator drops the `|` tokens and the executor then
ran the segments as one argv, so `cat notes.txt | sort` ran as
`cat notes.txt sort` and `grep a x.txt | wc -l` returned "x.txt" instead of
a count. Windows was unaffected because it goes through cmd.exe.

Validated segments are now chained as separate processes, still without a
shell. The exit code is the rightmost failing stage, so `pytest | tail`
cannot turn a failing suite into a verified pass; an upstream stage killed
by SIGPIPE (`| head`) is not a failure. Every stage's stderr is kept, and a
timeout kills the whole pipeline.

test_a_pipeline_is_not_run_as_argv only pinned the shell flag, so it passed
while the bug was live; it now checks that the stages are chained.
Agents reach for `python -m pytest` first, and the shell refused it with
"only read-only commands are allowed" - no hint that pytest exists behind
the coding skill. In a 14-task benchmark run on main that dead end was hit
5 times; the agent gave up on the tests and twice reported them as passing.

`python -m pytest` is now judged as `pytest`: same grant, same flag and path
policy, no extra prompt. Without the grant it gets pytest's "load that skill
first" refusal. The typed spelling is what runs, because `-m` puts the
working directory on the import path, so a checkout that was never
installed imports without a pytest.ini workaround. Only the exact
`python|python3|py -m pytest` shape maps; `-c`, a script, another module or
an interpreter flag stays refused.

An inline `PYTHONPATH=. pytest` was refused as an unknown command named
"pythonpath=."; it now says inline environment assignments are unsupported.
A shell command over the rate limit (3 per 10 s, 10 per minute) was refused
with "wait N seconds", so the model spent a whole step sending the same
command again after the same wait. In a benchmark run the refused command was
the recovery itself - `python -m pytest` right after bare `pytest` failed to
import the project - in 2 of 14 tasks.

The tool now waits for the window and then runs the command, reporting
waited_seconds. The rate stays exactly as capped; a wait longer than
max_rate_limit_wait_seconds (60 s) is still refused.
The shell tool refused `&&`, `||` and `;` outright, so work that is one call
elsewhere — `cd src && ls`, `pytest -q | tail -5; grep -rn parse_` — cost GAIA
three or four. Two benchmark runs of 14 tasks hit 4 operator refusals and about
7 recovery steps, and used 100 steps where Claude Code used 82; every extra step
re-sends a ~12K-token prompt, and fresh input is 53% of the cost.

A line is now split into its pipelines, and every segment of every pipeline goes
through the same tiered validation as before, before any of it runs: one refused
command refuses the whole line, one confirm-tier command raises a single prompt
showing the whole line, and a skill grant covers the line only when it covers
every segment. The steps then run sequentially in-process with sh's semantics —
`&&` on success, `||` on failure, `;` regardless — through the existing pipeline
runner, so no line reaches a shell on POSIX and Windows gets one pipeline per
cmd.exe call instead of the line. `cd <dir>` is allowed as a bare one-argument
command, path-validated like `working_directory`, and moves only the rest of its
own line.

Redirection, command substitution, a background `&` and inline `VAR=value` are
still refused; newlines now are too, which they were not before, and cmd.exe
reads one as a command separator. The line costs the rate limiter one command
because it is one model step, and a failure no `||` handled still sets
`has_errors`, so `pytest -q; ls` cannot report a failing suite as a passing
check.
Across seven benchmark runs of 14 tasks on four models, 19 of the 21 shell
operator refusals were `2>/dev/null` or `2>&1` — neither of which creates a
file. They are how every model asks for a test run (`pytest -q 2>&1 | tail -20`,
`ls tests/ 2>/dev/null`), each refusal cost the call plus a median of one more
to recover (43 wasted tool calls, ~5% of all of them), and the refusal's own
hint said to use `write_file`, which is not advice for a stderr redirect. One
measured case became a false claim: the agent could not test a patch in a
scratch copy, and reported a later run against unpatched code as if it had
covered the patch.

Both forms are now lifted out of the line before the operator scan and recorded
as a flag on the segment that wrote them — exact standalone tokens only, and
never inside double quotes. `2>&1` points that segment's stderr at its own
stdout pipe, so a later stage's `grep` sees it; `2>/dev/null` points it at the
null device. Neither names a file, and on POSIX neither reaches a shell: they
are destinations for a stream this process already captures. On Windows the
step is a cmd.exe string, so the redirection travels in it, spelled `2>nul`.

Everything else stays refused: `2>` to any other path, `1>`, `>`, `>>`, `<`,
`&>`, `>&`, backticks, `$()`, `&`, and newlines. Return codes are untouched, so
discarding stderr cannot turn a failing command into a passing one.
Every inline assignment the shell tool refused across four models' benchmark
runs was a PYTHONPATH the agent needed to import the project under test —
`PYTHONPATH=. pytest -q tests/` and two variants, three of the 28 measured shell
refusals. The refusal's hint said to run the command without the assignment,
which fails with ImportError, so the agent was left with no way to verify its
own work and wrote a throwaway runner script or gave up.

Leading `NAME=value` tokens are now split off each segment of a line and applied
as that subprocess's environment. The value never reaches a shell — it is an
entry in the env dict handed to the process — and what is left after the
assignments is what the allowlist sees, so `PYTHONPATH=. rm -rf /` is refused
exactly as `rm -rf /` is. The variable reaches that one process: not a later
segment, not a later step, and never this process's own environment. On Windows
a step carrying one runs as argv rather than through cmd.exe, which would apply
it to the whole string.

The names that change WHICH binary runs, or what code one loads, stay refused by
family, so the list does not go stale the next time one of these tools adds a
hook:

- the dynamic linkers (LD_*, DYLD_*, GCONV_*), the shells (BASH_*, SHELL, ENV,
  IFS) and PATH itself
- the hook and option variables of the binaries this tool can actually run:
  GIT_* (GIT_SSH_COMMAND, GIT_EXTERNAL_DIFF, GIT_CONFIG_* inject commands), GH_*
  (GH_PAGER runs one), PYTEST_* (PYTEST_ADDOPTS re-injects the flags the pytest
  grant denies), LESS* (LESSOPEN is an input filter), NODE_*, PERL*, RUBY*,
  JAVA*, PS*
- PAGER/EDITOR/VISUAL/BROWSER, and the PYTHON* variables that run code
  (PYTHONSTARTUP, PYTHONHOME, PYTHONEXECUTABLE, PYTHONBREAKPOINT)

Matching is case-insensitive, because Windows matches environment names that
way. PYTHONPATH is deliberately not on that list: its containment is that every
assignment's value is path-checked against the agent's allowed paths — on every
segment, granted binaries included, because a value is never a remote id.
Asking the agent to run `for f in a b; do ...; done` told it
`[Errno 2] No such file or directory: 'for'`, which reads as a PATH problem
and sends it hunting for an install. Commands run directly rather than
through a shell, so `for` is not a binary that happens to be absent — it can
never run, and the refusal now says so and names run_python as the thing that
can.

Seen in a benchmark run, where two agents each burned steps on it.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #4042 (allow-scoped-env-assignment), and now carries only its own commit. Merge after #4042.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Everything in this PR is already on main, so there is nothing left to merge.

It landed as part of #4049, which squash-merged the tip of the stack this branch sits in and carried every commit below it along. GitHub does not auto-close the lower PRs in a stack when the tip is squashed, which is why this stayed open — and why it has been showing a conflict against a main that already contains its work.

Closing as superseded. No work is lost; reopen if you disagree.

🔍 Technical details

Verified rather than assumed — merged origin/main into this branch taking main's side, then diffed the result against main:

git checkout -B probe <branch> && git merge origin/main --no-edit -X theirs
git diff --stat origin/main HEAD

Residual: empty. The merge produces a tree identical to main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents cli CLI changes devops DevOps/infrastructure changes documentation Documentation changes eval Evaluation framework changes llm LLM backend changes performance Performance-critical changes security Security-sensitive changes sidecar Agent sidecar contract / harness tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants