Skip to content

fix(agent): shell views count as reads; short-circuit repeated tool calls - #4399

Closed
kovtcharov wants to merge 31 commits into
amd:mainfrom
kovtcharov:feat/step-adaptive-reasoning
Closed

kovtcharov wants to merge 31 commits into
amd:mainfrom
kovtcharov:feat/step-adaptive-reasoning

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

17 of 29 edit failures in the benchmark runs were the read-before-edit guard rejecting a file the model had just shown itself with sed -n, head or cat, each costing a re-read and a retry step. And when a model stops reasoning between steps it can loop: DeepSeek repeated the same grep 101 times in a row (281 calls in 43 steps, no edit), and GAIA executed every one and re-sent the same output each time.

  • Shell views count as reads. A successful cat, head, tail, less, more, sed -n or grep -n on a file records it as read for the edit guard, resolved against the directory the command ran in, so the next edit_file on it goes through. A never-viewed file is still refused, and so is one that changed on disk since the view.
  • Repeated tool calls are short-circuited. A call identical to one that already ran this turn (same tool, same arguments, within the last 6 steps, no error, no file changed since) is not run again: the model gets a pointer to the step that ran it and a read_tool_output handle to the archived output. After 3 short-circuits in a turn the message warns; after 6 the turn ends through the existing loop guard with one closing call to answer from the work done. GAIA_DUPLICATE_GUARD=0 disables it.

The reasoning-effort policy and the reasoning-history switch that this branch first carried were measured, rejected and removed: disabling reasoning makes the model loop, and dropping reasoning history loses the carried plan and lowers judged quality on every model.

Stacked: merges after #4384 (delegate subtask, which this branch contains, with #4379 and #4397 beneath it) and #4055 (keep the model's reasoning; its five commits are carried here). The branch has main merged in so the edit-guard change builds on #4029.

Test plan

  • pytest tests/unit/agents hub/agents/gaia/python/tests — 2,314 passed, 53 skipped; the only failures (3 tool-count, 3 test_lemonade_start_hint) fail identically on the parent commit
  • tests/unit/agents/test_duplicate_call_guard.py (14), test_shell_view_counts_as_read.py (15), test_read_before_edit.py (66) green
  • black, isort, flake8, pylint clean on changed files
  • Adversarial suites on DeepSeek V4.1 Flash: batch 9 (15 planted traps) 15/15 with nothing on and 15/15 with eviction; batch 11 (13 traps aimed at these guards, incl. a shell script rewriting a file, creating files and a side effect run twice between identical reads) 10/10 with the guard on and 10/10 off, 13/13 in orchestrate mode; zero tasks pass with the guard off and fail with it on, and the guard on used 13% fewer input tokens

Validation pass (2026-09-26, integration build with both guards on). DeepSeek V4.1 Flash: 14 everyday tasks 14/14, quality 4.96, $0.086 (baseline 14/14, 4.88, $0.098); TheRock 4/4. GLM-5.3 Flash: 13/14, 4.71, $0.095; TheRock 4/4, closed-book 4.75, $0.27. Neither guard fired in any of the 36 runs — the transcripts show no short-circuit and no loop-guard exit — so the numbers are the build's baseline with the guards armed, and the adversarial suites above remain the evidence that they act when they should. The GLM miss was the test-claim correction erasing the answer, fixed separately in #4401.

Kalin Ovtcharov and others added 24 commits September 25, 2026 15:57
Every tool result is re-sent on every later step, and on a real 144K-line
repository accumulated results were 83% of the conversation. An over-budget
result now reaches the model as the parts that fit plus an index of the rest,
split where the document splits: functions and methods, headings, JSON
records, a search's files, test sections, diff hunks, paragraphs. Each index
entry is an exact offset/length that read_tool_output returns verbatim, so
nothing is lost and no new tool is needed. check_result and the other result
fields stay in view.

A remote model reached through Lemonade gets its own budget (8,000/6,000
chars) sized by re-send cost; 46% of the benchmark's result bytes sat above
8,000. Local NPU/GPU budgets are unchanged. Replaying 12 benchmark
transcripts offline, tool-result characters re-sent fall 29.7% (23.9% if
every condensed result is read back once).

The message backstop now caps at the threshold the gate passes, not the
smaller target, so results between the two are no longer cut unarchived; a
read_tool_output page is never condensed again.
…n view

Index entries could be longer than the 8,000-char page read_tool_output
allowed, so the model was told to make a call that failed: a 1 MB Python file
had every entry over the limit, and a 50,000-char stdout line was one. A read
now takes any length, returns at most one page, and reports `remaining` with
`next_offset` to continue, so every entry reads back exactly.

When one line too long to split is most of a result, the result keeps its
head and tail in view with the middle indexed, instead of showing only the
first line. Search matches with no file group under "(no file)" instead of
crashing, and a text `context` is one line, not one per character.

On NPU, a non-string tool result between 20,000 and 30,000 chars now reaches
the model whole, where the message backstop used to cut it to 20,000 without
archiving it; that path wants an NPU eval before merge.
On a live GLM run the model ignored the index and paged through whole archived
outputs 8,000 chars at a time, re-sending every file on top of its condensed
copy, because the reader advertised offset/limit with 8,000 as the page size.
Index entries are now numbered, read_tool_output(artifact, entry=n) returns
exactly that part, and every condensed result carries a `fetch` line saying
so. The docstring leads with the entry, lets limit default to the entry's
length, and says paging through a whole output is almost never needed.
offset/limit still work; an entry number outside the index is an error that
names the valid range.
The 8,000-char cloud threshold made files of 20-30K chars, which the model
needs whole to edit, arrive indexed; it then read them back one entry per
round trip, so steps rose and tokens did not fall (GLM, 4 tasks: 8.39M vs
8.29M; DeepSeek's worst task: 77 vs 72 steps, 20 entry reads). A remote model
reached through Lemonade again gets truncation_budget(None), as before. The
index, numbered entry reads, the fetch field, paging and the message-backstop
change stay: the index now applies only to results over the device threshold,
where it keeps every omitted byte reachable.
…sitory

Coding tasks in a repository ran without a shell, because the flagship's tool
loader admitted run_shell_command only when the request's wording was close to
the tool's description. "Skip gfx90a tests on PRs unless labeled" is not, so
every grep and sed went through run_python, one command per call.

Shell availability now follows the working context: when the session's project
root (the one the project map already resolves) is a code repository,
run_shell_command joins CORE for the life of the loader. It is fixed at
construction, so the offered prefix is stable from the first turn. Outside a
repository selection is unchanged, and the shell's approval gate is untouched.
An explicit project root pointing at a non-repository directory still rendered
"run_shell_command accepts: ..." in the project map, because the map asked the
tool registry whether the agent owns the shell rather than the per-turn filter
whether it was offered. That is the guaranteed failed call has_shell_tool
exists to prevent.

Also makes the negative shell test deterministic. It asserted "no repository"
by chdir-ing into tmp_path and trusting the upward walk to find nothing before
$HOME — on a runner whose TMPDIR sits under a checkout the walk finds a
repository and the assertion flips. The no-project case now stubs the root; the
non-repository case covers both ways a root is supplied.

The npm CHANGELOG promised the behaviour without saying which root it follows.
A sidecar's working directory is the daemon's, not the user's, so the entry now
names GAIA_PROJECT_ROOT the way SKILL.md section 11 already does.
On a real repository two-thirds of the flagship's tool calls before its first
edit are exploration, and every one of those results is re-sent on every later
step. delegate_task hands such a subtask to a child agent whose whole context
is discarded when it finishes; the parent's conversation grows only by a small
result plus evidence, and the full transcript stays readable through
read_tool_output.

The child is a fresh instance of the same agent class with the same config
(model, backend, working directory, tools, permissions, system prompt), a
fresh conversation, its own step budget, a silent console, and no delegate
tool of its own (depth 1). A child exception or provider failure comes back as
an error result, never retried; a child that runs out of steps returns what it
has with hit_step_limit set. The child's tokens are added to the parent's turn
totals as a delegated stats entry and tracked separately in delegated_tokens,
so any saving is measured with the child's cost included.

Off by default on the flagship: GaiaAgentConfig.delegate_enabled or
GAIA_DELEGATE=1 turns it on, and when on it is always offered regardless of
per-turn tool selection. GAIA_DELEGATE_MAX_STEPS sizes the child's budget
(default 40).
…n is on

With delegate_task offered on every turn, a live run still never called it:
the model explored a repository with 40 shell commands itself. The tool's
docstring alone does not change behaviour, so the mixin now contributes a
short system-prompt fragment through the same get_*_system_prompt discovery
every other mixin uses: delegate the investigation before editing an
unexplored repository, delegate any subtask whose output is a short answer,
write a complete brief because the worker has no memory of the conversation,
and do the edits and final verification yourself.

The fragment renders only while delegation is enabled, so the prompt is
byte-identical with it off, and the child (depth 1, delegation disabled)
never carries it.
…r excerpt

Three live runs delegated once each with a good brief, but the parent got
nothing usable back and re-explored the repository itself, so the arm came
out worse than baseline. The child's 6-7K answer was elided to ~200 chars to
fit a 3,800-char cap, and the excerpt's artifact pointed at the 137K child
transcript, so the parent paged the transcript twice, gave up, and started
over.

The answer is the deliverable. The returned dict may now be one
read_tool_output page (8,000 chars) and the answer is kept whole up to
6,500 chars. A longer one is archived under its own handle and returned as a
chunk index of that archive (shown parts plus numbered entries), so artifact
always resolves to the answer; the transcript stays in its own field, labelled
as the worker's full log for drilling only. commands_run drops the shell
tool's "cd <workdir> &&" prefix and is capped at 12 so it cannot crowd out
the answer.
…nt can trust

A live run delegated the investigation, received a 7K answer, and then made
33 exploration calls anyway before editing: for an edit task the parent has
to read the files it edits regardless, so delegating only the understanding
saves nothing. The split that can save is the opposite one: the worker reads,
edits and runs the tests for one bounded component, and the parent plans,
reviews each worker's evidence, and runs the final verification.

The prompt fragment and the tool docstring now say exactly that, and the
evidence carries what trusting a worker needs: files_changed lists each file
with added/removed line counts from git diff --numstat (names only outside a
repository; an untracked file counts every line as added), and tests reports
how many checks ran plus the last one's command, pass/fail and summary lines,
capped at 600 characters. The 8,000-character result budget is unchanged.
…btask

Offered the choice, the model never delegates: every measured run opened
with the same four shell commands and spent a third to a half of its tokens
exploring before its first edit, whatever the prompt said. Recursive
composition has to be a mode the harness enforces, not a tool the model may
pick.

GAIA_DELEGATE=orchestrate (config delegate_mode="orchestrate"; 1/true/on
still mean "tool") offers the parent exactly delegate_task and
read_tool_output on every turn: no tool loader, so no load_tools escape
hatch, and any other tool call returns an error without running. The
ORCHESTRATION prompt fragment replaces the DELEGATION one and lays out the
shape: one investigate subtask, one implement subtask per component, one
verify subtask. Children keep the full ordinary tool set and cannot
delegate, as before.

delegate_task takes an optional kind (investigate | implement | verify,
default implement), recorded in the result, the archived transcript and the
delegated stats entry so a run can be broken down by subtask kind. A parent
starts at most delegate_max_children workers (default 12,
GAIA_DELEGATE_MAX_CHILDREN); the next call returns an error telling it to
finish with the evidence it has. Malformed GAIA_DELEGATE and delegate_mode
values now fail at construction instead of quietly meaning "off".
…n record

A judge reading an orchestrated run could not see what the workers did: the
child transcripts lived only in the in-memory artifact store, gone when the
run ended, and the parent's log held nothing but the delegate result dicts.
The parent then wrote "re-ran just now: 61 passed" for a test run a worker
had made, and was scored as untruthful.

After each delegation the parent's turn log now gets a
type="delegated_transcript" system entry carrying the kind, the brief, the
archive handle, the step count and the child's full conversation, so a
transcript written from outcome["conversation"] shows every command a worker
ran and its output. Like the stats entries it is a log record only: the
model's messages are a separate list, and a test pins that the entry never
reaches them. The orchestrate prompt and the tool docstring now say the
worker's run is the worker's — name which one ran what and quote its
evidence, never "I ran".
On a 144K-line repository the context the agent re-sends each step reaches
130-195K tokens, 83% of it old tool results the model has already acted on.
Whether dropping them saves money depends on the provider's cached-versus-
uncached input price: every eviction changes the prompt prefix, so the next
call re-reads everything after the eviction point uncached once. Simulated
on real per-step counts, Kimi K2.7 (cached $0.19/M vs $0.95/M) saves 27%,
GLM-5.3 Flash 11%, and DeepSeek V4.1 Flash (0.006 vs 0.30) loses.

This is not the context compaction the roadmap rules out ("memory + RAG
handles long conversations"): nothing is summarised or dropped. An evicted
result is archived whole in the agent's ArtifactStore and its message in the
list sent to the model becomes a one-line stub naming the read_tool_output
call that fetches it; a result that already arrived as a chunk index keeps
its handle and index. The turn's conversation log is never touched. It is
off by default.

context_eviction is off | on | auto (GAIA_CONTEXT_EVICTION wins). auto is
on only for a cloud model whose cached/uncached input price ratio, from the
table in gaia.llm.cache_pricing, is at least 0.1; a local or unknown model
is off, said once at info level, never guessed. Eviction fires at the head
of a step only when the previous step's measured prompt_tokens exceed
context_eviction_threshold_tokens (60000, GAIA_EVICT_THRESHOLD) and the
results older than context_eviction_keep_steps (8, GAIA_EVICT_KEEP) add up
to context_eviction_min_batch_tokens (30000, GAIA_EVICT_MIN_BATCH); then all
of them go in one batch and stay evicted, so the prefix is deterministic
afterwards. read_tool_output pages and delegate_task results are never
evicted; user and assistant messages are never changed. Each batch adds
evicted_results and evicted_tokens_est to that step's stats record and logs
one info line. Malformed env values or arguments fail at construction.
Kimi K3 lists at $3.00 input, $0.30 cached, $15 output on Fireworks (2026-09-26), a
0.10 ratio, so auto eviction turns on for it.
… workers

In orchestrate mode each worker starts from zero: on the measured runs the
four to six investigation workers per task each spent about ten steps
re-reading the same files, tripling the cost of the exploration.

Whenever delegation is on, the parent and every child now share one
SessionLedger (gaia.agents.base.session_ledger) and one artifact store. The
ledger records, deterministically and with no model in the loop, what every
tool result of the session established: files read (path, size, and for text
of 2K+ chars the chunk index's outline with line ranges, the full text archived
under the ledger's own index), searches with per-file hit counts (the search
tool and grep/rg commands), checks with their runner summary, files changed,
and each worker's report. Entries name the step and who found them, and dedup
on (kind, path or pattern). Eviction never touches it.

It reaches the model two ways. Every child brief opens with the digest under a
fixed header, after the system prompt and before the brief, so children spawned
from one ledger state share a byte-identical prefix for provider caching; the
digest carries no handles or timestamps, so identical findings render to
identical bytes. And a session_findings(query) tool on the parent and every
worker (part of the orchestrator's set, never condensed or evicted, capped at
8,000 chars) returns the digest, or the matching entries with their artifact
handle and entry numbers so read_tool_output(artifact, entry=n) fetches the
exact part instead of re-reading. The mode paragraphs, the tool docstring and
a one-line worker fragment say to check it before reading or searching.
…uest

GAIA threw away almost everything a reasoning model wrote. The provider read
reasoning_content only when a reply had no text (and then passed it off as
the answer), and the loop deleted inline <think> blocks. On one DeepSeek call
91% of the output tokens were reasoning, so every step of a tool-calling job
re-derived its plan from scratch.

Reasoning now travels as its own field: the provider returns it apart from
the answer, the transcript records it on each assistant step, and each step's
reasoning goes back to the model as reasoning_content on its assistant
message for the rest of the request. Reasoning stored from earlier user
requests is not resent unless resend_reasoning_across_requests is set.
Providers that reject the field (OpenAI, LiteLLM) never receive it.
A reply that merely mentioned `<think>` part-way through prose was cut at
that point, and everything the model said after it was silently deleted as
reasoning. Only a reply that *opens* with an unclosed block was ever cut off
mid-thought, so the pattern is now anchored there.

Also from review:

- Restore the reasoning_content-as-answer recovery for llama.cpp builds that
  route a finished reply into that field, gated on finish_reason="stop" so a
  reply cut off by the token limit still is not shown as the answer.
- Route BuilderAgent's history through a shared _history_for_request, so
  resend_reasoning_across_requests holds for every subclass rather than only
  the base loop.
- Document `usage` and `reasoning` on AgentResponse; both were missing from
  the SDK reference and the spec.
- Cover the streaming loop, which reads reasoning off the is_complete chunk
  only, and pin the mid-prose-mention regression.
…odes

The trace tests stubbed the chat response with a bare MagicMock, so
once this branch started carrying the model's reasoning forward,
getattr(response, "reasoning", None) returned an auto-created MagicMock
instead of None. That rode into the turn record as reasoning_content
and json.dump refused it, failing all ten tests in the file.

Priming reasoning=None on both stubs keeps them a faithful stand-in for
a backend that returns no reasoning. Production code is untouched.
Three tests in tests/unit/agents/test_model_history.py broke once this
branch met current main: the agent loop read `.reasoning` straight off
the chat response, and the MagicMock stubs that drive most agent-loop
tests answer that with another MagicMock. It rode into the request
history as `reasoning_content`, where json.dumps cannot serialise it.

The same shape was patched once already in test_trace_tool_schema.py by
priming the stub. There are 14 such _stub_chat helpers under
tests/unit/agents/, so fixing them one at a time is a treadmill --
and any of them not asserting on serialised messages would keep
silently polluting the history. Normalise at the capture point instead:
AgentResponse.reasoning is Optional[str], so anything that is not a
non-empty string is no reasoning.
…ending reasoning

Reasoning is 58-85% of every output token on the benchmark runs and, at
output prices, about 40% of the bill; and each step's reasoning was re-sent
on every later step of the request, 14-24% of all prompt tokens. Both are
now under the caller's control, off by default.

- reasoning_policy (GAIA_REASONING): off sends nothing; none sends
  reasoning_effort="none" on every step; adaptive decides each step from the
  previous step's tool results, before the call -- the model's default for
  the first step of a turn and after a tool error, a refused call, a
  test-runner summary, an edit or a delegate_task result; none after a
  plain read, search, list or shell look. Each step's stats record carries
  the choice as reasoning_effort.
- reasoning_history (GAIA_REASONING_HISTORY): send re-sends each step's
  reasoning_content within the request as before; drop omits it from what
  is sent while the conversation log keeps every step's reasoning. The
  first stats record of a turn names the setting. The cut-off continuation
  now logs its partial reply too, so drop loses nothing.
- The provider forwards reasoning_effort only when set and only to a cloud
  model; a backend that answers 400 for the field raises an error naming
  the fix instead of a generic cloud failure, and never retries.
…it guard

17 of 29 edit failures in the benchmark runs were the read-first guard
refusing a file the model had just shown itself with sed -n, head or cat,
each followed by a re-read and a retry step. The shell tool now records the
files a successful cat/head/tail/less/more, sed -n or grep -n showed,
resolved against the directory that step ran in (so a cd target counts),
into the same record the edit tools consult. A never-viewed file is still
refused, and so is one that changed on disk since the view.
@github-actions github-actions Bot added documentation Documentation changes chat Chat SDK changes llm LLM backend changes tests Test changes performance Performance-critical changes agents labels Sep 26, 2026
With reasoning off, DeepSeek repeated the identical shell command 101 times
in a row, and its twin 101 times: 281 calls in 43 steps, no edit, until the
step budget ran out, and GAIA ran every one and re-sent the same output each
time. Runs with reasoning on still show 1-3 exact repeats per task.

The duplicate-call guard sits at the tool-execution seam, on by default and
model-agnostic. A call identical to one that already ran this turn (same
tool, same arguments after JSON canonicalisation) within the last
duplicate_window steps (6) is not run again; the model gets a structured
duplicate result naming the step that ran it and a read_tool_output handle
to the archived output, so nothing is lost. A call still runs when its
previous execution errored or was refused, when an edit or write tool has
since touched a path it references (or any file, for a shell command), and
for read_tool_output, session_findings, delegate_task, sleep and
request_user_input. After duplicate_limit (3) short-circuits the message
warns and the step's stats record loop_suspected; after twice that the turn
ends through the existing loop-guard path, with one closing call to answer
from the work done. GAIA_DUPLICATE_GUARD=0 disables it; the window and
limit have env overrides that fail loudly on a malformed value.

The verification-scope test for a newly broken check now writes a file
between its two runs: without a change, the same check is not run twice.
@kovtcharov kovtcharov changed the title feat(agent): step-adaptive reasoning effort, reasoning history switch, shell views count as reads fix(agent): shell views count as reads; short-circuit repeated tool calls Sep 26, 2026
Kalin Ovtcharov and others added 2 commits September 26, 2026 14:13
…isk is unchanged

The duplicate-call guard took "no GAIA edit tool ran" to mean "nothing
changed", so a shell command that rewrote a file (python tools/bump.py),
created files or bumped a counter was invisible: the repeated cat or ls was
served the stale result, and a repeated python tools/tick.py was itself
short-circuited, so the second side effect never happened.

Only a read-only call is ever short-circuited now: the read, search and
listing tools, and a shell command whose every pipeline segment starts with
a read-only program (cat, sed, head, tail, grep, rg, find, ls, wc, tree,
stat, file, diff, sort, uniq, cut, awk, echo, printf, cd, pwd, and git with
log/show/status/diff/branch/rev-parse/blame/ls-files) with no output
redirection, no command substitution, no sed -i / awk -i inplace and no
find action that writes or executes. The classifier reuses the shell tool's
connector and pipeline splitters, git subcommand resolver, in-place-flag
check and find-action list. Anything else runs every time.

A read-only repeat also runs again unless the world is unchanged: at record
time the guard fingerprints what the call looked at (size and mtime of each
file it names, mtime and entries of each directory, or the working
directory's top level when nothing resolves) and a different fingerprint at
check time means a fresh run. Tool-level mutation tracking stays as a
second invalidation.

Either invalidation, and every recorded edit, marks the session ledger's
read entries for the affected files stale; the digest renders them as
"(stale: file changed after this outline)" and a fresh read replaces the
entry. The ledger also records each read file's size and mtime and
re-checks them when it renders, so a change no tool reported is still
caught.
The guard imported a helper that only some branches carry; a repeated
git log or git show could not be classified without it.
@kovtcharov
kovtcharov marked this pull request as ready for review September 26, 2026 22:57
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

Both fixes target real waste seen in benchmarks: file views through the shell now count as reads for the edit guard, and repeated identical read-only calls are answered from the earlier result instead of running again. The shell-view change looks solid. The duplicate guard has one correctness gap: it can tell the model "nothing has changed" when something did.

  • Stale results after a script edits a file in a subfolder. A repeated recursive search (for example grep -rn foo src) only checks the top level of the folder it names. If a python or shell command rewrote a file two or more levels down in between, the repeat is still skipped and the model gets the old matches, labelled "nothing has changed since". I reproduced this locally (repro below). Either make the fingerprint cover recursive reads, or clear the guard's memory whenever a non-read-only shell or Python call succeeds.
  • The gaia agent's CHANGELOG doesn't mention either behavior, or the GAIA_DUPLICATE_GUARD=0 switch. Per the repo's doc-sync rule, a behavior change has to be named in the CHANGELOG.

Real-world evidence

N/A: the evidence bundle wasn't produced for this run. The PR description reports adversarial benchmark runs on DeepSeek V4.1 Flash (batch 9: 15/15, batch 11: 10/10 with the guard on and off). The verdict rests on static review plus the local reproduction of the stale-result case below.

🔍 Technical details

Issues

🟡 Duplicate guard serves stale output for recursive reads after a side-effecting run (src/gaia/agents/base/duplicate_guard.py, fingerprint / _state_of / _entry_state)

A directory's fingerprint is its own mtime plus (name, size, mtime) of its direct entries. Editing src/pkg/mod.py in place doesn't change src's mtime or the pkg entry's mtime, so the fingerprint doesn't change. _changed_since only tracks is_mutating_tool calls (edit/write tools). run_shell_command running python fix.py, as well as run_python and execute_python_file, never add anything to _changes. The pattern-only fallback (rg foo → cwd top level) has the same gap, and so do search_code, search_file_content, find, tree and ls -R on a directory.

Repro against this branch:

step 1  run_shell_command {"command": "grep -rn foo src"}   -> executed, recorded
step 2  run_shell_command {"command": "python fix.py"}      -> executed (rewrites src/pkg/mod.py)
step 3  run_shell_command {"command": "grep -rn foo src"}   ->
  "Identical call already ran at step 1 with the same result; nothing has changed since. ... Take a different action."

This is the "edit via script, then re-grep to confirm" loop, so it can come up in normal coding work. The model is told to take a different action based on stale data. Cheapest fix: in record(), when a successful call is not read-only (any shell/python run that isn't classified read-only), drop every read-only record (or push a wildcard change) so later reads run fresh:

        if ok and not read_only and tool_name not in ALWAYS_EXECUTE:
            # An arbitrary run may have written anywhere; trust no earlier read.
            for record in self._executed.values():
                record["ok"] = False

Place this before the new record is stored, so the current call's own entry isn't invalidated. Please add a test in test_duplicate_call_guard.py with a nested file changed by a non-mutating-tool run. The batch-11 "shell script rewriting a file" trap probably used a file named directly in the read, which the per-file fingerprint does catch.

🟡 CHANGELOG missing the two headline behaviors (hub/agents/gaia/npm/CHANGELOG.md)
The CHANGELOG hunk in this diff covers the shell-in-repos change from the stacked branch, but has nothing on shell views counting as reads, the duplicate short-circuit, or GAIA_DUPLICATE_GUARD / GAIA_DUPLICATE_WINDOW / GAIA_DUPLICATE_LIMIT. docs/sdk/core/agent-system.mdx does document the guard.

🟢 git branch is classed read-only (duplicate_guard.py, READ_ONLY_GIT_SUBCOMMANDS)
git branch <name> / -D / -m write refs. Low impact, since a repeat would error or be a no-op, but a short-circuit would report the first call's success instead of the real "already exists" error. Consider allowing branch only with no positional args, or with --list / -a / -r / --show-current.

Strengths

  • The read-only classifier is conservative in the right places: any >, command substitution, sed -i/awk -i, or a writing find action disqualifies the call, and a line shlex can't parse runs.
  • Shell views only count as reads on exit code 0, and are resolved against the step's cwd. viewed_paths skips value flags (-n 5, -A 3, -e pat), so pattern operands aren't mistaken for files.
  • The guard fails loudly: malformed env vars raise, and a missing artifact store raises instead of dropping the archived output.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

@itomek: flagging this one for a careful look rather than a mechanical rebase-and-merge.

The fix is well-motivated — real benchmark data (17/29 edit failures from the read-before-edit guard rejecting files the model had just viewed via `sed`/`head`/`cat`, plus a 101-call repeated-grep loop) — but both changes alter core tool-execution behavior: what counts as a "read" for the edit guard, and when a repeated tool call gets short-circuited instead of executed. A false-positive short-circuit could suppress a legitimate repeated call, so this is worth a second pair of eyes on the exact match/trigger conditions before merging, not just a passing test suite.

# Conflicts:
#	docs/sdk/core/agent-system.mdx
#	docs/sdk/sdks/chat.mdx
#	docs/spec/agent-sdk.mdx
#	src/gaia/agents/base/agent.py
#	src/gaia/agents/base/chunk_index.py
#	src/gaia/agents/tools/shell_tools.py
#	src/gaia/chat/sdk.py
#	tests/unit/agents/test_chunk_index.py
#	tests/unit/test_claude_provider.py
#	tests/unit/test_project_map.py
…write

A script's file rewrite via run_shell_command, run_python or
execute_python_file left the duplicate-call guard's cached reads stale:
none of the three register with is_mutating_tool, so record() never
invalidated anything for them, and the on-disk fingerprint diff at
check() time only sees a directory's own top-level entries and mtime --
missing a rewrite of an existing file further down the tree. A repeated
read-only call after such a script ran could come back with the
pre-edit cached result.

These tools' command text can't be parsed for exactly which paths they
touch, unlike a named write/edit tool, so instead of naming paths a
successful non-read-only run now drops every fingerprinted read cached
this turn.

Also drops a duplicate resend_reasoning_across_requests parameter (and
its docstring paragraph) that the merge with main left declared twice
in Agent.__init__, which raised SyntaxError on import.
Merging main's independent amd#4376 (shell offered whenever the session
works in a repo) reintroduced an older, simpler copy of this method
right after the one this branch already had -- Python keeps only the
second definition, so it silently overrode the version that also puts
delegate_task and the session-findings ledger tool in core when
delegation is on. hub/agents/gaia/python/tests/test_delegate_wiring.py
caught it (delegate_task/session_findings missing from tool_loader._core).
@itomek

itomek commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator

Closing this one. You flagged it as stacked, and that's exactly the difficulty: #4384 and #4397 both still target main themselves, so there's no way to look at this change on its own — and the copy of #4397's work carried in here has already fallen behind #4397's own head, while #4384 is conflicting. Waiting for the stack doesn't untangle that. The half I actually want is 221 lines buried under nearly six thousand.

The shell-view fix is the good half, and I do want it. It stands on real numbers, it's self-contained, everything it needs is already on main, and its tests pass on their own. Bring just that back as its own PR off current main and I'll move it quickly.

The duplicate guard needs one more pass first. The fixes you pushed over the weekend and this morning closed three of the four stale-read cases I could reproduce — that was solid work, and the invalidation approach is the right one. One still fires, and it's the most common motion there is: edit a file, then run git status. Separately, #4408's persistent shell session landed underneath this branch and the guard doesn't know about it, so it checks the wrong directory after any cd. Your own validation notes neither guard fired across the 36 everyday runs, so the adversarial batches are carrying all the weight there.

Nothing is lost by closing. The branch stays exactly as it is, and this reopens in one click if you'd rather carry it forward than split it.

🔍 Technical details

Checked against head d41694375 — 4 commits behind main, MERGEABLE. Not stale; the recent fixes are real.

Composition (git diff --numstat origin/main...), +5,989 / −15 across 22 files:

part lines status
#4384 delegate + #4397 eviction + session_ledger + cache_pricing 3,828 (64%) both PRs still open
duplicate guard (duplicate_guard.py 614 + tests 737) 1,351 gap below
shell view (shell_tools.py +62, test_shell_view_counts_as_read.py +159) 221 ready
docs / shared wiring 589 —

Stack drift. git diff <4384> <4399> -- src/gaia/agents/tools/delegate_tools.py → empty (byte-identical), but git diff <4397> <4399> -- src/gaia/agents/base/context_eviction.py → 16+/31−. #4397 has moved on since, so merging this would land the older version of its own work. #4384 is CONFLICTING.

Shell-view half extracts cleanly. Only new import is file_read_record (file_edit.py:149, on main); it uses step_cwd and step.segments, both on main. Main's shell_tools.py records no reads at all (git grep file_read_record origin/main -- src/gaia/agents/tools/shell_tools.py → empty), so nothing here duplicates main. Because it resolves against the step's real cwd it doesn't inherit the guard's directory problem. 15/15 green locally.

git status after edit_file — reproduced on d41694375. Record git status at step 1 → edit_file on src/pkg/mod.py at step 2 → git status at step 3 returns "Identical call already ran at step 1 … nothing has changed since."

Why: _changed_since (duplicate_guard.py:549) only invalidates when the cached call's argument text references the changed path, and git status names nothing. edit_file is a mutating tool, so it records paths rather than calling _invalidate_cached_reads — that clean sweep is reserved for OPAQUE_EXEC_TOOLS (:95). The fallback fingerprint is the cwd's mtime plus top-level entries (fingerprint, :292), and a nested edit moves neither.

Shell-session divergence. _call_cwd resolves from os.getcwd() (duplicate_guard.py:229), but the command runs at self.shell_session.cwd (shell_tools.py:2901) and a cd persists via set_cwd (:3109). grep -c shell_session src/gaia/agents/base/duplicate_guard.py → 0. No test covers it.

CHANGELOG. grep -niE "duplicate|short-circuit|counts as read|GAIA_DUPLICATE" hub/agents/gaia/npm/CHANGELOG.md → empty. The CHANGELOG hunk in the diff is the shell-in-repos entry carried up from the stack.

Scope note on the guard. Main already stops 4 consecutive identical calls (agent.py:8199, max_consecutive_repeats default at :1346), so the new ground is non-consecutive repeats inside the 6-step window plus the 13% input-token saving — real, but narrower than the 101-repeat example implies.

Local runs (Linux, py3.12): test_shell_view_counts_as_read.py 15, test_duplicate_call_guard.py 47, test_turn_metrics_wire.py 25 — all green.

CI: 39 pass / 2 fail, both smoke lanes — Windows on test_delegate_tools.py::test_ledger_reaches_the_parent_context_only_through_the_tool (a path-escaping assert in the stacked work), macOS on test_memory_turn_recall.py::…test_the_relevant_note_reaches_the_turn_with_its_age. Neither touches the two headline halves.

@itomek itomek closed this Sep 29, 2026
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Sep 29, 2026
…ted (amd#4465)

A long session re-sends every tool result in full on every step, so the
context the model is charged for grows without bound — a big `grep`
early in a session keeps costing on every turn after it. This swaps
results the model has already moved past for a one-line stub, keeping
the full text in the artifact store and reachable through
`read_tool_output` if the model wants it back.

Off by default. `auto` only fires where the saving is worth more than
the re-read, using the provider's cached-input price ratio, and a mode
it doesn't recognise raises rather than quietly falling back.

Replaces amd#4397. Every commit from that branch is an ancestor here,
authorship intact.

### Test plan

- [x] `pytest tests/unit/agents/` — **1982 passed, 50 skipped, 0
failed**
- [x] Purely additive: `git diff --stat origin/main...HEAD` is **7
files, +984/−0**
- [x] Off by default confirmed in source: `context_eviction: str =
"off"` (`agent.py:1364`), and `context_eviction_from_env()` returns
`None` when `GAIA_CONTEXT_EVICTION` is unset
- [ ] `gaia eval agent` — this changes what context reaches the model,
so CLAUDE.md's eval gate applies before this is relied on in anger

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

**Why now.** Three open PRs were shipping byte-identical copies of this
module — amd#4384 and amd#4399 alongside amd#4397. Those two are closed; this is
the surviving copy, and the only one carrying the multi-turn fix.

**The bug that was blocking it is fixed.** The first review found that
eviction stopped working after turn one: the agent remembered which
results it had evicted by `tool_call_id`, but the next turn reloaded
saved history with those results back at full size and still marked
"already evicted", so they were never re-stubbed. `18a7917b2` ("keep
evicting stale tool results past a session's first turn") fixes it, and
the suite covers it.

**Ancestry**, with original authorship preserved by merge rather than
squash:

```
$ for c in 18a7917 f4924e3 2c21f48; do git merge-base --is-ancestor $c HEAD && echo "$c ANCESTOR"; done
18a7917 ANCESTOR
f4924e3 ANCESTOR
2c21f48 ANCESTOR
```

**One thing to watch.** `cache_pricing.py` hardcodes vendor list prices
captured 2026-09-26. Nothing detects drift. The design is deliberate
under the no-silent-fallbacks rule — an unknown model logs once and
stays off rather than guessing a ratio — but whether a hand-maintained
price table belongs in-tree is worth a separate decision.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents chat Chat SDK changes 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.

3 participants