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([issue-2855]): repair stored Gmail activity rows when send-as aliases are first learned
[._.]/ Adam Eivybf9ae6df656b
diff --git a/server/services/humanActivity.db.test.js b/server/services/humanActivity.db.test.jsindex 6adb5a9660..088ce4cc66 100644--- a/server/services/humanActivity.db.test.js+++ b/server/services/humanActivity.db.test.js@@ -3,6 +3,7 @@* - recordEvents() — idempotent insert via ON CONFLICT (source, dedupe_key)* - listEvents() — range / source / kind / personId filters* - getDaySummary() — local-day window + hourly histogram + tallies+ * - stripParticipantsForAccount() — scoped send-as-alias backfill (#2855)** `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`, never* the real `portos` DB (the db.js runner guard + the suite skip below enforce@@ -12,7 +13,7 @@*/import { describe, it, expect, afterAll } from 'vitest';import { checkHealth, ensureSchema, close, query } from '../lib/db.js';-import { recordEvents, listEvents, getDaySummary } from './humanActivity.js';+import { recordEvents, listEvents, getDaySummary, stripParticipantsForAccount } from './humanActivity.js';let dbReady = false;let skipReason = '';@@ -30,10 +31,14 @@ if (!dbReady) console.log(`⏭️ humanActivity.db.test: skipping suite — ${skconst nonce = `ha${Date.now()}`;const SOURCE = `test-${nonce}`;const PERSON = `person-${nonce}`;+// The alias-backfill tests need their own source: stripParticipantsForAccount is+// scoped by (account_id, source), and a shared source would let one test's repair+// touch another's rows.+const ALIAS_SOURCE = `test-${nonce}-alias`;afterAll(async () => {if (dbReady) {- await query('DELETE FROM human_activity_events WHERE source = $1', [SOURCE]).catch(() => {});+ await query('DELETE FROM human_activity_events WHERE source = ANY($1::text[])', [[SOURCE, ALIAS_SOURCE]]).catch(() => {});await close();}});@@ -129,3 +134,97 @@ describe.skipIf(!dbReady)('humanActivity store (#2150)', () => {expect(summary.counts.bySource).toBeTruthy();});});++describe.skipIf(!dbReady)('stripParticipantsForAccount — send-as alias backfill (#2855)', () => {+ const ACCT = `acct-${nonce}`;+ const OTHER_ACCT = `other-${nonce}`;+ const ALIAS = '[email protected]';++ const aliasRow = (over = {}) => ({+ source: ALIAS_SOURCE,+ accountId: ACCT,+ kind: 'message.received',+ happenedAt: '2026-07-04T15:00:00Z',+ title: 'Hey',+ metadata: { handle: '[email protected]', threadId: 't-1' },+ ...over,+ });++ const fetchRow = async (dedupeKey) => {+ const rows = await listEvents({ source: ALIAS_SOURCE, limit: 2000 });+ return rows.find((r) => r.dedupeKey === dedupeKey);+ };++ it('strips the alias from an existing 1:1 row, leaving the sender and metadata.handle intact', async () => {+ await recordEvents([aliasRow({+ dedupeKey: 'alias-1',+ participants: [{ email: '[email protected]' }, { email: ALIAS }],+ })]);++ const repaired = await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [ALIAS]);+ expect(repaired).toBeGreaterThanOrEqual(1);++ const row = await fetchRow('alias-1');+ // Now a true 1:1 — exactly one counterpart, so outreach detection stops+ // rejecting it as a group conversation.+ expect(row.participants).toEqual([{ email: '[email protected]' }]);+ // The sender pointer is untouched — it identifies the person, not the owner.+ expect(row.metadata.handle).toBe('[email protected]');+ });++ it('matches the alias case-insensitively and accepts an unnormalized input list', async () => {+ await recordEvents([aliasRow({+ dedupeKey: 'alias-case',+ participants: [{ email: '[email protected]' }, { email: ALIAS }],+ })]);+ await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [' [email protected] ']);+ const row = await fetchRow('alias-case');+ expect(row.participants).toEqual([{ email: '[email protected]' }]);+ });++ it('leaves rows with no alias participant untouched', async () => {+ const participants = [{ name: 'Pat', email: '[email protected]' }, { email: '[email protected]' }];+ await recordEvents([aliasRow({ dedupeKey: 'alias-none', participants })]);+ await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [ALIAS]);+ const row = await fetchRow('alias-none');+ expect(row.participants).toEqual(participants);+ });++ it('is scoped to the account — another account keeping the same address is untouched', async () => {+ await recordEvents([aliasRow({+ dedupeKey: 'alias-other-acct',+ accountId: OTHER_ACCT,+ participants: [{ email: '[email protected]' }, { email: ALIAS }],+ })]);+ await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [ALIAS]);+ const row = await fetchRow('alias-other-acct');+ expect(row.participants.map((p) => p.email)).toContain(ALIAS);+ });++ it('yields an empty array (not NULL) when every participant was an owner address', async () => {+ await recordEvents([aliasRow({+ dedupeKey: 'alias-all',+ participants: [{ email: ALIAS }],+ })]);+ await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [ALIAS]);+ const row = await fetchRow('alias-all');+ expect(row.participants).toEqual([]);+ });++ it('is idempotent — a second repair matches nothing and reports 0 rows', async () => {+ await recordEvents([aliasRow({+ dedupeKey: 'alias-idem',+ participants: [{ email: '[email protected]' }, { email: ALIAS }],+ })]);+ await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [ALIAS]);+ const second = await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [ALIAS]);+ expect(second).toBe(0);+ });++ it('no-ops without touching the DB when the alias list is empty or the scope is missing', async () => {+ expect(await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [])).toBe(0);+ expect(await stripParticipantsForAccount(null, ALIAS_SOURCE, [ALIAS])).toBe(0);+ expect(await stripParticipantsForAccount(ACCT, '', [ALIAS])).toBe(0);+ expect(await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, ['', null])).toBe(0);+ });+});diff --git a/server/services/humanActivity.js b/server/services/humanActivity.jsindex 27d83f5d57..6f7d451570 100644--- a/server/services/humanActivity.js+++ b/server/services/humanActivity.js@@ -230,6 +230,20 @@ export function messageActivityCandidates(account, messages = []) {return out;}+// Owner addresses present in `next` but not in `previous` — the aliases an+// account just LEARNED (#2855). Only these can appear as a stale participant on+// already-stored rows, so the backfill repairs exactly this set; a removed alias+// needs no repair, and an unchanged set means there is nothing to do (which keeps+// every routine sync from re-UPDATEing the whole table). Lowercased + deduped so+// a casing-only refresh doesn't read as a change.+export function newlyLearnedAliases(previous, next) {+ const norm = (list) => (Array.isArray(list) ? list : [])+ .map((e) => String(e || '').trim().toLowerCase())+ .filter(Boolean);+ const before = new Set(norm(previous));+ return [...new Set(norm(next))].filter((e) => !before.has(e));+}+// Resolve a calendar time value to a UTC instant, interpreting OFFSET-LESS// values in the given timezone instead of the Node process's OS timezone.// Google all-day events are normalized to "YYYY-MM-DDT00:00:00" (no offset) —@@ -374,6 +388,54 @@ async function insertActivityChunk(rows) {return result.rowCount || 0;}+// Repair already-stored events whose participants still list an owner address+// (#2855, follow-up to #2831). `messageActivityCandidates` strips every owner+// address at INSERT time, but rows written BEFORE an account's send-as aliases+// were learned kept the alias as a second participant — and since re-syncs are+// no-ops (`ON CONFLICT (source, dedupe_key) DO NOTHING`, a deliberate contract+// shared with `tribe_touchpoints`), they never self-correct. A 1:1 message+// delivered to an alias therefore keeps looking like a group conversation to+// `findUnansweredTribeThreads` until it ages out of the 14-day window.+//+// This is a SCOPED backfill, not a change to the insert contract: it rewrites+// only rows for one account+source that actually contain one of the named+// alias emails, and only removes those participant entries. `metadata.handle`+// (the counterpart sender) is left untouched. Returns the number of rows+// repaired. Emails are compared lowercased (participants are stored that way).+export async function stripParticipantsForAccount(accountId, source, aliasEmails = []) {+ const emails = [...new Set(+ (Array.isArray(aliasEmails) ? aliasEmails : [])+ .map((e) => String(e || '').trim().toLowerCase())+ .filter(Boolean),+ )];+ if (!accountId || !source || emails.length === 0) return 0;+ await ensureReady();+ // jsonb_agg over the filtered elements rebuilds the array; COALESCE covers the+ // case where every participant was an owner address (jsonb_agg returns NULL for+ // an empty set, which would null out a NOT NULL column).+ const result = await query(+ `UPDATE human_activity_events+ SET participants = COALESCE((+ SELECT jsonb_agg(p)+ FROM jsonb_array_elements(participants) AS p+ WHERE lower(COALESCE(p->>'email', '')) <> ALL($3::text[])+ ), '[]'::jsonb)+ WHERE account_id = $1+ AND source = $2+ AND EXISTS (+ SELECT 1+ FROM jsonb_array_elements(participants) AS p+ WHERE lower(COALESCE(p->>'email', '')) = ANY($3::text[])+ )`,+ [String(accountId), String(source), emails],+ );+ const repaired = result.rowCount || 0;+ if (repaired > 0) {+ console.log(`🗓️ Repaired ${repaired} activity event(s) for account ${accountId} (${emails.length} owner alias(es) stripped)`);+ }+ return repaired;+}+// 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 metadatadiff --git a/server/services/humanActivity.test.js b/server/services/humanActivity.test.jsindex d64ccbc33b..c49cf91f98 100644--- a/server/services/humanActivity.test.js+++ b/server/services/humanActivity.test.js@@ -16,6 +16,7 @@ import {summarizeCounts,messageActivityCandidates,calendarActivityCandidates,+ newlyLearnedAliases,} from './humanActivity.js';describe('shortSummary', () => {@@ -261,3 +262,28 @@ describe('calendarActivityCandidates', () => {expect(z.happenedAt).toBe('2026-07-04T09:00:00.000Z');});});++describe('newlyLearnedAliases (#2855)', () => {+ it('returns only the aliases added since the previous set', () => {+ expect(newlyLearnedAliases(['[email protected]'], ['[email protected]', '[email protected]'])).toEqual(['[email protected]']);+ });+ it('treats a first-ever fetch (no prior set) as all-new', () => {+ expect(newlyLearnedAliases(undefined, ['[email protected]', '[email protected]'])).toEqual(['[email protected]', '[email protected]']);+ expect(newlyLearnedAliases([], ['[email protected]'])).toEqual(['[email protected]']);+ });+ it('is empty for an unchanged set, so a routine sync does no repair work', () => {+ expect(newlyLearnedAliases(['[email protected]', '[email protected]'], ['[email protected]', '[email protected]'])).toEqual([]);+ });+ it('ignores casing and whitespace so a cosmetic refresh is not a change', () => {+ expect(newlyLearnedAliases(['[email protected]'], [' [email protected] '])).toEqual([]);+ });+ it('ignores removals — a dropped alias needs no backfill', () => {+ expect(newlyLearnedAliases(['[email protected]', '[email protected]'], ['[email protected]'])).toEqual([]);+ });+ it('dedupes and drops empty entries', () => {+ expect(newlyLearnedAliases([], ['[email protected]', '[email protected]', '', null])).toEqual(['[email protected]']);+ });+ it('returns [] for non-array input', () => {+ expect(newlyLearnedAliases(null, null)).toEqual([]);+ });+});diff --git a/server/services/messageSync.js b/server/services/messageSync.jsindex ad54395f27..7665c31bc7 100644--- a/server/services/messageSync.js+++ b/server/services/messageSync.js@@ -264,9 +264,16 @@ export async function syncAccount(accountId, io, options = {}) {// Best-effort: a `null` sentinel (fetch failed / non-Gmail provider) leaves the// stored set untouched; persist failure must not fail the sync.if (Array.isArray(sendAsAliases)) {+ // Aliases learned for the FIRST time this sync (#2855). Rows recorded before+ // the alias set was known still carry the alias as a participant, and the+ // `ON CONFLICT DO NOTHING` insert contract means they never self-correct —+ // so repair exactly those rows once, right when the set changes.+ const previousAliases = account.sendAsAliases;account.sendAsAliases = sendAsAliases;await updateSendAsAliases(accountId, sendAsAliases).catch((err) =>console.error(`📧 Send-as alias persist failed for account ${accountId}: ${err.message}`));+ await repairActivityAliasParticipants(account, previousAliases, sendAsAliases).catch((err) =>+ console.error(`🗓️ Activity alias backfill failed for account ${accountId}: ${err.message}`));}// Populate the human-activity timeline (#2150) — secondary effect, must NOT@@ -521,3 +528,14 @@ export async function recordMessageActivity(account, messages = []) {if (candidates.length === 0) return { recorded: 0, skipped: 0 };return recordEvents(candidates);}++// One-shot repair of activity rows recorded BEFORE this account's send-as aliases+// were known (#2855). Runs only for the aliases newly learned this sync, so a+// routine sync with an unchanged set does no DB work at all. Returns the number of+// rows repaired. Secondary effect — the caller must not let it fail the sync.+export async function repairActivityAliasParticipants(account, previousAliases, nextAliases) {+ const { newlyLearnedAliases, stripParticipantsForAccount } = await import('./humanActivity.js');+ const learned = newlyLearnedAliases(previousAliases, nextAliases);+ if (learned.length === 0) return 0;+ return stripParticipantsForAccount(account?.id, account?.type || 'message', learned);+}diff --git a/server/services/messageSyncAliasBackfill.test.js b/server/services/messageSyncAliasBackfill.test.jsnew file mode 100644index 0000000000..8ad42c2de7--- /dev/null+++ b/server/services/messageSyncAliasBackfill.test.js@@ -0,0 +1,76 @@+/**+ * Wiring test for the send-as-alias activity backfill (#2855).+ *+ * The pure diff (`newlyLearnedAliases`) and the JSONB repair+ * (`stripParticipantsForAccount`) are covered in humanActivity.test.js /+ * humanActivity.db.test.js. What's asserted here is the piece neither covers:+ * that a sync which learns a NEW alias triggers the repair with the right scope,+ * and that a sync with an unchanged alias set touches the DB not at all.+ *+ * Lives in its own file so `./humanActivity.js` can be mocked wholesale without+ * affecting the rest of messageSync.test.js.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/fileUtils.js', () => ({+ tryReadFile: vi.fn(),+ atomicWrite: vi.fn().mockResolvedValue(undefined),+ ensureDir: vi.fn(),+ // `data` is needed too: the real humanActivity.js (kept unmocked for its pure+ // helpers) pulls in lib/timezone.js → services/settings.js, which resolves a+ // settings path at module load.+ PATHS: { messages: '/mock/data/messages', data: '/mock/data' },+ safeJSONParse: vi.fn((content, fallback) => (content ? JSON.parse(content) : fallback)),+ UUID_RE: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,+ safeDate: (d) => { const t = new Date(d).getTime(); return Number.isNaN(t) ? 0 : t; },+ filterBySearch: (items) => items,+}));++vi.mock('./messageAccounts.js', () => ({+ getAccount: vi.fn(),+ updateSyncStatus: vi.fn(),+ markSentIngested: vi.fn(() => Promise.resolve()),+ updateSendAsAliases: vi.fn(() => Promise.resolve()),+}));++// Keep the REAL pure helpers (notably `newlyLearnedAliases` — re-stating it in a+// mock would test the mock) and stub only the DB-touching entry points.+const stripParticipantsForAccount = vi.fn(() => Promise.resolve(2));+vi.mock('./humanActivity.js', async (importOriginal) => ({+ ...(await importOriginal()),+ stripParticipantsForAccount,+ recordEvents: vi.fn(() => Promise.resolve({ recorded: 0, skipped: 0 })),+}));++const { repairActivityAliasParticipants } = await import('./messageSync.js');++const account = { id: 'acct-1', type: 'gmail', email: '[email protected]' };++describe('repairActivityAliasParticipants (#2855)', () => {+ beforeEach(() => stripParticipantsForAccount.mockClear());++ it('repairs scoped to the account + source when an alias is learned for the first time', async () => {+ await repairActivityAliasParticipants(account, undefined, ['[email protected]']);+ expect(stripParticipantsForAccount).toHaveBeenCalledWith('acct-1', 'gmail', ['[email protected]']);+ });++ it('repairs only the newly-added alias when the set grows', async () => {+ await repairActivityAliasParticipants(account, ['[email protected]'], ['[email protected]', '[email protected]']);+ expect(stripParticipantsForAccount).toHaveBeenCalledWith('acct-1', 'gmail', ['[email protected]']);+ });++ it('does no DB work when the alias set is unchanged (every routine sync)', async () => {+ await repairActivityAliasParticipants(account, ['[email protected]'], ['[email protected]']);+ expect(stripParticipantsForAccount).not.toHaveBeenCalled();+ });++ it('does no DB work when an alias is only removed', async () => {+ await repairActivityAliasParticipants(account, ['[email protected]', '[email protected]'], ['[email protected]']);+ expect(stripParticipantsForAccount).not.toHaveBeenCalled();+ });++ it('falls back to a generic source when the account has no type', async () => {+ await repairActivityAliasParticipants({ id: 'acct-2' }, [], ['[email protected]']);+ expect(stripParticipantsForAccount).toHaveBeenCalledWith('acct-2', 'message', ['[email protected]']);+ });+});