Skip to content

fix(memory): only extract knowledge the user or a tool established - #4060

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:fix/memory-extract-from-tool-record
Sep 26, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:fix/memory-extract-from-tool-record

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

The agent's memory was storing its own answers as facts. After each turn, extraction saw only the user's message and the final answer, not what the tools returned. So a wrong or outdated claim in an answer became a permanent "Known fact". In a 2,121-task benchmark sweep it stored "run_shell_command is limited to read-only operations; rm is blocked", which became false after a permissions change. It also stored the answer's own "parse_deleted now accepts z", and throwaway narration like "User is working in directory /…/b4-scoping". About 40 of the 161 memories left behind were extractions of this kind.

Extraction now also gets this turn's tool record: each call, its arguments, whether it succeeded, failed or was refused, and a short result. Every stored item must say where it came from: the user's message or a tool result. Code drops anything that doesn't, and drops a "the tool showed it" claim when no tool succeeded that turn. The instructions also rule out session narration and permission refusals.

🔍 Technical details
  • The record is built in MemoryMixin._execute_tool, reset per turn in process_query, and capped at 20 calls of 240 chars each in the prompt. "Refused" comes from the result's executed: False flag.
  • Grounding fails closed: an op with no grounded field is dropped. Explicit "remember this" requests go through the remember tool and are unaffected.
  • Risk: a model that ignores the new required field extracts nothing. The eval below checks for this.

Test plan

  • pytest tests/unit/test_memory_extraction_grounding.py: 6 new tests on a real SQLite store, all fail on main. Covers what the tool record looks like in the prompt (ok, failed, refused), the per-turn reset, which rows get stored (answer-only and unlabeled facts dropped, user and tool-grounded kept), a tool claim with no successful tool, and an ungrounded delete
  • pytest tests/unit -k memory: 1094 passed. tests/integration/test_memory_eval.py: 38 passed
  • python util/lint.py --black --isort
  • gaia eval agent on the memory categories vs the committed baseline (extraction prompt changed)

Post-turn extraction saw only the user's text and the final answer, so the
answer's claims were stored as facts and replayed into later sessions: "rm is
blocked" (false after a permissions change), "parse_deleted now accepts z"
(the answer's own claim), plus per-session narration like "User is working in
/…/b4-scoping".

- Extraction now receives this turn's tool record: each call, its arguments,
  whether it succeeded, failed, or was refused, and a brief result.
- Every add/update/delete must say it is grounded in the user's message or a
  tool result. An op grounded in neither is dropped, and so is one citing a
  tool when no tool succeeded this turn.
- The prompt now rules out session narration and refusals/permission limits.
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

Good fix for a real problem: the agent was turning its own answers into permanent "facts", and requiring every extracted item to name its source (the user's message or a tool result) is the right shape. Two things should be settled before merge.

The extractor can now silently stop learning anything, and nobody would notice. Every stored item must carry a new field; if the local model doesn't reliably emit it, every item is thrown away and memory quietly goes dark — the only trace is a debug-level log line. You flagged this risk yourself and left the eval unchecked in the test plan. Please run the memory eval against the committed baseline before merging, and make the "everything was dropped" case log loudly rather than at debug.

The email agent doesn't get this fix. Because of how that agent's class is composed, neither the per-turn reset nor the tool recording runs there, so its extractor is always told "no tools ran this turn" and now discards anything the model attributes to a tool. It fails safe (it stores less, not wrong things), but it's worth either fixing or saying out loud, since the agent still looks covered from the outside.

🔒 SECURITY CONCERN: tool output now flows into the memory-extraction prompt as the authoritative source of truth. Before this change the extractor only saw the user's text and the assistant's answer; content the agent fetched or read is now presented to it as evidence worth storing. Worth confirming that's the intended trust boundary for memory writes. No exploit details here — @kovtcharov-amd for the call.

Real-world evidence

No evidence bundle was produced for this PR (evidence-bundle.md absent), and the change touches no CLI/API/UI surface directly — the matching proof for a prompt-path change is the agent eval, which the PR lists as not yet run. I could not execute the test suite in this environment (no pytest available), so my verdict rests on static review plus the unit-test results reported in the description. That unchecked eval box is the reason this is "request changes" rather than "approve with suggestions".

🔍 Technical details

🟡 Grounding is fail-closed with no visible signal (src/gaia/agents/base/memory.py:1600)

grounded is now required on every add/update/delete; an op without it is dropped at memory.py:1601-1611 with a logger.debug. With Gemma-4-E4B-it-GGUF (the default) a newly added required JSON field is exactly the kind of instruction a small local model drops — and the failure mode is "memory extraction returns 0 ops forever", which looks identical to "nothing worth storing". CLAUDE.md requires gaia eval agent against the committed baseline for any change to an LLM-facing prompt; the test plan's last box is unchecked.

Two asks:

  • Run the memory categories vs. tests/fixtures/eval_baselines/…/scorecard_*.json and paste the comparison.
  • When operations was non-empty but valid_ops came back empty, log at warning with the count — a model ignoring the field should be loud, not a debug line.

🟡 MemoryMixin._execute_tool / process_query never run for EmailTriageAgent

EmailTriageAgent(Agent, MemoryMixin, …) (hub/agents/email/python/gaia_agent_email/agent.py:667) puts Agent ahead of the mixin — its own comment at agent.py:1227 says so for process_query, and the same shadowing applies to _execute_tool. So _turn_tool_record is never initialised (memory.py:2561) and _record_tool_call never fires (memory.py:1663). _after_process_query still runs via the base hook, so that agent's extractor now sees (no tools ran this turn) and a_tool_succeeded=False on every turn, dropping all tool-grounded ops. Either route the record through a hook that survives the MRO, or note the limitation in the mixin docstring so the next reader doesn't assume coverage.

🟢 "ran and failed" is treated as "no evidence" (memory.py:1545)

The record carefully distinguishes refused, did not run from failed, but the gate collapses them: a pytest run that executed and reported 1 failed, 4 passed is genuine evidence, yet any tool-grounded op is dropped unless something returned ok. The refusal flag already carries the distinction:

        a_tool_succeeded = any(
            entry["outcome"] != "refused, did not run" for entry in tool_record
        )

If the stricter behaviour is deliberate, a one-line why would help — and either way the "refused, did not run" literal is now load-bearing in two places and wants a module constant.

🟢 Full result is split before truncation (memory.py:1674)

" ".join(detail.split())[:cap] tokenises the entire result string first — a multi-MB read_file or shell result builds a ~million-element temp list on every tool call, to keep 240 chars.

        detail = (error_msg if error_msg is not None else str(result))[: cap * 8]

🟢 _record_tool_call is the only unguarded call in _execute_tool

Both log_tool_call blocks are wrapped in try/except (memory.py:2615, memory.py:2645); the two new _record_tool_call calls are not. In the exception branch the call sits before the raise, so a failure inside it (e.g. json.dumps on unexpected args) would replace the tool's original exception. Low likelihood, but the surrounding code already decided bookkeeping must never break a tool call.

🟢 Cap behaviour is untested

EXTRACTION_TOOL_RECORD_MAX_CALLS / _DETAIL_CHARS and the (N earlier calls omitted) line have no coverage — a 25-call turn would be the natural case to add to TestToolRecordReachesExtraction.

Strengths

  • The tests read like the bug report: real MemoryStore on tmp_path, the three outcome shapes (ok / failed / refused) asserted against the actual prompt text, and the per-turn reset covered. The module docstring naming the two real poisoned memories is exactly the context a future reader needs.
  • Reusing check_was_executed from verification.py rather than re-deriving "was this refused" from the result shape keeps the one place that decision is made.
  • Dropping the ungrounded delete is the easy case to forget — covered.

@github-actions github-actions Bot added the documentation Documentation changes label Sep 21, 2026
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Merged current main into this branch — it was behind, but nothing in the PR's own change had to move. The overlap with main was in the memory docs and memory.py, and all of it auto-merged.

🔍 Technical details

Merge commit 56231683c (git merge origin/main, no rebase/force-push). Auto-merged: docs/guides/memory.mdx, docs/sdk/sdks/memory.mdx, src/gaia/agents/base/memory.py. PR content vs main: 5 files, +339/-18.

Tests: python -m pytest tests/unit/test_memory_extraction_grounding.py tests/unit/test_memory_mixin.py tests/unit/test_starter_skills.py -q → 496 passed, 15 skipped.

Grounding fails closed, so a model that stops emitting the field stores
nothing — and at a debug line that is indistinguishable from "nothing worth
storing". Extraction now warns when every proposed write was dropped for a
missing or unrecognised label, naming the count, so memory going dark is
visible rather than inferred.

Also from review:

- A crash in the turn record could replace a tool's own exception, or turn a
  successful call into a failure. Both _record_tool_call sites are now
  wrapped, matching the log_tool_call blocks beside them.
- The per-entry detail sliced the whole result before truncating it, building
  a million-element word list on a multi-MB read to keep 240 characters.
- The outcome literals are module constants now that the "ok" one gates
  tool-grounded extraction, with a comment on why a failed or refused call is
  not evidence.
- MemoryMixin._record_tool_call documents that an agent listing Agent ahead of
  the mixin shadows it, so its extractor always sees "no tools ran".
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Pushed fixes for the code findings. The two that still need a human are the eval and the trust-boundary question — neither is something I can settle from here.

Memory going dark is now loud. The review was right that this was the risk worth guarding: grounding fails closed, so a model that stops emitting the field stores nothing, and at debug level that looks exactly like "nothing worth storing". Extraction now warns, with the count, when every proposed write was dropped for a missing or unrecognised label.

The email agent really is uncovered, and I did not paper over it. I confirmed it by resolving the MRO rather than reading it: _execute_tool resolves to Agent, so no tool is ever recorded there, and its extractor sees "no tools ran this turn" on every turn. It fails safe — it stores less, never wrong things — but the honest fix is reordering that agent's bases, which is a change with real blast radius and does not belong in this PR. It is now documented where the next reader will hit it.

🔒 The security question from the review is still open and is yours to call, @kovtcharov-amd. Tool output is now presented to the extractor as evidence worth storing, where before only the user's text and the answer reached it. That is a deliberate widening of what can write to memory and it is the right shape for the bug being fixed, but it is a trust-boundary decision, not a code one. I have not changed it either way.

Still outstanding: gaia eval agent on the memory categories. I can't run it from here, and it is the finding I would least want skipped — the extraction prompt gained a required field, which is exactly the instruction a small local model drops.

🔍 Technical details

1. Fail-closed with no signal — fixed (memory.py). _extract_via_llm counts proposed add/update/delete ops and how many carried no recognised grounded value; when those are equal and non-zero it logs at WARNING naming the count and the accepted values. Deliberately not "valid_ops is empty": a turn where the model correctly returns noop, or where ops are dropped for a privileged category, must stay quiet. Three tests pin all three cases (all-unlabelled warns, noop stays quiet, one good write among unlabelled ones stays quiet).

2. EmailTriageAgent coverage — documented, not patched. Resolved against the real MRO:

agent _execute_tool process_query _after_process_query
ChatAgent MemoryMixin MemoryMixin MemoryMixin
GaiaAgent MemoryMixin MemoryMixin MemoryMixin
EmailTriageAgent Agent EmailTriageAgent MemoryMixin

EmailTriageAgent.__mro__ is (EmailTriageAgent, Agent, ABC, MemoryMixin, …), so both the _execute_tool override and the per-turn reset are shadowed, while _after_process_query still runs via agent.py's hasattr dispatch — extraction happens with a permanently empty record. Note _execute_tool = MemoryMixin._execute_tool is not a viable patch: its super() call resolves past MemoryMixin, and Agent sits before it, so the base implementation is unreachable. The fix is reordering the bases. Documented on _record_tool_call.

3. Bookkeeping can no longer break a tool call. Both _record_tool_call sites are wrapped. The exception-branch one was the one that mattered — it sat before the raise, so a failure there would have replaced the tool's original exception. A test monkeypatches it to throw and asserts the turn still completes.

4. Detail truncation. " ".join(detail.split())[:cap] → slice to cap * 8 first, then collapse. 8× slack so whitespace-heavy output still fills the 240-char budget.

5. failed vs refused — kept strict, with the why written down. Taking the reviewer's "if deliberate, a one-line why" option rather than loosening it. Worth noting the suggested example does not actually hit this branch: error_msg is set only when the tool returns status: "error" or raises, so a pytest run reporting 1 failed, 4 passed records as ok and already grounds extraction. failed means the call itself errored, which is not a finding. The three outcome literals are now module constants (OUTCOME_OK / OUTCOME_FAILED / OUTCOME_REFUSED) since the ok one is load-bearing in two places.

6. Cap behaviour — now tested. A 25-call turn asserts the (N earlier calls omitted) line, that exactly EXTRACTION_TOOL_RECORD_MAX_CALLS entries render, and that the oldest are the ones dropped.

Validation. tests/unit/test_memory_extraction_grounding.py: 12 passed (6 new). pytest tests/unit -k memory: 1147 passed, 76 skipped, 1 failed — test_memory_discovery.py::…::test_windows_email_failures_warn_like_the_other_platforms[_scan_outlook_registry-…], which fails identically with main's memory.py restored and lives in discovery.py, untouched here. python util/lint.py --black --isort --fix and --flake8 clean. Current main merged in; no conflicts.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 5904a1f Sep 26, 2026
39 of 41 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/memory-extract-from-tool-record branch September 26, 2026 04:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants