Skip to content

fix(email): apply a combined transcript budget to get_thread (fair-share + [truncated] markers) - #2076

Merged
itomek merged 3 commits into
mainfrom
tmi/2073-get-thread-transcript-budget
Jul 14, 2026
Merged

itomek merged 3 commits into
mainfrom
tmi/2073-get-thread-transcript-budget

Conversation

@itomek

@itomek itomek commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Closes #2073

Why this matters

Before: get_thread capped each message body at 4,000 chars but had no combined cap, so a 50-message thread pushed ~200K chars into the local model's fixed context in a single tool result. After: the whole thread shares the same 24K soft budget the summarize path already uses — when exceeded, every message body is clipped to a fair share with an explicit ...[truncated] marker (per-message floor of 200 chars), messages are never dropped, and threads that fit are returned byte-identical to today, differential-tested down to the JSON wire.

Evidence

Hermetic pytest per the issue's "How to verify" — the 10-test contract covers the differential fits path, the exact 24,000-char boundary from both sides, and over-budget fair-share/floor threads:

$ python -m pytest hub/agents/python/email/tests/test_read_tools_thread_budget.py -v
collected 10 items

...::TestFitsUnderBudgetDifferential::test_d2_uniform_bodies_at_fair_share_are_unshrunk PASSED [ 10%]
...::TestFitsUnderBudgetDifferential::test_d3_one_large_body_among_many_tiny_ones_is_not_count_blind PASSED [ 20%]
...::TestWireLevelByteIdentity::test_w1_under_budget_thread_matches_envelope_byte_for_byte PASSED [ 30%]
...::TestExactBoundaryPair::test_db_exact_boundary_output_unchanged PASSED [ 40%]
...::TestExactBoundaryPair::test_db_boundary_plus_one_triggers_reformat PASSED [ 50%]
...::TestOverBudgetFairShare::test_b1_every_message_present_and_shrunk_to_fair_share PASSED [ 60%]
...::TestOverBudgetFairShare::test_b2_combined_total_stays_within_the_soft_bound PASSED [ 70%]
...::TestOverBudgetFairShare::test_b3_floor_kicks_in_when_fair_share_would_undercut_it PASSED [ 80%]
...::TestOverBudgetFairShare::test_b5_empty_thread_returns_empty_messages_no_zero_division PASSED [ 90%]
...::TestGetThreadToolSurface::test_s1_docstring_mentions_truncated_and_envelope_marks_truncation PASSED [100%]

============================== 10 passed in 0.49s ==============================

Tests were authored independently from the issue's acceptance criteria and committed first as a fixed contract (verified 5-green/5-red against the pre-change code), then the implementation turned the red half green.

Tests

  • Unit — new contract file 10/10; hub/agents/python/email/tests/ + tests/unit/agents/email/: 982 passed
  • Integration — the full test_email_agent_unit.yml command: 2191 passed, 6 skipped, 1 failed: tests/unit/eval/test_claude_judge.py::test_raises_on_missing_api_key, a pre-existing local-only artifact (a parent-checkout .env re-injects ANTHROPIC_API_KEY via import-time load_dotenv() after the test's delenv; zero overlap with this 2-file diff — CI has no .env and is unaffected)
  • Capability-matrix drift guard (packaging/capability_matrix.py --check) green — no new tools, docstring-only tool-surface change
  • Real-world: N/A — the issue specifies hermetic pytest as the verification
Scope notes
  • Read-tool contract is clipping only (no summarization, no reordering, no dropped messages) — the summarize-to-fit fold stays with feat(email): long-thread handling via iterative summarization to fit the context budget #1889 per the issue's scope note.
  • Signature of get_thread_impl and the tool schema are unchanged; the budget reuses the existing DEFAULT_THREAD_TRANSCRIPT_CHARS / THREAD_MIN_PER_MESSAGE_CHARS constants from the summarize path.
  • A thread message-COUNT ceiling remains a candidate fast-follow (pre-existing, strictly improved by this change).

Tomasz Iniewicz added 3 commits July 14, 2026 12:54
…2073)

Pins the acceptance criteria for a combined transcript budget on
get_thread_impl: threads under DEFAULT_THREAD_TRANSCRIPT_CHARS format
byte-identically to today (D2/D3/W1/DB), over-budget threads must
fair-share-clip every message with a [truncated] marker rather than
drop any (B1/B2/B3/B5), and the tool docstring must say so (S1).

5 of 10 tests pass against current main (pinning today's unbudgeted
behavior); 5 fail (the budget/truncation/docstring behavior that
get_thread_impl does not implement yet).
get_thread_impl formatted every thread message at the per-message
4000-char default with no combined cap, so a long thread (e.g. 50
messages) could push ~200K chars into a single tool result on a
fixed-ctx local model. Mirror the sibling summarize path's soft-target
budget: under DEFAULT_THREAD_TRANSCRIPT_CHARS (24000) the default
per-message limit still applies untouched (byte-identical to today);
over budget, every message re-formats at a shared fair-share limit
(floored at THREAD_MIN_PER_MESSAGE_CHARS) so long threads stay bounded
without ever dropping a message. Truncated bodies carry the existing
'...[truncated]' marker, and the tool docstring now tells the calling
LLM results may be truncated.

Signature is unchanged (no new parameters) and the budget constants are
the same module-level constants the summarize path already uses.
result_summary now also reports bodies_clipped for observability
(log-only, no envelope contract change).

All 10 new tests in test_read_tools_thread_budget.py pass, plus the
existing 21 in test_read_tools_body_limit.py and the full
hub/agents/python/email/tests/ + tests/unit/agents/email/ suites
(982 passed).
Formatting only (list-comp line fold + isort import ordering); no
behavior or test-semantics change. All 982 email suite tests still
pass and the capability-matrix drift guard (--check) is green.
@github-actions github-actions Bot added the agent::email Email agent changes label Jul 14, 2026
@itomek itomek self-assigned this Jul 14, 2026
@itomek
itomek marked this pull request as ready for review July 14, 2026 17:22
@itomek
itomek requested a review from kovtcharov-amd as a code owner July 14, 2026 17:22
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve ✅

This closes the unbounded-context risk in get_thread: a 50-message thread could previously shove ~200K chars into the local model's fixed context. Now the whole thread shares the same 24K soft budget the summarize path already uses — over-budget bodies get clipped to a fair share with an explicit ...[truncated] marker (floored per-message), no message is ever dropped, and threads that already fit come back byte-identical. The 10-test contract is genuinely rigorous: it exercises the exact budget boundary from both sides, a count-blind-vs-total-aware trap, the per-message floor, and the empty-thread zero-division guard — with every expected value derived from module constants rather than hardcoded. Nothing blocking.

🔍 Technical details

Correctness — verified clean

  • The gate messages and total > DEFAULT_THREAD_TRANSCRIPT_CHARS (read_tools.py:199) guards the // len(messages) division, so the empty-thread path can't divide by zero (pinned by test_b5).
  • fair_share = max(THREAD_MIN_PER_MESSAGE_CHARS, budget // len(messages)) then the fair_share < DEFAULT_BODY_LIMIT_CHARS guard (read_tools.py:207) correctly makes the shrink a no-op at the exact boundary, matching the "only shrink when it actually tightens the limit" intent (pinned by test_d2).
  • Because total is summed over already-per-message-capped bodies, a small thread with one oversized message can exceed budget only via wrapper overhead (≤6 messages), leaving it unshrunk — acceptable given the documented soft-target semantics, and the test_b2 soft bound accounts for the per-message overhead honestly.
  • The ...[truncated] marker is applied by _truncate before wrap_untrusted_body, so it lands inside the untrusted delimiter pair — test_b1 explicitly asserts open_idx < marker_idx < close_idx, which is the right invariant for prompt-injection safety.
  • Duplicating (rather than sharing) the summarize path's fair-share formula is a reasonable call and the inline comment (read_tools.py:36-38) names the actual reason (the limit<=0 unlimited-mode branch doesn't belong on a read tool).

Docs / contract

  • Tool docstring (read_tools.py:895) now tells the LLM results may be ...[truncated] (AC4), asserted at the registered-tool surface by test_s1. get_thread isn't referenced in the email agent's README/SPEC, so no bundled-doc sync is owed here.

🟢 Minor (optional, non-blocking): bodies_clipped in result_summary (read_tools.py:211) counts any body_truncated message, including ones clipped by the default per-message limit when the thread is under the combined budget — so as a "combined-budget clip" metric it slightly over-reports. It reads fine as a generic "bodies clipped for any reason" debug counter; only worth a one-word rename if you intended it to mean specifically budget-driven clips.

Strengths

  • Textbook TDD split: tests committed first as a fixed contract (5-green pinning today's behavior / 5-red encoding the new budget), every expected number computed from DEFAULT_THREAD_TRANSCRIPT_CHARS / THREAD_MIN_PER_MESSAGE_CHARS / DEFAULT_BODY_LIMIT_CHARS plus dynamically-measured wrapper overhead — no brittle literals.
  • Reuses the existing summarize-path constants instead of inventing new tunables, and the wire-level test_w1 pins the "byte-identical when it fits" claim at the actual JSON envelope, not just dict equality.
  • Fail-loudly respected: _truncate still raises on a non-positive limit, and the fair-share floor keeps body_limit positive.

@itomek
itomek added this pull request to the merge queue Jul 14, 2026
Merged via the queue into main with commit 1403992 Jul 14, 2026
37 checks passed
@itomek
itomek deleted the tmi/2073-get-thread-transcript-budget branch July 14, 2026 17:32
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Aug 17, 2026
Release notes had grown into long blocks of prose with a marketing-toned
paragraph on top. They now generate as short bullets grouped by section,
with a word cap on the narrative part. Nothing informational is lost —
every PR link, contributor credit, and changelog entry is preserved; the
prose around them is cut.

Two generators write `docs/releases/<tag>.mdx` and they had drifted
apart. The `gaia-release` skill told the model GAIA's notes "read dry"
and to make them "engaging"; the `release-notes` job in `claude.yml`
asked for "comprehensive" notes with an `## Overview` paragraph and
emoji headings. Fixing one alone would have been overwritten by the
other on the next tag, so both now share one spec.

Closes amd#2961

## What it looks like now

Regenerated from the last two releases — same facts, same PR numbers,
new template. Narrative words (the capped part, excluding
bug-fix/contributor/changelog lists):

| Release | Published | Regenerated | Cap |
|---|---|---|---|
| v0.22.0 (minor) | 1705 | **538** | 600 |
| v0.23.0 (minor) | 1119 | **280** | 600 |

<details>
<summary>Example 1 — v0.23.0 regenerated</summary>

```markdown
---
title: "v0.23.0"
description: "Install and run agents from the terminal, add capabilities as skills, and connect a Microsoft account without a secret."
---

# GAIA v0.23.0 Release Notes

Agents are now installable from the terminal, and the confirmation gate that pauses an agent before a consequential action works everywhere, not just in the Agent UI.

## Breaking Changes

- **`GAIA_MICROSOFT_TENANT` is gone** — the Microsoft connector split into Personal and Work/School, each with its own tenant. Drop the variable and pick the matching connector. (PR [amd#2729](amd#2729))

## What's New

- **Install and run agents from the terminal** — `gaia hub list`, `gaia hub install <agent> --trust`, `gaia hub uninstall <agent>`. `--trust` is required for an unverified agent. (PRs [amd#2484](amd#2484), [amd#2530](amd#2530), [amd#2708](amd#2708))
- **Every agent asks before it acts** — the confirmation gate for sending mail, writing files, and running commands now fires from the terminal, the local API, and MCP tool calls, not only the Agent UI. Set `GAIA_AUTO_APPROVE_TOOLS=1` to opt out. (PRs [amd#2475](amd#2475), [amd#2544](amd#2544), [amd#2846](amd#2846), [amd#2854](amd#2854))
- **Safer by default** — the MCP bridge binds to localhost and enforces `--auth-token`; the local API refuses credentialed cross-origin requests from non-allow-listed sites; MCP servers launch without a shell; agents cannot write to `~/.gaia` or pass crafted SQL to the database agent. (PRs [amd#2246](amd#2246), [amd#2238](amd#2238), [amd#2344](amd#2344), [amd#2844](amd#2844), [amd#2847](amd#2847), [amd#2860](amd#2860))
- **Add capabilities as skills** — `gaia skill create|import|list|info` gives an agent a new capability from a folder and a manifest. Skills are signed with trust tiers, audited before publish, and opt-in. (PRs [amd#2669](amd#2669), [amd#2692](amd#2692), [amd#2702](amd#2702), [amd#2693](amd#2693))
- **Connect a Microsoft account without a secret** — Personal and Work/School are separate connectors with device-code sign-in. (PRs [amd#2718](amd#2718), [amd#2364](amd#2364))
- **Lemonade Server 11.5.0.**

## Bug Fixes

- **Triage paginates large inboxes and reports truncation** (PR [amd#2646](amd#2646)) — mail past a hidden limit is no longer dropped without saying so.
- **Thread messages come back sorted and numbered** (PR [amd#2570](amd#2570)) — "reply to 3" hits the message shown at position 3.
- **The inbox pre-scan reports uncertainty as uncertainty** (PR [amd#2587](amd#2587)).
- **An email conversation survives its turns** (PR [amd#2837](amd#2837)) — a follow-up keeps session context.
- **A bare reconnect keeps existing grants** (PR [amd#2733](amd#2733)).
- **Restore from Trash anytime** (PR [amd#2542](amd#2542)) — no time window on undo.
- **Sender priority no longer overrides content classification** (PR [amd#2774](amd#2774)).
- **The agent survives an OpenMP double-init** (PR [amd#2508](amd#2508)).
- **Large tool results truncate to valid JSON** (PR [amd#2645](amd#2645)).
- **A missing model surfaces as a real 404** (PR [amd#2245](amd#2245)).
- **GPU is detected on all platforms and `default_device` is honoured** (PR [amd#2244](amd#2244)).
- **A sidecar that is alive but not serving is detected** (PR [amd#2707](amd#2707)).
- **The model-slot lease is held across inference** (PR [amd#2394](amd#2394)) — a second agent can't evict the model mid-generation.
- **A browser that never launched is surfaced** (PR [amd#2507](amd#2507)).
- **Stop aborts in-flight streaming** (PR [amd#2166](amd#2166)).

## Known Issues

- **The email agent is beta and CLI-first** — treat its output as a draft to review.
- **A full inbox triage can time out on larger mailboxes.**
- **Email autonomy is experimental** and not wired up in the packaged sidecar.

## Contributors

- [@handle](https://github.com/handle) — <contribution> (PR [#NNN](https://github.com/amd/gaia/pull/NNN))
  <!-- generated from the commit log; v0.23.0's list is unchanged from the published notes -->


## Full Changelog

**N commits** since v0.22.0:

- `<sha>` — <subject>

Full Changelog: [v0.22.0...v0.23.0](amd/gaia@v0.22.0...v0.23.0)
```
</details>

<details>
<summary>Example 2 — v0.22.0 regenerated (the largest recent
release)</summary>

```markdown
---
title: "v0.22.0"
description: "The email agent tracks follow-ups and action items, drafts in your voice, and runs as its own process. Plus a cron scheduler and Word document support in RAG."
---

# GAIA v0.22.0 Release Notes

A large release built around the email agent, which now tracks what you're waiting on instead of forgetting it after triage.

## Breaking Changes

- **Triage returns a reply scaffold, not an empty draft** — `POST /v1/email/triage` and `/triage/batch` now return a `DraftScaffold` without `body`. Code reading `result.draft.body` gets a missing key instead of `""`; use `POST /v1/email/draft` for composed prose. (PR [amd#1984](amd#1984))
- **RoutingAgent and DocumentQAAgent moved to standalone packages** — install `gaia-agent-routing` and `gaia-agent-docqa`. The old imports fail; there is no deprecation shim. (PR [amd#1455](amd#1455))

## What's New

- **An inbox agent that keeps track** — `gaia email` scans Sent folders across every connected mailbox and flags threads still waiting on a reply past a window you set (default 3 days). Detection only; it never nudges anyone for you. (PRs [amd#1922](amd#1922), [amd#1917](amd#1917), [amd#1919](amd#1919), [amd#1918](amd#1918))
- **Drafts in your own voice** — the agent derives greeting, sign-off, length, and formality from your Sent history and composes against that. Only the derived characteristics are stored, never old mail content. (PR [amd#1925](amd#1925))
- **Attachments work end to end** — triage surfaces each attachment's name, type, and size, and drafting and sending accept real attachments as Gmail multipart MIME or Outlook Graph attachments. (PRs [amd#1921](amd#1921), [amd#1883](amd#1883))
- **Email runs as its own process in the Agent UI (beta)** — install it from the Agent Hub panel and the UI talks to it over HTTP, instead of loading the email stack into the UI process. (PRs [amd#1884](amd#1884), [amd#1910](amd#1910), [amd#2100](amd#2100), [amd#2101](amd#2101), [amd#2105](amd#2105))
- **Run prompts on a cron from the terminal** — `gaia schedule add --name digest --cron "0 9 * * *" --prompt "summarize my inbox" --sink stdout`, then `gaia schedule daemon`. Schedules live in a hand-editable `~/.gaia/schedules.toml`; sinks are `stdout`, `file:<path>`, `notification`, or `telegram`. (PR [amd#1371](amd#1371))
- **Agents learn from work they repeat** — after enough successes on the same shape of goal, an agent distills the tool sequence into a reusable procedure and recalls it next time. Runs inside the existing memory pass; nothing to install. (PR [amd#1794](amd#1794))
- **Pick your model once** — `gaia config set default_model <id>` persists across `gaia chat`, `gaia llm`, and `gaia prompt`. An explicit `--model` still wins for a one-off. (PR [amd#1863](amd#1863))
- **RAG reads Word documents** — `.docx` files index like PDF and PPTX, including table cells, nested tables, content controls, hyperlinks, and textboxes, so filled-in form values get indexed. (PR [amd#1866](amd#1866))
- **A new default embedder** — the previous default cannot be loaded by current llama.cpp builds, which broke indexing, code search, and memory embedding on an up-to-date Lemonade. The default is now EmbeddingGemma 300M at the same 768 dimensions. (PRs [amd#1952](amd#1952), [amd#1761](amd#1761), [amd#1748](amd#1748))
- **The Agent Hub shows what an agent is worth** — an agent's page now carries its eval scorecard with a score badge and a code-derived capability matrix. (PRs [amd#1985](amd#1985), [amd#2020](amd#2020), [amd#2066](amd#2066))
- **Lemonade Server 10.10.0** — adds an audio-generation endpoint, lets Windows reuse system ROCm, and inhibits suspend during inference. Two upstream breaking changes are Linux-specific. (PR [amd#1969](amd#1969))

## Bug Fixes

- **`gaia init` said a working Lemonade wasn't installed** (PR [amd#1940](amd#1940)) — modern Lemonade (10.7+) dropped the `lemonade-server` CLI that GAIA probed for.
- **Installing the email agent from the Hub failed on every platform** (PR [amd#2086](amd#2086)).
- **Bulk triage broke on any real inbox** (PR [amd#2088](amd#2088)) — 60 emails overflowed the 16K context window; the result envelope is now condensed.
- **RAG silently indexed nothing** (PR [amd#1979](amd#1979)) — a failed `sentence-transformers` import made every indexing call a no-op.
- **Email bodies were truncated at 4,000 characters with no override** (PR [amd#2036](amd#2036)) — MFA codes and precise replies lost content past the cutoff.
- **Long threads overflowed the model's context** (PR [amd#2076](amd#2076)).
- **A disabled device was treated as usable** (PR [amd#2081](amd#2081)) — a device reporting `available: false`, such as an unpowered NPU, was misread as ready.
- **A newly connected mailbox was skipped** (PR [amd#1808](amd#1808)) — mailboxes connected mid-session were not picked up.
- **JSON with a `}` inside a string was dropped** (PR [amd#1824](amd#1824)).
- **Outlook users were told to reconnect Google** (PR [amd#1757](amd#1757)) — `AGENT_NOT_GRANTED` named the wrong provider.
- **The Agent UI hard-crashed on a recoverable GPU crash** (PR [amd#1799](amd#1799)) — it now falls back to software rendering.
- **A user-edited memory could be silently downgraded and then wiped** (PR [amd#1958](amd#1958)).
- **The builder agent ignored an agent name you had already given** (PR [amd#1981](amd#1981)).
- **The landing and hub pages scrolled sideways on phones** (PR [amd#1959](amd#1959)).

## Known Issues

- **Inbox pre-scan needs a single mailbox for now** — with both Gmail and Outlook connected, an Agent UI pre-scan errors. Disconnect one in Settings → Connectors; triage itself still spans every mailbox. ([amd#2127](amd#2127))
- **Spam detection under-flags over the REST API** — `/v1/email/triage` uses a narrow sender check rather than the model's reading. The agent's own inbox scanning is unaffected. ([amd#2124](amd#2124))
- **The email agent is beta** — treat its output as a draft to review. It never sends without your confirmation.

## Contributors

- [@alexey-tyurin](https://github.com/alexey-tyurin) — skill auto-synthesis / procedural memory (PR [amd#1794](amd#1794))
- [@TravisHaa](https://github.com/TravisHaa) — the `gaia schedule` CLI and cron-based dispatch (PR [amd#1371](amd#1371))
- [@Rohithmatham12](https://github.com/Rohithmatham12) — refresh resolved email backends before multi-mailbox triage (PR [amd#1808](amd#1808))
- [@Osamaali313](https://github.com/Osamaali313) — fix `extract_json_from_text` dropping JSON containing `}` (PR [amd#1824](amd#1824))
- [@eeee2345](https://github.com/eeee2345) — offline model-endpoint guard-proxy integration guide (PR [amd#1809](amd#1809))
- [@somo9909](https://github.com/somo9909) — prerequisites section for the memory guide (PR [amd#1665](amd#1665))

## Full Changelog

**N commits** since v0.21.2:

- `<sha>` — <subject>

Full Changelog: [v0.21.2...v0.22.0](amd/gaia@v0.21.2...v0.22.0)
```
</details>

<details>
<summary>What changed in the templates</summary>

- The narrative overview paragraph and the `**Why upgrade:**` block are
gone — the latter restated `What's New` verbatim.
- `What's New` entries are bullets, not `###` prose blocks.
- Tone guidance is no longer restated in the skill; it points at
CLAUDE.md § How You Communicate.
- The skill's embedded example now shows the old prose block as **bad**
and the bullet form as **good**.
- Emoji removed from the CI prompt (it asked for 🚀 / 🎯 / 🐛 headings
against the skill's own no-emoji rule).
- Both generators now emit the same sections in the same order, so the
file's shape no longer depends on which one ran.
- The cap excludes `Bug Fixes` / `Known Issues` / `Contributors` / `Full
Changelog`. Those are reference lists sized by how many fixes shipped —
capping them would hide work. This was caught by regenerating v0.22.0,
which overflowed a whole-file cap purely on its 14 bug-fix bullets.

**Follow-up, not in this PR:** the cap lives in prompt text, so it is
advisory. Making it a hard check in `util/validate_release_notes.py`
would enforce it in CI.
</details>

## Test plan

- [ ] `python util/validate_release_notes.py <regenerated sample> --tag
v0.23.0` exits 0 — passes unmodified, no validator changes in this PR
- [ ] `awk '/^## (Bug Fixes|Known Issues|Contributors|Full
Changelog)/{exit} {print}' <file> | wc -w` is under 350 (patch) / 600
(minor-major)
- [ ] `.github/workflows/claude.yml` parses as valid YAML and its
release-notes prompt contains no emoji
- [ ] `.claude/skills/gaia-release/SKILL.md` is under 500 lines (498)
- [ ] Both generators list the same sections in the same order
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::email Email agent changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(email): get_thread has no combined transcript cap — a long thread can emit ~200K chars

2 participants