Skip to content

fix(agent): check a test claim against the record before answering - #4049

Merged
kovtcharov-amd merged 16 commits into
amd:mainfrom
kovtcharov:claude/answer-contract-test-claims
Sep 22, 2026
Merged

kovtcharov-amd merged 16 commits into
amd:mainfrom
kovtcharov:claude/answer-contract-test-claims

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

GAIA decides whether a test ran by reading the text it printed, and that guess goes wrong in both directions. Twice while benchmarking, the guess missed a real unittest run (Ran 69 tests … OK) and reported "no tests ran", so an honest answer looked like it had invented its results. In the other direction, a command that only mentioned pytest (cat pytest.ini) counted as a test run, and a failing run piped through tail counted as a pass.

This makes the tools that run tests record the result as a fact — which runner, what it ran, whether it passed — so the verification footer and everything else read that instead of re-parsing output. On top of it, an answer that claims a test result the record doesn't show gets one chance to run the check or drop the claim.

A correction on how this PR was first described: it originally quoted a benchmark answer as a fabricated test result. That was wrong — the tests had run under unittest, which the checker being used at the time did not recognise. The answer was accurate. That mistake is itself the case for this change.

Test plan

  • python -m pytest tests/unit/agents tests/unit/test_run_python_tool.py tests/unit/test_code_bench.py tests/unit/test_shell_*.py hub/agents/chat/python/tests (2257 passed)
  • New tests failed before the change: the seam tests fail with the guard removed, and the rest fail at import
  • Real run_python runs of pytest (pass, fail, subtests) report the right passed
  • gaia eval agent --category tool_selection: this changes what the model is asked at the end of a turn
  • gaia eval agent --category rag_quality
🔍 Technical details

What landed

  • checks.py (new, pure): a CheckResult fact. run_shell_command, run_python, and execute_python_file attach it as check_result on every call that ran, set to None when the program wasn't a check runner. All runner and summary parsing lives here and runs once, in the producer, on the full output (not the truncated excerpt the model sees).
  • A shell run only counts as a check when argv[0] is the runner. echo pytest and cat pytest.ini used to register as passing pytest runs. A failing summary now beats exit code 0 from pytest | tail.
  • Footer: verification_record takes a declared result at its word and parses text only for results with no check_result (MCP, older hub agents). A malformed check_result raises instead of being guessed around.
  • Answer seam: this is the last guard before finalize_answer / _with_verification_scope. It uses the same budgeting as the unfinished-answer re-prompt: one correction per turn, and none on the last step.
  • claims_success moved from the code benchmark to claims.py. The benchmark imports it, so there is one detector with two vocabularies.

Known limits / follow-up

  • The claim side still reads prose. claims_success alone misses 111 passed, the measured case, so a test-specific vocabulary sits on the same sentence and negation machinery. It also skips advice ("run pytest to confirm the tests pass") so it doesn't accuse an honest answer. Because the evidence side is now a fact, a missed claim means no correction, not a false accusation.
  • At the step cap there is no correction: the claim goes out beside a footer that contradicts it. Automatically softening or stripping the claim would be a larger change and is not done here.
  • Shell in-place edits (sed -i, git apply) don't count as file mutations, so a stale pass after them still supports a claim. This errs toward no correction.
  • This conflicts with fix(agent): count a pytest-subtests summary as a real test run #4048, which is open and touches the same files. The subtests spelling it fixes is also covered here.
  • Out of scope: typed outcomes for the rest of the tool surface.

@github-actions github-actions Bot added documentation Documentation changes eval Evaluation framework changes tests Test changes performance Performance-critical changes agents labels Sep 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes — two things to settle before merge; the design itself is the right one.

This stops the agent from telling you "111 passed" when it never ran a test. The tool that runs the check now records what actually happened, and an answer that claims a result the record can't show gets one chance to run the check or drop the claim. Moving the truth from "re-guess it from the text blob" to "the producer states it once" is the right call, and the tests are unusually good — the seam is driven through the real agent loop, not a mock of it.

What needs doing:

  1. Run the two evals. This changes what the model is asked at the end of a turn, which is exactly the case the project's rules say must not ship on unit tests alone. Both boxes are still unchecked in the test plan.

  2. A piped test run can still read as passing. The PR correctly fixes pytest | tail — the failure summary now beats a zero exit code. But pytest | head, which cuts the summary off entirely, still reads as a pass, and the new guard will now accept a "tests pass" claim on the strength of it. Not a regression, but it's the one hole left in the honesty guarantee this PR exists to provide — worth either closing or writing down as a known limit next to the others.

Also worth a look before merge: shell runs are now recognised only when the program is the runner, which is a good tightening, but it quietly drops a few real check runs the old text match caught — including the project's own documented lint command. And a couple of honest sentences ("I added 5 passing tests to the suite") trip the claim detector and burn a correction round. Details below.

Real-world evidence

N/A — no evidence-bundle.md in the tree for this run, so the verdict rests on static review plus the PR's own test plan. The plan does show real run_python pytest runs (pass / fail / subtests) reporting the right outcome, which covers the producer side. What isn't shown anywhere is the surface the PR is actually about: a real gaia chat turn where a fabricated claim gets corrected. The seam tests drive the genuine loop with a stubbed chat client, which is strong evidence for the wiring — but a transcript of the original fabricating task, before and after, is what would prove the fix lands. The two unrun evals are the other half of that gap.

🔍 Technical details

🟡 A pipeline that drops the summary reads as a pass (src/gaia/agents/base/checks.py:499)

passed=return_code == 0 and not summary_reports_failure(summary) needs the summary to be present to catch a failure. Verified against the module directly:

check_from_command("pytest -q | head -5", [["pytest","-q"],["head","-5"]], 0, "F.\n", "")
→ CheckResult(label='pytest', target='pytest -q | head -5', kind='test',
              passed=True, summary='')

head is in ALLOWED_COMMANDS and pytest is granted by the coding skill, so this is reachable today. Before this PR the same run also read as verified (via return_code != 0), so it's not a regression — but unsupported_test_claim now treats that record as positive evidence and lets a pass claim through unchallenged, which is a new consequence.

The conservative fix is narrow: when the label is a runner whose summary format you do parse (pytest, unittest) and the pipeline found none, treat the outcome as unknown rather than passed. npm test / go test / cargo test keep the current exit-code-only rule, so nothing gets falsely accused. If that's too aggressive for now, the "Known limits" list in the PR body is the right home for it — it already names sed -i and the step-cap case in the same spirit.

🟡 Evals not run (src/gaia/agents/base/agent.py:7361)

CLAUDE.md → "Run agent evals when changing LLM-affecting code paths — do NOT skip" lists the agent loop's end-of-turn prompting explicitly. This appends a new user message mid-loop and can cost the model a step. tool_selection and rag_quality are both unchecked in the test plan; the author already identified them as the right categories.

Remember Claude access comes from the Claude Code subscription, not ANTHROPIC_API_KEY — an empty env var is not a reason to skip. Run serially against one Lemonade Server, then gaia eval agent --compare <baseline>/scorecard_<category>.json <run-dir>/scorecard.json.

🟢 argv-only matching drops real runs the fallback used to catch

Because run_shell_command now declares check_result: None, verification_record takes that at its word and never reaches command_check_label — so anything argv_check_label misses is now silently "not a check". Measured:

['python','util/lint.py','--all']  → argv: None  | text: util/lint.py
['python','-m','ruff','check','src'] → argv: None  | text: ruff
['bash','-c','pytest -q']         → argv: None  | text: pytest
['timeout','600','pytest']        → argv: None  | text: pytest
['env','CI=1','pytest']           → argv: None  | text: pytest

Practically narrow today — only pytest is skill-granted, and ALLOWED_COMMANDS has no env/timeout/bash — so the blast radius is a skill that grants python. Two notes anyway: util[/\\]lint\.py in _CHECK_COMMAND_RE (checks.py:357) is now unreachable from the argv path, and the project's own python util/lint.py --all is the exact invocation that stops counting. Extending _LAUNCHER_RE to consume python/python3 before a script path would cover it.

🟢 Honest prose trips the claim detector (src/gaia/agents/base/claims.py:568)

"I added 5 passing tests to the suite."          → "5 passing"
"There are 12 tests passing in the file I read." → "12 tests passing"

Neither asserts a run happened, and both cost a correction round when no test ran. _UNASSERTED catches advice; it doesn't catch description. Adding these two to the test_no_concrete_test_outcome_is_not_a_claim parametrize would pin the intended behaviour either way.

🟢 Timeout paths disagree on declaring

run_shell_command's timeout branch attaches a check (return_code=None → passed=False), but execute_python_file's TimeoutExpired branch (hub/agents/chat/python/gaia_agent_chat/agent.py:1518) returns a bare dict, so a timed-out pytest run falls through to the text fallback and lands on "no test run recorded" rather than "did not pass". Same outcome for the claim guard, different route — worth making symmetric.

Strengths

  • The fix is at the right layer. Producing CheckResult where the argv, exit code and full output are all in hand — and judging on the full output rather than the excerpt the model sees (shell_tools.py:1317) — removes a whole class of re-derivation bugs rather than patching the symptom. declares_check cleanly separating "not a check" from "said nothing" is what makes the legacy fallback safe to keep.
  • The tests earn their length. test_the_footer_reads_the_fact_without_the_text_parser patches the regex helpers to raise, which proves the declared path bypasses them rather than merely agreeing with them. The seam tests run the genuine process_query loop with a scripted chat client and assert on the correction text the model actually receives.
  • The asymmetry is reasoned, not accidental. Every ambiguous case — unknown label → "test", shell in-place edits not counted as mutations, _NEGATION and _UNASSERTED — is biased toward not accusing an honest answer, and the docstrings say why. That's the right direction for a guard whose failure mode is calling a truthful agent a liar.
  • claims_success deduplicated. One detector with two vocabularies, and test_the_broad_success_detector_lives_in_one_place asserts the eval imports rather than re-copies it.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Merge order matters here: merge after #4048 and #4025, and keep what they add.

Combining this with both on a test branch, a text merge silently dropped two things. Both were caught only because their tests failed:

If this is rebased after either of those lands, run tests/unit/agents/test_answer_quality_checks.py and test_verification_scope.py before merging — those are what catch it.

Kalin Ovtcharov and others added 13 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.
The verification line read "partially verified - pytest passed, pytest did
not." when two differently spelled test runs shared a label: a shell pytest
that failed at collection, then a pytest run through run_python that passed.
A reader, and the benchmark's judge, took that as the harness contradicting
itself; it appeared in 3 of 14 tasks in one benchmark run.

The verdict is unchanged - a narrower passing rerun still does not hide a run
that failed - but a label on both sides is now counted: "1 of 2 pytest runs
did not pass".
… one

The agent could change source, check it with a couple of prints, and report
the fix as done without running the project's tests. In an adversarial
benchmark task that meant a test that was already failing went unreported:
GAIA fixed the bug, never ran the suite, and never saw it; Claude Code ran the
suite and reported the old failure.

The check reads the turn's tool record, not the answer's wording. It fires when
a write/edit tool changed a code file in the project, no check ran after that
change (a labelled check, or a run_python / execute_python_file /
run_shell_command whose output holds a pytest or unittest summary line), the
project has a test suite, and steps remain. It asks once; the corrective
message starts with [check:verify-after-change] and stays in the returned
conversation so transcripts can count it. Only the tail of Python and shell
outputs is kept for the check, so reading a large file doesn't copy it.
GAIA's verification line said "verified - pytest ran and passed" for a run
whose own output was "1 failed, 3 passed". The agent had run pytest inside
run_python and printed the result; the snippet itself exited 0, and the
check was judged by that exit code alone. In an adversarial benchmark task
(a hanging test) the harness therefore certified a suite that had failed.

A run_python or execute_python_file result whose last pytest or unittest
summary reports failures or errors is now a failed check, whatever the
snippet's exit code. The last summary printed wins, since a snippet may run
the suite more than once.
With pytest-subtests installed the summary reads "70 passed, 19 subtests
passed in 1.32s". The word between the count and the outcome broke the
summary pattern, so the whole line failed to match and a run that really did
pass was reported "unverified — none of them a test, lint, or build".

Measured on a benchmark task: the agent ran pytest seven times, got
"70 passed", said so accurately, and its own footer called it unverified.
An LLM judge reading that footer scored the agent 1 of 5 for fabrication —
a false accusation produced entirely by the pattern.

The failure detector had the same gap, so "2 subtests failed" did not
register as a failure either.
The agent reported test results it never produced. On a benchmark task
against a 144K-line codebase it answered "111 passed, 13 passed" after 71
tool calls, none of which ran a test; a second run claimed "69 passed" the
same way. Its own verification footer said nothing had been checked, but
nothing compared the footer to the answer.

The tools that run checks now report the outcome as a fact. run_shell_command,
run_python and execute_python_file attach a CheckResult (label, target, kind,
passed, summary) to every result for a call that ran, or None when the
program was not a check runner. The footer reads that fact, and falls back
to parsing text only for results that declare nothing (MCP tools, older hub
agents). A shell run counts only when the program itself is the runner, so
`cat pytest.ini` no longer reads as a passing pytest, and a failing summary
beats a zero exit code from `pytest | tail`.

Before an answer is emitted, one that reports a test outcome with no passing
test run after the last file edit gets one correction naming the gap. A
second unsupported answer is emitted as written, beside the footer. The claim
detector from the code benchmark moved to a shared module so both use one
implementation.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #4048 (verify-counts-subtests). Merge after #4048.

Ovtcharov added 3 commits September 21, 2026 11:57
The pacing tests were green on Windows and red on Linux. The fixture replaced
`sleep` on the real `time` module, so CPython's POSIX `Popen.wait` backoff
(0.001s doubling to a 0.05s ceiling) was recorded as if the pacer had slept:
the burst test asserted one 9s sleep and saw 37. Windows waits on a handle and
never sleeps, which is why every local run was green.

Swapping the module's own `time` handle leaves every other caller on the real
clock. `monotonic` stays real, as it already was.
The coding starter skill declares run_python, which ChatAgent registers
inline rather than through a mixin, so the starter-skill tool check
called it a tool no mixin registers and Test Gaia Agent failed.

Mirrors amd#4016 so this stack tip is green without waiting on that PR.
# Conflicts:
#	src/gaia/agents/base/agent.py
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 22, 2026
Merged via the queue into amd:main with commit 05ecb4e Sep 22, 2026
46 of 47 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes eval Evaluation framework changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants