Skip to content

feat(shell): adaptive timeouts and a wait-for-condition primitive - #3402

Merged
kovtcharov-amd merged 14 commits into
mainfrom
kalin/3382-adaptive-shell-timeouts
Sep 25, 2026
Merged

kovtcharov-amd merged 14 commits into
mainfrom
kalin/3382-adaptive-shell-timeouts

Conversation

@kovtcharov-amd

@kovtcharov-amd kovtcharov-amd commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

The agent could not run anything that takes minutes. A shell command was killed at 30 seconds no matter what it was, so a test suite, a build or an install never finished — and a timed-out command on Windows did not even stop: a verified 5-second timeout took over two minutes and never returned, because the kill missed the grandchild still holding the pipes. Waiting was just as bad: with no way to wait for a condition, the agent slept and re-checked, which is what a user sees as spinning and what burns the loop's step budget. Now the timeout comes from what the command is — 900s for test runners, 1800s for builds and installs, 300s for git/network calls, 30s for everything else — the kill actually fires, Stop still lands while a command is running, and wait_for_condition waits for a server to answer or a file to appear in one step instead of one per check.

Closes #3382.

🔍 Technical details
  • The class table is src/gaia/agents/tools/command_timeouts.py — four named classes, one default each, plus the classifier. Wrappers are transparent (python -m pytest, uv run pytest, npx jest), and a pipeline takes its longest segment.
  • An explicit timeout= still wins; out of range is refused, not clamped, so a command is never killed at a limit its caller did not choose.
  • The signal reaches the model through the docstring: the registry takes a tool's description from __doc__, and the non-native prompt path renders only its first line. A test fails if a class default drifts out of that line.
  • The executor drives Popen and waits on it in short slices, so it kills the process tree both at the deadline (taskkill /T / process group) and the moment Stop lands — the per-tool guard is now over an hour, so nothing else would end a 30-minute build early. Partial output is truncated to 10K like the success path.
  • The longer classes only apply to a binary a loaded skill granted (shell:execute:<binary>); the base allowlist is read-only and refuses pytest/pip/npm outright. The guide says so, and a test drives a granted binary through the real allowlist into the test class.
  • wait_for_condition is confirmation-gated, runs its predicate through run_shell_command (same allowlist, refused before the prompt), is charged once against the shell rate limit rather than once per probe, and wakes on both cancel channels immediately.
  • A call stopped before it reached a process reports executed: False, so the verification footer (fix(agent): verification footer counts rejected test commands as executed #3677) never calls a refused check one that ran.

Test plan

  • python -m pytest tests/unit/test_shell_adaptive_timeouts.py tests/unit/test_shell_guardrails.py tests/unit/test_shell_output_encoding.py tests/unit/test_skill_binary_grants.py -q — 393 pass. Each timeout class is asserted as the budget the command is really killed at, plus the wait primitive's deadline, and Stop landing before, during, and between commands.
  • python -m pytest tests/unit/agents/ -q — 783 pass; covers the verification-scope contract this touches.
  • python util/lint.py --all — clean.
  • Live check on Windows, real subprocesses: a command that previously hung on timeout returns in 5.1s with its partial output; a wait for a file created after 8s returns at 11.7s after 3 polls and one rate-limit charge. test_a_blown_deadline_really_kills_the_process pins it with a real child process.
  • gaia eval agent --category tool_selection on Gemma-4-E4B — judged pass rate unchanged vs the gemma-4-e4b-d71cd914 baseline (75% → 75%), avg score 8.4 → 8.7. known_path_read went FAIL → PASS. Nothing prompt-visible has changed since that run: the tool docstrings are byte-identical.
  • Expected red: the rag_quality + context_retention + tool_selection check — Eval gate fails identically on main: tool_selection scenarios die in 3s and claude's stderr is swallowed #3341 tracks it failing identically on main.

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

github-actions Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Verdict: Request changes

This gives shell commands a timeout that matches what they are (test runs get 15 minutes, builds 30, network calls 5, everything else 30 seconds), makes a timed-out command actually die instead of hanging on a surviving grandchild, and adds a wait_for_condition primitive so waiting costs one agent step instead of sixty. The core work is careful and well-tested — but it registers a new tool without updating the tool counts the packages publish, which breaks a CI drift guard.

What needs fixing before merge:

  1. The new tool isn't counted anywhere except the docs. Adding wait_for_condition grows every chat profile's tool registry by one. The guide was updated from 67 to 68, but the two shipped package manifests and the three per-profile registration counts still declare the old numbers. There are tests that compare those declared numbers against the real registry, so this fails CI — and the flagship's published manifest would under-report what it offers.

  2. Stop no longer interrupts a running shell command. The per-tool guard was raised from 3 minutes to just over an hour so a long build isn't abandoned mid-run — but nothing checks the cancel signal while the command runs. Before this change a user clicking Stop waited at most half a minute; now they wait until a 30-minute build finishes. wait_for_condition already does this right by waiting on the cancel event; run_shell_command should do the same and kill the process tree when it fires.

  3. The longer timeout classes can't be reached by default, and the guide implies they can. The shell allowlist is read-only — pytest, pip, npm, make, curl, docker and git clone/fetch/pull/push are all refused unless a loaded skill grants that binary. So today essentially every command still lands in the 30-second class. The new guide paragraph promising 15-minute test runs sits one paragraph after the sentence saying installs and arbitrary binaries are refused, which reads as a contradiction. Say the longer classes need a skill grant, and add one test that drives a granted binary through the real path — every classification test currently disables the allowlist.

Real-world evidence

The automated evidence harness failed to run on this PR (evidence-bundle.md reports an error before producing any evidence), so the changed surface was not exercised here and this verdict rests on static review alone. The PR description does describe a live Windows run and a tool_selection eval, but the harness did not confirm either and every test-plan box is unchecked. Given finding 1 predicts a CI failure, please confirm the full unit suite is green before merge.

🔍 Technical details

🔴 Critical

tools_count drift — new tool registered, every literal left stale (hub/agents/gaia/python/gaia_agent/__init__.py:77)

register_shell_tools() now registers two tools (run_shell_command, wait_for_condition), and every ChatAgent profile calls it unconditionally — including the early-return chat profile (hub/agents/chat/python/gaia_agent_chat/agent.py:1295,1300). So every profile's real registry size is +1. The docs moved 67→68; these did not:

Location Declared Should be
hub/agents/gaia/python/gaia-agent.yaml:23 67 68
hub/agents/gaia/python/gaia_agent/__init__.py:77 67 68
hub/agents/chat/python/gaia-agent.yaml:14 54 55
hub/agents/chat/python/gaia_agent_chat/__init__.py:93 (build_chat) 1 2
hub/agents/chat/python/gaia_agent_chat/__init__.py:122 (build_doc) 37 38
hub/agents/chat/python/gaia_agent_chat/__init__.py:152 (build_file) 33 34

tests/unit/test_chat_fix_contracts.py::test_yaml_top_level_tools_count_matches_default_profile_registry and ::test_registration_tools_count_matches_real_registry introspect the registry and assert against these literals — all four assertions fail as-is. The comment at gaia_agent/__init__.py:76 states the invariant explicitly ("Must equal the real registry size for the default construction, and the manifest's own tools_count"). Neither file is in the PR's test plan.

        tools_count=68,

🟡 Important

Cancel is not observed during a long run_shell_command (src/gaia/agents/tools/shell_tools.py:812)

The @tool(timeout=MAX_COMMAND_TIMEOUT + 60) override raises the per-tool guard to 3660s. Agent._call_tool_bounded (src/gaia/agents/base/agent.py:3159) joins the worker thread for that whole window, and the cancel event is only checked between steps (agent.py:4596) and per generated token (agent.py:5001) — never inside a tool body. process.communicate(timeout=timeout) blocks for the full class default, so Stop during a build-class command is honoured up to 1800s late (3600s with an explicit timeout=). Pre-PR worst case was the flat 30s.

_wait_interrupt_signal() already resolves the right event; reuse it here — wait on the process in slices and terminate_process_tree(process) when the event fires, returning the same cancelled: True shape wait_for_condition uses.

The non-default classes are unreachable through the shipped allowlist, and no test covers the reachable path (src/gaia/agents/tools/shell_tools.py:44, tests/unit/test_shell_adaptive_timeouts.py:1274)

ALLOWED_COMMANDS contains no pytest/pip/npm/make/cmake/curl/wget/docker, and SAFE_GIT_COMMANDS excludes clone/fetch/pull/push — so test, build and network only apply to a binary a loaded skill granted via shell:execute:<binary>. The unrestricted fixture concedes exactly this ("it refuses pytest and pip install outright today — so with it in place only the default class would ever be reachable") and every classification test monkeypatches _validate_command away. That leaves the feature's real path — a granted binary classifying as build/test and reaching subprocess with the longer timeout — untested end to end. One test with _granted_binaries populated would close it.

Same gap in the docs: docs/guides/gaia.mdx:106 promises "a test run gets 15 minutes, a build or install 30" directly under gaia.mdx:104's "Anything that writes, installs, or executes an arbitrary binary is refused." Add the grant caveat.

🟢 Minor

  • normalize_binary name collision (src/gaia/agents/tools/command_timeouts.py:454) — gaia.skills.binaries.normalize_binary deliberately returns "" for a path spelling so ./gh can never match a grant; this one strips the path so /opt/evil/pytest classifies as test. Divergent security semantics under one name invites importing the wrong one. Suggest command_basename.
  • _split_segments duplicates _split_pipeline (command_timeouts.py:501 vs shell_tools.py:286) — same pipeline split, two implementations. Extract one.
  • The description= / parameters= block on wait_for_condition is dead (shell_tools.py:959-1000) — @tool accepts them into **kwargs and never reads them (src/gaia/agents/base/tools.py:25); the registry takes description from __doc__. Forty lines that can silently disagree with the docstring that is actually used. (Matches the pre-existing style on run_shell_command, so a sweep, not a blocker.)
  • A pipeline without spaces misclassifies (command_timeouts.py:501) — _split_segments only recognises | as a standalone token, so ls|pytest classifies as default (30s). shlex keeps it as one token.
  • truncated is inferred by comparing strings (shell_tools.py:1147) — stdout != (stdout_str or "") works but is indirect. Have _truncate return (text, was_truncated).

Strengths

  • The process-tree kill is proven, not asserted. test_a_blown_deadline_really_kills_the_process spawns a real child and measures the kill latency — exactly the class of bug (subprocess.run re-entering communicate() with no timeout) that a mocked test could never catch.
  • Refuse-not-clamp on an out-of-range timeout, with an error naming the ceiling and the alternative. Silently clamping would produce a command killed at a limit nobody chose — the failure mode the Fail-Loudly rule exists for.
  • test_the_docstring_states_every_class guards the one line the model actually sees. Encoding "the non-native prompt path renders only the first line of __doc__" as a test is the right way to keep a prompt-visible table honest.
  • wait_for_condition's safety wiring is complete and consistent — confirmation-gated (agent.py:203), grant-scoped so "always allow" binds to the command not the tool (tool_grants.py:90), refused before the prompt via policy_refusal_for_call, deliberately not grant-exempt, and charged once against the rate limit rather than per probe.

Ovtcharov added 5 commits September 8, 2026 09:27
…it primitive

A shell command was killed at 30 seconds no matter what it was, so a test
suite, a build or an install never finished — and while `timeout` was already
a parameter the model could raise, nothing told it how long the command it was
about to run should take, so it almost never did.

The timeout now comes from the command itself: test runners get 900s, builds
and installs 1800s, VCS and network calls 300s, everything else the unchanged
30s. The applied value and its class come back in the result, and an explicit
`timeout=` still wins. Out-of-range values are refused rather than clamped, so
a command is never killed at a limit its caller did not choose.

`wait_for_condition` replaces sleep-and-recheck: it polls a predicate against a
monotonic deadline inside one call, so waiting for a server to answer or a
build to land costs one agent step instead of one per check. It is bounded
(600s ceiling, 5-60s poll interval), gated behind the same confirmation and
guardrails as the command it polls with, charged once against the shell rate
limit, and interrupted by the agent's cancel signal.
The tool registry takes a tool's description from its docstring — @tool's
`description=` and `parameters=` kwargs are swallowed and ignored — and the
non-native prompt path renders only the first line of it. The class defaults
were in the ignored kwarg, so the model would never have seen them. They now
lead the docstring, with a test that fails if a class default drifts out of
that line.

Also documents both tools in the mixin spec and the flagship's tool surface.
…eturns

A 5-second timeout took over two minutes and never returned: `subprocess.run`
kills only the process it launched, then re-enters `communicate()` with no
timeout, so a surviving grandchild holding the pipes blocks the call for as
long as it lives. With 30-minute build timeouts now reachable, that hang would
have held the agent loop for an hour instead of three minutes.

The executor now drives Popen itself and kills the whole tree on expiry —
`taskkill /T` on Windows, the process group on POSIX — then reads the buffered
output with a short grace. Verified live: the same command that hung returns in
5.1s with its partial output intact.

That partial output is also truncated to 10K now, like the success path always
was. A command killed at 30 minutes has printed far more than one killed at 30
seconds; the live run returned 806KB straight into the model's context.
The flagship shows the model a subset of its registry per turn, chosen by
bundle. A tool in no bundle is registered but unreachable, so wait_for_condition
joins the shell bundle in both the chat and full profiles.

Also repoints the granted-CLI argv tests at Popen, which is what the executor
drives now — the behaviour they pin (a granted binary never goes through
cmd.exe) is unchanged.
CI caught three kinds of drift the new tool created: the `taskkill` nosec had
no entry in .security-suppressions.json (which fails both the gate and a unit
test), and every hand-maintained tool count — the flagship manifest and the
chat agent's four profile literals — was one short.

Also formats with the black CI actually runs; the local cache was a version
behind and passed files CI rejects.
@kovtcharov-amd
kovtcharov-amd force-pushed the kalin/3382-adaptive-shell-timeouts branch from 3d20326 to 3668ec5 Compare September 8, 2026 16:45
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

🔴 The prior review's tools-count fix is incomplete — gaia_agent/__init__.py was left behind.

gaia-agent.yaml now declares tools_count: 69, but gaia_agent/__init__.py still says tools_count=68. The test test_registration_tools_count_matches_manifest (hub/agents/gaia/python/tests/test_gaia_agent.py:166) asserts these two values are equal — it will fail.

Fix: bump tools_count from 68 to 69 in hub/agents/gaia/python/gaia_agent/__init__.py:77.

🔍 Technical details

hub/agents/gaia/python/gaia_agent/__init__.py:77:

        tools_count=69,

The drift guard at tests/test_gaia_agent.py:166-167:

def test_registration_tools_count_matches_manifest(manifest):
    assert build_gaia().tools_count == manifest["tools_count"]

…compares __init__.py's tools_count=68 against gaia-agent.yaml's tools_count: 69 — those are now out of sync.

This file was not in the prior review's fix either (it stayed at 67 while the yaml moved to 68 in the previous partial fix, then 69 in this push). It has been one step behind throughout.

build_gaia() carries a second hand-typed copy of the count, one the manifest
test does not read. Both now say 69.
Ovtcharov added 3 commits September 12, 2026 16:10
Closes the review's 🔴: `gaia-agent.yaml` and `gaia_agent/__init__.py` now
agree at 74, which is main's 73 plus this branch's `wait_for_condition`.
ChatAgent's "full" profile is 58 — 55, plus transcribe_media/refine_transcript
from #3597 and wait_for_condition from here.

The shell_tools conflict was not really a conflict. #3252 made `@tool` reject
unknown keyword arguments and #3583 taught it to derive the tool's name,
description and per-argument schema from the function and its docstring, so
main deleted the hand-written `name=`, `description=` and `parameters=` blocks
everywhere. This branch still passed them on `run_shell_command` and
`wait_for_condition`, which is now a TypeError at import. Both functions
already carry full docstrings with `Args:` covering every parameter, so the
arguments are dropped rather than migrated — they had been silently ignored,
and nothing the model sees changes. `timeout=` stays on both: it is a
supported argument and it is what keeps the agent-level guard outliving the
longest command class.

`_shell_tools()` in the adaptive-timeout spec keyed its captured tools on the
`name=` argument, so every lookup returned None once it was gone; it reads
`fn.__name__` now, the same place the decorator does.
Import-only conflict: #3703 added the verification import beside this
branch's command-timeout imports. Kept both.
Ovtcharov and others added 3 commits September 12, 2026 17:36
Raising the per-tool guard so a 30-minute build is not abandoned mid-run left
nothing watching the cancel signal: clicking Stop during a build waited for the
build. The executor now waits on the process in short slices, kills the whole
tree the moment either cancel channel fires, and refuses outright if Stop landed
before the spawn. A wait between probes wakes on the same signals.

Also from the review:

- `wait_for_condition`'s dead `name=`/`description=`/`parameters=` kwargs are
  gone; `@tool` rejects them outright since the merge, so they were a hard error.
- `normalize_binary` -> `command_basename`, so it no longer shares a name with
  the security-critical `gaia.skills.binaries.normalize_binary` that returns ""
  for path spellings on purpose.
- One `split_pipeline`, used by both the validator and the classifier, and the
  classifier now tokenizes `|` as its own token so `ls|pytest` is a pipeline.
- Pre-execution refusals declare `executed: False` (#3677), including the wait's
  — but only when no probe ever reached a process.
- Tests: a granted binary reaching the `test` class through the real allowlist
  (every other classification test stands it down), the same command refused
  without the grant, and Stop landing before, during, and between commands.
  Deadline tests now drive a clock, so a 1800s budget is asserted, not waited on.
Main rebuilt the shell execution path around parsed steps, so the branch's
adaptive-timeout and cancellation work had to be re-applied on top of it
rather than merged textually.

- Kept main's `_run_pipeline(segments, modes, envs, cwd, timeout)` and its
  step loop; the branch's cancel/timeout behaviour now rides on an optional
  `waiter` callback threaded through `_run_pipeline` and `_run_step`, so a
  Stop still lands mid-command without the branch reintroducing the older
  signature.
- Replaced `subprocess.run` in `_run_step` with a Popen the waiter can poll,
  spawned with `start_new_session` on POSIX so `terminate_process_tree` kills
  the child's group and not the agent's own.
- Dropped the branch's `split_pipeline` — main already defines
  `_split_pipeline` and re-adding it would have shadowed the newer parser.
- Chat manifest tool counts follow the merged registry: doc 38 -> 39 (main's
  `read_tool_output` plus the branch's `wait_for_condition`).
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

Rebuilt this branch's merge with main by hand — it's conflict-free again and the shell suites are green.

The interesting part wasn't textual. main rewrote the shell execution path around parsed steps, so the adaptive-timeout and cancel work here had to be re-applied on top of that rewrite rather than merged. Stop still kills a running command mid-flight, and a killed child no longer risks taking the agent's own process group with it on POSIX.

One thing a human should confirm: the doc profile's tool count moved 38 → 39, because main added read_tool_output and this branch adds wait_for_condition. That's the merged registry's real size, but it does mean this PR now touches the chat agent's manifest.

🔍 Technical details

Merge commit 16f17e68a (plain merge of origin/main, no rebase, no force-push). Eleven conflict hunks, all in src/gaia/agents/tools/shell_tools.py plus the chat/gaia manifests and two docs pages.

Resolution shape:

  • Kept main's _run_pipeline(segments, modes, envs, cwd, timeout) and its step loop verbatim. The branch's cancellation now rides on an optional waiter callback threaded through _run_pipeline and _run_step, defaulting to a plain communicate(timeout=…) for callers with no cancel channel. The older _run_pipeline(segments, cwd, timeout) signature this branch carried was dropped.
  • _run_step swaps subprocess.run for a Popen the waiter can poll in CANCEL_POLL_SECONDS slices, spawned with start_new_session=os.name != "nt" — without it terminate_process_tree's killpg(getpgid(pid), 9) would kill the agent's own group. A BaseException handler reaps the child if the waiter itself throws.
  • New _CommandCancelled carries the partial stdout/stderr, so a stopped command reports what it printed instead of an empty result.
  • Dropped the branch's split_pipeline — main already defines _split_pipeline; re-adding it would have shadowed the newer parser.
  • tests/unit/test_skill_binary_grants.py::_run_capturing_subprocess now patches both seams (Popen for a lone segment, _run_pipeline for a chain), since main splits those paths.

Tests: test_shell_adaptive_timeouts, test_shell_pipelines, test_skill_binary_grants, test_shell_guardrails, test_shell_output_encoding → 491 passed, 7 skipped. test_starter_skills, test_chat_fix_contracts, test_adaptive_skills → 269 passed, 15 skipped. python util/lint.py --black --isort clean.

No eval run — Lemonade is down locally.

…uses

The Windows compound-line guard recorded zero invocations after the merge, so
its four security assertions were all passing vacuously — the exact shape that
would let a real regression through unnoticed.

main added this test hard-coding `subprocess.run` as the spawn point. This
branch had already replaced that call site with `subprocess.Popen`, because a
Stop mid-command needs a process you can poll — `run()` blocks for the whole
deadline, so a Stop during a 30-minute build would land 30 minutes late. Git
merged the file as a clean add and had nothing to flag.

Only the observation point moves. `shell=use_shell` is still on the Popen call
and every assertion is byte-for-byte unchanged: two separate spawns, each a
string, neither containing `&&`, and exactly `["ls", "cat notes.txt"]`.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

The three red unit-test lanes were a mocking seam that moved, not a lost guard — pushed a fix, and the guard itself is untouched.

test_windows_never_hands_a_compound_line_to_cmd_exe_as_one_string was recording zero invocations (assert [] == [True, True]), which meant its four security assertions were all passing vacuously. Worth saying plainly: it was watching the wrong spawn point, so it would not have caught a real regression either.

🔍 Technical details

main added that file hard-coding subprocess.run as the spawn point in _run_step. This branch had already replaced that call site with subprocess.Popen — adaptive timeouts and Stop-mid-command need a process you can poll in slices; run() blocks for the entire deadline, so a Stop during a 30-minute build would be honoured 30 minutes late. The test file does not exist on the branch tip, so git merged it as a clean file-add with nothing to flag.

The fix repoints monkeypatch.setattr(shell_tools.subprocess, "run", ...) to Popen, with a fake exposing Popen's surface (communicate, returncode, args, pid). All four assertions are byte-for-byte unchanged:

  • [shell for _, shell in calls] == [True, True] — two separate spawns
  • all(isinstance(args, str) for args, _ in calls)
  • not any("&&" in args for args, _ in calls)
  • [args for args, _ in calls] == ["ls", "cat notes.txt"]

shell=use_shell is still on the Popen call and the per-step splitting is intact, so no call site was dropped. Verified both directions locally against the module's win32 skip: with the fix, 1 passed; reverted, it reproduces CI's assert [] == [True, True] exactly.

Full shell suite on the merged branch: 725 passed, 127 skipped, 0 failed.

Not a shared cause with #3808 — that one changes refusal into a prompt (TIER_REFUSE, _blanket_approval_refusal) and does not touch this file.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator Author

This merges cleanly into main today. A real merge with rerere disabled reported "Automatic merge went well" with zero unmerged paths, and the merged tree passes 467 tests (127 skipped).

The part that matters more: this does not share #3400's structural problem, and the two should not be treated as one decision. #3402 was written on top of main's current multi-step shell engine and extends it. #3400 predates that engine entirely, which is why it needs an author rework decision about who owns connectors and cd. Nothing equivalent is pending here.

🔍 Technical details

Head 50e8e7beb, base main — 3 commits behind / 13 ahead. Merge run as git -c rerere.enabled=false merge --no-commit --no-ff into a scratch worktree at origin/main; git diff --name-only --diff-filter=U returned nothing.

The branch's shell_tools.py diff is +504/-22 and references _Step, _run_step and step.connector in nine places — it builds on the engine rather than replacing its execution tail. For contrast, #3400 is 208 commits behind, has no _Step class, and no connector support at all.

Tests against the merged tree, not the branch in isolation: tests/unit/test_shell_*.py (11 files, including this PR's test_shell_adaptive_timeouts.py) plus test_starter_skills.py and test_powershell_command_injection.py — 467 passed, 127 skipped.

One correction for future readers: the brief circulating for this batch names tests/unit/test_shell_tools.py, which does not exist. The real coverage is the 11 tests/unit/test_shell_*.py files. Do not chase that filename.

kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 24, 2026
…#4136)

## Why this matters

A Windows contributor running the four shell test suites sees `112
skipped`, which is visually indistinguishable from green. CI on ubuntu
and macOS sees 112 real results. So the loop is: verify locally, see no
red, push, watch CI fail — which is exactly how the confirm-gate defect
in amd#3808 reached CI undetected.

The skip reason is genuine for the tests that actually launch a process:
Windows runs each pipeline through `cmd.exe`, and `os.killpg` / process
groups are POSIX-only. It is *not* genuine for the refusal, parsing,
grant and tool-description tests — those decide before anything reaches
a shell, and a module-level skip was hiding them on the platform most
GAIA contributors develop on. After this change Windows runs **70 passed
/ 42 skipped** instead of `112 skipped`, and every one of those 70 is a
real assertion about the security-adjacent refusal path.

POSIX is untouched: the per-test mark carries the same `sys.platform ==
"win32"` condition the module-level one did, so off Windows it is a
no-op and all 112 still run.

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

**Membership was measured, not guessed.** A throwaway pytest plugin
stripped the `cmd.exe` skipifs, wrapped `shell_tools.subprocess.Popen` /
`.run`, and recorded which node IDs actually spawned a child. 42 did; 70
did not. The 70 were then run on Windows 11 and all passed; every one of
the 10 failures fell inside the 42. So the split is empirical, not a
reading of the test names.

That measurement mattered, because *running the tests* would have given
the wrong answer. This dev box has MSYS coreutils on `PATH`, so `ls`,
`cat`, `sort` and `date` resolve and most execution tests pass here —
they would not on a clean Windows machine or a `windows-latest` runner.
Classifying on "does it pass on my box" is the hidden-state trap
CLAUDE.md warns about; classifying on "does it spawn a process" is not.

- `pytestmark = pytest.mark.skipif(...)` → `posix_only =
pytest.mark.skipif(...)`, same reason string per module, applied as
`@posix_only` to the 35 spawning tests across three files.
- **No assertion was weakened, relaxed, or deleted.** The diff is 53
insertions / 3 deletions; the 3 deletions are the `pytestmark` name on
each of the three lines.
- Node IDs are unchanged (no reorganisation into classes), so other
in-flight PRs that name these tests in their test plans still resolve.
- `test_shell_env_assignment.py`'s two existing `shutil.which("pytest")`
skipifs stack above `@posix_only`; pytest ORs them, so behaviour off
Windows is identical.
- `tests/unit/test_shell_pipelines.py` keeps its module-level mark — all
seven of its tests genuinely run a pipeline, so there is nothing to
promote. `test_shell_output_encoding.py` already used per-test marks and
is untouched.
- One pleasing side effect:
`test_windows_never_hands_a_compound_line_to_cmd_exe_as_one_string` — a
fully-mocked test *about* the Windows path — was itself skipped on
Windows. It now runs there.

**Merge-conflict note for reviewers:** amd#3721 and amd#3402 both touch
`test_shell_compound_commands.py`, neither near the `pytestmark` line.
Whichever lands second may need a trivial rebase.
</details>

## Scope

This does **not** close amd#4127. That issue asks for `windows-latest` in
the `test_unit.yml` matrix, gated on amd#4115 and amd#4119 landing first so
the lane starts green. This is a prerequisite for that lane being worth
anything — without it, 112 of the tests the new lane would run are
skipped by construction.

## Test plan

- [x] `python -m pytest tests/unit/test_shell_compound_commands.py
tests/unit/test_shell_env_assignment.py -q` on Windows 11 — was `77
skipped`, now `51 passed, 26 skipped`
- [x] Same for all four modules — was `112 skipped`, now `70 passed, 42
skipped`
- [x] `python -m pytest tests/unit/test_shell*.py
tests/unit/test_powershell_command_injection.py -q` — `266 passed, 42
skipped`
- [x] `python util/lint.py --all` — output byte-identical to a clean
`origin/main` worktree (both exit 1 on the same pre-existing mypy
findings in `src/gaia/`, none in files this PR touches)
- [ ] CI on ubuntu/macOS — expect the same counts as before this PR; the
mark is a no-op off Windows

Towards amd#4127.

Co-authored-by: Kalin Ovtcharov <[email protected]>
Conflicts were additive on both sides: main added `capture_skill` and the
shell cancellation hook, this branch added `wait_for_condition` and the
adaptive-timeout imports. Both kept.

The tool count needed a real fix rather than a pick. Both sides read 81 for
different reasons (main 59+8, branch 60+7), so git auto-merged the literal
while only the comment conflicted. The merged agent registers 82; the
generator and the build-the-agent drift test both confirm it. Updated the
manifest, the registration literal and the test's expected total, and
regenerated CAPABILITY_MATRIX.md (shell bundle 4 -> 5).
@github-actions

Copy link
Copy Markdown
Contributor

Skill audit

Skill Verdict Claimed tier Cleared tiers Findings Rules
hub/skills/transcribe-meeting ✅ ALLOW community experimental, community none —

✅ All audited skills cleared the tier they claim.

Per-finding detail is withheld here on purpose. Read it in the Security > Code scanning tab, or download the skill-audit-reports artifact from this run. Offending source text is withheld from CI everywhere — reproduce it locally with gaia skill audit <dir> --show-snippets.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into main with commit a0beca1 Sep 25, 2026
47 of 60 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/3382-adaptive-shell-timeouts branch September 25, 2026 18:17
kovtcharov-amd added a commit that referenced this pull request Sep 25, 2026
main's #3390 moved git out of ALLOWED_COMMANDS into the binary-policy
table, and #3402 added the adaptive-timeout waiter. Five conflicts, four
mechanical: _run_step gained both sides' kwargs (waiter, bypass),
_validate_command keeps main's body with the bypass short-circuit ahead
of it, run_shell_command resolves the timeout after reading the bypass
flag, and the deleted SAFE_GIT_COMMANDS stays deleted.

The fifth was behavioural. With git no longer in ALLOWED_COMMANDS and
never in DEVELOPER_COMMANDS, bypass refused it outright — so `git status`
ran by default but not under bypass, leaving the permissive mode stricter
than the default one. git joins the developer set, which restores the
pre-merge behaviour and the build/test/land loop this mode exists for.

That means git's policy refusals (push, reset, rebase) do not survive
bypass. They are a tripwire rather than a boundary here: python and make
are in the same set and reach git by shelling out regardless — the same
reasoning already recorded for excluding rm. Noted on the six surfaces
that enumerate the set, including the TUI's /bypass warning, so the
consent text matches what the mode actually grants.
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
…amd#4370)

`main` has been red since 2026-09-25 18:29, so nothing can leave the
merge queue. Three separate regressions landed within minutes of each
other; this clears all three. The worst is a literal `SyntaxError` —
`ChatAgentConfig(...)` was passed `device=` twice, so the Agent UI
backend and everything importing it failed at module load, taking out
the Linux, Windows and macOS unit-test jobs. Nobody wrote that
duplicate: amd#3666 and amd#4275 each added the same kwarg a few lines apart,
neither diff conflicted textually, and the merge queue merged both
cleanly into a file that does not parse.

The other two are one-liners: amd#3402 re-imported `tool_cancelled` over a
name the module already imports (failing the pylint gate) and shipped
`wait_for_condition` with no UI label, and amd#4271 landed an over-long
assertion (failing the black gate).

**Worth knowing:** the ~13 "new pylint errors" that appear in the
failing job's log are not pylint errors. They are the first 20 lines of
the **non-blocking MyPy** output (1224 warnings, truncated for display)
and have never gated anything. Only one pylint hit was real. No
dependency or tool-version drift was involved — pylint 4.0.9 and black
26.5.1 both predate the last green run.

## Test plan

- [ ] `python util/lint.py --black` — clean (1180 files unchanged)
- [ ] `uvx pylint src/gaia --rcfile .pylintrc --disable
C0103,C0301,W0246,W0221,E1102,R0401,E0401,W0718,W0212` — clean on Linux
- [ ] `python -m compileall -q src/gaia tests` — no syntax errors
- [ ] `python -m pytest tests/unit/test_schedule_daemon.py -q` — 28
passed
- [ ] `python -m pytest tests/unit/chat/ui -q` — 1040 passed (was 17
collection errors)

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

**`src/gaia/ui/agent_loop.py`** — the two `device=session.get("device")`
lines were textually identical, so deleting the later one restores
exactly the intended call. `git blame` attributes line 461 to
`1caad2ade5` (amd#4275) and line 465 to `7a8fea58b1` (amd#3666); amd#3666 is an
ancestor of the last green commit `69f76ab57`, so amd#4275 is the one that
created the duplicate.

**`src/gaia/agents/tools/shell_tools.py`** —
`gaia.agents.base.tools.tool_cancelled` is a pure re-export of
`gaia.tool_cancellation.tool_cancelled`, which the module already
imports at line 31. Verified the bindings are the same object, so
dropping the function-local import is a no-op rather than a behaviour
change.

**Follow-up worth a maintainer's eye, deliberately not bundled here:**
`wait_for_condition` executes arbitrary commands against the same
allowlist as `run_shell_command`, but unlike `run_shell_command` it is
not in `_GAIA_MUTATING_TOOLS`. By that set's own stated criterion ("or
execute code") it looks like it belongs there, and omitting it means the
tool skips the confirmation gating its sibling gets. That is a behaviour
change, not a CI fix, so it should be reviewed on its own rather than
smuggled into an unblock PR.

**Also noted:** `.pylintrc` uses `disable = all` plus an explicit
`enable` list that does not include `syntax-error`, which is why the
pylint gate walked past a file it could not parse. Enabling `E0001`
would have caught this at PR time.
</details>
kovtcharov-amd added a commit that referenced this pull request Sep 25, 2026
wait_for_condition (#3402) ships in the same shell bundle as
run_shell_command, so it now reaches the bare chat profile fast mode
composes as. Pin and ceiling updated to the new, intentional baseline
-- still under a quarter of the default profile's cost.

Also drops a stray agent_type key from a scenario this branch owns:
the eval runner no longer honors per-scenario pins.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
Resolves the tool-count collision and hardens the wait mixin's host contract.

main added `wait_for_condition` (amd#3402) while this branch added `sleep`, so both
sides claimed a flagship tool count of 82. The real merged count is 83; CORE
goes to 16 and `dynamic_tools_max` to 29, keeping the dynamic share at 13.
`gaia_agent/__init__.py` auto-merged to a stale 82 without conflicting — the
capability-matrix reconciler is what caught it.

Also: composing `wait` from KNOWN_TOOLS onto a host that is not an `Agent` used
to die with a bare `AttributeError` several lines into a wait, after the model
had already spent a step on it. `_sleep` now names the missing stop channel and
refuses before waiting a single second. Registration stays permissive, because
the registry is also built by skeletons (`build_full_agent_skeleton`) that only
count tools and never call one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(shell): adaptive timeouts and a wait-for-condition primitive

2 participants