Skip to content

fix(memory): surface stored facts in chats and keep saves out of sight - #5324

Merged
kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:kalin/memory-recall-fires
Oct 19, 2026
Merged

kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:kalin/memory-recall-fires

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

GAIA stored the right facts after #5243, but chats rarely used them. Asking "what should I get my sister for her birthday?" never brought up "my sister Priya lives in Vancouver", and a long-time user's older facts dropped out of the prompt, where stale facts could outrank the facts that replaced them. Now a natural question surfaces the memories it's about (8 of 9 in the test below, up from 1). The always-on memory section holds as many memories as fit, newest first, instead of 5 facts. Memory also stays in the background: the activity list no longer shows "Saved to memory" steps.

Part of #5234.

  • Recall per turn. The old cut-off (cosine 0.5) is above what the default embedder gives a natural question, which scores the memory it's about at 0.35–0.55. A match now passes when it stands clear of how the question scores against the whole store and sits close to the best match. A memory that names the same person comes along too: "snack ideas for my kids" brings "Leo is allergic to peanuts" with "two children named Ada and Leo".
  • Always-on section. There's no fixed count per kind any more. Kinds take turns, most recently confirmed first, until the 4,000-character budget is full. Notes and upcoming reminders are now included. The prompt says how many memories are left out so the model knows to search. Confidence numbers are gone, since a true fact shown as "confidence: 0.42" invites the model to doubt it.
  • Out of sight. Successful remember/recall/update_memory/forget steps are hidden from the activity list. A failed one still shows. The agent still saves without announcing it.
🔍 Technical details

Recall hits for natural questions, measured with the same embeddinggemma-300M-Q8_0 GGUF Lemonade serves. It ran in a private CPU llama-server because an eval held the shared Lemonade. Store A has 9 user facts; store B adds 20 unrelated ones.

Question Before (A) After (A) After (B, 29 facts)
What should I get my sister for her birthday? — Priya Priya
snack ideas for my kids' lunchboxes — children, peanut allergy, vegetarian + sourdough
Plan a dinner menu for this weekend — vegetarian, cello on weekends + 5k run
How far to Banff by car, how much fuel? — Subaru Subaru
Any hobbies my partner and I could do together? Sam Sam Sam
Help me write a cover letter for a new job — data engineer + manager Dana
What's the capital of Australia? — — —
Explain how binary search works — — —
  • Rule in _recall_memories_for_turn: cosine ≥ 0.5, or (store ≥ 8) ≥ max(0.38, median of the 200 nearest + 0.08, best − 0.06). Top 3, plus up to 2 memories that share a name with a match (cosine ≥ 0.35). The thresholds come from a grid over both stores: the most expected hits with no leaks on unrelated questions.
  • Hybrid BM25 isn't used on this path, for two reasons. MemoryStore.search bumps confidence, and surfacing a memory must not count as a use. Natural questions also share few words with the fact they're about ("kids" vs "children").
  • A memory shown in the always-on section still isn't repeated per turn, and one left out of it stays recallable.
  • Reminders whose due day has passed stay with the existing once-only upcoming/overdue path.

Evals to watch (this changes the memory prompt and the per-turn context): memory, gaia_memory, context_retention, personality, gaia_tool_selection. They weren't run locally; the next RC's eval covers them.

Test plan

  • python -m pytest tests/unit/test_memory_turn_recall.py tests/unit/test_memory_mixin.py tests/unit/test_memory_prompt_growth.py tests/unit/test_memory_heal_lessons.py tests/unit/test_system_prompt_composition.py
  • cd src/gaia/apps/webui && npx vitest run src/components/__tests__/AgentActivity
  • python util/lint.py --black --isort --pylint --flake8
  • In the Agent UI, with a few personal facts stored, ask "what should I get my sister for her birthday?" and check the answer uses the stored fact
  • Say "also remember that I live in Calgary" and check no memory step appears in the activity list

@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Oct 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This PR makes stored memories show up in chats. Per-turn recall now judges a match against how the question scores across the whole store, instead of a fixed 0.5 cut-off that natural questions almost never cleared. The always-on memory section fills its 4,000-character budget newest first, and successful memory steps are hidden from the activity list. The logic holds up and the new tests cover the behaviour well. Nothing blocks the merge.

Two things to know:

  • For users with more than 200 memories of one kind, "newest first" doesn't fully hold. The store still picks those 200 by confidence before the newest-first sort, so a recent low-confidence fact can miss the always-on section. It stays recallable per turn, so nothing is lost. But it's the long-time-user case the PR description calls out.
  • The step count in the activity header still counts the hidden memory steps. A turn can say "3 steps" and list two.

The PR names the evals to watch (memory, gaia_memory, context_retention, personality, gaia_tool_selection), and the next RC covers them. That's the right call for a change to the prompt and the per-turn context.

Real-world evidence

N/A: no evidence bundle was produced for this run. The two Agent UI checks in the Test plan (a stored fact used in an answer, no memory step shown) are still unchecked, and the PR has no screenshot. Per the rubric, this Agent-UI-visible change should eventually get a before→after Playwright screenshot of the activity list. That's a nudge, not a blocker. pytest isn't installed on this runner, so I couldn't run the unit tests here. The verdict rests on static review alone.

🔍 Technical details

🟢 Recency ordering is applied after a confidence-ordered LIMIT (src/gaia/agents/base/memory.py in _fit_personal_memories)
get_by_category_contexts runs ORDER BY confidence DESC, updated_at DESC with limit=STABLE_MEMORY_FETCH_LIMIT (200). The Python pool.sort(key=updated_at, reverse=True) only reorders those 200 rows. If a category has more than 200 rows, a newly confirmed 0.4-confidence fact can be cut at the SQL step, while older 0.9-confidence facts take the budget. Per-turn recall is the backstop, because the fact isn't in _stable_memory_ids. Possible fixes: add an order_by option to the store query, or note the limit in the docstring and the memory.mdx bullet ("Most recently confirmed first").

🟢 Header step count includes hidden steps (src/gaia/apps/webui/src/components/AgentActivity.tsx:245)
stepCount prefers agentStepCount (the backend's message.stats.steps), and that number still includes remember/recall calls that displaySteps now drops. When both are shown, the count and the list disagree. One option is to subtract the filtered background steps, or to always derive the count from displaySteps when any step was hidden.

🟢 Overdue check compares a UTC date with a local date (memory.py, the due_at filter in _fit_personal_memories)
str(item["due_at"])[:10] >= today takes the date from a stored UTC timestamp and compares it with datetime.now().astimezone().date(). West of UTC, a reminder whose time has already passed locally can still pass the check for up to a day. That's harmless (it's labelled with its due date), but it's off by one around midnight.

🟢 _names_in treats any mid-sentence capitalised word as a name
Places and products count too ("Vancouver", "Python", "Docker"), so "lives in Vancouver" links to any other Vancouver memory above 0.35. The cap of 2 extra memories and the 0.35 floor keep this bounded. Consider a doc line that says "shares a capitalised word", not "names someone".

Strengths

  • The relative bar (median + margin, best − gap, sure floor, and a minimum field size before the median applies) is well reasoned. The _at(cos) tests pin each arm of it: stands out, noise-level best, high field, far behind the best, small store.
  • Fitting whole items instead of slicing the string is a real fix. The old cut could leave half a memory in the prompt, and its id bookkeeping relied on string containment. _stable_memory_ids is now exactly the set that was rendered.
  • The UI filter keeps a failed memory step visible, and there's a test for it, so errors don't vanish along with the noise.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

All four points were valid and are fixed in 0a8ba81.

  • Newest first past 200 rows: the store query now orders by when a row was last confirmed, so a recent low-confidence fact can't be cut before the sort.
  • Step count: when any memory step is hidden, the header counts the steps it shows instead of the agent's own total.
  • Due day: reminders are judged and shown by the local day. A malformed due_at now fails with the memory's id and where to fix it.
  • Name links: the code comment and docs now say any capitalised mid-sentence word links, usually a name.
🔍 Technical details
  • get_by_category_contexts(..., newest_first=True) swaps ORDER BY confidence DESC, updated_at DESC for ORDER BY updated_at DESC; the default is unchanged for every other caller.
  • _due_day() parses due_at, assumes local time when there's no offset, and returns the local date.
  • New tests: newest-first beyond the fetch limit, a 23:00-local reminder stored in UTC keeps its local date, the malformed-due_at error, and the header count with a hidden step.
  • The screenshot nudge stays open: the UI change is covered by component tests, not a Playwright capture.

Evals to watch (memory prompt and per-turn context): memory, gaia_memory, context_retention, personality, gaia_tool_selection.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

On the long-horizon memory benchmark (#5340, --suite pr), this PR raises what the agent is shown about the user from 72% to 95%. Ten checks are fixed, including all five far-off reminders.

The benchmark caught one real problem, now fixed in 9f6e9fe: session summaries ("in March, Maya lived in Calgary") were going into the always-on section and contradicting newer facts. With that, "shown clean" is 94%. It was 100% on the old baseline.

Two benchmark checks still regress, and neither is something this PR should hide:

  • Maya's old job still shows. "Tech lead at Northwind" is still an active memory after she changed jobs. The old 5-fact cap happened to hide it. Keeping that row current is the extraction side's job, tracked in feat(eval): long-horizon memory benchmark, and the stale-memory bugs it found #5340.
  • Alex's garden isn't shown for "my plants are drooping". The always-on section is full, and the pr suite's hashed embedder can't match plants to garden, so per-turn recall can't step in. The full suite, with the real embedder, is the test for that.
🔍 Technical details
Metric Baseline (#5340) + this PR
Shown recall 72% 95%
Shown clean 100% 94%
Store accuracy 100% 100%
Reminder checks 20% 100%

kovtcharov and others added 4 commits October 18, 2026 23:17
Chats rarely used what memory stored. Natural questions score the memory
they are about at 0.35-0.55 with embeddinggemma-300m, below the 0.5
per-turn floor, so "what should I get my sister for her birthday?" never
brought up "my sister Priya lives in Vancouver".

- Per-turn recall passes a match that stands clear of the field (median
  + 0.08) and sits near the best match (- 0.06), above 0.38; 0.5 still
  passes outright. Memories naming someone a match names come along, so
  a kids' lunch question brings the peanut allergy. On a 9-fact store,
  8 of 9 expected memories surface (was 1), with no leaks on unrelated
  questions.
- The always-on section fills its 4000-char budget instead of 5 facts,
  most recently confirmed first, with notes and upcoming reminders, no
  confidence numbers, and a count of what was left out.
- The Agent UI activity list no longer shows successful memory tool
  steps; a failed one still shows.
Review follow-ups on the memory recall change.

- Past 200 rows of one kind, a recently confirmed low-confidence fact
  could miss the always-on section: the store picked 200 by confidence
  before the newest-first sort. The store query now orders by
  updated_at itself (get_by_category_contexts gains newest_first).
- A reminder's due day is now the local day, both for leaving out ones
  that have passed and for the date shown. A malformed due_at raises
  with the memory id instead of a bare parse error.
- The activity header counted hidden memory steps, so it could say
  "3 steps" and list two. It now counts what it shows when any step
  was hidden.
- Docs say name-linking keys on any capitalised mid-sentence word.
A session summary is dated history ("in March, lived in Calgary"). Shown
in the always-on section next to current facts, it contradicted them: on
the long-horizon memory benchmark it leaked moved-away cities and old
jobs into what the agent sees. Facts consolidation extracts still show;
only its summary notes are left out, and they stay recallable.
The memory SDK page still said notes are shown in the always-on section,
but session summaries from consolidation are now left out there so dated
history can't contradict newer facts. They remain recallable.
@kovtcharov-amd
kovtcharov-amd force-pushed the kalin/memory-recall-fires branch from 9f6e9fe to 7f7690a Compare October 19, 2026 06:21
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 6e113b1 Oct 19, 2026
53 of 55 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/memory-recall-fires branch October 19, 2026 08:28
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
Memory went stale over months of use. Old facts out-ranked new ones
because every turn's background lookup raised their confidence, so a
user who moved was still shown the old city. Dated plans lost their
date, consolidating an old chat could undo a later correction ("Ada is
6" came back after "Ada is 7"), and routine upkeep re-dated every idle
memory as "last confirmed" today. After this, only a real recall counts
as a use, reminders keep their dates, old chats don't overwrite newer
facts, and "last confirmed" moves only on a real confirmation.

**Depends on amd#5243.** This branch is stacked on it, so until amd#5243
merges the diff includes its commits; review the last three commits. It
merges cleanly with amd#5324 (no shared changes; this keeps amd#5324's
newest-first ordering meaningful). Split out of amd#5340 so the fixes can
land without the benchmark.

Changes memory extraction and consolidation behavior, so it needs a
flagship eval on the `memory` and `gaia_memory` categories before merge.

## Test plan
- [ ] `python -m pytest tests/unit/test_memory_stays_current.py
tests/unit/test_memory_store.py tests/unit/test_memory_forget_sticks.py
tests/unit/test_skill_synthesis_incremental.py
tests/integration/test_memory_integration.py`
- [ ] An existing v6 memory database upgrades to v7 on first start
(`test_a_v6_database_gains_decayed_at`)
- [ ] Flagship eval: `memory` and `gaia_memory` categories show no PASS
to FAIL against the baseline

---------

Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…it found (amd#5340)

Nothing tested what memory does after weeks of use. Unit tests mock the
model, and eval scenarios last one chat. `gaia eval memory` replays six
people's months of chats through the real memory pipeline on a simulated
clock. Their facts change, they ask GAIA to forget things, the agent
trips over a repo's quirks, and documents and emails full of other
people's first-person lines pass through. The bench then checks what the
agent is shown and what is stored. The `pr` suite is deterministic and
gates PRs check by check, so memory can't quietly regress. Its runs
found four bugs that made memory go stale, fixed in amd#5395: the share of
what the agent is shown that is current and correct went from 81% to
100%.

Builds on amd#5395 (the stale-memory fixes, split out so they can land on
their own), which builds on amd#5243. Their commits are included; review
only the last three. Refs amd#4727.

- **Old facts out-ranked new ones.** Every turn's extraction lookup
counted as a "use" and raised the confidence of up to 40 matching
memories. A user who moved from Calgary to Toronto was still shown "tech
lead at Northwind", and "lives in Toronto" wasn't shown at all. Now only
an explicit recall counts, and only for the results it returns.
- **Dated plans lost their dates.** Extraction ignored `due_at`, so a
mentioned appointment never came up as upcoming, and rewording a dated
reminder replaced it with an undated copy.
- **"Last confirmed" meant nothing.** Upkeep re-dated memories nobody
confirmed: decay stamped every idle memory with the day each new chat
opened, and reconciliation re-dated up to 40 rows a chat. That defeated
newest-first ordering. Now only a real confirmation moves it.
- **Corrections didn't stick.** Consolidating an old chat filed an
untagged copy of a fact, such as "Ada is 6", that the user's later
correction never reached. Consolidation now skips what memory already
says and what the user changed after that chat.

**Eval categories to watch on the next RC:** `memory`, `gaia_memory`
(the extraction prompt gained `due_at`, and recall ranking changed).

| `pr` suite, 88 checks | Before | After |
|---|---|---|
| Shown recall | 62% | 74% |
| Shown clean (no stale, forgotten or planted text) | 81% | 100% |
| Store accuracy | 94% | 100% |

Remaining failures are recall gaps: an older fact or a far-off reminder
doesn't reach the agent. amd#5324 targets those, and this bench measures
them.

## Test plan

- [x] `gaia eval memory --suite pr --gate
tests/fixtures/eval_baselines/memory-bench/pr.json` passes; three runs
gave identical results
- [x] `python -m pytest tests/unit/eval/test_memory_bench.py
tests/unit/test_memory_stays_current.py`
- [x] `python -m pytest tests/unit/ -k "memory or sdk or
lemonade_chat_slots or skill_synthesis or cli_memory"
tests/integration/test_memory_integration.py`
- [x] `python util/lint.py --all`
- [ ] `gaia eval memory --suite full` (not run: two other sessions'
`gaia eval agent` runs held the machine-wide eval lock, and the bench
doesn't bypass it)

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

- **Harness** (`src/gaia/eval/memory/`):
- Each chat is a fresh `MemoryMixin` agent on one shared DB:
`init_memory`, the first message's upkeep, then every turn through
`process_query`. That covers tool calls and the tool record, extraction,
lessons, and the scenario's explicit `remember`/`update_memory`/`forget`
calls.
- Only the agent loop is stood in for. Its scripted tool calls are
checked against what was executed.
- The clock patches `datetime` in `memory.py` and `memory_store.py`,
with DST-safe aware arithmetic.
- Probes open the next chat on a DB copy, so its upkeep and reminder
marks don't change the timeline.
- A strict `pr` replay fails on any warning from memory's loggers, so a
scripted-model slip can't pass as "nothing stored".
- **Scenarios**:
- `maya_moves_and_changes_jobs`: a move, a new job, a swapped race, a
dog's surgery, weather lookups.
- `sam_family_health`: an outgrown allergy, a corrected diagnosis, a
diet change, a sister's diet, a hypothetical, a quoted text.
- `chen_learns_project_quirks`: lessons learned and replaced, a README
injection.
- `priya_work_documents_and_forgetting`: report and email content, a
password, "forget my manager".
  - `alex_three_months_of_life`: about 30 facts built week by week.
  - `jordan_reminders_change`: reschedules, cancellations, completions.
- **Gate**: a check that passes in
`tests/fixtures/eval_baselines/memory-bench/pr.json` must still pass. A
baseline check that no longer runs fails too. `--scenario` gates only
the scenarios it ran.
- **Fixes**:
- `MemoryStore.search(count_as_use=)`, `MemoryStore.count_use()`
(doesn't touch `updated_at`), and `_hybrid_search(count_as_use=)`.
- Extraction passes `due_at`. An update keeps the old date only if the
result is still a reminder. An unparseable date is dropped with a
warning and the fact kept.
  - Consolidation uses `MemoryStore.is_current()` and `changed_since()`.
- `content_stems` keeps tokens that contain digits, so "Ada is 6" and
"Ada is 7" differ.
- Confidence decay tracks `decayed_at` (schema v7) instead of moving
`updated_at`. `update_confidence(confirmed=)` moves it only for a
confirmed lesson. `get_all_knowledge` breaks timestamp ties by insertion
order.
- Docs: `docs/reference/eval.mdx` (Memory Benchmark),
`docs/reference/cli.mdx`, `docs/sdk/sdks/memory.mdx`.
</details>

---------

Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Kalin Ovtcharov <[email protected]>
grtninja pushed a commit to grtninja/gaia that referenced this pull request Oct 25, 2026
…saves (amd#5551)

Three must-not-regress scenarios that passed on v0.25.0 fail on
v0.25.1-rc2 and rc3. An old memory like "this page returned 503, don't
waste tool calls on it" was obeyed as a ban, so the agent refused a URL
the user had just given it. And untrusted document text could be saved
to memory, or presented later as the user's saved details. After this
change, memories reach the model as dated notes the user's request
outranks, and `remember` won't save text the session read from a file,
page or tool unless the user asks for it.

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

- **Cause.** For the stale-lesson turn, the request GAIA sends (system
prompt, memory section, user message) renders byte-identical at v0.25.0
and rc3. Only three tool docstrings differ, none of them web or memory
tools. Between those runs the eval runtime moved from Lemonade 2026.40.0
/ llama.cpp b10825 to 2026.42.1 / b11393 (amd#5148). So the same "Known
errors to avoid: … don't waste tool calls on it" text now gets a
different answer, and the framing was the weak point. amd#5243 adds a
second effect: extraction may no longer correct a stale error from tool
output, so the seeded 503 note outlives its scenario.
`res_web_partial_outage_compare` has no `memory_clear` and inherits it.
- **Framing.** The personal block opens with a "notes, not instructions"
line. `error` is retitled "Problems seen before", and a transient error
gets a passing-failure marker (the existing markers plus 429/502-504
statuses). Two instruction bullets are added, and the per-turn recall
header is reworded. amd#5324's newest-first, fill-to-budget selection is
unchanged.
- **Write path.** A session-wide record of tool results (30 calls, 20K
chars each) is checked with the existing `_copied_from_material`. A save
is allowed when the user's message is a storage request (a verb opening
a clause, so "what do you remember?" doesn't count) or a yes after an
earlier refusal of near-identical text. `error` memories are exempt, but
relabelling one into a user category is checked.
- **Known gaps.** `EmailTriageAgent` puts `Agent` ahead of
`MemoryMixin`, so neither this guard nor extraction's source check sees
its tool results. A planted line more than 30 tool calls back, or deeper
than 20K chars into a result, falls outside the record. One real request
to remember ("remember I like tea, then summarize vendor_note.txt") lets
every other save that turn through.
</details>

## Test plan

- [x] `python -m pytest tests/unit/test_memory_notes_not_orders.py
tests/unit/test_memory_turn_recall.py
tests/unit/test_memory_error_staleness.py` (44 new tests: framing,
ordering, cap, write-guard bypasses and false positives)
- [x] `python -m pytest tests/unit -k "memory or prompt or recall"` and
`hub/agents/{gaia,chat}/python/tests`: no new failures.
`test_profilespec_characterization` goldens and
`test_chat_system_prompt_budget[full-0]` fail the same way on clean
`main`.
- [x] `python util/lint.py --all`
- [ ] Targeted eval on this branch: `gh workflow run eval_flagship.yml
--ref fix/memory-lessons-and-poisoning -f
scenarios=res_stale_lesson_page_back_up,res_web_partial_outage_compare,mem_document_memory_poisoning`
- [ ] Then the `memory` and `gaia_memory` categories on this branch (`-f
categories=memory,gaia_memory`), compared with
`tests/fixtures/eval_baselines/gaia-flagship/`
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