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

feat: auto-log Tribe touchpoints from calendar + messages (#2033)

Adam Eivy25eee517e79e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7f39a644f3..dbf8b55941 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,7 @@
## Tribe
+- **Tribe touchpoints now auto-log from synced calendar events and messages (#2033).** The Tribe model always supported `source: 'calendar'|'message'` touchpoints but nothing produced them. You can now record known emails/handles on a person (new "Emails & handles" field), and whenever a calendar sync or message sync ingests an event/message involving that person, PortOS logs a touchpoint automatically — deterministic email/handle matching (plus exact unique-name fallback), no LLM calls. Calendar touchpoints dedupe per event id and only count events that have already happened; message touchpoints dedupe per thread + day so a long thread doesn't spam the timeline. Auto-logged touchpoints advance `last_contact_on` so overdue/cadence status reflects them, and the Tribe timeline shows each touchpoint's source with an icon (Calendar / Message / Manual). Matching is pure and unit-tested (`server/lib/tribeMatch.js`); idempotency is enforced by a partial unique index on `(person_id, dedupe_key)`.
- **"Who needs care" now surfaces outside the Tribe page — as a Proactive Alert and a dashboard widget (#2032).** Overdue-contact status is now computed server-side (`getCareSummary`/`personCadenceStatus` in `server/services/tribe.js`, exposed at `GET /api/tribe/care`) as a single source of truth mirroring the Tribe page's cadence logic. Proactive Alerts gains a `checkTribeCadence()` check that emits "N people are overdue for contact" linking to `/tribe` (quiet when none are), and a new gated `Tribe Care` dashboard widget lists the most-overdue people (or an "all caught up" state), hidden entirely on installs with no Tribe people.
## Delete confirmations
diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsx
index 014cf8cd34..650c8c055b 100644
--- a/client/src/pages/Tribe.jsx
+++ b/client/src/pages/Tribe.jsx
@@ -53,6 +53,7 @@ const emptyDraft = () => ({
channel: '',
energy: 'steady',
tags: '',
+ emails: '',
nextMove: '',
notes: '',
});
@@ -300,6 +301,18 @@ function ContactForm({ draft, onChange, onSave, onDelete, onNew, isExisting, sav
placeholder="comma, separated"
/>
</label>
+ <label className="block sm:col-span-2">
+ <span className="text-xs text-gray-500">Emails &amp; handles</span>
+ <input
+ value={draft.emails}
+ onChange={(event) => update('emails', event.target.value)}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ />
+ <span className="mt-1 block text-[11px] text-gray-600">
+ Auto-logs a touchpoint when this person appears in a synced calendar event or message.
+ </span>
+ </label>
<label className="block sm:col-span-2">
<span className="text-xs text-gray-500">Next Move</span>
<textarea
@@ -452,6 +465,26 @@ function MemoryLinksPanel({ personId }) {
);
}
+// Icon + label per touchpoint source so an auto-logged calendar/message
+// touchpoint is visually distinct from a hand-logged one (#2033).
+const SOURCE_BADGES = {
+ calendar: { Icon: Calendar, label: 'Calendar' },
+ message: { Icon: MessageCircle, label: 'Message' },
+ import: { Icon: Users, label: 'Import' },
+ user: { Icon: UserRound, label: 'Manual' },
+};
+
+function TouchpointSource({ source }) {
+ const badge = SOURCE_BADGES[source] || SOURCE_BADGES.user;
+ const { Icon, label } = badge;
+ return (
+ <span className="inline-flex items-center gap-1" title={`Source: ${label}`}>
+ <Icon size={12} aria-hidden="true" />
+ {label}
+ </span>
+ );
+}
+
function TouchpointsPanel({ personId }) {
const [touchpoints, setTouchpoints] = useState([]);
@@ -474,7 +507,7 @@ function TouchpointsPanel({ personId }) {
<div key={touchpoint.id} className="rounded border border-port-border bg-port-bg p-3">
<div className="flex items-center justify-between gap-3 text-xs text-gray-500">
<span>{touchpoint.happenedAt?.slice(0, 10)}</span>
- <span>{touchpoint.source}</span>
+ <TouchpointSource source={touchpoint.source} />
</div>
<p className="mt-1 text-sm text-gray-300">{touchpoint.summary || touchpoint.channel || 'Touchpoint'}</p>
</div>
@@ -728,6 +761,7 @@ export default function Tribe() {
...emptyDraft(),
...contact,
tags: tagsToInput(contact.tags),
+ emails: tagsToInput(contact.emails),
cadenceDays: contact.cadenceDays || ringFor(contact.ring).cadenceDays,
});
@@ -744,6 +778,7 @@ export default function Tribe() {
channel: draft.channel.trim(),
energy: draft.energy,
tags: tagsToArray(draft.tags),
+ emails: tagsToArray(draft.emails),
nextMove: draft.nextMove.trim(),
notes: draft.notes.trim(),
};
diff --git a/server/lib/README.md b/server/lib/README.md
index 169f1438c5..4762f96fb7 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -230,6 +230,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). |
| `timezone.js` | Timezone utilities for scheduling. |
| `tribeCadence.js` | Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to `client/src/lib/tribeCadence.js`): `cadenceStatus(entity)` → `{ state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS` (45), `SOON_WINDOW_DAYS` (7). Consumed by `personCadenceStatus` / `getCareSummary` in `services/tribe.js` (proactive alert + Care widget) and by the client Tribe page/map. |
+| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033): `buildPersonMatchIndex(people)` → `{ byIdentifier, byName }`, `matchPerson(identity, index)` (email/handle authoritative, exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`. Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar and message sync producers. |
| `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. |
| `buildId.js` | Build-ID derived from the built client bundle. |
diff --git a/server/lib/db.js b/server/lib/db.js
index 97f347626c..531a4c081a 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -371,8 +371,13 @@ async function ensureSchemaImpl() {
deleted BOOLEAN DEFAULT FALSE,
deleted_at TIMESTAMPTZ
)`,
+ // Known emails/handles for a person — the deterministic key that maps a
+ // calendar attendee / message counterpart back to this tracked person so
+ // touchpoints can be auto-logged (#2033).
+ `ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS emails TEXT[] DEFAULT '{}'`,
`CREATE INDEX IF NOT EXISTS idx_tribe_people_live ON tribe_people (deleted, ring, updated_at DESC)`,
`CREATE INDEX IF NOT EXISTS idx_tribe_people_tags ON tribe_people USING gin (tags)`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_people_emails ON tribe_people USING gin (emails)`,
`CREATE TABLE IF NOT EXISTS tribe_touchpoints (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
@@ -382,11 +387,17 @@ async function ensureSchemaImpl() {
source VARCHAR(32) NOT NULL DEFAULT 'user',
calendar_account_id TEXT,
calendar_event_id TEXT,
+ dedupe_key TEXT,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ // Idempotency key for auto-logged touchpoints (calendar event id / message
+ // thread+day). Partial unique index so re-syncs never double-log a person
+ // for the same event/thread-day; NULL for hand-logged user touchpoints.
+ `ALTER TABLE tribe_touchpoints ADD COLUMN IF NOT EXISTS dedupe_key TEXT`,
`CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_person ON tribe_touchpoints (person_id, happened_at DESC)`,
`CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_calendar ON tribe_touchpoints (calendar_account_id, calendar_event_id)`,
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_tribe_touchpoints_dedupe ON tribe_touchpoints (person_id, dedupe_key) WHERE dedupe_key IS NOT NULL`,
`CREATE TABLE IF NOT EXISTS tribe_memory_links (
person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
memory_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
diff --git a/server/lib/index.js b/server/lib/index.js
index b11e85d472..0fd1fa1795 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -204,6 +204,7 @@ export * from './platform.js';
export * from './ports.js';
export * from './timezone.js';
export * from './tribeCadence.js';
+export * from './tribeMatch.js';
export * from './viteAllowedHosts.js';
// === General utilities ===
diff --git a/server/lib/tribeMatch.js b/server/lib/tribeMatch.js
new file mode 100644
index 0000000000..ecb2c354c5
--- /dev/null
+++ b/server/lib/tribeMatch.js
@@ -0,0 +1,75 @@
+/**
+ * Tribe identity matcher — pure, deterministic mapping of a calendar attendee /
+ * message counterpart ({ email, name }) back to a tracked Tribe person (#2033).
+ *
+ * Matching is intentionally deterministic (no LLM, no fuzzy string distance):
+ * 1. Email / handle — authoritative. Compared case-insensitively against the
+ * identifiers the user stored on the person record (`person.emails`).
+ * 2. Exact name — case-insensitive, and only when EXACTLY ONE tracked person
+ * owns that name (ambiguous names never resolve, so a shared first name can
+ * not mis-log). This is a convenience fallback before the user has recorded
+ * any emails; fuzzy name-matching is a separate consent-gated follow-up.
+ */
+
+export function normalizeIdentifier(value) {
+ if (value == null) return '';
+ return String(value).trim().toLowerCase();
+}
+
+/**
+ * Build lookup indexes from a list of tribe people. Returns
+ * `{ byIdentifier: Map<email, personId>, byName: Map<name, personId[]> }`.
+ * The first person to claim an identifier wins (identifiers are meant to be
+ * unique to one person); names collect every owner so ambiguity is detectable.
+ */
+export function buildPersonMatchIndex(people = []) {
+ const byIdentifier = new Map();
+ const byName = new Map();
+ for (const person of people) {
+ if (!person?.id) continue;
+ for (const identifier of person.emails || []) {
+ const key = normalizeIdentifier(identifier);
+ if (key && !byIdentifier.has(key)) byIdentifier.set(key, person.id);
+ }
+ const nameKey = normalizeIdentifier(person.name);
+ if (nameKey) {
+ const owners = byName.get(nameKey) || [];
+ owners.push(person.id);
+ byName.set(nameKey, owners);
+ }
+ }
+ return { byIdentifier, byName };
+}
+
+/**
+ * Resolve a single `{ email, name }` identity to a personId, or `null`.
+ * Email/handle wins; exact unique name is the fallback.
+ */
+export function matchPerson(identity, index) {
+ if (!identity || !index) return null;
+ const email = normalizeIdentifier(identity.email);
+ if (email && index.byIdentifier.has(email)) return index.byIdentifier.get(email);
+ const name = normalizeIdentifier(identity.name);
+ if (name) {
+ const owners = index.byName.get(name);
+ if (owners && owners.length === 1) return owners[0];
+ }
+ return null;
+}
+
+/**
+ * Resolve many identities (mixed `{ email, name }` objects or bare email/handle
+ * strings) to a de-duplicated Set of personIds. A single event/message that
+ * involves the same tracked person twice (organizer + attendee) yields one id.
+ */
+export function matchPeople(identities = [], index) {
+ const ids = new Set();
+ if (!index) return ids;
+ for (const raw of identities) {
+ if (!raw) continue;
+ const identity = typeof raw === 'string' ? { email: raw } : raw;
+ const id = matchPerson(identity, index);
+ if (id) ids.add(id);
+ }
+ return ids;
+}
diff --git a/server/lib/tribeMatch.test.js b/server/lib/tribeMatch.test.js
new file mode 100644
index 0000000000..82349097cb
--- /dev/null
+++ b/server/lib/tribeMatch.test.js
@@ -0,0 +1,89 @@
+import { describe, it, expect } from 'vitest';
+import {
+ normalizeIdentifier,
+ buildPersonMatchIndex,
+ matchPerson,
+ matchPeople,
+} from './tribeMatch.js';
+
+const PEOPLE = [
+ { id: 'ada', name: 'Ada Lovelace', emails: ['[email protected]', '[email protected]'] },
+ { id: 'grace', name: 'Grace Hopper', emails: ['[email protected]'] },
+ // Two people share the first name "Sam" — an ambiguous name must not resolve.
+ { id: 'sam1', name: 'Sam', emails: [] },
+ { id: 'sam2', name: 'Sam', emails: [] },
+ { id: 'lin', name: 'Lin', emails: [] },
+];
+
+describe('tribeMatch', () => {
+ describe('normalizeIdentifier', () => {
+ it('lowercases and trims', () => {
+ expect(normalizeIdentifier(' [email protected] ')).toBe('[email protected]');
+ });
+ it('returns empty string for nullish', () => {
+ expect(normalizeIdentifier(null)).toBe('');
+ expect(normalizeIdentifier(undefined)).toBe('');
+ });
+ });
+
+ describe('buildPersonMatchIndex', () => {
+ it('indexes every email case-insensitively, first claimant wins', () => {
+ const { byIdentifier } = buildPersonMatchIndex(PEOPLE);
+ expect(byIdentifier.get('[email protected]')).toBe('ada');
+ expect(byIdentifier.get('[email protected]')).toBe('ada');
+ expect(byIdentifier.get('[email protected]')).toBe('grace');
+ });
+ it('collects every owner of a name so ambiguity is detectable', () => {
+ const { byName } = buildPersonMatchIndex(PEOPLE);
+ expect(byName.get('sam')).toEqual(['sam1', 'sam2']);
+ expect(byName.get('lin')).toEqual(['lin']);
+ });
+ it('skips people without an id', () => {
+ const { byIdentifier } = buildPersonMatchIndex([{ name: 'X', emails: ['[email protected]'] }]);
+ expect(byIdentifier.size).toBe(0);
+ });
+ });
+
+ describe('matchPerson', () => {
+ const index = buildPersonMatchIndex(PEOPLE);
+ it('matches by email regardless of case', () => {
+ expect(matchPerson({ email: '[email protected]' }, index)).toBe('ada');
+ });
+ it('falls back to an exact unique name when no email match', () => {
+ expect(matchPerson({ name: 'lin' }, index)).toBe('lin');
+ });
+ it('refuses an ambiguous name (multiple owners)', () => {
+ expect(matchPerson({ name: 'Sam' }, index)).toBeNull();
+ });
+ it('prefers email over name', () => {
+ // email belongs to grace, name says ada — email wins.
+ expect(matchPerson({ email: '[email protected]', name: 'Ada Lovelace' }, index)).toBe('grace');
+ });
+ it('returns null for an unknown identity', () => {
+ expect(matchPerson({ email: '[email protected]' }, index)).toBeNull();
+ expect(matchPerson({}, index)).toBeNull();
+ expect(matchPerson(null, index)).toBeNull();
+ });
+ });
+
+ describe('matchPeople', () => {
+ const index = buildPersonMatchIndex(PEOPLE);
+ it('de-duplicates the same person appearing twice (organizer + attendee)', () => {
+ const ids = matchPeople(
+ [{ email: '[email protected]' }, { email: '[email protected]' }, { name: 'Ada Lovelace' }],
+ index,
+ );
+ expect([...ids]).toEqual(['ada']);
+ });
+ it('accepts bare email strings as well as { email, name } objects', () => {
+ const ids = matchPeople(['[email protected]', { name: 'lin' }], index);
+ expect(ids.has('grace')).toBe(true);
+ expect(ids.has('lin')).toBe(true);
+ expect(ids.size).toBe(2);
+ });
+ it('drops unmatched and empty identities', () => {
+ const ids = matchPeople([null, '', { email: '[email protected]' }, { name: 'Sam' }], index);
+ expect(ids.size).toBe(0);
+ });
+ });
+});
diff --git a/server/routes/tribe.js b/server/routes/tribe.js
index a1084dc164..88015ef80a 100644
--- a/server/routes/tribe.js
+++ b/server/routes/tribe.js
@@ -21,6 +21,10 @@ const personSchema = z.object({
channel: z.string().max(200).optional().default(''),
energy: energySchema.optional().default('steady'),
tags: z.array(z.string().max(80)).max(50).optional().default([]),
+ // Known emails/handles used to auto-match calendar attendees / message
+ // counterparts to this person (#2033). Service-side `normalizeEmails` lowercases
+ // and de-duplicates; the UI splits its single-line input to an array like tags.
+ emails: z.array(z.string().max(320)).max(100).optional().default([]),
nextMove: z.string().max(2000).optional().default(''),
notes: z.string().max(10000).optional().default(''),
});
diff --git a/server/routes/tribe.test.js b/server/routes/tribe.test.js
index 7396fba206..8a95367b9d 100644
--- a/server/routes/tribe.test.js
+++ b/server/routes/tribe.test.js
@@ -80,6 +80,19 @@ describe('Tribe Routes', () => {
expect(emit).toHaveBeenCalledWith('tribe:changed', { personId: PERSON_ID });
});
+ it('accepts and forwards an emails array on create', async () => {
+ tribe.createPerson.mockResolvedValue({ id: PERSON_ID, name: 'Ada' });
+
+ const response = await request(app)
+ .post('/api/tribe/people')
+ .send({ name: 'Ada', emails: ['[email protected]', '[email protected]'] });
+
+ expect(response.status).toBe(201);
+ expect(tribe.createPerson).toHaveBeenCalledWith(expect.objectContaining({
+ }));
+ });
+
it('updates a person with partial fields', async () => {
tribe.updatePerson.mockResolvedValue({ id: PERSON_ID, name: 'Ada', nextMove: 'Coffee' });
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 79232f3442..30ca95a9ed 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -95,8 +95,12 @@ CREATE TABLE IF NOT EXISTS tribe_people (
deleted BOOLEAN DEFAULT FALSE,
deleted_at TIMESTAMPTZ
);
+-- Known emails/handles for a person — the deterministic key that maps a calendar
+-- attendee / message counterpart back to this tracked person (#2033).
+ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS emails TEXT[] DEFAULT '{}';
CREATE INDEX IF NOT EXISTS idx_tribe_people_live ON tribe_people (deleted, ring, updated_at DESC);
CREATE INDEX IF NOT EXISTS idx_tribe_people_tags ON tribe_people USING gin (tags);
+CREATE INDEX IF NOT EXISTS idx_tribe_people_emails ON tribe_people USING gin (emails);
CREATE TABLE IF NOT EXISTS tribe_touchpoints (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -107,11 +111,16 @@ CREATE TABLE IF NOT EXISTS tribe_touchpoints (
source VARCHAR(32) NOT NULL DEFAULT 'user',
calendar_account_id TEXT,
calendar_event_id TEXT,
+ dedupe_key TEXT,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ DEFAULT NOW()
);
+-- Idempotency key for auto-logged touchpoints (calendar event id / message
+-- thread+day); NULL for hand-logged user touchpoints.
+ALTER TABLE tribe_touchpoints ADD COLUMN IF NOT EXISTS dedupe_key TEXT;
CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_person ON tribe_touchpoints (person_id, happened_at DESC);
CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_calendar ON tribe_touchpoints (calendar_account_id, calendar_event_id);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_tribe_touchpoints_dedupe ON tribe_touchpoints (person_id, dedupe_key) WHERE dedupe_key IS NOT NULL;
CREATE TABLE IF NOT EXISTS tribe_memory_links (
person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
diff --git a/server/services/calendarGoogleApiSync.js b/server/services/calendarGoogleApiSync.js
index 11d7f19ae8..aaae0a9173 100644
--- a/server/services/calendarGoogleApiSync.js
+++ b/server/services/calendarGoogleApiSync.js
@@ -48,7 +48,10 @@ export async function apiSyncAccount(accountId, io) {
end: item.end,
location: item.location || '',
description: item.description || '',
- status: item.status || 'confirmed'
+ status: item.status || 'confirmed',
+ // Attendee/organizer identities feed Tribe touchpoint auto-logging (#2033).
+ organizer: item.organizer || null,
+ attendees: item.attendees || []
})));
pageToken = response.data.nextPageToken;
} while (pageToken);
diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.js
index 998323b1b5..89725ae615 100644
--- a/server/services/calendarGoogleSync.js
+++ b/server/services/calendarGoogleSync.js
@@ -1,7 +1,7 @@
import { v4 as uuidv4 } from '../lib/uuid.js';
import { createHash } from 'crypto';
import { getAccount, updateSyncStatus, updateSubcalendars, mergeDiscoveredSubcalendars } from './calendarAccounts.js';
-import { loadCache, saveCache } from './calendarSync.js';
+import { loadCache, saveCache, logCalendarTouchpoints } from './calendarSync.js';
import { getAllProviders } from './providers.js';
import { getSettings } from './settings.js';
import { pickCliProvider, runCliProviderPrompt } from '../lib/cliProviderRun.js';
@@ -26,6 +26,18 @@ export function normalizeGoogleEvent(event, subcalendarId, subcalendarName) {
const endDate = event.end?.date;
const isAllDay = !startDateTime && !!startDate;
+ // Normalize organizer/attendees to the shared { name, email } shape used by
+ // the Outlook path so Tribe touchpoint matching (#2033) works uniformly. The
+ // "self" attendee's responseStatus is surfaced as myStatus for the
+ // declined-event filter.
+ const attendees = (event.attendees || []).map((a) => ({
+ name: a.displayName || '',
+ email: a.email || '',
+ status: a.responseStatus || '',
+ }));
+ const self = (event.attendees || []).find((a) => a.self);
+ const myStatus = self?.responseStatus === 'declined' ? 'declined' : undefined;
+
return {
id: uuidv4(),
externalId: `gcal-${md5(event.id || uuidv4())}`,
@@ -37,6 +49,11 @@ export function normalizeGoogleEvent(event, subcalendarId, subcalendarName) {
endTime: endDateTime || (endDate ? `${endDate}T00:00:00` : null),
isAllDay,
isCancelled: event.status === 'cancelled',
+ organizer: event.organizer
+ ? { name: event.organizer.displayName || '', email: event.organizer.email || '' }
+ : null,
+ attendees,
+ myStatus,
subcalendarId,
subcalendarName,
source: 'google-calendar',
@@ -102,6 +119,11 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEve
await saveCache(accountId, cache);
await updateSyncStatus(accountId, 'success');
+ // Auto-log Tribe touchpoints from this subcalendar batch (#2033) — secondary
+ // effect, must not fail the sync; idempotent on event id.
+ await logCalendarTouchpoints(accountId, normalized).catch((err) =>
+ console.error(`🤝 Tribe auto-log failed for account ${accountId}: ${err.message}`));
+
io?.emit('calendar:sync:completed', {
accountId,
calendarId,
diff --git a/server/services/calendarSync.js b/server/services/calendarSync.js
index b87c42d321..c360937d2b 100644
--- a/server/services/calendarSync.js
+++ b/server/services/calendarSync.js
@@ -211,6 +211,11 @@ export async function syncAccount(accountId, io, options = {}) {
await saveCache(accountId, cache);
await updateSyncStatus(accountId, providerStatus === 'success' ? 'success' : providerStatus);
+ // Auto-log Tribe touchpoints from this batch (secondary effect — must not
+ // fail the sync). Idempotent on event id, so re-processing fetched events is safe.
+ await logCalendarTouchpoints(accountId, newEvents).catch((err) =>
+ console.error(`🤝 Tribe auto-log failed for account ${accountId}: ${err.message}`));
+
io?.emit('calendar:sync:completed', { accountId, newEvents: uniqueNew.length, pruned, status: providerStatus });
console.log(`📅 Sync complete for ${account.name}: ${uniqueNew.length} new, ${pruned} pruned, status=${providerStatus}`);
@@ -238,3 +243,49 @@ export async function getSyncStatus(accountId) {
lastSyncStatus: account.lastSyncStatus
};
}
+
+// Auto-log Tribe touchpoints for synced calendar events (#2033). Deterministic:
+// an event's organizer/attendees are matched to tracked people by email/handle
+// (or unique exact name) and one touchpoint per person is logged, idempotent on
+// the event id so re-syncs never double-log. Only events that have already
+// happened (start/end <= now) and weren't declined/cancelled count as contact.
+// Called from both the Outlook (syncAccount) and Google (pushSyncEvents) paths;
+// a no-op when nothing is tracked. Tribe is imported dynamically to avoid a
+// static import cycle (tribe.js → calendarSync.js).
+export async function logCalendarTouchpoints(accountId, events = []) {
+ const now = Date.now();
+ const candidates = [];
+ for (const event of events) {
+ if (event.isCancelled || event.myStatus === 'declined') continue;
+ const when = event.startTime || event.endTime;
+ if (!when) continue;
+ if (safeDate(when) > now) continue; // future event — hasn't happened yet
+ const identities = [event.organizer, ...(event.attendees || [])].filter(Boolean);
+ if (identities.length === 0) continue;
+ const eventKey = event.externalId || event.id;
+ if (!eventKey) continue;
+ candidates.push({
+ identities,
+ source: 'calendar',
+ happenedAt: when,
+ channel: event.location || 'Calendar',
+ summary: event.title || 'Calendar touchpoint',
+ dedupeKey: `cal:${accountId}:${eventKey}`,
+ calendarAccountId: accountId,
+ calendarEventId: eventKey,
+ metadata: {
+ title: event.title,
+ location: event.location,
+ startTime: event.startTime,
+ endTime: event.endTime,
+ },
+ });
+ }
+ if (candidates.length === 0) return { created: 0, matched: 0 };
+ const tribe = await import('./tribe.js');
+ const result = await tribe.autoLogTouchpoints(candidates);
+ if (result.created > 0) {
+ console.log(`🤝 Auto-logged ${result.created} calendar touchpoint(s) for account ${accountId}`);
+ }
+ return result;
+}
diff --git a/server/services/calendarSync.test.js b/server/services/calendarSync.test.js
index bcffb8919c..d6ff1d173c 100644
--- a/server/services/calendarSync.test.js
+++ b/server/services/calendarSync.test.js
@@ -16,7 +16,14 @@ vi.mock('./googleAuth.js', () => ({
getAuthenticatedClient: vi.fn(async () => null),
}));
-import { syncAccount } from './calendarSync.js';
+// tribe.js is loaded dynamically by logCalendarTouchpoints; mock it so the
+// producer test asserts the candidates without a live Postgres.
+vi.mock('./tribe.js', () => ({
+ autoLogTouchpoints: vi.fn().mockResolvedValue({ created: 0, matched: 0 }),
+}));
+
+import { syncAccount, logCalendarTouchpoints } from './calendarSync.js';
+import { autoLogTouchpoints } from './tribe.js';
import { mcpSyncAccount, mcpDiscoverCalendars } from './calendarGoogleSync.js';
import { apiSyncAccount, apiDiscoverCalendars } from './calendarGoogleApiSync.js';
import { getAccount } from './calendarAccounts.js';
@@ -80,3 +87,47 @@ describe('calendar sync services throw ServerError with the documented statuses'
});
});
});
+
+describe('logCalendarTouchpoints — candidate building (#2033)', () => {
+ const PAST = '2020-01-01T10:00:00Z';
+ const FUTURE = new Date(Date.now() + 7 * 86400000).toISOString();
+
+ beforeEach(() => {
+ autoLogTouchpoints.mockClear();
+ autoLogTouchpoints.mockResolvedValue({ created: 1, matched: 1 });
+ });
+
+ it('builds a calendar candidate with a stable per-event dedupe key', async () => {
+ await logCalendarTouchpoints(ACCOUNT_ID, [{
+ externalId: 'evt-1',
+ title: 'Coffee with Ada',
+ location: 'Cafe',
+ startTime: PAST,
+ organizer: { name: 'Ada', email: '[email protected]' },
+ attendees: [{ name: 'Me', email: '[email protected]' }],
+ }]);
+
+ expect(autoLogTouchpoints).toHaveBeenCalledTimes(1);
+ const [candidates] = autoLogTouchpoints.mock.calls[0];
+ expect(candidates).toHaveLength(1);
+ expect(candidates[0]).toMatchObject({
+ source: 'calendar',
+ dedupeKey: `cal:${ACCOUNT_ID}:evt-1`,
+ calendarEventId: 'evt-1',
+ happenedAt: PAST,
+ summary: 'Coffee with Ada',
+ });
+ expect(candidates[0].identities).toHaveLength(2);
+ });
+
+ it('skips future, cancelled, declined, and attendee-less events', async () => {
+ await logCalendarTouchpoints(ACCOUNT_ID, [
+ { externalId: 'future', startTime: FUTURE, attendees: [{ email: '[email protected]' }] },
+ { externalId: 'cancelled', startTime: PAST, isCancelled: true, attendees: [{ email: '[email protected]' }] },
+ { externalId: 'declined', startTime: PAST, myStatus: 'declined', attendees: [{ email: '[email protected]' }] },
+ { externalId: 'empty', startTime: PAST, attendees: [] },
+ ]);
+ // All four filtered out → producer never calls the logger.
+ expect(autoLogTouchpoints).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index 66e6cdf121..2833788f64 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -185,6 +185,11 @@ export async function syncAccount(accountId, io, options = {}) {
await saveCache(accountId, cache);
await updateSyncStatus(accountId, providerStatus === 'success' ? 'success' : providerStatus);
+ // Auto-log Tribe touchpoints from newly synced messages (#2033) — secondary
+ // effect, must not fail the sync; deduped per thread + day so re-syncs are safe.
+ await logMessageTouchpoints(account, uniqueNew).catch((err) =>
+ console.error(`🤝 Tribe auto-log failed for account ${accountId}: ${err.message}`));
+
io?.emit('messages:sync:completed', { accountId, newMessages: uniqueNew.length, pruned, status: providerStatus });
if (providerStatus === 'success') {
io?.emit('messages:changed', {});
@@ -322,3 +327,49 @@ export async function getSyncStatus(accountId) {
lastSyncStatus: account.lastSyncStatus
};
}
+
+// Normalize a message participant (from is `{ name, email }`, to/cc are bare
+// email strings) to the `{ email, name }` shape the Tribe matcher expects.
+function toIdentity(participant) {
+ if (!participant) return null;
+ if (typeof participant === 'string') return { email: participant };
+ return { email: participant.email || '', name: participant.name || '' };
+}
+
+// Auto-log Tribe touchpoints for synced messages (#2033). Deterministic: the
+// message counterparts (sender + recipients, excluding the account's own
+// address) are matched to tracked people by email/handle (or unique exact name)
+// and one touchpoint per person is logged, deduped per thread + calendar day so
+// a long thread doesn't spam touchpoints. Tribe is imported dynamically to avoid
+// a static import cycle. A no-op when nothing is tracked.
+export async function logMessageTouchpoints(account, messages = []) {
+ const selfEmail = String(account?.email || '').trim().toLowerCase();
+ const candidates = [];
+ for (const message of messages) {
+ const participants = [message.from, ...(message.to || []), ...(message.cc || [])];
+ const identities = participants
+ .map(toIdentity)
+ .filter((identity) => identity && identity.email
+ && identity.email.trim().toLowerCase() !== selfEmail);
+ if (identities.length === 0) continue;
+ const when = message.date || new Date().toISOString();
+ const day = new Date(safeDate(when)).toISOString().slice(0, 10);
+ const threadKey = message.threadId || message.id;
+ candidates.push({
+ identities,
+ source: 'message',
+ happenedAt: when,
+ channel: account?.type || 'Message',
+ summary: message.subject || 'Message touchpoint',
+ dedupeKey: `msg:${account?.id}:${threadKey}:${day}`,
+ metadata: { subject: message.subject, threadId: message.threadId || null },
+ });
+ }
+ if (candidates.length === 0) return { created: 0, matched: 0 };
+ const tribe = await import('./tribe.js');
+ const result = await tribe.autoLogTouchpoints(candidates);
+ if (result.created > 0) {
+ console.log(`🤝 Auto-logged ${result.created} message touchpoint(s) for account ${account?.id}`);
+ }
+ return result;
+}
diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.js
index 3791f72265..8e18e0b8f8 100644
--- a/server/services/messageSync.test.js
+++ b/server/services/messageSync.test.js
@@ -46,9 +46,16 @@ vi.mock('./messagePlaywrightSync.js', () => ({
refreshMessageDetail: vi.fn()
}));
+// tribe.js is loaded dynamically by logMessageTouchpoints; mock it so the
+// producer test asserts the candidates without a live Postgres.
+vi.mock('./tribe.js', () => ({
+ autoLogTouchpoints: vi.fn().mockResolvedValue({ created: 0, matched: 0 }),
+}));
+
import { readdir, unlink } from 'fs/promises';
import { tryReadFile as readFile, atomicWrite } from '../lib/fileUtils.js';
-import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage } from './messageSync.js';
+import { getMessages, getMessage, syncAccount, deleteCache, getSyncStatus, refreshMessage, logMessageTouchpoints } from './messageSync.js';
+import { autoLogTouchpoints } from './tribe.js';
import { getAccount, updateSyncStatus } from './messageAccounts.js';
import { syncGmail } from './messageGmailSync.js';
import { syncPlaywright, refreshMessageDetail } from './messagePlaywrightSync.js';
@@ -566,3 +573,53 @@ describe('refreshMessage', () => {
expect(original.bodyText).toBe('');
});
});
+
+describe('logMessageTouchpoints — candidate building (#2033)', () => {
+ const account = { id: VALID_UUID, type: 'gmail', email: '[email protected]' };
+
+ beforeEach(() => {
+ autoLogTouchpoints.mockClear();
+ autoLogTouchpoints.mockResolvedValue({ created: 1, matched: 1 });
+ });
+
+ it('builds a message candidate keyed per thread + day, excluding the account owner', async () => {
+ await logMessageTouchpoints(account, [{
+ id: 'm1',
+ threadId: 'thread-9',
+ subject: 'Lunch?',
+ date: '2026-06-01T12:00:00Z',
+ from: { name: 'Ada', email: '[email protected]' },
+ cc: [],
+ }]);
+
+ expect(autoLogTouchpoints).toHaveBeenCalledTimes(1);
+ const [candidates] = autoLogTouchpoints.mock.calls[0];
+ expect(candidates).toHaveLength(1);
+ expect(candidates[0]).toMatchObject({
+ source: 'message',
+ dedupeKey: `msg:${VALID_UUID}:thread-9:2026-06-01`,
+ summary: 'Lunch?',
+ });
+ // Own address excluded; sender + other recipient remain.
+ const emails = candidates[0].identities.map((i) => i.email).sort();
+ expect(emails).toEqual(['[email protected]', '[email protected]']);
+ });
+
+ it('falls back to the message id when there is no threadId', async () => {
+ await logMessageTouchpoints(account, [{
+ id: 'm2', subject: 'Hi', date: '2026-06-02T00:00:00Z',
+ from: { name: 'Grace', email: '[email protected]' }, to: [], cc: [],
+ }]);
+ const [candidates] = autoLogTouchpoints.mock.calls[0];
+ expect(candidates[0].dedupeKey).toBe(`msg:${VALID_UUID}:m2:2026-06-02`);
+ });
+
+ it('skips a message with no counterpart beyond the account owner', async () => {
+ await logMessageTouchpoints(account, [{
+ id: 'm3', date: '2026-06-01T00:00:00Z',
+ from: { name: 'Me', email: '[email protected]' }, to: ['[email protected]'], cc: [],
+ }]);
+ expect(autoLogTouchpoints).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/tribe.js b/server/services/tribe.js
index 86c3b04091..73f2c51bac 100644
--- a/server/services/tribe.js
+++ b/server/services/tribe.js
@@ -16,6 +16,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureSchema, query, withTransaction } from '../lib/db.js';
import { ServerError } from '../lib/errorHandler.js';
import { cadenceStatus } from '../lib/tribeCadence.js';
+import { buildPersonMatchIndex, matchPeople, normalizeIdentifier } from '../lib/tribeMatch.js';
import * as calendarSync from './calendarSync.js';
// Default check-in cadence (days) per ring. Mirrored on the client in
@@ -52,6 +53,21 @@ export function normalizeTags(tags) {
return String(tags).split(',').map((tag) => tag.trim()).filter(Boolean);
}
+// Known emails/handles used to match a person to calendar attendees / message
+// counterparts. Lowercased + trimmed + de-duplicated so matching (which also
+// lowercases) is stable and the stored set has no near-duplicates.
+export function normalizeEmails(emails) {
+ const list = Array.isArray(emails)
+ ? emails
+ : (emails == null ? [] : String(emails).split(','));
+ const seen = new Set();
+ for (const raw of list) {
+ const key = normalizeIdentifier(raw);
+ if (key) seen.add(key);
+ }
+ return [...seen];
+}
+
export function rowToPerson(row) {
return {
id: row.id,
@@ -64,6 +80,7 @@ export function rowToPerson(row) {
channel: row.channel || '',
energy: row.energy || 'steady',
tags: row.tags || [],
+ emails: row.emails || [],
nextMove: row.next_move || '',
notes: row.notes || '',
touchpointCount: Number(row.touchpoint_count || 0),
@@ -210,8 +227,8 @@ export async function createPerson(data) {
const result = await query(
`INSERT INTO tribe_people (
id, name, relationship, ring, cadence_days, last_contact_on, channel,
- energy, tags, next_move, notes, updated_at
- ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,NOW())
+ energy, tags, emails, next_move, notes, updated_at
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,NOW())
RETURNING *, 0 AS touchpoint_count, 0 AS linked_memory_count`,
[
id,
@@ -223,6 +240,7 @@ export async function createPerson(data) {
data.channel || '',
data.energy || 'steady',
normalizeTags(data.tags),
+ normalizeEmails(data.emails),
data.nextMove || '',
data.notes || '',
],
@@ -245,8 +263,9 @@ export async function updatePerson(id, updates) {
channel = $7,
energy = $8,
tags = $9,
- next_move = $10,
- notes = $11,
+ emails = $10,
+ next_move = $11,
+ notes = $12,
updated_at = NOW()
WHERE id = $1 AND deleted = FALSE
RETURNING *,
@@ -262,6 +281,7 @@ export async function updatePerson(id, updates) {
next.channel || '',
next.energy || 'steady',
normalizeTags(next.tags),
+ normalizeEmails(next.emails),
next.nextMove || '',
next.notes || '',
],
@@ -354,6 +374,80 @@ export async function createCalendarTouchpoint(personId, { accountId, eventId, s
});
}
+// Insert an auto-logged touchpoint for one person, idempotent on `dedupeKey`
+// (the partial unique index idx_tribe_touchpoints_dedupe). Returns the created
+// touchpoint, or `null` when this person+dedupeKey was already logged (re-sync).
+// Only advances last_contact_on when a row is actually inserted.
+async function autoCreateTouchpoint(personId, data) {
+ const happenedAt = data.happenedAt || new Date().toISOString();
+ return withTransaction(async (client) => {
+ const result = await client.query(
+ `INSERT INTO tribe_touchpoints (
+ id, person_id, happened_at, channel, summary, source,
+ calendar_account_id, calendar_event_id, dedupe_key, metadata
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
+ ON CONFLICT (person_id, dedupe_key) WHERE dedupe_key IS NOT NULL
+ DO NOTHING
+ RETURNING *`,
+ [
+ uuidv4(),
+ personId,
+ happenedAt,
+ data.channel || '',
+ data.summary || '',
+ data.source || 'user',
+ data.calendarAccountId || null,
+ data.calendarEventId || null,
+ data.dedupeKey || null,
+ data.metadata || {},
+ ],
+ );
+ if (!result.rows[0]) return null; // duplicate — already logged for this key
+
+ await client.query(
+ `UPDATE tribe_people
+ SET last_contact_on = GREATEST(COALESCE(last_contact_on, DATE '1900-01-01'), $2::date),
+ channel = CASE WHEN $3::text = '' THEN channel ELSE $3::text END,
+ updated_at = NOW()
+ WHERE id = $1`,
+ [personId, happenedAt, data.channel || ''],
+ );
+ return rowToTouchpoint(result.rows[0]);
+ });
+}
+
+/**
+ * Auto-log touchpoints from a batch of sync candidates (calendar events /
+ * messages). Each candidate:
+ * { identities: [{ email, name } | string], source, happenedAt, channel,
+ * summary, dedupeKey, calendarAccountId?, calendarEventId?, metadata? }
+ *
+ * Identities are matched deterministically (email/handle, unique exact name) to
+ * tracked people via the shared matcher; one deduped touchpoint is inserted per
+ * matched person. `dedupeKey` MUST be set for idempotency across re-syncs.
+ * Returns `{ created, matched }`. No LLM calls.
+ */
+export async function autoLogTouchpoints(candidates = []) {
+ if (!Array.isArray(candidates) || candidates.length === 0) return { created: 0, matched: 0 };
+ await ensureReady();
+ const people = await listPeople();
+ if (people.length === 0) return { created: 0, matched: 0 };
+
+ const index = buildPersonMatchIndex(people);
+ let created = 0;
+ let matched = 0;
+ for (const candidate of candidates) {
+ if (!candidate?.dedupeKey) continue; // no idempotency key → refuse to log
+ const personIds = matchPeople(candidate.identities, index);
+ for (const personId of personIds) {
+ matched++;
+ const touchpoint = await autoCreateTouchpoint(personId, candidate);
+ if (touchpoint) created++;
+ }
+ }
+ return { created, matched };
+}
+
export async function listMemoryLinks(personId) {
await ensureReady();
const result = await query(
diff --git a/server/services/tribe.test.js b/server/services/tribe.test.js
index b0dbbc0432..837d3bdcbc 100644
--- a/server/services/tribe.test.js
+++ b/server/services/tribe.test.js
@@ -9,17 +9,19 @@ vi.mock('../lib/db.js', () => ({
withTransaction: vi.fn(),
}));
-import { query } from '../lib/db.js';
+import { query, withTransaction } from '../lib/db.js';
import {
listPeople,
createPerson,
normalizeTags,
+ normalizeEmails,
isoDate,
isoDateTime,
rowToPerson,
rowToTouchpoint,
personCadenceStatus,
getCareSummary,
+ autoLogTouchpoints,
DEFAULT_RING_CADENCE,
} from './tribe.js';
@@ -251,9 +253,103 @@ describe('tribe service — createPerson', () => {
const [, params] = query.mock.calls[0];
// INSERT param order: id,name,relationship,ring,cadence_days,last_contact,
- // channel,energy,tags,next_move,notes
+ // channel,energy,tags,emails,next_move,notes
expect(params[3]).toBe('core');
expect(params[4]).toBe(DEFAULT_RING_CADENCE.core); // 21, not the flat SQL default
expect(params[8]).toEqual(['a', 'b']);
});
+
+ it('normalizes emails to a lowercased de-duplicated array on insert', async () => {
+ query.mockResolvedValue({ rows: [{ id: 'p1', name: 'Ada', ring: 'tribe', cadence_days: 45 }] });
+ await createPerson({ name: 'Ada', emails: [' [email protected] ', '[email protected]', '[email protected]'] });
+ const [, params] = query.mock.calls[0];
+ expect(params[9]).toEqual(['[email protected]', '[email protected]']); // emails at $10
+ });
+});
+
+describe('tribe service — normalizeEmails', () => {
+ it('lowercases, trims, splits a comma string, and de-dupes', () => {
+ });
+ it('handles an array and drops empties', () => {
+ expect(normalizeEmails([' [email protected] ', '', '[email protected]'])).toEqual(['[email protected]']);
+ });
+ it('returns [] for nullish', () => {
+ expect(normalizeEmails(null)).toEqual([]);
+ expect(normalizeEmails(undefined)).toEqual([]);
+ });
+});
+
+describe('tribe service — rowToPerson emails', () => {
+ it('maps the emails array and defaults to []', () => {
+ expect(rowToPerson({ id: 'p', name: 'N', ring: 'tribe', cadence_days: 45, emails: ['[email protected]'] }).emails)
+ .toEqual(['[email protected]']);
+ expect(rowToPerson({ id: 'p', name: 'N', ring: 'tribe', cadence_days: 45 }).emails).toEqual([]);
+ });
+});
+
+describe('tribe service — autoLogTouchpoints', () => {
+ beforeEach(() => {
+ query.mockReset();
+ withTransaction.mockReset();
+ });
+
+ // One tracked person "Ada" with a known email; listPeople() is the first query.
+ function mockPeople() {
+ query.mockResolvedValue({ rows: [
+ { id: 'ada', name: 'Ada', ring: 'tribe', cadence_days: 45, emails: ['[email protected]'] },
+ ] });
+ }
+
+ it('matches identities and inserts one deduped touchpoint per matched person', async () => {
+ mockPeople();
+ // INSERT returns a row (new); UPDATE returns nothing.
+ withTransaction.mockImplementation(async (fn) => fn({
+ query: vi.fn()
+ .mockResolvedValueOnce({ rows: [{ id: 't1', person_id: 'ada', source: 'calendar' }] })
+ .mockResolvedValueOnce({ rows: [] }),
+ }));
+
+ const result = await autoLogTouchpoints([
+ { identities: [{ email: '[email protected]' }], source: 'calendar', dedupeKey: 'cal:a:e1', happenedAt: '2026-06-01T10:00:00Z' },
+ { identities: [{ email: '[email protected]' }], source: 'calendar', dedupeKey: 'cal:a:e2' },
+ ]);
+
+ expect(result).toEqual({ created: 1, matched: 1 });
+ });
+
+ it('counts a matched-but-duplicate insert (ON CONFLICT no row) as matched, not created', async () => {
+ mockPeople();
+ // INSERT returns no row → duplicate; UPDATE must not run.
+ const clientQuery = vi.fn().mockResolvedValueOnce({ rows: [] });
+ withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));
+
+ const result = await autoLogTouchpoints([
+ { identities: [{ email: '[email protected]' }], source: 'message', dedupeKey: 'msg:a:t:2026-06-01' },
+ ]);
+
+ expect(result).toEqual({ created: 0, matched: 1 });
+ expect(clientQuery).toHaveBeenCalledTimes(1); // no last_contact_on UPDATE on a dup
+ });
+
+ it('skips candidates without a dedupeKey (idempotency required)', async () => {
+ mockPeople();
+ const result = await autoLogTouchpoints([{ identities: [{ email: '[email protected]' }], source: 'calendar' }]);
+ expect(result).toEqual({ created: 0, matched: 0 });
+ expect(withTransaction).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op when nothing is tracked', async () => {
+ query.mockResolvedValue({ rows: [] });
+ const result = await autoLogTouchpoints([
+ { identities: [{ email: '[email protected]' }], dedupeKey: 'cal:a:e1' },
+ ]);
+ expect(result).toEqual({ created: 0, matched: 0 });
+ });
+
+ it('returns zeros for an empty batch without touching the DB', async () => {
+ const result = await autoLogTouchpoints([]);
+ expect(result).toEqual({ created: 0, matched: 0 });
+ expect(query).not.toHaveBeenCalled();
+ });
});