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
fix: per-account Gmail event capping + account-namespaced conv key + full sent pagination for Tribe outreach (#2820)
[._.]/ Adam Eivy3ac290e882e8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 41c47162e5..77587148f2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -24,6 +24,8 @@- **[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.+## Changed- `[issue-2651]` The CoS `claim-issue-gitlab` work detector now short-circuits the group-owner filter trap the same way `claim-issue` handles a GitHub org owner. A GitLab group-owned project's namespace is the group, which never authors issues, so `owner` author-filter mode previously found nothing and parked with the vague `no-authored-issues` reason. GitLab's owner resolver now resolves the full project namespace (including nested subgroups like `parent/subgroup`) and probes `glab api groups/<url-encoded-namespace>` (200 = group, 404 = user namespace); for a group it skips the guaranteed-empty `--author <group>` query and parks with a distinct `owner-is-group` reason carrying the real open count. The on-demand toast reads *"the \"owner\" filter matches a group, which can't author issues — set it to \"self\" or \"any\""* — GitLab-appropriate wording ("group", not "org"). A probe failure degrades to the pre-existing behavior, so no new transient park appears.diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex 4fd9db3926..a563046071 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -621,6 +621,9 @@ function OutreachQueue() {const seed = {personId: thread.personId,source: thread.source,+ // Scopes the email grounding query to the right account (#2820) — a Gmail+ // threadId is only unique within its account.+ accountId: thread.accountId,threadId: thread.threadId,chatGuid: thread.chatGuid,conversationId: thread.conversationId,diff --git a/server/routes/tribe.js b/server/routes/tribe.jsindex d4f25bf194..a6dbc52a5d 100644--- a/server/routes/tribe.js+++ b/server/routes/tribe.js@@ -65,6 +65,9 @@ const memoryLinkSchema = z.object({const outreachDraftSchema = z.object({personId: z.string().guid().nullable().optional(),source: z.string().max(60).nullable().optional(),+ // Message-account id (#2820) — scopes the email grounding query so a threadId+ // shared across accounts can't merge conversations. Optional/back-compat.+ accountId: z.string().max(200).nullable().optional(),threadId: z.string().max(500).nullable().optional(),chatGuid: z.string().max(500).nullable().optional(),conversationId: z.string().max(500).nullable().optional(),diff --git a/server/services/humanActivity.js b/server/services/humanActivity.jsindex 1ab608bfce..802aa1c36a 100644--- a/server/services/humanActivity.js+++ b/server/services/humanActivity.js@@ -366,14 +366,21 @@ async function insertActivityChunk(rows) {// Query events with optional filters. `from`/`to` are ISO timestamps (inclusive// lower, exclusive upper); `personId` matches a participant via the JSONB// containment operator. `chatGuid` / `handle` match iMessage-style metadata-// pointers. Newest first, capped by `limit` (default 500, max 2000).-export async function listEvents({ from, to, source, kind, personId, chatGuid, conversationId, threadId, handle, limit } = {}) {+// pointers. `accountId` scopes to one source account (#2820). Newest first,+// capped by `limit` (default 500, max 2000).+export async function listEvents({ from, to, source, accountId, kind, personId, chatGuid, conversationId, threadId, handle, limit } = {}) {await ensureReady();const clauses = [];const params = [];if (from) { params.push(new Date(from).toISOString()); clauses.push(`happened_at >= $${params.length}`); }if (to) { params.push(new Date(to).toISOString()); clauses.push(`happened_at < $${params.length}`); }if (source) { params.push(source); clauses.push(`source = $${params.length}`); }+ // Optional per-account scope (#2820): lets a caller cap events one account at a+ // time so a high-volume account can't fill a shared cap and starve another.+ if (accountId != null && String(accountId).length > 0) {+ params.push(String(accountId));+ clauses.push(`account_id = $${params.length}`);+ }if (kind) { params.push(kind); clauses.push(`kind = $${params.length}`); }if (personId) {params.push(JSON.stringify([{ personId: String(personId) }]));diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex 508d0739be..3130570725 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -23,11 +23,15 @@ export const SENT_INGEST_DAYS = 14;// Sent mail gets its OWN fetch budget (a separate list pass), never a share of the// inbox cap — sent is activity-only and must not crowd inbox out of the primary-// sync. This also bounds the per-sync detail-fetch cost (sent isn't cached, so it's-// re-fetched each sync). 14 days of a normal person's replies fit under this; a-// heavier sender whose replies fall beyond it is a filed follow-up (full date-bounded-// pagination / fail-closed) — see the issue linked from the changelog.-export const SENT_INGEST_MAX = 100;+// sync. The sent pass paginates the ENTIRE `in:sent newer_than:14d` window up to+// 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.+export const SENT_INGEST_MAX = 1000;// The inbox search query for a sync mode. `unread` scopes to unread inbox; `full`// takes the whole inbox (capped downstream).@@ -55,6 +59,42 @@ export function gmailSyncPasses(mode, ingestSent, inboxCap) {return passes;}+/**+ * List message ids across every pass, paginating each pass FULLY up to its cap+ * (#2820) — the sent pass must walk past the first page or a heavy sender's reply+ * beyond page 1 goes un-ingested and its inbound falsely reads as unanswered.+ * Dedupes by gmail id across passes (a thread can appear in both inbox and sent).+ *+ * `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+ */+export async function collectMessageIds(passes, listFn, { onProgress } = {}) {+ const messageIds = [];+ const seen = new Set();+ for (const pass of passes) {+ let pageToken = null;+ let fetched = 0;+ do {+ onProgress?.(messageIds.length);+ const { messages = [], nextPageToken = null } = await listFn({+ q: pass.query,+ maxResults: Math.min(100, pass.cap - fetched),+ pageToken,+ });+ fetched += messages.length;+ for (const item of messages) {+ if (seen.has(item.id)) continue;+ seen.add(item.id);+ messageIds.push(item);+ }+ pageToken = nextPageToken;+ } while (pageToken && fetched < pass.cap);+ }+ return messageIds;+}+function getHeader(headers, name) {return headers?.find(h => h.name.toLowerCase() === name.toLowerCase())?.value || '';}@@ -172,35 +212,22 @@ export async function syncGmail(account, cache, io, options = {}) {console.log(`📧 Gmail API sync (${mode}${ingestSent ? '+sent' : ''}) for ${account.email}`);- // Step 1: List message IDs — one pass per (query, cap). Dedupe across passes by- // gmail id (a thread can appear in both inbox and sent) so a message is fetched- // and recorded once.- const messageIds = [];- const seenGmailIds = new Set();-- for (const pass of passes) {- let pageToken = null;- let fetched = 0;- do {- io?.emit('messages:sync:progress', { accountId: account.id, current: messageIds.length, total: totalCap });-+ // 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(+ passes,+ async ({ q, maxResults, pageToken }) => {const listResult = await gmailClient.users.messages.list({userId: 'me',- q: pass.query,- maxResults: Math.min(100, pass.cap - fetched),- ...(pageToken && { pageToken })+ q,+ maxResults,+ ...(pageToken && { pageToken }),});-- const items = listResult.data.messages || [];- fetched += items.length;- for (const item of items) {- if (seenGmailIds.has(item.id)) continue;- seenGmailIds.add(item.id);- messageIds.push(item);- }- pageToken = listResult.data.nextPageToken;- } while (pageToken && fetched < pass.cap);- }+ return { messages: listResult.data.messages || [], nextPageToken: listResult.data.nextPageToken || null };+ },+ { onProgress: (current) => io?.emit('messages:sync:progress', { accountId: account.id, current, total: totalCap }) },+ );console.log(`📧 Gmail: found ${messageIds.length} message IDs, fetching details`);diff --git a/server/services/messageGmailSync.test.js b/server/services/messageGmailSync.test.jsindex a64eeca218..4354d41f2d 100644--- a/server/services/messageGmailSync.test.js+++ b/server/services/messageGmailSync.test.js@@ -4,6 +4,7 @@ import {inboxQuery,sentQuery,gmailSyncPasses,+ collectMessageIds,SENT_INGEST_DAYS,SENT_INGEST_MAX,} from './messageGmailSync.js';@@ -52,3 +53,57 @@ describe('sent-ingest window covers the outreach detection window', () => {expect(SENT_INGEST_DAYS).toBeGreaterThanOrEqual(DEFAULT_WITHIN_DAYS);});});++// #2820: the sent pass must paginate the ENTIRE window (up to the generous ceiling),+// not stop at the first page — a heavy sender's reply beyond page 1 would otherwise+// go un-ingested and its inbound would falsely read as unanswered.+describe('collectMessageIds — full pagination', () => {+ // Build a paginating fake Gmail list: `total` ids in pages of 100, keyed by query+ // so distinct passes don't collide.+ const pagingListFn = (countByQuery) => {+ const cursors = new Map();+ return async ({ q, maxResults, pageToken }) => {+ const total = countByQuery[q] ?? 0;+ const start = pageToken ? Number(pageToken) : 0;+ const end = Math.min(start + maxResults, total);+ const messages = [];+ for (let i = start; i < end; i++) messages.push({ id: `${q}#${i}`, threadId: `t-${i}` });+ const next = end < total ? String(end) : null;+ cursors.set(q, end);+ return { messages, nextPageToken: next };+ };+ };++ it('walks past the first 100 sent results up to the pass cap', async () => {+ // 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+ });++ it('stops at the pass cap when the window exceeds the ceiling (bounded fail-safe)', 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+ });++ it('dedupes an id that appears in both the inbox and sent passes', async () => {+ // Same query id space would collide; simulate cross-pass overlap by hand.+ let call = 0;+ const listFn = async () => {+ call += 1;+ 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']);+ });++ it('SENT_INGEST_MAX is a generous ceiling well past the old first-page limit of 100', () => {+ expect(SENT_INGEST_MAX).toBeGreaterThanOrEqual(1000);+ });+});diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.jsindex 3584277dfa..5d8a124ccf 100644--- a/server/services/tribeOutreach.js+++ b/server/services/tribeOutreach.js@@ -86,7 +86,9 @@ const SENT_INGEST_SOURCES = new Set(['gmail']);** @param {Array} accounts message-account records ({ id, type, email, enabled, syncConfig, sentIngestedAt })* @param {{ now?: number, coverageMs?: number }} opts staleness bound for the watermark- * @returns {{ sources: string[], isTwoWay: (ev: object) => boolean }}+ * @returns {{ sources: string[], emailAccounts: Array<{ id: string, source: string }>, isTwoWay: (ev: object) => boolean }}+ * `emailAccounts` are the two-way email accounts to query PER ACCOUNT (#2820) so+ * one high-volume account can't fill a shared cap and suppress another's nudges.*/export function buildTwoWayGate(accounts = [], { now = Date.now(), coverageMs = Infinity } = {}) {const twoWayEmailAccountIds = new Set(@@ -104,15 +106,19 @@ export function buildTwoWayGate(accounts = [], { now = Date.now(), coverageMs =);// Only scan an email source when at least one of its accounts is two-way — a// one-way-only provider is never queried, so a high-volume inbox can't burn the- // per-source 2000-row cap on data we'd discard anyway.+ // per-account 2000-row cap on data we'd discard anyway.const sources = new Set(TWO_WAY_CHAT_SOURCES);+ const emailAccounts = [];for (const a of accounts || []) {- if (twoWayEmailAccountIds.has(a?.id)) sources.add(a.type);+ if (twoWayEmailAccountIds.has(a?.id)) {+ sources.add(a.type);+ emailAccounts.push({ id: a.id, source: a.type });+ }}const isTwoWay = (ev) =>TWO_WAY_CHAT_SOURCES.has(ev?.source) ||(ev?.accountId != null && twoWayEmailAccountIds.has(ev.accountId));- return { sources: [...sources], isTwoWay };+ return { sources: [...sources], emailAccounts, isTwoWay };}// Channel-appropriate reply prompt for chat outreach — generateReplyBody's default@@ -143,11 +149,17 @@ export function outreachTemplateForSource(source) {// handle-less inbound groupable, but is deliberately last so that sent + received// turns of the SAME thread always share a key (a person fallback would split them// whenever one side lacks a person match — e.g. an iMessage/Signal sent turn).+//+// Email threadId is namespaced by accountId (#2820): a Gmail threadId is only+// unique WITHIN one account, so two accounts that happen to share a threadId value+// would otherwise merge into one (false) conversation — one account's sent turn+// could then "answer" the other's inbound. chatGuid/conversationId are already+// globally unique (iMessage/Signal), so they stay un-namespaced.function conversationKey(event) {const m = event?.metadata || {};if (m.chatGuid) return `chat:${m.chatGuid}`;if (m.conversationId) return `convo:${m.conversationId}`;- if (m.threadId) return `thread:${m.threadId}`;+ if (m.threadId) return `thread:${event?.accountId ?? 'x'}:${m.threadId}`;if (m.handle) return `handle:${String(m.handle).toLowerCase()}`;if (event?.personId) return `person:${event.personId}`;return null;@@ -169,6 +181,9 @@ function threadFields(inbound, eventCount, ageMs) {chatGuid: m.chatGuid || null,conversationId: m.conversationId || null,handle: m.handle || null,+ // Round-trips to draft generation so the grounding query can scope to this+ // account (#2820) — an email threadId is only unique within its account.+ accountId: inbound.accountId || null,lastInboundAt: inbound.happenedAt,daysAgo: Math.floor(ageMs / DAY_MS),// Only the real message text — NOT `title`, which for an attachment-only/@@ -258,10 +273,11 @@ export async function findUnansweredTribeThreads({if (!ctx) return [];const now = Date.now();const withinMs = withinDays * DAY_MS;- // Per-account two-way gate: which sources to scan, and which inbound events are- // trustworthy (chat source-wide, email only from sent-ingesting accounts whose- // reply-evidence watermark covers the detection window).- const { sources: twoWaySources, isTwoWay } = buildTwoWayGate(+ // Per-account two-way gate: which chat sources to scan source-wide, which email+ // accounts to scan per-account, and which inbound events are trustworthy (chat+ // source-wide, email only from sent-ingesting accounts whose reply-evidence+ // watermark covers the detection window).+ const { emailAccounts: twoWayEmailAccounts, isTwoWay } = buildTwoWayGate(await listAccounts().catch(() => []),{ now, coverageMs: withinMs });@@ -272,43 +288,54 @@ export async function findUnansweredTribeThreads({if (!hasTribe) return [];const from = new Date(now - withinMs).toISOString();- // Query each two-way source × kind separately, each with its own 2000-row cap.- // A single shared query would let a high-volume source (e.g. thousands of- // imported email events) fill the newest-2000 slice and push older iMessage /- // Signal turns out of range — missing an alert, or hiding the reply that would- // mark a thread answered.+ const EVENT_CAP = 2000;const received = [];const sent = [];- await Promise.all(twoWaySources.map((src) =>- // Fail CLOSED per source: if EITHER direction's query fails, drop this source's- // turns entirely. Substituting [] for only the failed direction would leave- // received without its sent counterpart, making every inbound look unanswered- // and emitting false nudges — the function's contract is to stay quiet on a- // read failure, not to nudge on half the data.+ // Fetch one scope's received + sent turns under its OWN cap, failing CLOSED.+ // `label` is source-only (never the account id) so nothing sensitive is logged.+ //+ // Fail CLOSED on a read error: if EITHER direction's query fails, drop this+ // scope's turns entirely. Substituting [] for only the failed direction would+ // leave received without its sent counterpart, making every inbound look+ // unanswered and emitting false nudges — the contract is to stay quiet on a read+ // failure, not to nudge on half the data.+ //+ // Fail CLOSED on the cap too: the two directions are capped independently, so a+ // truncated `sent` result could omit an older reply while its inbound survives in+ // `received` — reporting an answered thread as unanswered. Better no nudge for+ // that (very heavy) scope than a false one. (received-cap is a false-negative+ // only, but skip either to be safe.)+ const fetchScope = (label, filter) =>Promise.all([- listEvents({ from, source: src, kind: 'message.received', limit: 2000 }),- listEvents({ from, source: src, kind: 'message.sent', limit: 2000 }),+ listEvents({ ...filter, from, kind: 'message.received', limit: EVENT_CAP }),+ listEvents({ ...filter, from, kind: 'message.sent', limit: EVENT_CAP }),]).then(([r, s]) => {- // Fail CLOSED when either direction hits the 2000-row cap: the two queries- // are capped independently, so a truncated `sent` result could omit an older- // reply while its inbound survives in `received` — reporting an answered- // thread as unanswered. Better no nudge for that (very heavy) source than a- // false one. (received-cap is a false-negative only, but skip either to be safe.)- if (r.length >= 2000 || s.length >= 2000) {- console.warn(`🤝 Skipping ${src} outreach scan — timeline query hit the 2000-row cap (can't verify reply state)`);+ if (r.length >= EVENT_CAP || s.length >= EVENT_CAP) {+ console.warn(`🤝 Skipping ${label} outreach scan — timeline query hit the ${EVENT_CAP}-row cap (can't verify reply state)`);return;}received.push(...r); sent.push(...s);- }).catch(() => { /* partial read → drop this source to avoid false nudges */ })- ));+ }).catch(() => { /* partial read → drop this scope to avoid false nudges */ });++ // Chat sources are queried source-wide (both directions carry the same source,+ // and their conversation keys are globally unique). Email accounts are queried+ // PER ACCOUNT (#2820) under their own cap — a shared per-source query let one+ // high-volume opted-out/heavy account fill the newest-2000 slice and suppress a+ // legitimately opted-in account's nudges.+ await Promise.all([+ ...[...TWO_WAY_CHAT_SOURCES].map((src) => fetchScope(src, { source: src })),+ ...twoWayEmailAccounts.map((acct) =>+ fetchScope(acct.source, { source: acct.source, accountId: acct.id })),+ ]);// Drop Tapbacks/reactions from both directions — a reaction is not a message// awaiting a reply (it must not anchor an "unanswered" thread), and a sent- // reaction is not a real reply (it must not mark a thread answered). Also drop any- // event from a non-two-way account: querying source `gmail` returns events from- // ALL gmail accounts, but only the sent-ingesting ones are trustworthy — a reply- // from a one-way account is invisible, so its inbound must not surface (and its- // sent turns, if any lingered, must not vouch for another account's thread).+ // reaction is not a real reply (it must not mark a thread answered). The+ // `isTwoWay` filter is now a defensive backstop: email is queried per two-way+ // accountId (#2820) so only trustworthy accounts' events are fetched, but the+ // guard still drops any stray one-way event — a reply from a one-way account is+ // invisible, so its inbound must not surface (and its sent turns must not vouch+ // for another account's thread).const tagged = sent.filter((ev) => !ev.metadata?.isReaction && isTwoWay(ev));for (const ev of received) {if (ev.metadata?.isReaction) continue;@@ -375,7 +402,9 @@ export async function generateOutreachDraft(params = {}) {const conversationKey = params.chatGuid || params.conversationId || params.threadId || params.handle || null;// No key to guard on (validated away at the route, but defensive) → run directly.if (!conversationKey) return generateOutreachDraftImpl(params);- const guardKey = `${conversationKey}::${params.lastInboundAt || ''}`;+ // Prefix the accountId (#2820): an email threadId is only unique within its+ // account, so two accounts sharing a threadId must not coalesce onto one guard.+ const guardKey = `${params.accountId ?? ''}::${conversationKey}::${params.lastInboundAt || ''}`;const pending = inflightOutreach.get(guardKey);if (pending) return pending;const promise = generateOutreachDraftImpl(params);@@ -389,6 +418,7 @@ export async function generateOutreachDraft(params = {}) {async function generateOutreachDraftImpl({personId = null,source = null,+ accountId = null,chatGuid = null,conversationId = null,threadId = null,@@ -405,15 +435,23 @@ async function generateOutreachDraftImpl({]);const person = personId ? await getPerson(personId).catch(() => null) : null;- const conversationKey = chatGuid || conversationId || threadId || handle || null;+ // The draft-reuse / guard key. Email threadId is namespaced by accountId (#2820)+ // — it's only unique within its account — while chatGuid/conversationId are+ // globally unique and stay raw. Kept consistent with the detection grouping key.+ const conversationKey = chatGuid || conversationId+ || (threadId ? (accountId ? `thread:${accountId}:${threadId}` : threadId) : null)+ || handle || null;// Ground the reply in the actual conversation, pulled from the timeline by the// DETECTED conversation key — chatGuid (iMessage) / conversationId (Signal) /// threadId (email) / handle (counterpart). NOT personId: message events don't// persist it on their participants, so a personId query returns nothing. Pass- // exactly the most-selective key present (listEvents ANDs its filters).+ // exactly the most-selective key present (listEvents ANDs its filters). For email,+ // also scope by accountId (#2820) so a threadId shared across accounts can't pull+ // another account's turns into the grounding context.const convoEvents = await listEvents({source: source || undefined,+ accountId: accountId || undefined,chatGuid: chatGuid || undefined,conversationId: chatGuid ? undefined : (conversationId || undefined),threadId: (chatGuid || conversationId) ? undefined : (threadId || undefined),diff --git a/server/services/tribeOutreach.test.js b/server/services/tribeOutreach.test.jsindex 1372c8054a..22b7223250 100644--- a/server/services/tribeOutreach.test.js+++ b/server/services/tribeOutreach.test.js@@ -1,19 +1,23 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { groupUnansweredThreads, generateOutreachDraft, buildTwoWayGate, outreachTemplateForSource } from './tribeOutreach.js';+import { groupUnansweredThreads, generateOutreachDraft, findUnansweredTribeThreads, buildTwoWayGate, outreachTemplateForSource } from './tribeOutreach.js';-// generateOutreachDraft dynamically imports these — mock them so the draft-side-// logic (idempotent reuse, anchoring the reply to the detected inbound) is-// testable without a DB or a live LLM.+// generateOutreachDraft / findUnansweredTribeThreads dynamically import these —+// mock them so the draft-side logic (idempotent reuse, anchoring the reply to the+// detected inbound) and the detector are testable without a DB or a live LLM.vi.mock('./tribe.js', () => ({ getPerson: vi.fn() }));vi.mock('./humanActivity.js', () => ({ listEvents: vi.fn() }));vi.mock('./messageEvaluator.js', () => ({ generateReplyBody: vi.fn() }));vi.mock('./messageDrafts.js', () => ({ createDraft: vi.fn(), listDrafts: vi.fn() }));+vi.mock('./identityResolve.js', () => ({ loadResolverContext: vi.fn(), enrichActivityEvent: vi.fn() }));+vi.mock('./messageAccounts.js', () => ({ listAccounts: vi.fn() }));import { getPerson } from './tribe.js';import { listEvents } from './humanActivity.js';import { generateReplyBody } from './messageEvaluator.js';import { createDraft, listDrafts } from './messageDrafts.js';+import { loadResolverContext, enrichActivityEvent } from './identityResolve.js';+import { listAccounts } from './messageAccounts.js';// `groupUnansweredThreads` is the pure detection core — no DB, no LLM. These// tests pin the "unanswered inbound from a Tribe person, within the actionable@@ -138,13 +142,28 @@ describe('groupUnansweredThreads', () => {it('keys email conversations by threadId so sent + received turns unify', () => {const out = groupUnansweredThreads([- { kind: 'message.received', source: 'gmail', personId: 'p1', personName: 'Alex', ring: 'tribe',+ { kind: 'message.received', source: 'gmail', accountId: 'acct-a', personId: 'p1', personName: 'Alex', ring: 'tribe',happenedAt: daysAgo(4), summary: 'proposal attached', metadata: { threadId: 't-9' } },- { kind: 'message.sent', source: 'gmail', happenedAt: daysAgo(3), metadata: { threadId: 't-9' } },+ { kind: 'message.sent', source: 'gmail', accountId: 'acct-a', happenedAt: daysAgo(3), metadata: { threadId: 't-9' } },], WINDOW);expect(out).toHaveLength(0); // replied within the same email thread});+ it('does NOT merge two accounts that share a threadId value (#2820)', () => {+ // A Gmail threadId is only unique within one account. Account A got an inbound;+ // account B sent a reply on ITS OWN thread that happens to share the id value.+ // Namespacing by accountId keeps them separate so B's reply can't answer A's+ // inbound — A's thread must still surface as unanswered.+ const out = groupUnansweredThreads([+ { kind: 'message.received', source: 'gmail', accountId: 'acct-a', personId: 'p1', personName: 'Alex', ring: 'tribe',+ happenedAt: daysAgo(4), summary: 'proposal attached', metadata: { threadId: 'shared-id' } },+ { kind: 'message.sent', source: 'gmail', accountId: 'acct-b', happenedAt: daysAgo(3), metadata: { threadId: 'shared-id' } },+ ], WINDOW);+ expect(out).toHaveLength(1);+ expect(out[0].conversationKey).toBe('thread:acct-a:shared-id');+ expect(out[0].accountId).toBe('acct-a');+ });+it('ignores Tapback/reaction turns — a reaction neither anchors nor answers', () => {// A reaction as the last inbound must NOT create an unanswered nudge.const out = groupUnansweredThreads([@@ -215,6 +234,8 @@ describe('buildTwoWayGate (per-account #2796)', () => {expect(gate.sources).toContain('gmail'); // scanned because g1 is two-wayexpect(gate.isTwoWay({ source: 'gmail', accountId: 'g1' })).toBe(true);expect(gate.isTwoWay({ source: 'gmail', accountId: 'g2' })).toBe(false);+ // Only g1 is surfaced for per-account querying (#2820) — g2 is never queried.+ expect(gate.emailAccounts).toEqual([{ id: 'g1', source: 'gmail' }]);});it('Outlook is never two-way (no sent-fetch path yet), even with ingestSent:true', () => {@@ -241,6 +262,61 @@ describe('outreachTemplateForSource (#2796)', () => {});});+describe('findUnansweredTribeThreads — per-account email querying (#2820)', () => {+ const RECENT = new Date(NOW - 3600000).toISOString();++ beforeEach(() => {+ vi.clearAllMocks();+ // One tribe person, resolved from the inbound's handle.+ loadResolverContext.mockResolvedValue({ people: [{ id: 'p1', ring: 'tribe', name: 'Alex' }] });+ enrichActivityEvent.mockReturnValue({ personId: 'p1', displayName: 'Alex' });+ });++ it('queries each two-way Gmail account under its OWN cap so a noisy account cannot suppress an opted-in one', async () => {+ // acct-opted is two-way; acct-noisy opted out (high volume, never trustworthy).+ listAccounts.mockResolvedValue([+ { id: 'acct-opted', type: 'gmail', email: '[email protected]', enabled: true, syncConfig: {}, sentIngestedAt: RECENT },+ { id: 'acct-noisy', type: 'gmail', email: '[email protected]', enabled: true, syncConfig: { ingestSent: false }, sentIngestedAt: RECENT },+ ]);++ const openInbound = {+ kind: 'message.received', source: 'gmail', accountId: 'acct-opted',+ happenedAt: daysAgo(3), summary: 'lunch soon?',+ metadata: { threadId: 't-opted', handle: '[email protected]' },+ };++ // Per-account query returns the opted account's unanswered inbound; a source-wide+ // gmail query (no accountId — the OLD, cap-sharing path) would return a full+ // noisy slice with NO opted inbound, suppressing the nudge. Chat sources empty.+ listEvents.mockImplementation(async ({ source, accountId, kind }) => {+ if (source === 'gmail' && accountId === 'acct-opted') {+ return kind === 'message.received' ? [openInbound] : [];+ }+ if (source === 'gmail' && accountId == null) {+ // Simulate the pre-#2820 cap-filling noise (2000 rows, none from acct-opted).+ return kind === 'message.received'+ ? Array.from({ length: 2000 }, (_, i) => ({+ kind: 'message.received', source: 'gmail', accountId: 'acct-noisy',+ happenedAt: daysAgo(1), summary: `noise ${i}`, metadata: { threadId: `n-${i}` },+ }))+ : [];+ }+ return [];+ });++ const threads = await findUnansweredTribeThreads();++ // The opted-in account's nudge surfaces despite the noisy account's volume.+ expect(threads).toHaveLength(1);+ expect(threads[0]).toMatchObject({ personId: 'p1', source: 'gmail', threadId: 't-opted', accountId: 'acct-opted' });+ // It queried the opted account PER ACCOUNT and never ran a cap-sharing+ // source-wide gmail query.+ const gmailCalls = listEvents.mock.calls.map(([a]) => a).filter((a) => a.source === 'gmail');+ expect(gmailCalls.every((a) => a.accountId === 'acct-opted')).toBe(true);+ expect(gmailCalls.length).toBeGreaterThan(0);+ });+});+describe('generateOutreachDraft', () => {beforeEach(() => {vi.clearAllMocks();