Skip to content

refactor(email): dedupe envelope helpers, unify token path, guard tools_count - #2035

Merged
itomek merged 11 commits into
mainfrom
tmi/1232-email-refactor-cleanup
Jul 13, 2026
Merged

itomek merged 11 commits into
mainfrom
tmi/1232-email-refactor-cleanup

Conversation

@itomek

@itomek itomek commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

Closes #1232

Three copies of the same tech debt in the packaged email agent could each drift silently: the JSON envelope helpers were copy-pasted across 12 tool modules, Calendar resolved OAuth tokens through a different (weaker) path than Gmail, and the hub-facing tools_count was hand-pinned in two files with nothing checking either. All three are now single-sourced and drift-guarded — a future tool added without bumping both tools_count pins fails CI, and Calendar auth failures now surface as an actionable reconnect message instead of an opaque 502.

Deliberate behavior change (Part 3): Calendar's move onto get_access_token_sync adds the OAuth scope-coverage pre-flight Gmail already had. In the broken state (agent granted calendar, but the stored Google connection missing calendar scope) the API now returns 403 with a reconnect message pre-flight instead of 502 after a wasted Google round-trip. Same immutable CALENDAR_SCOPES, no scope widening; Outlook backends intentionally unchanged.

Note: the issue's "actual ~37" premise was stale — the live registered count is 52, matching both existing pins; the fix here is the guard, not the number. EmailTriageAgent also now calls _snapshot_tools() like every other agent, fixing a latent bug where a second agent built in the same process could silently swap its effective tool set.

Test plan

  • Full email suite green: python -m pytest hub/agents/python/email/tests/ -q → 317 passed, 0 failed (includes 20 new tests written TDD-first from the acceptance criteria, red before implementation)
  • python util/lint.py --all — all blocking gates pass
  • Local end-to-end smoke (below)

Evidence

Real-world tier is degraded to a local end-to-end smoke by design: this is an internal refactor with no new user-facing feature, and the token-path contract is pinned by mocked tests (AGENT_NOT_GRANTED parity + the new CONNECTION_MISSING_SCOPES propagation).

CLI — full suite (provenance-verified worktree venv):

$ python -m pytest hub/agents/python/email/tests/ -q
317 passed, 1 warning in 3.32s

CLI — end-to-end smoke (instantiate agent, guarded count, calendar tool through the shared envelope):

[1] live registered tool count (memory off): 52
[2] calendar_tools envelope fn IS tools/envelope.py's fn (identity)
[3] list_calendar_events envelope: {"ok": true, "data": {"events": [{"id": "evt1", "summary": "Smoke meeting", ...
SMOKE PASS
Reviewer call-outs
  • src/gaia/ui/email_sidecar/proxy_agent.py:92 keeps its own envelope copy intentionally — it lives in core gaia.ui, which cannot depend on the hub package (dependency direction).
  • Framework follow-up (out of scope, src/gaia/connectors/): OAuthPkceHandler.get_credential lacks the scope-coverage check api.get_access_token has, so Microsoft/Outlook token resolution retains the weaker pre-existing guarantee.
  • AuthRequiredError.missing_scopes precision differs between the two paths on AGENT_NOT_GRANTED (full requested list vs. computed diff); the rendered user message is unaffected.
  • The AST anti-regression test in tests/test_envelope.py fails on any future re-introduction of a local _envelope_ok/_envelope_err def in tools/.

Tomasz Iniewicz added 4 commits July 13, 2026 11:45
…ath ACs

These pin the three acceptance criteria for the upcoming email-agent
refactor before the implementation lands, so the refactor has a concrete
TDD contract: tools_count stays anti-drift guarded, the envelope helpers
collapse to one source, and Calendar shares Gmail's token path.
The _envelope_ok/_envelope_err pair was copy-pasted byte-for-byte across
11 tool modules, with followup_tools importing them from read_tools as a
12th consumer. All 12 now import from tools/envelope.py, so the envelope
contract has one home and a drift in one copy can no longer diverge the
tool output format. Now-unused json/Any imports dropped per module.
…#1232)

Calendar token resolution now goes through get_access_token_sync — the
same gaia.connectors.api path Gmail uses — instead of the handler-level
get_credential_sync. Besides removing the dict-unwrap asymmetry, this
adds the scope-coverage pre-flight Gmail already had: a connection
missing calendar scope now fails fast with an actionable
CONNECTION_MISSING_SCOPES reconnect message (HTTP 403 at the email API
boundary) instead of surfacing as an opaque Google 403 -> 502 after a
wasted network call. Same immutable CALENDAR_SCOPES, same connector, no
scope widening.
#1232)

The live email-tool count is 52 (memory off), matching both pinned
tools_count copies, so the values stand — but nothing guarded them, and
the npm changelog shows the dual pin drifting stale before. Both copies
now carry a pointer to the drift-guard test that derives the count from
the live registry and fails on any unbumped tool addition.

EmailTriageAgent was also the outlier that never called
_snapshot_tools(): its registry stayed a live alias to the shared global
dict, so constructing any other agent in the same process would silently
swap the email agent's effective tool set. Snapshotting at the end of
_register_tools() aligns it with every other agent and makes the guard
deterministic by construction.
@github-actions github-actions Bot added the agent::email Email agent changes label Jul 13, 2026
Consolidates the orchestration artifacts onto the PR branch: the plan
(with its adversarial-reflection record) lives next to the change it
drove, matching the committed .claude/plans/ convention.
@itomek
itomek marked this pull request as ready for review July 13, 2026 18:24
@itomek
itomek requested a review from kovtcharov-amd as a code owner July 13, 2026 18:24
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve ✅

This PR retires three copies of the same drift-prone tech debt in the packaged email agent: the JSON envelope helpers (copy-pasted across 12 tool modules → one shared module), Calendar's weaker OAuth token path (now unified onto Gmail's grant-checked get_access_token_sync), and the hand-pinned tools_count (now guarded against drift in both places it's declared). It's TDD-first, the deliberate 502→403 behavior change is clearly documented, and I found nothing blocking.

The one thing worth a reviewer's eye is the intentional behavior change called out in the description: in the broken state (agent granted Calendar but the stored Google connection lacks calendar scope), Calendar now fails pre-flight with an actionable 403 reconnect message instead of a 502 after a wasted round-trip. Same immutable scope set, no widening — a strict fail-loud improvement aligned with GAIA's "No Silent Fallbacks" rule.

🔍 Technical details

Correctness checks performed (all pass):

  • Unused-import hygiene after removing local defs: every module that dropped import json (delete/organize/phishing/schedule/summarize/read_tools) has zero remaining json. uses; calendar_tools.py (2 uses) and preference_tools.py (3) correctly kept it. voice_tools.py dropped from typing import Any and no longer references Any. No F401 introduced.
  • Token-path swap: get_access_token_sync (src/gaia/connectors/api.py:157) is keyword-only (provider, scopes, agent_id, account_email); the new _get_calendar_token (calendar_backend.py:248) passes provider=/agent_id=/scopes= — matches the signature and Gmail's call shape.
  • Envelope identity: followup_tools.py correctly splits its import (envelope helpers from .envelope, extract_sender_email from read_tools), so the wiring test's module._envelope_ok is envelope._envelope_ok assertion holds for all 12 consumers.
  • _snapshot_tools() addition (agent.py:564): backed by base Agent._tools_registry/_snapshot_tools (src/gaia/agents/base/agent.py:717,728) — aligns EmailTriageAgent with every other agent and makes the AC1 guard deterministic by construction.

🟢 Minor / optional (not blocking):

  • The AC1 guard test (test_email_agent.py:900) mutates os.environ["GAIA_MEMORY_DISABLED"] with manual save/restore. That's correct given there's no conftest, but monkeypatch.setenv (already used elsewhere in this file, e.g. test_triage_fails_fast_when_lemonade_unreachable) would drop the try/finally boilerplate. Fine to leave.

Strengths:

  • Genuinely drift-proof: the guard test pins tools_count against the live registry AND both declared copies (__init__.py + gaia-agent.yaml), and the AST anti-regression test in test_envelope.py fails on any future re-introduced local copy — the debt can't silently come back.
  • Behavior change is handled the right way: isolated to its own increment, covered by explicit AGENT_NOT_GRANTED parity + CONNECTION_MISSING_SCOPES propagation tests, and surfaced in the PR body rather than buried.
  • Scope discipline: core proxy_agent.py's envelope copy and the Outlook/Microsoft token paths are deliberately left untouched (dependency direction / unverified provider support) and both are documented as follow-ups.

kovtcharov-amd
kovtcharov-amd previously approved these changes Jul 13, 2026
@itomek
itomek enabled auto-merge July 13, 2026 18:52
…or-cleanup

# Conflicts:
#	hub/agents/python/email/gaia_agent_email/tools/read_tools.py
@github-actions

Copy link
Copy Markdown
Contributor

🟡 The planning document .claude/plans/issue-1232.md is still tracked in the HEAD commit of this branch and will be added to main when merged — undoing #2041, which explicitly removed committed session scratch from .claude/plans/ and gitignored the directory. The file is deleted from disk (gitStatus shows D) but not from git history.

Fix before merging:

git rm .claude/plans/issue-1232.md
git commit -m "chore: drop session plan artifact from tracking"

The rest of the changes look clean — envelope dedup, token-path unification, _snapshot_tools() call, and all three test files are correct.

🔍 Technical details

git show HEAD:.claude/plans/issue-1232.md returns the file content, confirming it is in the HEAD commit. git diff origin/main HEAD -- .claude/plans/issue-1232.md confirms it is a new-file addition relative to main.

bcef2c4d (merged into this branch via 3164bda2) updated .gitignore to ignore .claude/plans/, but gitignore does not un-track files that were already committed. Since commit 74155126 docs(plans): add the #1232 implementation plan committed the file to this branch before the merge, the file remains tracked and will ship to main.

Tomasz Iniewicz and others added 2 commits July 13, 2026 15:54
Main gitignored .claude/plans/ and purged committed plans (#2041) after
this branch added its plan file; remove it so the merge doesn't reintroduce
session scratch to main.
@itomek

itomek commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator Author

The one red check ("Re-run eval, refresh-or-reject scorecard") is a pre-existing main-side failure, not something this PR introduced — this PR changes no eval code.

Two independent problems, both filed as #2047:

All other checks are green. Details and evidence in #2047.

@itomek
itomek added this pull request to the merge queue Jul 13, 2026
Merged via the queue into main with commit f914d7e Jul 13, 2026
27 checks passed
@itomek
itomek deleted the tmi/1232-email-refactor-cleanup branch July 13, 2026 20:30
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.

refactor(email): post-demo cleanup — tools_count, envelope dedup, token-path unify

2 participants