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: logging a calendar event on a Tribe person twice no longer creates duplicate touchpoints
Adam Eivyb9000cba8c8f
diff --git a/server/lib/tribeMatch.js b/server/lib/tribeMatch.jsindex fcbf1e721d..213560f4e6 100644--- a/server/lib/tribeMatch.js+++ b/server/lib/tribeMatch.js@@ -211,3 +211,16 @@ export function classifyNetworkHandle(value) {export function resolveLinkedPersonId(tribePersonId, tribePersonDeleted) {return tribePersonId && !tribePersonDeleted ? tribePersonId : null;}++/**+ * The idempotency key a calendar event carries on `tribe_touchpoints.dedupe_key`.+ * ONE builder for both producers — the sync auto-logger (`calendarSync.js`) and+ * the manual "log this event" route (`tribe.createCalendarTouchpoint`) — so a+ * hand-logged event and a synced one collide on the unique index instead of+ * both inserting. Keyed on the provider id when present, matching the cache's+ * `externalId || id` convention. Returns null when the event has no usable id.+ */+export function calendarTouchpointDedupeKey(accountId, event) {+ const eventKey = event?.externalId || event?.id;+ return eventKey ? `cal:${accountId}:${eventKey}` : null;+}diff --git a/server/services/calendarSync.js b/server/services/calendarSync.jsindex 1d92c16bad..a9bf723e83 100644--- a/server/services/calendarSync.js+++ b/server/services/calendarSync.js@@ -3,6 +3,7 @@ import { join } from 'path';import { atomicWrite, ensureDir, filterBySearch as genericFilterBySearch, PATHS, readJSONFile, safeDate, UUID_RE } from '../lib/fileUtils.js';import { createKeyedFileWriteQueue } from '../lib/fileWriteQueue.js';import { ServerError } from '../lib/errorHandler.js';+import { calendarTouchpointDedupeKey } from '../lib/tribeMatch.js';import { getUserTimezone } from './userTimezone.js';import { getAccount, updateSyncStatus } from './calendarAccounts.js';@@ -317,7 +318,7 @@ export async function logCalendarTouchpoints(accountId, events = []) {happenedAt: startedAt,channel: event.location || 'Calendar',summary: event.title || 'Calendar touchpoint',- dedupeKey: `cal:${accountId}:${eventKey}`,+ dedupeKey: calendarTouchpointDedupeKey(accountId, event),calendarAccountId: accountId,calendarEventId: eventKey,metadata: {diff --git a/server/services/tribe.js b/server/services/tribe.jsindex e6edf11185..e9e0767fcc 100644--- a/server/services/tribe.js+++ b/server/services/tribe.js@@ -16,7 +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, DEFAULT_RING_CADENCE } from '../lib/tribeCadence.js';-import { buildPersonMatchIndex, matchPeople, normalizeIdentifier, normalizePhone } from '../lib/tribeMatch.js';+import { buildPersonMatchIndex, calendarTouchpointDedupeKey, matchPeople, normalizeIdentifier, normalizePhone } from '../lib/tribeMatch.js';import { toUserDayKey } from '../lib/activeDays.js';import { getUserTimezone } from './userTimezone.js';import * as calendarSync from './calendarSync.js';@@ -450,12 +450,18 @@ export async function createTouchpoint(personId, data = {}) {const happenedAt = data.happenedAt || new Date().toISOString();const contactDate = data.localDate || happenedAt;+ const dedupeKey = data.dedupeKey || null;return withTransaction(async (client) => {+ // With a dedupeKey the insert is idempotent per person (partial unique index+ // idx_tribe_touchpoints_dedupe): a retry, a double-click, or an event the+ // calendar sync already auto-logged returns the existing row untouched.const result = await client.query(`INSERT INTO tribe_touchpoints (id, person_id, happened_at, channel, summary, source,- calendar_account_id, calendar_event_id, metadata- ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)+ 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 NOTHINGRETURNING *`,[data.id || uuidv4(),@@ -466,9 +472,17 @@ export async function createTouchpoint(personId, data = {}) {data.source || 'user',data.calendarAccountId || null,data.calendarEventId || null,+ dedupeKey,data.metadata || {},],);+ if (!result.rows[0]) {+ const existing = await client.query(+ 'SELECT * FROM tribe_touchpoints WHERE person_id = $1 AND dedupe_key = $2',+ [personId, dedupeKey],+ );+ return rowToTouchpoint(existing.rows[0]);+ }await client.query(`UPDATE tribe_people@@ -499,6 +513,7 @@ export async function createCalendarTouchpoint(personId, { accountId, eventId, ssource: 'calendar',calendarAccountId: accountId,calendarEventId: eventId,+ dedupeKey: calendarTouchpointDedupeKey(accountId, event),metadata: {title: event.title,description: event.description,diff --git a/server/services/tribe.test.js b/server/services/tribe.test.jsindex 6b13cf5c99..9d3e9cb625 100644--- a/server/services/tribe.test.js+++ b/server/services/tribe.test.js@@ -284,6 +284,30 @@ describe('tribe service — createCalendarTouchpoint (#8451 UTC-offset day shift});});+describe('tribe service — createCalendarTouchpoint idempotency', () => {+ beforeEach(() => {+ query.mockReset();+ withTransaction.mockReset();+ getEvent.mockReset();+ });++ it('keys the insert on the same cal:<account>:<externalId> the sync auto-logger uses, and returns the existing row on conflict', async () => {+ getEvent.mockResolvedValue({ id: 'local-id', externalId: 'provider-evt', title: 'Dinner', startTime: '2026-09-11T01:00:00.000Z' });+ query.mockResolvedValue({ rows: [{ id: 'person-1', name: 'Example Person', ring: 'tribe', cadence_days: 45 }] });+ const clientQuery = vi.fn()+ .mockResolvedValueOnce({ rows: [] }) // ON CONFLICT DO NOTHING — row already logged by sync or a prior click+ .mockResolvedValueOnce({ rows: [{ id: 'touch-existing', person_id: 'person-1' }] });+ withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));++ const result = await createCalendarTouchpoint('person-1', { accountId: 'acct-1', eventId: 'local-id' });++ expect(clientQuery.mock.calls[0][0]).toContain('ON CONFLICT (person_id, dedupe_key)');+ expect(clientQuery.mock.calls[0][1][8]).toBe('cal:acct-1:provider-evt');+ expect(clientQuery).toHaveBeenCalledTimes(2); // no last_contact_on / channel rewrite for a duplicate+ expect(result.id).toBe('touch-existing');+ });+});+describe('tribe service — autoCreateTouchpoint (#8451 UTC-offset day shift)', () => {beforeEach(() => {withTransaction.mockReset();