Skip to content

fix(memory): stop storing permission refusals as errors to avoid - #4058

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:fix/memory-skip-refusal-errors
Sep 22, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:fix/memory-skip-refusal-errors

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

The agent was teaching itself to avoid things it's allowed to do. In a 2,121-task benchmark sweep, 114 of the 161 memories left behind were auto-stored tool errors, and most were permission refusals like "Command 'rm' is not in the allowed list" or "Access denied: … is not in allowed paths". Those describe one run's permission settings. They were replayed into later sessions as "Known errors to avoid" and kept steering the model away after the settings changed. Clean-up was also too blunt: one successful ls deleted every stored shell error, including real lessons.

Now a call the permission layer refused before running is never stored. The tool reports the refusal fresh each time anyway. The signal is the result's executed: False flag: the shell tool already set it, and the file tools' path-guard refusals now set it too. A success now clears only errors from the same operation (same tool plus the same command binary or path). Errors from tools that actually ran and failed are still stored.

🔍 Technical details
  • Errors now carry metadata.operation. A shell operation is keyed by the program it runs. Leading env / VAR=value tokens are skipped and python -m X counts as X, so env TOYBOX_CLOCK=frozen pytest working again clears a pytest failure. Rows stored before this have no operation key, so they are still cleared per tool as before. Legacy refusal rows go away the first time the tool succeeds.
  • Marking the file tools' path refusals executed: False also makes the verification footer report them as "not run" instead of "ran and failed". That's the same meaning the flag already had for shell refusals (fix(agent): verification footer counts rejected test commands as executed #3677).
  • Not changed: the chat hub agent's own execute_python_file path check (2 of the 114 rows). It lives in a separately versioned hub package.

Test plan

  • pytest tests/unit/test_memory_error_refusals.py: new tests with a real SQLite store. 16 of 18 fail on main. Covers a real shell refusal, a real write_file path refusal (nothing stored), a real failure (stored, with its operation key), and per-operation clean-up
  • pytest tests/unit -k memory: 1102 passed
  • pytest tests/unit -k "file_io or file_tools or shell or verification or security or write": 1121 passed
  • python util/lint.py --black --isort

Most auto-stored tool errors were permission refusals (a command not on the
allowlist, a path outside allowed_paths). They describe that run's settings,
go stale when the settings change, and were replayed into later prompts as
"Known errors to avoid", teaching the model to skip calls that are now allowed.

- A result the tool marks executed: False (refused before running) is no
  longer stored. The file tools' path-guard refusals now carry that flag, as
  the shell tool's already did.
- A success retires only errors stored for the same operation (tool plus the
  command's binary, or the path), so a working `ls` no longer wipes a real
  lesson about pytest. Rows stored before this keep the old per-tool rule.
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This stops the agent from writing "you're not allowed to do that" into its long-term memory and replaying it at itself forever — a good fix, aimed at the biggest single source of junk memories in the benchmark sweep. The new tests are strong: they drive the real shell and file tools through a real SQLite store rather than asserting against mocks, so they'd actually catch a regression.

Two things worth a look before merge, neither of them a regression this PR introduces:

  • The mirror case is still open. When a user declines a confirmation prompt, nothing runs — but the memory layer counts that as the tool working, and deletes the errors remembered for it. So declining a risky command quietly erases a real lesson the agent had learned. The flag this PR just wired up is exactly what's needed to tell the two apart; it's a one-line change on the success branch.
  • The fix covers the file and shell tools, not every tool that refuses. Document indexing and a couple of other tools still hand back the same "Access denied: … is not in allowed paths" message without marking it as never-run, so those refusals keep getting stored as memories. Since that exact string is one of the two the PR description names as the problem, it's worth sweeping the remaining refusal points rather than leaving a second source feeding the same pile.

Real-world evidence

N/A — no evidence-bundle.md was produced for this run, and this change touches internal agent-memory bookkeeping rather than the CLI, REST, MCP, or Agent UI surfaces the evidence rules cover. pytest isn't installed in the review environment, so I could not re-run the suite; the verdict rests on static review plus the test runs reported in the PR description. The behaviour is observable only indirectly (what shows up under "Known errors to avoid" in a later session), so a follow-up sanity check on a real machine after a permission-refused call would be reassuring but isn't a merge blocker.

🔍 Technical details

🟡 A declined confirmation retires stored errors (src/gaia/agents/base/memory.py:2567)

Agent._execute_tool returns {"status": "denied"} when confirm_tool_execution is refused (agent.py:4163). That isn't status == "error", so is_error is False and the elif not is_error: branch runs _forget_errors_for_operation — deleting the remembered failures for an operation that never executed. Pre-existing (the old _forget_errors_for_tool did it tool-wide, so this PR actually shrinks the blast radius), but check_was_executed is already imported here and returns False for "denied" by design:

                elif not is_error and check_was_executed(result):
                    # It worked. Retire what this same operation was blamed for,
                    # so a fixed bug stops being replayed into every prompt.
                    self._forget_errors_for_operation(tool_name, tool_args)

Failure scenario: agent stores run_shell_command: rm: cannot remove 'x': No such file; user later declines a confirmation for a different rm; the stored lesson is deleted as if rm had just succeeded.

🟡 NOT_EXECUTED coverage stops at the file tools

Still returning bare refusal dicts, so _auto_store_error persists them:

  • src/gaia/agents/tools/rag_tools.py:1211 — index_document: "Access denied: {real_file_path} is not in allowed paths"
  • src/gaia/agents/tools/rag_tools.py:569 — query_specific_file auto-index guard, same string
  • src/gaia/agents/tools/file_monitor_tools.py:38 — "Access denied: {directory}"
  • src/gaia/agents/tools/filesystem_tools.py:114 — _validate_path raises ValueError(f"Access denied: {reason}"), which lands in the exception branch at memory.py:2540 where no result exists to carry the flag. That path may need its own guard (e.g. treat a PermissionError/validator exception as not-executed) rather than a NOT_EXECUTED spread.

Same one-line pattern as the diff for the first three:

                        return {
                            **NOT_EXECUTED,
                            "status": "error",
                            "error": f"Access denied: {real_file_path} is not in allowed paths",
                        }

browser_tools.py:263 returns a plain string, so it never reaches the error-store path at all — no change needed there.

🟢 Dedup can strand an error the narrowed retirement can no longer reach

MemoryStore.store merges >80% word-overlap rows in the same category+context and applies metadata = COALESCE(?, metadata), so the surviving row carries the newest operation key. When the error text doesn't name its target — read_file: UnicodeDecodeError: invalid start byte for /a.txt and /b.txt — both collapse into one row keyed to /b.txt, and a later successful read of /a.txt no longer retires it. Under the old tool-wide rule either success cleared it. Bounded and not worth blocking on, but it slightly reopens the staleness problem the previous fix closed; a note in the docstring, or matching legacy-style by prefix as a fallback when the operation key misses, would cover it.

🟢 Fallback operation key embeds the whole argument dict (memory.py:2677)

f"{tool_name} {json.dumps(args, sort_keys=True, default=str)}" is unbounded for any tool without a command/path-style key — a code or content argument goes into metadata.operation verbatim, and with it anything sensitive the caller passed. It also makes the key brittle for matching (one whitespace difference and the error is never retired). Truncating, or hashing the serialized args, keeps the identity without the payload:

        digest = hashlib.sha1(
            json.dumps(args, sort_keys=True, default=str).encode()
        ).hexdigest()[:12]
        return f"{tool_name} #{digest}"

(Note this changes the key shape asserted in TestOperationKey, so take it only if you like the trade.)

Strengths

  • The executed: False signal is reused rather than reinvented — the same flag the verification footer already relies on (verification.py:179), so refusals now read consistently as "never ran" in both the memory layer and the answer footer.
  • Two except Exception: pass blocks replaced with debug logging, in line with the fail-loudly rule, without changing control flow.
  • tests/unit/test_memory_error_refusals.py calls the real ShellToolsMixin._validate_shell_command and the registered write_file tool against a real PathValidator and a real MemoryStore, and asserts the file was not written — it verifies the refusal is genuine, not that a mock was called. _TOOL_REGISTRY is saved and restored around the registration, so it doesn't leak into other tests.
  • Backward compatibility for rows written before metadata.operation existed is handled explicitly and covered by a test.

Kalin Ovtcharov added 3 commits September 21, 2026 09:02
`env TOYBOX_CLOCK=frozen pytest -q` was keyed as `env`, so the call that fixed
a pytest failure never retired it. Leading `env` and `VAR=value` tokens are now
skipped, and `python -m <module>` is keyed by the module.
Declining a tool's confirmation prompt used to wipe the errors GAIA had
remembered for that operation, so a call the agent knew was broken came
back looking clean the next time it planned around it.

A denied confirmation returns {"status": "denied"}, not "error", so the
retire branch in MemoryMixin._execute_tool read it as proof the operation
works. It now gates on check_was_executed(), which is already how
_auto_store_error tells a refusal apart from a real failure.

Three permission refusals returned bare error dicts and so were persisted
into "Known errors to avoid" despite the tool never running: index_document,
its auto-index guard in query_specific_file, and add_watch_directory. They
now carry NOT_EXECUTED like the file and shell tools already do.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Both 🟡 findings are fixed. Declining a confirmation prompt was wiping the errors GAIA had remembered for that operation, so a call the agent knew was broken came back looking clean the next time it planned around it. Separately, three permission refusals in the RAG and file-monitor tools were being written into "Known errors to avoid" even though the tool never ran.

I did not touch filesystem_tools.py. The finding's mechanism doesn't hold there — the exception it describes never reaches the memory layer. There is a real but different issue at that spot, which needs its own change; reasoning below.

Both 🟢 findings skipped as scoped.

Tests: 22 pass in the refusal suite (3 new), 352 pass across the memory suites. Each new test was confirmed to fail with the fix reverted.

🔍 Technical details

Finding 1 — declined confirmation retires stored errors. Verified before relying on it: check_was_executed returns False for {"status": "denied"} — there is no executed key, so it falls through to the _DENIED_STATUS comparison. Gate applied at memory.py:2567 as suggested.

Finding 2 — NOT_EXECUTED coverage. Added at rag_tools.py index_document, the query_specific_file auto-index guard, and file_monitor_tools.py add_watch_directory. Both files import from gaia.agents.base.verification, the same module the file and shell tools already use.

filesystem_tools.py — left unchanged, deliberately. The finding states the ValueError(f"Access denied: {reason}") raised by _validate_path lands in the exception branch at memory.py:2540. It does not. Every call site sits inside a tool body that ends with except ValueError as e: return str(e) — browse_directory, tree, file_info, read_file, bookmark, plus the inline per-entry filter. The exception never escapes the tool, so _auto_store_error is never reached and the refusal is never stored.

The real issue there is the one the review scoped out for browser_tools.py:263: a plain-string return makes is_error False, so the refusal reaches the retire branch, and check_was_executed returns True for a non-dict. Fixing it means changing six tools' return contract from str to dict — larger than this PR, and it can't be done by sniffing the refusal out of the string's text, which is precisely what check_was_executed's own docstring argues against. Worth a separate issue.

🟢 skipped: dedup stranding, and hashing the fallback operation key — the latter breaks TestOperationKey's assertions, as flagged.

Docs synced. docs/guides/memory.mdx and docs/sdk/sdks/memory.mdx both said "a success clears errors stored for the same operation"; both now state that a refusal clears nothing and only a call that ran and succeeded does.

Tests added to tests/unit/test_memory_error_refusals.py, matching the file's real-objects style — a real Agent + MemoryMixin with a real MemoryStore and a console that declines, and the real PathValidator (no TTY under pytest, so it auto-denies without mocking).

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 22, 2026
Merged via the queue into amd:main with commit 741c16f Sep 22, 2026
44 checks passed
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 28, 2026
…amd#4066)

**Stacked on amd#4058.** The first four commits are that PR. Review the
last two here.

The agent rediscovered the same project quirk every session. When a call
failed and the agent worked around it (say `pytest` fails with "test
clock not configured", it reads the doc, reruns with `env
TOYBOX_CLOCK=frozen` and it passes), memory stored the error and then
deleted it on the success. Nothing recorded what fixed it, so the next
session started from scratch.

Now that fail-then-fix sequence in one turn becomes a lesson, built only
from the two calls: the failing call and its error, the call that
worked, and what changed ("added `env TOYBOX_CLOCK=frozen`"). It belongs
to the workspace it happened in, and the next session there sees it in
its memory prompt with the date learned. It gains confidence each
session the fix works again and is dropped when the fix itself fails.
Other folders never see it.

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

- The pairing key is amd#4058's operation key: the tool plus the program it
runs (past `env`, `VAR=value` and `python -m`) or the path. The failing
and working calls must have different arguments, so a plain retry that
happens to pass teaches nothing. Refusals (`executed: False`) never
count, either as the failure or as a failed fix. There's no matching on
error wording.
- Scope: stored as `category="note"`, `domain="lesson"`, in the memory
context `workspace:<most specific allowed path>`. That context keeps
lessons out of every other workspace's prompt and retrieval, including
amd#4061's per-request recall. So lessons are shown in their own
stable-prompt section (top 3 by confidence), not through relevance
search, which would also hide them whenever the request is worded
differently from the lesson.
- Within a session, later turns get the new lessons in the per-turn
context, since the stable prompt is frozen. Within a turn there was a
real loss path: overflow recovery stubs every tool result except the
latest, which drops the failure a fix answered. The recovery now
restates this turn's lessons on the last user message. The cache is
already lost at that moment, so this costs nothing extra.
- A lesson whose text looks like a credential isn't stored.
</details>

## Test plan
- [x] `pytest tests/unit/test_memory_heal_lessons.py`: 14 tests on a
real on-disk store, over several sessions sharing one DB. All 7 positive
tests fail on the pre-change source. Covers the exact lesson text and
row shape, no lesson for a same-call retry / a refused failure / a
different program / a failure and fix in different turns, a path tool's
changed argument, the next session's prompt in the same workspace but
not another, the rest of the session, confirm once per session (0.5 →
0.6), drop when the fix fails, keep when the fix is refused, and
overflow recovery keeping the lesson (idempotent)
- [x] `pytest tests/unit -k "memory or overflow or shrink"`: 1155
passed. The 1 failure, `test_tool_loader_token_budget`, also fails on
main
- [x] black + isort on changed files
- [ ] `gaia eval agent` on the memory categories vs the committed
baseline (memory prompt content changed)

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: 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 documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants