Skip to content

fix(agent): answer from the work done when the loop guard stops - #4035

Merged
kovtcharov-amd merged 14 commits into
amd:mainfrom
kovtcharov:claude/loop-break-answer-from-work
Sep 26, 2026
Merged

kovtcharov-amd merged 14 commits into
amd:mainfrom
kovtcharov:claude/loop-break-answer-from-work

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

An agent that finished a task and then re-ran the same check a few times used to have its answer thrown away: the user got "I stopped after calling run_python 3 times in a row without making progress, so I can't confirm the task is finished" on runs where the code had been changed, documented, and pytest had passed — the verification line on that same answer said "verified — pytest ran and passed". A judge scored one of those tasks 3.00 against Claude Code's 4.75, the largest quality gap left in the suite. The agent now answers from the work it actually did; repeats that failed or were refused still report the failure, because there the failure is what the user needs to hear.

Stacked on #4028 and #3908, merged in that order (main → #4028 → #3908 → this), so the diff here includes both until they land. Together the guard corrects once in place of the repeated call and only ends the turn on the next identical call — that closing turn is what this PR changes.

Test plan

  • python -m pytest tests/unit/agents/test_loop_break_answer.py tests/unit/agents/test_loop_guard_correction.py tests/unit/agents/test_step_cap_final_answer.py tests/unit/agents/test_loop_break_truthful.py -q — closing answer on both tool paths after the correction round, error/refused repeats unchanged, failure and cancel handling
  • python -m pytest tests/unit/agents -q (1056 passed locally on the merged tree)
  • gaia eval agent --category tool_selection shows no regression against the committed baseline — not run here
🔍 Technical details
  • The step-limit closing call was generalised to _closing_answer(messages, conversation, instruction, step); the step-limit and loop-guard paths differ only in the instruction they pass. Both loop-guard call sites (native fan-out and legacy embedded-JSON) go through _answer_after_repeated_calls, which returns (answer, steps_taken) and (None, …) when the user pressed Stop.
  • Merge resolution at both call sites: if current_call not in loop_corrected_calls: … continue first, then print_repeated_tool_warning() followed by _answer_after_repeated_calls(...) with consecutive_count - 2 — the calls that actually ran, the same number _build_loop_break_summary reports.
  • The gate is _repeats_carry_a_failure: an errored or status: "denied" last result keeps _build_loop_break_summary, so fix(agent): the loop guard corrects before it stops, and names the real cause #3908's rate-limited / not-permitted / dead-service wording is untouched. _build_loop_break_summary now calls that predicate instead of repeating the condition.
  • The guard stops mid-fan-out, which leaves an assistant tool-call turn with no result for the call it stopped — Anthropic and other spec-strict providers reject that outright. _unanswered_tool_call_messages answers every dangling id with "Not run — the turn stopped before this call" before the closing request goes out, and a test asserts the outgoing message list accounts for every id (the correction message answers its own id, so only the stopping call needs sealing).
  • On failure the behaviour mirrors the step-limit path: warn, and return the existing notice with one line saying why the summary couldn't be written. A reply that asks for a tool instead of answering counts as a failure.
  • The extra call counts as a step and its stats land in conversation, so tokens are aggregated as usual. The verification-scope line is still appended once, post-loop.
  • Both call sites pass recent_results (from previous_outputs), never step_results, which error recovery clears before every retry — a legacy-path test fails if that is swapped back.
  • fix(agent): the loop guard corrects before it stops, and names the real cause #3908's own test_repeat_after_the_correction_ends_the_turn needed no change: its repeats return an error, which stays on the summary branch.

@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes agents labels Sep 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

This makes an agent that ran out of steps — or got stopped for repeating one tool call — actually say what it found, instead of a canned "I can't confirm the task is finished". The idea and the implementation are sound, and the tests are genuinely good. Three things to settle before merge.

Stopping the run yourself now triggers one more model call. When an interactive run hits the step limit, GAIA asks "Continue with 50 more steps?". Answering no — or pressing Ctrl-C at that prompt — now goes on to make an extra call to the model before returning, and the run is reported as having hit the step limit even though the user is what stopped it. Answering no getting a summary is arguably fine; a Ctrl-C should return immediately.

The repeated-call path may never show its new answer. The step-limit path hands its answer to the console; the loop-guard path doesn't. On the CLI the console is the only thing that prints, so the answer this PR exists to produce can reach the user only as raw streamed text (without the verification line), or not at all when streaming is off. Worth confirming on a real run — if it's a gap, the fix is making both paths end the same way.

The eval wasn't run. This changes the agent loop and adds two new model-facing prompts, which is exactly the case CLAUDE.md says must not merge without gaia eval agent compared against the committed baseline. The PR notes it wasn't run. Claude access in a Claude Code session comes from the subscription, so an empty ANTHROPIC_API_KEY isn't a blocker here.

Real-world evidence

N/A — no evidence bundle was produced for this run, and the PR description carries no CLI transcript; the test-plan boxes are unchecked and the eval is marked "not run here". I also couldn't execute the new tests in this environment (no pytest available), so this verdict rests on static review alone. The change is user-visible on the CLI and Agent UI, so the natural evidence is a short gaia chat transcript showing a capped run answering from its work, plus the eval scorecard diff.

🔍 Technical details

🟡 Important

1. Declining the continue prompt still fires the closing call (src/gaia/agents/base/agent.py:7544-7582)

max_steps_reached = final_answer is None and not cancelled_by_console is true for every loop exit that left final_answer unset — including the interactive n answer at :7571 and the except (EOFError, KeyboardInterrupt) break at :7573. Both then run _closing_answer, and both report max_steps_reached: True, which docs/spec/agent-base.mdx:208 documents as "hit the step limit before answering". The Ctrl-C case is the one that matters: the user interrupted, and the agent issues another model call. Suggest tracking the reason for the exit rather than inferring it from final_answer is None — e.g. set a stopped_by_user flag in those two breaks and skip the closing call when it's set.

2. _answer_after_repeated_calls never reaches the console (src/gaia/agents/base/agent.py:7780-7823 vs :7604-7623)

The step-cap branch does _finish_turn_record → _publish_turn_metrics → console.print_final_answer(...). The loop-guard sibling returns its answer and breaks; print_final_answer is never called on that path, and print_completion is the only console output after the loop. src/gaia/cli.py:737 comments "the console … already handles printing", so for gaia chat "<query>" the loop-break answer is delivered by the console or not at all. In streaming mode _closing_answer has already emitted the tokens, so the user sees the text but not the _with_verification_scope line that gets appended at :7669; non-streaming, nothing prints. The pre-#4035 canned summary had the same gap, so this isn't a regression — but it does mean the PR's headline improvement may not be visible on the CLI. Worth a real run; if confirmed, mirror the seal-then-print block from the step-cap branch.

3. No eval run for an LLM-affecting change (CLAUDE.md → "Run agent evals when changing LLM-affecting code paths")

Two new model-facing prompts (_STEP_CAP_ANSWER_PROMPT, _REPEATED_CALL_ANSWER_PROMPT, agent.py:368-391) plus a change to the agent loop's exit behaviour. Run gaia eval agent --category tool_selection and diff against tests/fixtures/eval_baselines/<model>/scorecard_tool_selection.json, serially (one eval process at a time).

🟢 Minor

4. A refused tool gets a message that never mentions the refusal (agent.py:7773-7777)

_repeats_carry_a_failure routes status: "denied" to _build_loop_break_summary, but that helper only special-cases _is_error_result; a denial falls through to the generic "I stopped after calling X N times in a row without making progress". The test (test_failed_repeats_keep_their_message[not-permitted]) asserts exactly that, so it's deliberate — but the user who declined the tool is told the agent made no progress, not that their refusal ended the turn. If #3908 is going to add the denied branch to the summary helper, a comment pointing there would stop this reading as an oversight.

Strengths

  • The tests assert the contract, not the call. tests/unit/test_lemonade_tool_choice.py checks the actual JSON body on both the requests.post and streaming-OpenAI paths, and test_no_call_request_keeps_tool_history_and_tools asserts the full translated Anthropic message list. That's exactly the "mocks prove we called it, not that the call is valid" guidance from CLAUDE.md, and it's rare to see it followed this closely.
  • _unanswered_tool_call_messages (agent.py:4262-4293) closes a trap that would only have shown up in production — the guard stops mid-fan-out, leaving a tool-call turn with a dangling id that Anthropic rejects outright. Sealing every unanswered id before the closing request goes out, with a test that reconciles ids to results, is the right fix.
  • tool_choice fails loudly everywhere — LemonadeClient, LemonadeProvider and ClaudeProvider each raise a named ValueError when it arrives without tools or in an unsupported shape, rather than dropping it and letting the model call a tool anyway. The one place it is dropped (providers/lemonade.py:415-418, a model with no native tool calling) is withheld together with the tools it governs, and carries a comment saying so.
  • _generate_max_steps_message now reads role: tool entries (agent.py:4238-4245), which fixes a tools list that was always empty — the old scan looked for tool_calls on assistant entries in conversation, and those only ever carry the parsed dict. Nice catch, and covered by test_max_steps_message_lists_the_tools_that_ran.
  • Docs updated across cli.mdx, agent-system.mdx and agent-base.mdx in the same change, including the new max_steps_reached result key.

Kalin Ovtcharov and others added 6 commits September 21, 2026 04:32
…al cause

After four identical tool calls the loop guard ended the task and told the user
to "check that the underlying service is running" — even when calls were
throttled and never ran, refused by policy, or a script exited non-zero. In a
168-run benchmark it fired 6 times with no outage behind any of them, and twice
replaced a finished task's answer with a failure message.

- Rate-limited calls never executed, so they no longer count as repeats; the
  loop waits out the reported wait (capped at 15s) before continuing.
- The first time a call hits the limit, the model gets one correction as that
  call's result ("do not repeat it — try a different approach"); only a repeat
  after the correction ends the turn.
- The summary now says rate-limited, not permitted, or the actual failure, and
  only blames a service for connection errors. With no error key it quotes the
  last stderr line.
- The legacy path read step_results, which error recovery clears before every
  retry, so a loop of failures was summarised as "Task completed". It now reads
  previous_outputs like the native path.

Folded in from review:
- read a Windows socket error as a dead service, not a refusal
- read a dead service as a dead service, and count only calls that ran
- read "blocked" as a refusal only when it is one, and reject a repeat limit
  below 2

Fixes amd#3888
An agent that ran out of steps replied with a canned note that never said
what it found or why it stopped. In a benchmark run GitHub rate-limited every
`gh` call; the agent spent all 30 steps on workarounds and never mentioned the
rate limit. The note's "tools used" list was also always empty.

At the step limit the agent now makes one more model call on the loop's own
path, with no tools offered, asking for a final answer from what the tool
results show: what it found, what it couldn't finish and why, and what the
user can do next. The run still reports "incomplete" and sets
max_steps_reached. If that call fails or doesn't answer, the canned note comes
back with a line saying why and a warning is logged. The note now lists the
tools that actually ran.
On the Claude backend the step-limit summary would always have failed:
Anthropic rejects a request whose history holds tool calls and results when it
defines no tools, so the user got the canned note every time. The closing call
now sends the same tools as the loop with tool_choice="none", which every
backend accepts and which leaves the tool schemas at the front of the prompt
unchanged.

tool_choice is now an explicit parameter on the Lemonade and Claude providers
and on LemonadeClient.chat_completions. Lemonade sends it unchanged, top-level
on the streaming path too, and only when set. Claude maps "none" and "auto" to
Anthropic's shape and raises on anything else. Both raise when tool_choice
comes without tools. A reply that calls a tool anyway still counts as a failed
summary.
A turn stopped for repeating one tool call threw away everything the agent had
already done. The user got "I stopped after calling `run_python` 3 times in a
row without making progress, so I can't confirm the task is finished" on runs
where the code had been changed, documented, and pytest had passed — the
verification line on that same answer read "verified — pytest ran and passed".
A judge scored one such task 3.00 against Claude Code's 4.75.

The guard now makes the closing call the step limit already makes: the loop's
own tools with tool_choice="none", asking the model to answer from the results
it has — what it completed, what it could not confirm, what to do next. Repeats
that errored or were refused keep today's message, because there the failure is
the evidence. If the closing call fails or asks for a tool instead of
answering, the old notice comes back with a line saying why, and a warning is
logged.

Both the native and legacy tool paths go through the same helper, the extra
call counts as a step and its tokens, and any call the guard stopped
mid-fan-out is answered in the transcript so spec-strict providers don't reject
the request.
…nswer

With the loop-guard correction in place a repeated call no longer ends the turn
on the spot: the model gets one correction and only the next identical call
stops it. The scripts now drive that extra round, and assert the closing call
is told how many calls actually ran — two of the four, since the last two were
never dispatched.

A refused repeat now reads "not permitted here" rather than the generic notice,
which is the summary doing its job, so the parametrised case expects that text.
The two prose docs describing the guard gained the correction round.
Error recovery clears step_results before every retry, so a loop of failing
calls on the embedded-JSON path reads as a clean run if the closing answer is
handed that list — and the user gets a cheerful summary of a turn that failed
every time. Reintroducing the swap fails this test.
@kovtcharov
kovtcharov force-pushed the claude/loop-break-answer-from-work branch from 6ec6c96 to 23de8e3 Compare September 21, 2026 11:59
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #4028 (step-cap-final-answer). Merge after #4028.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

This PR is the top of a three-PR stack — #3908 and #4028 both have to merge before it.

Both of their commit sets are already inside this branch, but all three PRs say base: main, so GitHub shows them as independent. Merging this one first makes the other two redundant without closing them — the same pattern that left eleven PRs stranded when #4049 was squash-merged as a stack tip.

Order: #3908 → #4028 → #4035, as merge commits rather than squashes.

🔍 Technical details

git log --oneline origin/main..fork/claude/loop-break-answer-from-work lists 41b17cf9f (#3908) and 2dc1e47d7 / 50aa38fb0 (#4028) beneath this PR's own 4f5839609, 5394825fc, 23de8e361. The branch history is already correct (triage/3908 → triage/4028 → triage/4035); only the PR base fields are out of step.

The bases can't be retargeted as-is — both parent branches exist only on the kovtcharov fork, and a PR base must be a branch in amd/gaia.

This PR rewrites 479 lines of src/gaia/agents/base/agent.py, the single most contended file in the queue (30 of 97 open PRs touch it), which is why the merge order matters beyond these three.

# Conflicts:
#	src/gaia/llm/providers/claude.py
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
…md#4373)

When an agent ran out of steps, the user got a canned "Reached maximum
steps limit" note with an empty tool list and no word on what happened.
In a benchmark where GitHub rate-limited every `gh` call, GAIA spent all
30 steps on workarounds and never mentioned the rate limit. Now, at the
step limit, the agent gets one more model call in which it can't use
tools, and answers from what its tool results show: what it found, what
it couldn't finish and why, and what to do next. If that call fails, the
old note comes back with a line saying why.

Replicates amd#4028, which lives on the `kovtcharov/gaia` fork — push
access was revoked mid-review, so that PR could no longer be refreshed
against main and was stuck `CONFLICTING`. Same content, re-resolved
against current main. No content changes beyond the conflict resolution.

## Test plan

- [x] `python -m pytest tests/unit/agents/test_step_cap_final_answer.py
tests/unit/test_claude_provider.py
tests/unit/test_lemonade_tool_choice.py` — 89 passed
- [x] `python -m pytest tests/unit/agents` — 1511 passed, 50 skipped, 0
failed
- [x] Provider-layer selection (`-k "claude or lemonade or provider"`)
diffed against a clean-`main` worktree baseline — identical failure
sets, zero regressions (the 12 remaining are pre-existing macOS/posix
tests failing on a Windows host)
- [x] `python util/lint.py --black --isort --fix` clean, no changes;
`python util/lint.py --flake8` passes
- [ ] `gaia eval agent --category tool_selection` — not run here;
carried over unchecked from amd#4028
- [ ] Live step-capped run on NPU/FLM — the Lemonade half was confirmed
on amd#4028 (a `fireworks.kimi-k2p7-code` run accepted the closing call
with tools + `tool_choice="none"` and answered from its results);
NPU/FLM still unchecked

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

**Replication method.** amd#4028 was stacked on amd#3908, which main
squash-merged as `69fc540b5`. A plain merge would re-apply amd#3908's fork
commit on top of its own squash, so instead the three commits that are
amd#4028's own work were cherry-picked onto main: `2dc1e47d7`, `50aa38fb0`,
`429de6a48`. amd#3908's fork commit and main's squash were verified
byte-identical before dropping it.

**Only conflict: `src/gaia/llm/providers/claude.py`.** Main changed
`_build_params` to also return a `name_map` (`_to_anthropic_tools` now
returns a tuple); amd#4028 added a `tool_choice` parameter and passed it
through from `chat`. Both kept — the signature takes `tool_choice` and
returns `tuple[dict, Dict[str, str]]`. This is the identical resolution
the author made in `26d80fcfa` on the fork, confirmed by reading that
merge's combined diff; it was the only evil-merge content across all
three of the branch's merge commits, so the replicated tree reproduces
the PR head exactly. Verified by matching symbol counts for
`_STEP_CAP_ANSWER_PROMPT`, `_answer_at_step_cap`, `max_steps_reached`,
`user_stopped` and `tool_choice` against `refs/pull/4028/head`.

**Review findings from amd#4028 are all addressed in the replicated
commits.** The `user_stopped` guard (declining "Continue with 50 more
steps?" no longer fires the wrap-up call) landed in `429de6a48`, and the
Claude structural fix (keep the tools, send `tool_choice="none"`) in
`50aa38fb0`.

- The closing call goes through the loop's own path:
`self.chat.send_messages` or `send_messages_stream`, with the loop's
`messages` plus one user instruction, the same system prompt, the same
tools, and `tool_choice="none"`. Tools stay because Anthropic rejects
tool_use/tool_result history on a request with no tools. A model without
native tool calling sends no tools and no `tool_choice`.
- `tool_choice` is a new explicit parameter on `LemonadeProvider.chat`,
`ClaudeProvider.chat` and `LemonadeClient.chat_completions`. Both raise
if it comes without tools; Claude maps `"none"`/`"auto"` and raises on
anything else.
- `_generate_max_steps_message` looked for OpenAI-style `tool_calls` on
assistant entries, which GAIA's `conversation` never contains, so the
"tools used" list was always empty. It now counts `role: tool` entries.
- The closing call counts as one more step, so the CLI shows "Processing
stopped after 51/50 steps" at the cap. `max_steps_reached` is new on
every result.

**Stacking.** amd#3908 is merged. amd#4035 sits on top of this PR and
generalises the closing call to the loop-guard path (`_closing_answer`);
it will need retargeting onto this branch once this lands.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
amd#4373 landed this PR's step-cap half on main (replicating amd#4028), and amd#3908
merged as a squash, so both of this branch's stacked parents are now upstream.
Nine conflicts in agent.py, all in the code the two changes share:

- `_answer_at_step_cap` → `_closing_answer(messages, conversation, instruction,
  step)`. This PR generalises the method so the loop-guard path can reuse it;
  the step-cap call site now passes `_STEP_CAP_ANSWER_PROMPT` as the
  instruction. Same request, same prompt.
- `max_steps_reached` keeps main's `user_stopped` term. That is this PR's own
  first review finding — declining "Continue with 50 more steps?" or pressing
  Ctrl-C must not fire another model call — and amd#4373 fixed it while this
  branch was open.
- Both loop-guard call sites drop main's `_build_loop_break_summary`
  assignment: `_answer_after_repeated_calls` builds that summary itself and
  returns it for repeats that failed or were refused.
- `_build_loop_break_summary` keeps the extracted `_repeats_carry_a_failure`
  predicate over main's inline condition; they are equivalent, and `denied` is
  still used further down.
- `min_context_size`'s docstring takes main's wording, which describes the
  resolver that is now in place.

The closing answer is now printed, not just returned. The normal and step-cap
paths call `print_final_answer` where they set `final_answer`; the loop guard
returned its answer and broke out, so on the CLI — where the console is the
only thing that prints — the turn ended on the repeat warning and the answer
this path exists to produce was never shown. Confirmed by driving a real
loop-guard break: `print_final_answer` was called zero times while the answer
sat in `result["result"]`, which is why every existing test missed it. The
post-loop block mirrors the step-cap one, so the printed text carries its
verification-scope line and the turn record is sealed before it prints.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

This PR is no longer a stack, and it is not redundant with #4373. Both of its parents are upstream now — #3908 squash-merged, and #4028 landed as #4373 — so what is left is only this PR's own work: the loop-guard half. #4373 handled the step cap; this handles the loop guard. Different trigger, and #4373's own description says so: "#4035 sits on top of this PR and generalises the closing call to the loop-guard path."

The two are complementary, and the overlap is real but mechanical: this PR generalises the method #4373 added rather than adding a second one. Merged main in and resolved it that way. The net diff against main is now 5 files, +609/−23, all of it this PR.

One correction to the framing in the review request: there is no _gate_unsealed_answer on main. What #4373 added is _answer_at_step_cap, plus a user_stopped flag and a max_steps_reached result key. Worth knowing before anyone goes looking for a gate that is not there.

A real defect fell out of the merge review: the answer was never printed. The step-cap and normal paths call print_final_answer where they set the answer; the loop guard returned its answer and broke out, so on the CLI the turn ended on the repeat warning and the answer this PR exists to produce never appeared. I confirmed it by driving a real loop-guard break rather than reading the code — print_final_answer was called zero times while the correct answer sat in result["result"]. That is precisely why every existing test missed it: they all assert on the return value.

🔍 Technical details

The stack, resolved. git log origin/main..HEAD previously carried 41b17cf9f (#3908), 2dc1e47d7 / 50aa38fb0 (#4028) and this PR's three commits. #3908 is now main's squash 69fc540b5, and #4028's commits are main's cherry-picks via #4373 — so after git merge origin/main the diff reduces to this PR alone. Nothing needs merging in a particular order any more.

Nine conflicts, all in agent.py, all in the code #4373 and this PR share:

conflict resolution
_REPEATED_CALL_ANSWER_PROMPT, _UNRUN_TOOL_CALL_NOTE HEAD — new here, main has no equivalent
_answer_at_step_cap → _closing_answer(…, instruction, step) HEAD — the generalisation is the PR; the step-cap call site now passes _STEP_CAP_ANSWER_PROMPT.format(steps=…). Same request, same prompt, and _answer_at_step_cap has no callers left anywhere
request = … in the closing call HEAD — adds _unanswered_tool_call_messages sealing, which the step-cap path did not need
max_steps_reached MAIN — keeps and not user_stopped. This is review finding 1 on this PR (declining "Continue with 50 more steps?" or Ctrl-C fired another model call); #4373 fixed it in 429de6a48 while this branch was open
loop-guard sites ×2 HEAD — drops main's final_answer = self._build_loop_break_summary(...). _answer_after_repeated_calls builds that summary itself and returns it when _repeats_carry_a_failure, so the assignment is dead
_build_loop_break_summary condition HEAD — the extracted _repeats_carry_a_failure predicate. Verified equivalent to denied or Agent._is_error_result(last), and denied is still used further down
min_context_size docstring MAIN — its wording describes the resolver now in place
cli.mdx, agent-base.mdx HEAD — both add this PR's loop-guard paragraph; main has no competing text

The print gap — fixed. loop_break_answer_unprinted is set at both guard call sites when an answer comes back, and a post-loop block mirrors the step-cap one: finalize_answer → _with_verification_scope → _finish_turn_record → _publish_turn_metrics → print_final_answer, placed before print_completion. Sealing before printing matters for the same reason it does on the other two paths (total_s must mean "until it was on screen"), and setting verification_scope_applied keeps the post-loop catch-all from appending a second scope line. Verified: exactly one scope line in both the printed text and the returned result, streaming and not.

Three tests pin it — native path, legacy embedded-JSON path, and the failed-repeat summary branch — each asserting print_final_answer was called once and that what it printed equals result["result"].

Validation. tests/unit/agents: 1471 passed, 55 skipped, 0 failed. The four files this PR names: 32 + the rest, all green. util/lint.py --black --isort --fix and --flake8 clean; check_doc_links.py --internal-only passes. No conflict markers; agent.py AST-parses; no reference to _answer_at_step_cap survives anywhere in src/, tests/, hub/ or docs/.

Still open, unchanged: gaia eval agent --category tool_selection. This adds a model-facing prompt and changes the agent loop's exit behaviour, so it is the CLAUDE.md case that should not merge without a run. The minor note about a refused tool getting a message that never mentions the refusal is also untouched — _repeats_carry_a_failure routes it to _build_loop_break_summary deliberately, and #3908's wording for it is now on main.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Sep 26, 2026
The email agent would have repeated its own grounding corrections when the
loop guard ended a turn: four of its guards append a notice rather than
replace the text, and the answer passed through finalize_answer twice — once
where the closing reply was built, again in the post-loop print. A user who
hit the guard on a calendar or invite question would have seen the same
correction printed two times.

The closing reply now comes back raw, like the failure-branch summary already
did, so the post-loop block is the single place that finalizes. Both branches
behave the same way, and a regression test pins the count at one.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit d33ae57 Sep 26, 2026
40 of 44 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/loop-break-answer-from-work branch September 26, 2026 14:44
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Merged. The eval the review asked for was run as an A/B against main on the same backend, and one extra defect was found and fixed on the way in.

The eval is a non-regression check here, not a test of the new path: the repeat guard never fired in any of the 14 scenario runs, so the code this PR changes did not execute. Scores were 8.5 (main) vs 8.4 (PR) with mixed per-scenario movement in both directions — retrieval and judge variance, not a signal.

The defect: when the guard ended a turn, the answer went through the agent's post-processing hook twice. The base hook does nothing, but the email agent grounds its answer there and four of its guards append a correction rather than replace the text — so a user who hit the guard on a calendar or invite question would have seen the same correction printed twice. The closing reply now comes back raw and the post-loop block finalizes it once, with a test pinning the count.

🔍 Technical details

Eval — gaia eval agent --category tool_selection --agent-type chat, run twice back-to-back against a backend restarted on the same port from the same worktree, once at origin/main (dc6b4500e) and once at the merged branch. Chat rather than the flagship because the gaia sidecar would not start on this box; both sides used the same agent, so the comparison is internally consistent. Per-scenario: multi_step_plan 9.6→8.2 (turn 1 ran one broad query_specific_file instead of the three targeted queries it planned, and missed the remote-work eligibility rule — a retrieval choice on an untouched path), smart_discovery 7.5→9.3, skill_file_ops_guardrails 7.2→8.3, skill_file_ops_discovery FAIL on both sides. No trace in either run contains a loop-break closing prompt.

Fix — _answer_after_repeated_calls returned self.finalize_answer(answer, conversation) while the post-loop print block called finalize_answer again. Both now go through the single post-loop call, matching the failure-summary branch. tests/unit/agents/test_loop_break_answer.py::test_the_loop_break_answer_is_finalized_exactly_once fails on the old code for both streaming modes.

Merge — reconciled against #4031 (parse_failures, untouched) and #4021 (tool admission, lives in tool_loader.py, no overlap); an AST duplicate scan of agent.py found no doubled counters, kwargs, or state init. The two red checks on the pre-merge head were stale-base artifacts — both failing tests were last touched by #4309, which the branch lacked.

Review items — the Ctrl-C finding was resolved upstream by the user_stopped flag in #4373; the console finding is fixed by the post-loop print block; the denied-repeat wording stays as the tests pin it.

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

Labels

agents documentation Documentation changes llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants