Skip to content

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

refactor([issue-2855]): share one email normalizer and repair already-learned alias sets at boot

[._.]/ Adam Eivy2dffc35b8195
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0626372793..7030cb0163 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -7,7 +7,7 @@
## Tribe outreach
- **[issue-2831] Unanswered 1:1 emails to a Gmail alias now surface as outreach nudges** — a message delivered to one of your Gmail send-as aliases (not your primary address) is correctly treated as a one-on-one conversation instead of a group thread, so a genuinely unanswered email to an alias no longer gets silently skipped. Your own alias addresses never appear as a Tribe contact.
-- **[issue-2855] Alias-addressed emails already on your timeline get repaired too** — the first time an account's Gmail send-as aliases are learned, existing activity entries that still list your own alias as a participant are cleaned up in place. Previously only newly-synced mail benefited, so an unanswered 1:1 sent to an alias before the upgrade stayed invisible to outreach nudges until it aged out of the two-week window.
+- **[issue-2855] Alias-addressed emails already on your timeline get repaired too** — existing activity entries that still list one of your own Gmail aliases as a participant are cleaned up in place — once at upgrade for aliases already on file, and again whenever an account learns a new alias. Previously only newly-synced mail benefited, so an unanswered 1:1 sent to an alias before the upgrade stayed invisible to outreach nudges until it aged out of the two-week window.
## Render Queue
diff --git a/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.js b/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.js
new file mode 100644
index 0000000000..ac25f42cc3
--- /dev/null
+++ b/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.js
@@ -0,0 +1,47 @@
+/**
+ * 001 — strip already-known Gmail send-as aliases from stored activity participants (#2855).
+ *
+ * `messageActivityCandidates` excludes every owner address (primary + send-as
+ * aliases) from a received message's participants, but rows recorded BEFORE an
+ * account's alias set was learned kept the alias as a second participant. Because
+ * activity inserts are `ON CONFLICT (source, dedupe_key) DO NOTHING` (a deliberate
+ * "re-syncs are no-ops" contract), a re-sync never rewrites them — so a 1:1 email
+ * delivered to an alias keeps looking like a group thread to the Tribe-outreach
+ * detector.
+ *
+ * The sync path (`messageSync.repairActivityAliasParticipants`) repairs rows when
+ * an account learns a NEW alias, but that delta trigger can't help an install whose
+ * alias set was ALREADY learned by an earlier build — the set never changes again,
+ * so the trigger never fires. This migration closes that gap once, at upgrade, by
+ * stripping every currently-stored alias from that account's existing rows.
+ *
+ * Idempotent by construction (the `EXISTS` gate means a second run matches nothing),
+ * and recorded in `schema_migrations` so it only runs once anyway.
+ */
+import { join } from 'path';
+import { PATHS, safeJSONParse, tryReadFile } from '../../lib/fileUtils.js';
+import { isPlainObject } from '../../lib/objects.js';
+import { stripParticipantsForAccount } from '../../services/humanActivity.js';
+
+export async function up(client) {
+ const content = await tryReadFile(join(PATHS.messages, 'accounts.json'));
+ if (!content) return; // no message accounts on this install — nothing to repair
+ const parsed = safeJSONParse(content, {}, { context: 'migration-001-send-as-aliases' });
+ if (!isPlainObject(parsed)) return;
+
+ let repaired = 0;
+ for (const account of Object.values(parsed)) {
+ if (!account?.id) continue;
+ // Reuses the service's scoped rewrite, but on the migration's transaction
+ // client so the repair shares this migration's all-or-nothing semantics.
+ repaired += await stripParticipantsForAccount(
+ account.id,
+ account.type || 'message',
+ account.sendAsAliases,
+ { client },
+ );
+ }
+ if (repaired > 0) {
+ console.log(`🗓️ Migration 001: stripped owner send-as aliases from ${repaired} activity event(s)`);
+ }
+}
diff --git a/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.test.js b/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.test.js
new file mode 100644
index 0000000000..77a2838e21
--- /dev/null
+++ b/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.test.js
@@ -0,0 +1,74 @@
+/**
+ * Tests for migration 001 (#2855) — no live DB: the pg transaction client is a
+ * stub that records the statements the migration issues, and the accounts file
+ * is mocked. Asserts the migration reads each account's ALREADY-stored send-as
+ * aliases and issues the scoped repair on the supplied transaction client (the
+ * gap the sync-path delta trigger can't close, since the set never changes again
+ * on an install that learned it under an earlier build).
+ *
+ * `*.test.js` files in this directory are ignored by the migration runner.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const tryReadFile = vi.fn();
+vi.mock('../../lib/fileUtils.js', () => ({
+ tryReadFile,
+ PATHS: { messages: '/mock/data/messages', data: '/mock/data' },
+ safeJSONParse: (content, fallback) => { try { return JSON.parse(content); } catch { return fallback; } },
+ ensureDir: vi.fn(),
+ atomicWrite: vi.fn(),
+}));
+
+const { up } = await import('./001-strip-send-as-aliases-from-activity-participants.js');
+
+const makeClient = () => {
+ const calls = [];
+ return { calls, query: (sql, params) => { calls.push({ sql, params }); return Promise.resolve({ rowCount: 1 }); } };
+};
+
+const accountsFile = (accounts) => JSON.stringify(accounts);
+
+describe('migration 001 — strip send-as aliases from activity participants (#2855)', () => {
+ beforeEach(() => tryReadFile.mockReset());
+
+ it('repairs each account that already has stored aliases, scoped by id + type', async () => {
+ tryReadFile.mockResolvedValue(accountsFile({
+ a: { id: 'acct-a', type: 'gmail', sendAsAliases: ['[email protected]'] },
+ b: { id: 'acct-b', type: 'outlook', sendAsAliases: ['[email protected]', '[email protected]'] },
+ }));
+ const client = makeClient();
+ await up(client);
+ expect(client.calls).toHaveLength(2);
+ // Aliases are normalized (lowercased) before they reach the statement.
+ expect(client.calls[0].params).toEqual(['acct-a', 'gmail', ['[email protected]']]);
+ expect(client.calls[1].params).toEqual(['acct-b', 'outlook', ['[email protected]', '[email protected]']]);
+ expect(client.calls[0].sql).toContain('UPDATE human_activity_events');
+ });
+
+ it('skips accounts with no aliases, no id, or a non-Gmail account that never learned any', async () => {
+ tryReadFile.mockResolvedValue(accountsFile({
+ a: { id: 'acct-a', type: 'gmail', sendAsAliases: [] },
+ b: { id: 'acct-b', type: 'outlook' },
+ c: { type: 'gmail', sendAsAliases: ['[email protected]'] }, // no id — unscopeable
+ }));
+ const client = makeClient();
+ await up(client);
+ expect(client.calls).toHaveLength(0);
+ });
+
+ it('is a no-op on an install with no message accounts file', async () => {
+ tryReadFile.mockResolvedValue(null);
+ const client = makeClient();
+ await up(client);
+ expect(client.calls).toHaveLength(0);
+ });
+
+ it('is a no-op when the accounts file is corrupt or not an object', async () => {
+ const client = makeClient();
+ tryReadFile.mockResolvedValue('{ not json');
+ await up(client);
+ tryReadFile.mockResolvedValue('[]');
+ await up(client);
+ expect(client.calls).toHaveLength(0);
+ });
+});
diff --git a/server/services/humanActivity.db.test.js b/server/services/humanActivity.db.test.js
index 088ce4cc66..c3705ae86b 100644
--- a/server/services/humanActivity.db.test.js
+++ b/server/services/humanActivity.db.test.js
@@ -221,10 +221,19 @@ describe.skipIf(!dbReady)('stripParticipantsForAccount — send-as alias backfil
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);
+ it('runs on a caller-supplied transaction client when one is passed (boot migration path)', async () => {
+ await recordEvents([aliasRow({
+ dedupeKey: 'alias-tx',
+ participants: [{ email: '[email protected]' }, { email: ALIAS }],
+ })]);
+ // A thin client shim over the pool is enough to prove the option routes the
+ // statement through the supplied client instead of the module's own query().
+ const calls = [];
+ const client = { query: (sql, params) => { calls.push(sql); return query(sql, params); } };
+ const repaired = await stripParticipantsForAccount(ACCT, ALIAS_SOURCE, [ALIAS], { client });
+ expect(repaired).toBe(1);
+ expect(calls).toHaveLength(1);
+ const row = await fetchRow('alias-tx');
+ expect(row.participants).toEqual([{ email: '[email protected]' }]);
});
});
diff --git a/server/services/humanActivity.js b/server/services/humanActivity.js
index 6f7d451570..264b28759d 100644
--- a/server/services/humanActivity.js
+++ b/server/services/humanActivity.js
@@ -22,6 +22,7 @@
*/
import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureSchema, query } from '../lib/db.js';
+import { normalizeIdentifier } from '../lib/tribeMatch.js';
import { getUserTimezone, getLocalParts, getUtcOffsetMs, todayInTimezone } from '../lib/timezone.js';
// ---------------------------------------------------------------------------
@@ -162,7 +163,14 @@ export function summarizeCounts(events) {
function participantEmail(p) {
if (!p) return '';
- return String((typeof p === 'string' ? p : p.email) || '').trim().toLowerCase();
+ return normalizeIdentifier(typeof p === 'string' ? p : p.email);
+}
+
+// Lowercase + trim + dedupe a list of email addresses, dropping empties. Shares
+// `normalizeIdentifier` with the Tribe matcher so owner-address comparison here
+// can't drift from the identity matching that consumes these events.
+export function normalizeEmailList(list) {
+ return [...new Set((Array.isArray(list) ? list : []).map(normalizeIdentifier).filter(Boolean))];
}
// Map an account's cached messages to activity candidates. Direction (sent vs
@@ -176,9 +184,7 @@ export function messageActivityCandidates(account, messages = []) {
// (messageGmailSync → messageAccounts.sendAsAliases); absent/failed fetch leaves the
// set as just the primary email, i.e. today's behavior.
const ownerEmails = new Set(
- [selfEmail, ...(Array.isArray(account?.sendAsAliases) ? account.sendAsAliases : [])]
- .map((e) => String(e || '').trim().toLowerCase())
- .filter(Boolean)
+ normalizeEmailList([selfEmail, ...(Array.isArray(account?.sendAsAliases) ? account.sendAsAliases : [])])
);
const source = account?.type || 'message';
const accountId = account?.id || null;
@@ -237,11 +243,8 @@ export function messageActivityCandidates(account, messages = []) {
// 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));
+ const before = new Set(normalizeEmailList(previous));
+ return normalizeEmailList(next).filter((e) => !before.has(e));
}
// Resolve a calendar time value to a UTC instant, interpreting OFFSET-LESS
@@ -402,33 +405,50 @@ async function insertActivityChunk(rows) {
// 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),
- )];
+//
+// `client` (optional) runs the rewrite on a caller-supplied pg transaction client
+// instead of the pool — the boot db-migration that repairs already-known alias
+// sets passes its transaction client so the repair shares the migration's
+// all-or-nothing semantics, without re-stating the statement.
+//
+// The EXISTS gate keeps the rewrite off rows that don't need it (so a re-run is a
+// genuine no-op and reports 0 rows), and jsonb_agg over the filtered elements
+// rebuilds the array. COALESCE covers the all-owner row: jsonb_agg returns NULL
+// over an empty set, which would null the column.
+//
+// The predicate is deliberately stated twice (positive in EXISTS, negated in the
+// rebuild) rather than shared via one LATERAL unnest: Postgres rejects an
+// `UPDATE t … FROM LATERAL (… t.col …)` with "invalid reference to FROM-clause
+// entry", so the target row's participants can't be expanded once and reused.
+const STRIP_OWNER_PARTICIPANTS_SQL = `
+ 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[])
+ )`;
+
+export async function stripParticipantsForAccount(accountId, source, aliasEmails = [], { client } = {}) {
+ const emails = normalizeEmailList(aliasEmails);
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 params = [String(accountId), String(source), emails];
+ let result;
+ if (client) {
+ // The migration runner ensures the base schema before applying migrations,
+ // so ensureReady() (which would go through the pool) is neither needed nor
+ // safe to run inside someone else's transaction.
+ result = await client.query(STRIP_OWNER_PARTICIPANTS_SQL, params);
+ } else {
+ await ensureReady();
+ result = await query(STRIP_OWNER_PARTICIPANTS_SQL, params);
+ }
const repaired = result.rowCount || 0;
if (repaired > 0) {
console.log(`🗓️ Repaired ${repaired} activity event(s) for account ${accountId} (${emails.length} owner alias(es) stripped)`);
diff --git a/server/services/humanActivity.test.js b/server/services/humanActivity.test.js
index c49cf91f98..38e3f3b2aa 100644
--- a/server/services/humanActivity.test.js
+++ b/server/services/humanActivity.test.js
@@ -17,6 +17,7 @@ import {
messageActivityCandidates,
calendarActivityCandidates,
newlyLearnedAliases,
+ stripParticipantsForAccount,
} from './humanActivity.js';
describe('shortSummary', () => {
@@ -287,3 +288,19 @@ describe('newlyLearnedAliases (#2855)', () => {
expect(newlyLearnedAliases(null, null)).toEqual([]);
});
});
+
+describe('stripParticipantsForAccount guards (#2855)', () => {
+ // The DB round-trip lives in humanActivity.db.test.js; these cases never reach
+ // the database at all — they assert the early return that keeps a pointless
+ // UPDATE (and a pool connection) off every routine sync.
+ const noDbClient = { query: () => { throw new Error('should not query'); } };
+ it('no-ops when the alias list is empty or normalizes to empty', async () => {
+ expect(await stripParticipantsForAccount('acct-1', 'gmail', [], { client: noDbClient })).toBe(0);
+ expect(await stripParticipantsForAccount('acct-1', 'gmail', ['', null], { client: noDbClient })).toBe(0);
+ expect(await stripParticipantsForAccount('acct-1', 'gmail', 'not-an-array', { client: noDbClient })).toBe(0);
+ });
+ it('no-ops when the account or source scope is missing', async () => {
+ expect(await stripParticipantsForAccount(null, 'gmail', ['[email protected]'], { client: noDbClient })).toBe(0);
+ expect(await stripParticipantsForAccount('acct-1', '', ['[email protected]'], { client: noDbClient })).toBe(0);
+ });
+});