Skip to content

fix(email): find mail the user describes in their own words - #4148

Merged
itomek merged 1 commit into
mainfrom
issue-4134
Sep 23, 2026
Merged

itomek merged 1 commit into
mainfrom
issue-4134

Conversation

@itomek

@itomek itomek commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Before: describing a half-remembered email in your own words reported it missing — the flagship turned the sentence into six-to-eleven keywords, Gmail and Graph ANDed every one of them, and the zero result ended the turn as a confident "nothing matches" even though two words from the message found it instantly. After: it finds it. search_email now tells the model that a longer query is a narrower one, and broadens on its own when a query returns nothing, reporting which query the hits actually came from so an approximate match is never described as an exact one.

Closes #4134

Evidence

Same paraphrased question, same mocked mailbox holding one message ("The argument over Flock cameras"), driven through the real search_email tool entry point.

Before (main @ c3f949f3) — one search, zero hits, turn over:

GET /me/messages?$search="the argument over cameras police departments use" -> 0 hit(s)
{ "success": true, "count": 0, "order": "relevance", "messages": [] }

After — broadens until it hits, and says so:

GET /me/messages?$search="the argument over cameras police departments use" -> 0 hit(s)
GET /me/messages?$search="argument cameras police departments use"          -> 0 hit(s)
GET /me/messages?$search="argument departments"                             -> 0 hit(s)
GET /me/messages?$search="departments"                                      -> 0 hit(s)
GET /me/messages?$search="argument"                                         -> 1 hit(s)
{
  "success": true,
  "count": 1,
  "query_requested": "the argument over cameras police departments use",
  "query_used": "argument",
  "broadened": true,
  "attempts": [ ...each query with its count... ],
  "messages": [ { "subject": "The argument over Flock cameras", ... } ],
  "note": "'the argument over cameras police departments use' matched nothing; these results come from 'argument'. Say the match is approximate, and check each hit is the message the user meant."
}

Test plan

🔍 Technical details

The broadening ladder (_broadening_ladder in src/gaia/agents/tools/email_tools.py) is deterministic and bounded, never a silent fallback:

  1. the query as sent
  2. minus boolean operators (OR/AND/NOT) and stopwords
  3. the two longest remaining terms
  4. the three longest terms, one at a time

It stops at the first rung that returns results — at most six provider searches on a genuine miss, and exactly one when the query already hits. Longest-term is a proxy for distinctive; the single-term rungs are what actually recover a message whose own wording the user never used, which the two-term rung alone did not (measured while building the evidence above).

Nothing is hidden from the model: every attempt and its count is in the result, broadened is explicit, and a zero result names the broadest query tried rather than implying the mailbox is empty. An empty/whitespace query still fails loudly through the backend's existing validation instead of returning an empty list.

Scope: src/gaia/agents/tools/email_tools.py and its tests only — _email/gmail.py is untouched (owned by #4110 in the same wave).

@itomek
itomek marked this pull request as ready for review September 23, 2026 14:54
@github-actions github-actions Bot added tests Test changes agents labels Sep 23, 2026
@itomek
itomek changed the base branch from main to issue-4110 September 23, 2026 15:06
@itomek

itomek commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator Author

Retargeted this onto issue-4110 so the diff shows only its own change. Merge #4147 first — GitHub will then retarget this to main automatically.

🔍 Technical details

issue-4134 was branched while the working tree was on issue-4110, so it carries 20b49200 (#4110's Gmail error-envelope fix) underneath its own 04153d5d. Against main the diff showed four files; against issue-4110 it shows the two that belong to this change.

No history was rewritten — only the PR's base. Once #4147 merges, 20b49200 is in main and this reduces to a single commit with no further action.

@itomek
itomek marked this pull request as draft September 23, 2026 15:08
Base automatically changed from issue-4110 to main September 23, 2026 15:10
Describing a half-remembered email in your own words reported it missing.
The model turns a sentence into six-to-eleven keywords, both providers AND
every term, and the zero result ended the turn as "nothing matches" — while
two words from the message find it instantly.

Nothing told the model that a longer query is a narrower one, and a zero
result had no recovery path. `search_email` now says so in its docstring and
broadens on its own: drop boolean operators and stopwords, keep the two
longest terms, then try the longest terms one at a time, stopping at the
first rung that hits. Bounded to six searches.

Every broadened rung keeps at least one content term. A bare mailbox
operator is long, so length-ranking would otherwise make `is:unread` a rung
of its own — and an unread pile is never empty, so the ladder would stop
there and hand back 25 unrelated messages labelled as a match. That is the
same confident wrong answer this change exists to remove.

The broadening is reported, never hidden: the result carries every `attempt`
with its count, the `query_used` the hits actually came from, and
`broadened: true` so the model describes a looser match as one. It compares
terms, not the raw string, so the trailing space a small model emits does
not report an exact first-try hit as approximate. A genuine miss still
returns zero, with the broadest query it tried named in the note.

Closes #4134
@itomek
itomek marked this pull request as ready for review September 23, 2026 15:52
@itomek itomek added the ready_for_ci Run CI workflows on draft PR without requesting review label Sep 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

When someone describes a half-remembered email in their own words, mail search used to come back empty because every word gets ANDed together. This PR teaches the search tool to retry with progressively fewer, more distinctive words, and to say out loud which query the results actually came from — so an approximate match never gets presented as an exact one. It's a clear improvement, well bounded (at most six searches), and the tests and live evidence back it up.

One thing worth fixing, ideally before merge:

Broadening quietly throws away the user's filters. If the model searches for "unread mail from Dana about the invoice" and that finds nothing, the fallback search drops "unread" and "from Dana" and returns anyone's invoices — including ones the user explicitly excluded with a minus sign. The results are labelled approximate, so it isn't a silent wrong answer, but the model is never told that a constraint disappeared, only that the wording was loosened. Either keep those filters on the retries, or name the dropped ones in the message handed back to the model. This isn't a regression — today that search returns nothing at all — but it's the same confident-wrong-answer shape the PR exists to close.

Smaller items (an unbalanced quote switching the feature off entirely, and words containing a colon being mistaken for filters) are in the details below.

Real-world evidence

Strong, and it supports the verdict. evidence-bundle.md drove the changed tool through the flagship agent's real dispatch against a local HTTP mailbox speaking the Microsoft Graph contract with the same AND semantics — real sockets, real backend, no credentials. A paraphrase nobody in the mailbox used now finds the message:

1. $search='the argument over the surveillance cameras police departments use'  -> 0
2. $search='argument surveillance cameras police departments use'               -> 0
3. $search='surveillance departments'                                           -> 0
4. $search='surveillance'                                                       -> 1

A message that genuinely isn't there still reports zero after exactly six searches, with an instruction not to keep searching. A two-word query that hits costs one round trip and no hedging. A mid-ladder 401 surfaces the auth error instead of reading as "no such mail". Sibling tools (list_inbox, read_email, check_mailbox_access) were spot-checked on the same mailbox and are unchanged.

Gaps the bundle itself declares, and I'm taking at face value rather than treating as proven: the Agent UI screenshot is pending the strix-halo lane; no model actually drove a turn (no Lemonade on this runner), so nothing here shows a small model obeying the new docstring or repeating the hedge to the user; and only the Outlook backend was exercised — the Gmail path shares the ladder but its own query serialisation wasn't driven. Timing is loopback-only (2–6 ms), so it measures the ladder's overhead, not what six real provider round trips cost.

🔍 Technical details

🟡 Important

Broadened rungs drop search operators and negations without telling the model (src/gaia/agents/tools/email_tools.py:140)

_is_search_operator filters field:value terms and -negations out of content, so every rung after the first is content-only. Verified against the merged code:

'is:unread from:dana invoice'          -> ['is:unread from:dana invoice', 'invoice']
'-promo -newsletter receipt from Acme' -> [..., 'receipt Acme', 'receipt', 'Acme']
'newer_than:7d contract signature'     -> [..., 'contract signature', 'signature', 'contract']

Rung 2 of the first example returns every invoice in the mailbox from every sender, read or unread. The payload sets broadened: true and the note says "the match is approximate, check each hit" — which describes looser wording, not a dropped constraint. -promo is the sharpest case: the model explicitly excluded something and the retry brings it back.

The docstring's stated invariant ("every broadened rung is built from content terms only") is motivated by avoiding an operator-only rung — but keeping operators alongside content satisfies that too, and test_no_broadened_rung_is_a_bare_mailbox_filter would still pass. Two options:

  1. Preserve operator terms on every rung, shrinking only the content terms. Loses the case where the from: filter is itself what's wrong.
  2. Keep the current ladder but add the dropped terms to the payload ("filters_dropped": ["is:unread", "from:dana"]) and name them in the note.

Option 2 is the smaller change and keeps the "nothing is hidden from the model" property the PR description claims. Either way this deserves a test asserting the model is told which constraints were released.

🟢 Minor

An unbalanced quote disables broadening entirely (email_tools.py:82)

_search_terms toggles on ", so an odd number of quotes swallows the rest of the query into one term:

'"Fieldstone MSA needs a sig' -> ['"Fieldstone MSA needs a sig']    # one rung, no broadening

The feature's own premise is that small models emit sloppy queries (the test suite says as much about stray whitespace), and an unmatched quote is the same class of slip — except here it silently turns the whole ladder off. One-line guard:

def _search_terms(query: str) -> List[str]:
    """Split a search query into terms, keeping "quoted phrases" whole."""
    if query.count('"') % 2:  # an unmatched quote would swallow the rest of the query
        query = query.replace('"', " ")
    terms: List[str] = []

Any colon makes a term look like a filter (email_tools.py:111)

field.isidentifier() is true for plenty of non-operators, so real content gets dropped from the broadened rungs:

'Q3:budget forecast'    -> ['Q3:budget forecast', 'forecast']     # 'Q3:budget' dropped
'http://x.com invoice'  -> ['http://x.com invoice', 'invoice']    # URL dropped

Low impact — these are unusual query terms, and the first rung still runs them verbatim — but matching against the known operator names both providers accept (is, from, to, subject, label, newer_than, …) would be both narrower and more honest than "anything shaped like an identifier".

Six sequential provider searches on a miss, with no latency evidence

Worst case is 6 round trips to Gmail/Graph per search_email call. The bundle measures 5.6 ms, but that's a loopback server — a real provider at 200–800 ms/search makes a genuine miss a multi-second tool call, and multiplies search quota consumption 6× for exactly the queries that find nothing. Not blocking, and the bound is the right design; worth confirming on the strix-halo lane before assuming the worst case is comfortable.

Strengths

  • The broadening is reported, not hidden. query_requested, query_used, broadened, and the full attempts list mean the model can always reconstruct what actually ran — this is an explicit, bounded, deterministic behaviour rather than the kind of silent fallback CLAUDE.md prohibits.
  • The test suite tests the failure modes, not just the happy path. test_absent_message_still_reports_zero_after_broadening (broadening must not invent a hit), test_mid_ladder_backend_failure_is_reported_not_swallowed (a 401 on rung 2 must not read as "no such mail"), and test_limit_is_clamped_on_every_broadened_rung all target ways this feature could go wrong rather than ways it goes right.
  • broadened compares terms, not raw strings. Treating " Acme invoice " as an exact hit is a small detail that avoids teaching the model to hedge about a first-try match — and it has its own test.
  • Scope is tight: one module plus its tests, no provider backends touched.

@itomek

itomek commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator Author

Live Gmail re-verification — 2 of 3 pass, the third still misses

Ran the three recollection questions from #4134 against a real Gmail mailbox (1,137 messages) on an Acer Swift with the flagship loaded from source, at this PR's head 572e8b79.

The two camera questions now work. Both find the right thread on the model's first try — the docstring change did its job: the model sends cameras police and Flock cameras newsletter instead of the eleven-term sentence that returned nothing on main.

The contract question still does not find the message it is describing. Two independent runs, neither returned Re: Fieldstone MSA — counter-signature needed before Friday. The message is definitely there — searching counter-signature returns it instantly. The reason is a gap this fix cannot reach: broadening only fires when a search returns zero, and here the model's query returns two or three wrong messages, so the ladder never runs. That non-empty-but-wrong result is the exact symptom #4134 recorded for this question on main, and it is unchanged.

The agent's answer is at least honest about it now — it says it found no exact match and asks for the sender or project, rather than presenting the wrong mail as the answer. That is an improvement, but it is not the issue's acceptance bar ("describe it in your own words, using no word that appears in its subject — it should find it").

Both regressions the reviewers asked about are refuted on the live mailbox: a bare is:unread runs once as asked and never broadens, and a query differing only by a trailing space reports broadened: false.

I have not ticked the test-plan checkbox.

🔍 Technical details

Environment

  • Tested SHA: 572e8b79171ce836a712ee4088c3adb862bb42b0 (= PR head at time of run)
  • gaia_agent.__file__ = /home/amd/src/amd/gaia/hub/agents/gaia/python/gaia_agent/__init__.py
  • gaia.__file__ = /home/amd/src/amd/gaia/src/gaia/__init__.py
  • Driven in-process (GaiaAgent().process_query(...)) with search_email wrapped to record every payload, so the prebuilt binary under ~/.gaia/agents/gaia/ is never on the path.
  • Lemonade 11.9.0 on 127.0.0.1:13305, Gemma-4-E4B-it-GGUF @ ctx_size=32768.
  • Connector live before testing — check_mailbox_access → {"success": true, "provider": "google", "address": "[email protected]", "inbox_unread": 447, "inbox_total": 1137}; list_inbox(limit=3) returned three real messages.

Q1 — "the argument over cameras police departments use to watch streets" — PASS (reproduced, executed)

model sent query : 'cameras police'
query_used       : 'cameras police'
broadened        : False
count            : 1
attempts         : [{"query": "cameras police", "count": 1}]
  HIT: The Flock surveillance cameras debate. | Tangle <[email protected]> | 2026-08-18T15:55:07Z

Q2 — "a newsletter about Flock cameras" — PASS (reproduced, executed)

model sent query : 'Flock cameras newsletter'
query_used       : 'Flock cameras newsletter'
broadened        : False
count            : 1
attempts         : [{"query": "Flock cameras newsletter", "count": 1}]
  HIT: The Flock surveillance cameras debate. | Tangle <[email protected]> | 2026-08-18T15:55:07Z

Q3 — "asking me to sign off on a contract schedule before the end of the week" — FAIL (reproduced, executed, 2/2 runs)

Run 1 — ladder fires, stops on a non-empty but wrong rung:

model sent query : 'contract signoff schedule'
query_used       : 'contract schedule'
broadened        : True
count            : 11
attempts         : [{"query": "contract signoff schedule", "count": 0},
                    {"query": "contract schedule", "count": 11}]
  HIT: ROCm Kernel Fusion Pass: MI300 Regression Triage & Handoff Confirmation | 2026-05-07
  HIT: Benefits enrollment for 2026                                            | 2026-02-23
  HIT: Document Employment Package_General_… has been completed                | 2026-02-20
  HIT: Re: AMD Contract conversion/Extension                                   | 2026-01-25
  … 7 more, none the Fieldstone thread

Run 2 — ladder never fires at all, because the first query is non-empty:

model sent query : 'contract signature schedule'
query_used       : 'contract signature schedule'
broadened        : False
count            : 3
attempts         : [{"query": "contract signature schedule", "count": 3}]
  HIT: Document Employment Package_General_… has been completed  | 2026-02-20
  HIT: Document AMD Onboarding Compliance Paperwork - …          | 2026-02-18
  HIT: Document AMD Onboarding Compliance Paperwork_…            | 2026-02-17

Competing cause considered and discriminated: the target message is not in this mailbox. Refuted by running the backend directly —

QUERY: 'counter-signature'   → broadened: False, count: 5
  HIT: Re: Fieldstone MSA — counter-signature needed before Friday
QUERY: 'Fieldstone'          → broadened: False, count: 5
  HIT: Re: Fieldstone MSA — counter-signature needed before Friday

And the issue's own literal query still behaves as it did on main, with the ladder inert because the result is non-empty:

QUERY: 'sign off contract schedule this week'
  query_used: 'sign off contract schedule this week' | broadened: False | count: 2
  HIT: Benefits enrollment for 2026
  HIT: Document Employment Package_General_… has been completed

So the residual gap is count > 0 and wrong. The ladder's stop-at-first-non-empty rule also means run 1 never reached the single-term rungs (schedule, contract, signoff) — though on this mailbox none of those would have reached Fieldstone either, since the user's wording shares no term with the message. Recovering Q3 needs something other than term-dropping; term-dropping cannot bridge contract schedule → counter-signature.

D2 (a bare provider operator becomes a broadening rung) — refuted (reproduced, executed)

QUERY: 'is:unread'
  query_used: 'is:unread' | broadened: False | count: 5
  attempts: [{"query": "is:unread", "count": 5}]

One attempt, run as asked, not labelled as broadened. Matches _is_search_operator excluding it from the content terms.

D1 (whitespace-only difference reported as broadened) — refuted (reproduced, executed)

QUERY: 'cameras police '   (trailing space)
  query_used: 'cameras police' | broadened: False | count: 1

Out of scope, observed during the runs

  • Memory extraction LLM call times out at 8 s on every turn on this box (memory.py:1536).
  • Cross-encoder reranking is disabled under faiss/torch OpenMP conflict (memory.py:408).
  • counter-signature returns the same thread five times — the search appears to return per-message rather than per-thread hits, which eats the result budget.

Refs #4134

@itomek
itomek added this pull request to the merge queue Sep 23, 2026
Merged via the queue into main with commit 7c3bc60 Sep 23, 2026
72 of 77 checks passed
@itomek
itomek deleted the issue-4134 branch September 23, 2026 16:34
itomek added a commit that referenced this pull request Sep 23, 2026
Five tests, all failing at 7c3bc60, for the half of mail recollection
#4148 did not cover: a query that matches the wrong mail ends the search,
one conversation spends every result slot, and a result set the tool
cannot vouch for comes back looking like a confident match.
itomek added a commit that referenced this pull request Sep 23, 2026
Five tests, all failing at 7c3bc60, for the half of mail recollection
#4148 did not cover: a query that matches the wrong mail ends the search,
one conversation spends every result slot, and a result set the tool
cannot vouch for comes back looking like a confident match.
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Sep 23, 2026
amd#4155)

Asked what needed attention, the flagship put a phishing lure under
**Critical & Urgent Action Items** and then, in its own words, told the
user to do what the lure wanted ("this requires immediate
verification/action"). That advice was the agent's, carrying its own
authority. The retired hub email agent had guarded against exactly this,
but the flagship reaches mail through a different path and never
inherited the safeguard — and both existing guard tests are gated behind
an import of the retired package, so nothing went red when it failed to
port.

Now every message body the mail tools return is fenced as untrusted
content, a probable lure comes back flagged with the reason it was
flagged, and the result tells the model it must not be bucketed as
urgent and must not have its call to action repeated as advice. **The
guard lives in the tool result, not in a skill** — the turn that
produced the defect never loaded one, so a skill-only fix would not have
run at all.

🔒 **SECURITY CONCERN** — this is the fix for a reported prompt-injection
/ phishing-amplification defect. @kovtcharov-amd

## Test plan

- [ ] `python -m pytest
tests/unit/agents/tools/test_email_phishing_guard.py -q` — 19 tests on
the flagship path, no `importorskip`. Before the fix the whole module
errored at collection (the detector did not exist); after it, the skill
check still failed alone until the skill carried the rule.
- [ ] `python -m pytest tests/unit/agents/ -q` — passes.
- [ ] `python util/lint.py --all` — passes.
- [ ] Live, against a mailbox containing a lure: **ask a mail-scoped
question** — "check my inbox and tell me which emails need a reply" — in
a fresh process. **Do not use the wording in the issue.** "What needs
me?" was measured to make zero email tool calls and answer from memory,
so it looks like a pass while never touching the mailbox. Confirm the
turn actually called `list_inbox`, then that the lure is reported as
suspicious with its reason, never as an action item, and that nothing in
the answer tells the user to follow it.

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

- `src/gaia/agents/tools/_email/phishing.py` ports the retired agent's
deterministic, LLM-free `detect_phishing` — three precision-first
channels (subject keyword pairs, sender domain impersonation, body
phrases) — and returns `(suspicious, reasons)` rather than a bare bool,
so amd#4072's never-empty-rationale rule holds by construction rather than
by convention.
- `EmailToolsMixin` annotates every listing and search hit, fences every
read body, and attaches the do-not-bucket / do-not-restate guidance only
when something actually fired (no guidance noise on a clean inbox).
- Fixtures from the live baseline: the PayPal/Microsoft homoglyph
senders that the agent left unmentioned entirely are caught by the
domain channel, and `[email protected]` — Google's real
domain, whose "Security alert" reads exactly like a lure — is pinned as
a negative case.
- `hub/skills/inbox-triage/SKILL.md` carries the same rule as defence in
depth, with a test pinning that it still does. Note it also renumbers
the triage steps, which collides with amd#4159 — merge order matters.
- Three existing tests in `test_email_tools.py` asserted on the raw body
string and now unwrap the fence; they test truncation and the per-turn
budget, which charge the unfenced length.
- Not run here: `gaia eval agent`. The change adds tool-docstring text,
an LLM-affecting surface — no Lemonade backend in this environment.

amd#4148 has since merged, so this targets `main` directly and carries only
its own commits.
</details>

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

Labels

agents ready_for_ci Run CI workflows on draft PR without requesting review tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(email): the flagship cannot find mail you describe in your own words

1 participant