Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): fail closed when Gmail sent pagination truncates at its ceiling (#2820)
[._.]/ Adam Eivyd1a20c81dc59
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 77587148f2..2bc96452bc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -24,7 +24,7 @@- **[issue-2796]** Tribe unanswered-thread nudges now cover Gmail, not just iMessage/Signal: Gmail sync ingests your recent sent mail into the activity timeline (as activity only — sent mail never enters your inbox), so a thread you've already replied to is no longer surfaced as needing outreach while a genuinely unanswered email within the window still is. Reply detection is per-account (default-on for Gmail, opt out via a new "Reply detection" toggle in Messages > Config), only trusts an account once its sent history is actually present and current (so a just-upgraded or sync-failing account can't emit false nudges), honors Gmail's send-as aliases, and drafts email replies in an email tone rather than a text-message one. Follow-on hardening (per-account event querying, full sent-window coverage) tracked in #2820.-- **[issue-2820]** Hardened Gmail Tribe-outreach reply detection so a busy Gmail account can't mislead it. Timeline events are now queried per opted-in email account under each account's own cap (instead of one shared source-wide cap), so a high-volume opted-out or disabled Gmail account can no longer fill the cap and suppress a legitimately opted-in account's nudges. Email conversations are keyed by account + threadId (a Gmail threadId is only unique within one account), so two accounts that happen to share a threadId value never merge into one false conversation. And the sent-mail pass now paginates the entire 14-day window (up to a generous ceiling) rather than stopping at the first 100 results, so a heavy sender's reply beyond the first page still cancels its inbound instead of leaving it a false "unanswered" nudge.+- **[issue-2820]** Hardened Gmail Tribe-outreach reply detection so a busy Gmail account can't mislead it. Timeline events are now queried per opted-in email account under each account's own cap (instead of one shared source-wide cap), so a high-volume opted-out or disabled Gmail account can no longer fill the cap and suppress a legitimately opted-in account's nudges. Email conversations are keyed by account + threadId (a Gmail threadId is only unique within one account), so two accounts that happen to share a threadId value never merge into one false conversation. And the sent-mail pass now paginates the entire 14-day window (up to a generous ceiling) rather than stopping at the first 100 results, so a heavy sender's reply beyond the first page still cancels its inbound instead of leaving it a false "unanswered" nudge — and in the rare case the ceiling itself is hit, that account's reply detection is paused (fail-closed) for the scan rather than trusting an incomplete sent window.## Changeddiff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.jsindex 3405290d81..c5ae6a4b68 100644--- a/server/services/messageAccounts.js+++ b/server/services/messageAccounts.js@@ -93,10 +93,17 @@ export async function updateSyncStatus(id, status) {// successfully ingested sent mail into the activity timeline. The Tribe-outreach// detector trusts an account as two-way only when this is set and recent, so an// account is never trusted before its sent history actually exists.-export async function markSentIngested(id, at = new Date().toISOString()) {+//+// `partial` (#2820) records whether the sent window was FULLY covered this sync.+// When the sent pass truncates at its ceiling (>SENT_INGEST_MAX sent in the+// window) coverage is incomplete, so the detector must NOT trust this account's+// reply evidence — `sentCoveragePartial:true` drops it from the two-way set for+// the scan (fail closed). A later full sync clears it back to false.+export async function markSentIngested(id, { at = new Date().toISOString(), partial = false } = {}) {const accounts = await loadAccounts();if (!accounts[id]) return null;accounts[id].sentIngestedAt = at;+ accounts[id].sentCoveragePartial = partial;await saveAccounts(accounts);return accounts[id];}diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex 3130570725..49a2051ad5 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -27,10 +27,11 @@ export const SENT_INGEST_DAYS = 14;// this generous ceiling (#2820) so a heavy sender's reply beyond the first page// still gets ingested and can cancel its inbound — a reply un-ingested here would// falsely read as unanswered. The ceiling only bounds the pathological case (>1000-// sent in 14 days); if it's actually hit, coverage is partial for that sync — the-// per-account reliability watermark (`sentIngestedAt`) plus the detector's own-// row-cap fail-closed keep a truncated window from producing false nudges. Sent-// isn't cached, so this also bounds the per-sync detail-fetch cost.+// sent in 14 days); if it's actually hit the sync reports `sentTruncated`, which+// marks the reply-detection watermark PARTIAL (`sentCoveragePartial`) so the+// outreach detector drops that account for the scan rather than trusting an+// incomplete sent window (fail closed). Sent isn't cached, so this also bounds the+// per-sync detail-fetch cost.export const SENT_INGEST_MAX = 1000;// The inbox search query for a sync mode. `unread` scopes to unread inbox; `full`@@ -68,16 +69,22 @@ export function gmailSyncPasses(mode, ingestSent, inboxCap) {* `listFn({ q, maxResults, pageToken })` returns `{ messages: [{ id }], nextPageToken }`.* Injected so the pagination is unit-testable without a live Gmail client.*- * @returns {Promise<Array<{ id: string }>>} deduped message-id items, in fetch order+ * `truncated` lists the queries that hit their cap with MORE pages remaining — i.e.+ * coverage of that query's window is incomplete. The caller must fail CLOSED on a+ * truncated sent pass (don't trust that account's reply evidence for this scan),+ * or an un-ingested older reply would falsely read as unanswered.+ *+ * @returns {Promise<{ items: Array<{ id: string }>, truncated: string[] }>}*/export async function collectMessageIds(passes, listFn, { onProgress } = {}) {- const messageIds = [];+ const items = [];const seen = new Set();+ const truncated = [];for (const pass of passes) {let pageToken = null;let fetched = 0;do {- onProgress?.(messageIds.length);+ onProgress?.(items.length);const { messages = [], nextPageToken = null } = await listFn({q: pass.query,maxResults: Math.min(100, pass.cap - fetched),@@ -87,12 +94,14 @@ export async function collectMessageIds(passes, listFn, { onProgress } = {}) {for (const item of messages) {if (seen.has(item.id)) continue;seen.add(item.id);- messageIds.push(item);+ items.push(item);}pageToken = nextPageToken;- } while (pageToken && fetched < pass.cap);+ // Stopped by the cap while a next page still exists → incomplete coverage.+ if (pageToken && fetched >= pass.cap) { truncated.push(pass.query); break; }+ } while (pageToken);}- return messageIds;+ return { items, truncated };}function getHeader(headers, name) {@@ -215,7 +224,7 @@ export async function syncGmail(account, cache, io, options = {}) {// Step 1: List message IDs — one pass per (query, cap), each paginated fully up// to its cap and deduped across passes (a thread can appear in both inbox and// sent). See `collectMessageIds` for the pagination contract (#2820).- const messageIds = await collectMessageIds(+ const { items: messageIds, truncated } = await collectMessageIds(passes,async ({ q, maxResults, pageToken }) => {const listResult = await gmailClient.users.messages.list({@@ -228,6 +237,14 @@ export async function syncGmail(account, cache, io, options = {}) {},{ onProgress: (current) => io?.emit('messages:sync:progress', { accountId: account.id, current, total: totalCap }) },);+ // Sent-coverage fail-closed signal (#2820): the sent pass hit its ceiling with+ // more pages remaining, so an older reply may be un-ingested this scan. Reported+ // up so the reply-detection watermark is marked partial and the outreach detector+ // drops the account rather than nudging on incomplete reply evidence.+ const sentTruncated = ingestSent && truncated.includes(sentQuery());+ if (sentTruncated) {+ console.warn(`📧 Gmail sent-mail coverage partial for ${account.email} — >${SENT_INGEST_MAX} sent in ${SENT_INGEST_DAYS}d; reply detection paused for this account until a full sync`);+ }console.log(`📧 Gmail: found ${messageIds.length} message IDs, fetching details`);@@ -303,7 +320,7 @@ export async function syncGmail(account, cache, io, options = {}) {}console.log(`📧 Gmail API sync complete: ${inboxMessages.length} inbox, ${sentMessages.length} sent (activity-only)`);- return { messages: inboxMessages, sentMessages, status: 'success', syncMethod: 'api' };+ return { messages: inboxMessages, sentMessages, sentTruncated, status: 'success', syncMethod: 'api' };}/**diff --git a/server/services/messageGmailSync.test.js b/server/services/messageGmailSync.test.jsindex 4354d41f2d..3e0c593bd1 100644--- a/server/services/messageGmailSync.test.js+++ b/server/services/messageGmailSync.test.js@@ -78,17 +78,25 @@ describe('collectMessageIds — full pagination', () => {// 250 sent messages — a reply at index 200 lives well beyond the first page.const sentQ = sentQuery();const passes = [{ query: sentQ, cap: SENT_INGEST_MAX }];- const ids = await collectMessageIds(passes, pagingListFn({ [sentQ]: 250 }));- expect(ids).toHaveLength(250);- expect(ids.some((m) => m.id === `${sentQ}#200`)).toBe(true); // the far reply is fetched+ const { items, truncated } = await collectMessageIds(passes, pagingListFn({ [sentQ]: 250 }));+ expect(items).toHaveLength(250);+ expect(items.some((m) => m.id === `${sentQ}#200`)).toBe(true); // the far reply is fetched+ expect(truncated).toEqual([]); // fully covered — under the ceiling});- it('stops at the pass cap when the window exceeds the ceiling (bounded fail-safe)', async () => {+ it('stops at the pass cap AND reports truncation when the window exceeds the ceiling', async () => {const sentQ = sentQuery();const passes = [{ query: sentQ, cap: SENT_INGEST_MAX }];- const ids = await collectMessageIds(passes, pagingListFn({ [sentQ]: SENT_INGEST_MAX + 500 }));- expect(ids.length).toBeLessThanOrEqual(SENT_INGEST_MAX);- expect(ids.length).toBeGreaterThanOrEqual(SENT_INGEST_MAX); // fills exactly to the ceiling+ const { items, truncated } = await collectMessageIds(passes, pagingListFn({ [sentQ]: SENT_INGEST_MAX + 500 }));+ expect(items).toHaveLength(SENT_INGEST_MAX); // fills exactly to the ceiling+ expect(truncated).toEqual([sentQ]); // fail-closed signal — coverage incomplete+ });++ it('does not report truncation when the last page exactly fills the cap with no more pages', async () => {+ const sentQ = sentQuery();+ const passes = [{ query: sentQ, cap: SENT_INGEST_MAX }];+ const { truncated } = await collectMessageIds(passes, pagingListFn({ [sentQ]: SENT_INGEST_MAX }));+ expect(truncated).toEqual([]); // exhausted the window exactly — not truncated});it('dedupes an id that appears in both the inbox and sent passes', async () => {@@ -99,8 +107,8 @@ describe('collectMessageIds — full pagination', () => {if (call === 1) return { messages: [{ id: 'a' }, { id: 'b' }], nextPageToken: null };return { messages: [{ id: 'b' }, { id: 'c' }], nextPageToken: null };};- const ids = await collectMessageIds([{ query: 'in:inbox', cap: 100 }, { query: 'in:sent', cap: 100 }], listFn);- expect(ids.map((m) => m.id)).toEqual(['a', 'b', 'c']);+ const { items } = await collectMessageIds([{ query: 'in:inbox', cap: 100 }, { query: 'in:sent', cap: 100 }], listFn);+ expect(items.map((m) => m.id)).toEqual(['a', 'b', 'c']);});it('SENT_INGEST_MAX is a generous ceiling well past the old first-page limit of 100', () => {diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex 9037f4aa82..e1e58e6441 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -194,6 +194,9 @@ export async function syncAccount(accountId, io, options = {}) {// Sent mail (Gmail reply-detection ingest, #2796) is activity-only: recorded to// the timeline but never added to the inbox cache/eval/trim. Kept separate here.const sentMessages = Array.isArray(providerResult) ? [] : (providerResult?.sentMessages ?? []);+ // Whether the sent window truncated at its ceiling this sync (#2820) — coverage+ // is then partial, so the reply-detection watermark is marked partial (fail closed).+ const sentTruncated = Array.isArray(providerResult) ? false : Boolean(providerResult?.sentTruncated);// Deduplicate by externalId; update flags and body on existing messagesconst existingMap = new Map(cache.messages.filter(m => m.externalId).map(m => [m.externalId, m]));@@ -264,7 +267,9 @@ export async function syncAccount(accountId, io, options = {}) {// account default-on at upgrade (or after an OAuth/sync failure) would be trusted// before any reply evidence exists, producing false "unanswered" nudges.if (providerStatus === 'success' && account.type === 'gmail' && account.syncConfig?.ingestSent !== false) {- await markSentIngested(accountId).catch((err) =>+ // `partial` fails the account closed for the outreach detector when the sent+ // window truncated at its ceiling this sync (#2820) — incomplete reply evidence.+ await markSentIngested(accountId, { partial: sentTruncated }).catch((err) =>console.error(`🤝 Sent-ingest watermark failed for account ${accountId}: ${err.message}`));}diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.jsindex 5d8a124ccf..ee93bbdcf7 100644--- a/server/services/tribeOutreach.js+++ b/server/services/tribeOutreach.js@@ -77,6 +77,10 @@ const SENT_INGEST_SOURCES = new Set(['gmail']);* so every inbound would read as unanswered);* - it is enabled (a disabled account never syncs, so its sent history never* updates — trusting it would nudge on stale/absent reply evidence);+ * - its last sent sync was NOT truncated (`sentCoveragePartial !== true`, #2820):+ * a sync that hit the sent ceiling (>SENT_INGEST_MAX in the window) has an+ * incomplete sent window, so an un-ingested older reply could read as+ * unanswered — fail closed until a full sync clears the flag;* - it has a RECENT sent-ingest watermark (`sentIngestedAt` within `coverageMs`).* This is the reliability guard: an account default-on at upgrade, or one whose* OAuth/sync has been failing, has no current sent evidence — trusting it on@@ -98,6 +102,10 @@ export function buildTwoWayGate(accounts = [], { now = Date.now(), coverageMs =if (a?.syncConfig?.ingestSent === false) return false;if (String(a?.email || '').trim() === '') return false;if (a?.enabled === false) return false;+ // The last sent sync truncated at its ceiling (>SENT_INGEST_MAX in the+ // window, #2820) → an older reply may be un-ingested, so its reply evidence+ // is incomplete and can't be trusted until a full sync clears the flag.+ if (a?.sentCoveragePartial === true) return false;const at = Date.parse(a?.sentIngestedAt);if (Number.isNaN(at)) return false; // never successfully ingested sent mailreturn (now - at) <= coverageMs; // stale watermark → coverage can't be trusteddiff --git a/server/services/tribeOutreach.test.js b/server/services/tribeOutreach.test.jsindex 22b7223250..3ba46a6d55 100644--- a/server/services/tribeOutreach.test.js+++ b/server/services/tribeOutreach.test.js@@ -224,6 +224,15 @@ describe('buildTwoWayGate (per-account #2796)', () => {expect(buildTwoWayGate([gmail({ sentIngestedAt: stale })], OPTS).isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(false);});+ it('a PARTIAL sent-coverage watermark drops the account (#2820 — truncated sent window)', () => {+ // The last sync hit the sent ceiling → incomplete reply evidence → fail closed,+ // even with a fresh watermark, until a full sync clears the flag.+ const gate = buildTwoWayGate([gmail({ sentCoveragePartial: true })], OPTS);+ expect(gate.sources).not.toContain('gmail');+ expect(gate.emailAccounts).toEqual([]);+ expect(gate.isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(false);+ });+it('does NOT let one Gmail account vouch for another (per-account, not source-wide)', () => {// g1 ingests sent; g2 opted out. Both are source `gmail`, but only g1's events// are trustworthy — a source-wide gate would wrongly trust g2's inbound too.