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: serialize calendar cache mutations and provider admission (#8634)
[._.]/ Adam Eivyf606a559a89d
diff --git a/server/services/calendarCacheConcurrency.test.js b/server/services/calendarCacheConcurrency.test.jsnew file mode 100644index 0000000000..72dfcef578--- /dev/null+++ b/server/services/calendarCacheConcurrency.test.js@@ -0,0 +1,181 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { basename } from 'path';++vi.mock('../lib/fileUtils.js', async importOriginal => ({+ ...await importOriginal(), ensureDir: vi.fn(async () => {}),+ readJSONFile: vi.fn(), atomicWrite: vi.fn(),+}));+vi.mock('fs/promises', () => ({ readdir: vi.fn(), unlink: vi.fn() }));+vi.mock('./calendarAccounts.js', () => ({+ getAccount: vi.fn(), updateSyncStatus: vi.fn(async () => {}),+ updateSubcalendars: vi.fn(), mergeDiscoveredSubcalendars: vi.fn(),+}));+vi.mock('./calendarApiSync.js', () => ({ syncOutlookCalendarApi: vi.fn() }));+vi.mock('./humanActivity.js', () => ({+ calendarActivityCandidates: vi.fn(() => []), recordEvents: vi.fn(),+}));+vi.mock('./userTimezone.js', () => ({ getUserTimezone: vi.fn(async () => 'UTC') }));+vi.mock('./providers.js', () => ({ getAllProviders: vi.fn() }));+vi.mock('./settings.js', () => ({ getSettings: vi.fn() }));+vi.mock('../lib/cliProviderRun.js', () => ({+ pickCliProvider: vi.fn(), runCliProviderPrompt: vi.fn(),+}));+vi.mock('./googleAuth.js', () => ({ getAuthenticatedClient: vi.fn() }));+vi.mock('@googleapis/calendar', () => ({ calendar: vi.fn() }));++import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';+import { unlink } from 'fs/promises';+import { getAccount } from './calendarAccounts.js';+import { syncOutlookCalendarApi } from './calendarApiSync.js';+import { deleteCache, loadCache, purgeDisabledSubcalendars, syncAccount } from './calendarSync.js';+import { mcpSyncAccount, pushSyncEvents } from './calendarGoogleSync.js';+import { apiSyncAccount } from './calendarGoogleApiSync.js';++const ACCOUNT = '11111111-1111-1111-1111-111111111111';+const OTHER = '22222222-2222-2222-2222-222222222222';+let accounts;+let persisted;++function barrier() {+ let release;+ const promise = new Promise(resolve => { release = resolve; });+ return { promise, release };+}+const raw = id => ({ id, summary: id, start: { dateTime: '2099-01-01T10:00:00Z' } });+const push = (calendarId, id, accountId = ACCOUNT) =>+ pushSyncEvents(accountId, calendarId, calendarId, [raw(id)], null);++// Pause before persistence to expose competing stale reads. No sleeps or live I/O.+function holdFirstWrite() {+ const entered = barrier();+ const gate = barrier();+ atomicWrite.mockImplementationOnce(async (path, cache) => {+ entered.release();+ await gate.promise;+ persisted.set(basename(path, '.json'), structuredClone(cache));+ });+ return { entered: entered.promise, release: gate.release };+}++beforeEach(() => {+ vi.clearAllMocks();+ accounts = new Map([ACCOUNT, OTHER].map(id => [id, {+ id, name: 'Example Account', enabled: true, type: 'google-calendar',+ subcalendars: [{ calendarId: 'a', enabled: true }, { calendarId: 'b', enabled: true }],+ }]));+ persisted = new Map();+ getAccount.mockImplementation(async id => structuredClone(accounts.get(id) ?? null));+ readJSONFile.mockImplementation(async (path, fallback) =>+ structuredClone(persisted.get(basename(path, '.json')) ?? fallback));+ atomicWrite.mockImplementation(async (path, cache) => {+ persisted.set(basename(path, '.json'), structuredClone(cache));+ });+ unlink.mockImplementation(async path => { persisted.delete(basename(path, '.json')); });+});++describe('calendar cache mutation ownership', () => {+ it('preserves simultaneous pushes and counts while another account progresses', async () => {+ const write = holdFirstWrite();+ const first = push('a', 'event-a');+ await write.entered;+ const second = push('b', 'event-b');+ expect(await push('a', 'other-event', OTHER)).toMatchObject({ newEvents: 1, total: 1 });+ write.release();+ expect(await first).toMatchObject({ newEvents: 1, updated: 0, total: 1 });+ expect(await second).toMatchObject({ newEvents: 1, updated: 0, total: 2 });+ expect(persisted.get(ACCOUNT).events.map(e => e.apiId)).toEqual(['event-a', 'event-b']);+ expect(await push('a', 'event-a')).toMatchObject({ newEvents: 0, updated: 1, total: 2 });+ });++ it('purges against the completed push and rejects a delayed disabled-calendar push', async () => {+ await push('b', 'disabled-event');+ const write = holdFirstWrite();+ const refresh = push('a', 'fresh-event');+ await write.entered;+ accounts.get(ACCOUNT).subcalendars[1].enabled = false;+ const purge = purgeDisabledSubcalendars(ACCOUNT);+ const stalePush = push('b', 'late-event').catch(error => error);+ write.release();+ await refresh;+ expect(await purge).toEqual({ purged: 1, remaining: 1 });+ expect(await stalePush).toMatchObject({ status: 409 });+ expect(persisted.get(ACCOUNT).events.map(e => e.apiId)).toEqual(['fresh-event']);+ });++ it('drains an admitted write before deletion and refuses writes after account removal', async () => {+ const write = holdFirstWrite();+ const first = push('a', 'event-a');+ await write.entered;+ accounts.delete(ACCOUNT); // Account DELETE persists this before deleteCache.+ const deletion = deleteCache(ACCOUNT);+ const late = push('b', 'event-b').catch(error => error);+ write.release();+ await Promise.all([first, deletion]);+ expect(await late).toMatchObject({ status: 404 });+ expect(persisted.has(ACCOUNT)).toBe(false);+ });++ it('orders a cache-only clear before a new push without restoring old events', async () => {+ await push('a', 'old-event');+ await Promise.all([deleteCache(ACCOUNT), push('b', 'fresh-event')]);+ expect(persisted.get(ACCOUNT).events.map(e => e.apiId)).toEqual(['fresh-event']);+ });++ it.each([false, true])('reconciles Outlook after clear (account removed: %s)', async removed => {+ accounts.get(ACCOUNT).type = 'outlook-calendar';+ persisted.set(ACCOUNT, { events: [{ externalId: 'old', title: 'Old event' }] });+ const fetched = barrier();+ const entered = barrier();+ syncOutlookCalendarApi.mockImplementationOnce(async () => {+ entered.release();+ return fetched.promise;+ });+ const run = syncAccount(ACCOUNT, null).catch(error => error);+ await entered.promise;+ if (removed) accounts.delete(ACCOUNT);+ await deleteCache(ACCOUNT);+ fetched.release({ events: [{ externalId: 'fresh', title: 'Fresh event' }], status: 'partial' });+ const result = await run;+ if (removed) {+ expect(result).toMatchObject({ status: 404 });+ expect(persisted.has(ACCOUNT)).toBe(false);+ } else {+ expect(result).toMatchObject({ newEvents: 1, total: 1, pruned: 0, status: 'partial' });+ expect(persisted.get(ACCOUNT).events.map(e => e.externalId)).toEqual(['fresh']);+ }+ });++ it('preserves partial Outlook results and releases admission after provider failure', async () => {+ accounts.get(ACCOUNT).type = 'outlook-calendar';+ persisted.set(ACCOUNT, { events: [{ externalId: 'old' }] });+ syncOutlookCalendarApi.mockRejectedValueOnce(new Error('Provider failed'));+ await expect(syncAccount(ACCOUNT, null)).rejects.toMatchObject({ status: 502 });+ syncOutlookCalendarApi.mockResolvedValueOnce({ events: [{ externalId: 'fresh' }], status: 'partial' });+ expect(await syncAccount(ACCOUNT, null)).toMatchObject({ total: 2, pruned: 0, status: 'partial' });+ });++ it('recovers after a failed save and does not share missing-cache arrays', async () => {+ atomicWrite.mockRejectedValueOnce(new Error('Write failed'));+ await expect(push('a', 'failed')).rejects.toThrow('Write failed');+ expect(await push('b', 'saved')).toMatchObject({ total: 1 });+ readJSONFile.mockResolvedValueOnce(null).mockResolvedValueOnce(null);+ const missing = await loadCache(OTHER);+ missing.events.push({ id: 'unsaved' });+ expect((await loadCache(OTHER)).events).toEqual([]);+ });+});++describe.each([+ ['Outlook', syncAccount], ['MCP', mcpSyncAccount], ['Google API', apiSyncAccount],+])('%s provider admission', (_name, sync) => {+ it('reserves before lookup and releases on lookup failure', async () => {+ const lookup = barrier();+ getAccount.mockImplementationOnce(() => lookup.promise);+ const first = sync(ACCOUNT, null).catch(error => error);+ await expect(sync(ACCOUNT, null)).rejects.toMatchObject({ status: 409 });+ lookup.release(null);+ expect(await first).toMatchObject({ status: 404 });+ getAccount.mockResolvedValueOnce(null);+ await expect(sync(ACCOUNT, null)).rejects.toMatchObject({ status: 404 });+ });+});diff --git a/server/services/calendarGoogleApiSync.js b/server/services/calendarGoogleApiSync.jsindex b18aedb6ea..2e44261159 100644--- a/server/services/calendarGoogleApiSync.js+++ b/server/services/calendarGoogleApiSync.js@@ -4,7 +4,19 @@ import { getAuthenticatedClient } from './googleAuth.js';import { getAccount, updateSubcalendars, mergeDiscoveredSubcalendars } from './calendarAccounts.js';import { pushSyncEvents, getSyncDateRange } from './calendarGoogleSync.js';+const apiSyncLocks = new Set();+export async function apiSyncAccount(accountId, io) {+ if (apiSyncLocks.has(accountId)) throw new ServerError('Google API sync already in progress', { status: 409 });+ apiSyncLocks.add(accountId);+ try {+ return await runApiSyncAccount(accountId, io);+ } finally {+ apiSyncLocks.delete(accountId);+ }+}++async function runApiSyncAccount(accountId, io) {const account = await getAccount(accountId);if (!account) throw new ServerError('Account not found', { status: 404 });if (account.type !== 'google-calendar') throw new ServerError('Not a Google Calendar account', { status: 400 });diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.jsindex 5935be7483..a7bd2a1af3 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, logCalendarTouchpoints, recordCalendarActivity } from './calendarSync.js';+import { mutateCache, logCalendarTouchpoints, recordCalendarActivity } from './calendarSync.js';import { getAllProviders } from './providers.js';import { getSettings } from './settings.js';import { pickCliProvider, runCliProviderPrompt } from '../lib/cliProviderRun.js';@@ -90,72 +90,77 @@ export function getSyncDateRange(pastDays = 7, futureDays = 30) {export async function pushSyncEvents(accountId, calendarId, calendarName, rawEvents, io, options = {}) {const { prune: shouldPrune = true, status = 'success' } = options;const account = await getAccount(accountId);- if (!account) throw new Error('Account not found');+ if (!account) throw new ServerError('Account not found', { status: 404 });- const cache = await loadCache(accountId);const normalized = rawEvents.map(e => normalizeGoogleEvent(e, calendarId, calendarName));- // Heal legacy duplicates in this subcalendar, retaining the first local id.- const existingMap = new Map();- cache.events = cache.events.filter(event => {- if (!event.externalId || event.subcalendarId !== calendarId) return true;- if (existingMap.has(event.externalId)) return false;- existingMap.set(event.externalId, event);- return true;- });+ const { newCount, updatedCount, pruned, total } = await mutateCache(accountId, (cache, currentAccount) => {+ const subcalendar = currentAccount.subcalendars?.find(sc => sc.calendarId === calendarId);+ if (subcalendar && (!subcalendar.enabled || subcalendar.dormant)) {+ throw new ServerError('Subcalendar is disabled', { status: 409 });+ }+ // Heal legacy duplicates in this subcalendar, retaining the first local id.+ const existingMap = new Map();+ cache.events = cache.events.filter(event => {+ if (!event.externalId || event.subcalendarId !== calendarId) return true;+ if (existingMap.has(event.externalId)) return false;+ existingMap.set(event.externalId, event);+ return true;+ });- let newCount = 0;- let updatedCount = 0;- const incomingIds = new Set();-- for (const event of normalized) {- incomingIds.add(event.externalId);- if (existingMap.has(event.externalId)) {- // Update mutable fields- const existing = existingMap.get(event.externalId);- existing.title = event.title;- existing.description = event.description;- existing.location = event.location;- existing.startTime = event.startTime;- existing.endTime = event.endTime;- existing.isAllDay = event.isAllDay;- existing.isCancelled = event.isCancelled;- // Refresh the identity fields too so an event already in cache gains- // organizer/attendees for Tribe touchpoint matching and an up-to-date- // declined status (#2033) — not just newly-added events.- existing.organizer = event.organizer;- existing.attendees = event.attendees;- existing.myStatus = event.myStatus;- // `undefined` means this producer never described the event's- // conferencing — a legacy push, or an MCP payload predating the field —- // so the cached link stands. Anything else is the current snapshot:- // replace it, or clear it to null when the meeting no longer has one.- // Without this gate an older client silently drops a working Join action.- if (event.meetingUrl !== undefined) existing.meetingUrl = event.meetingUrl;- existing.syncedAt = event.syncedAt;- updatedCount++;- } else {- // A newly cached event always carries the key, so `meetingUrl` is absent- // from the cache only for records written before this shipped.- const retained = { ...event, meetingUrl: event.meetingUrl ?? null };- cache.events.push(retained);- existingMap.set(event.externalId, retained);- newCount++;+ let newCount = 0;+ let updatedCount = 0;+ const incomingIds = new Set();++ for (const event of normalized) {+ incomingIds.add(event.externalId);+ if (existingMap.has(event.externalId)) {+ // Update mutable fields+ const existing = existingMap.get(event.externalId);+ existing.title = event.title;+ existing.description = event.description;+ existing.location = event.location;+ existing.startTime = event.startTime;+ existing.endTime = event.endTime;+ existing.isAllDay = event.isAllDay;+ existing.isCancelled = event.isCancelled;+ // Refresh the identity fields too so an event already in cache gains+ // organizer/attendees for Tribe touchpoint matching and an up-to-date+ // declined status (#2033) — not just newly-added events.+ existing.organizer = event.organizer;+ existing.attendees = event.attendees;+ existing.myStatus = event.myStatus;+ // `undefined` means this producer never described the event's+ // conferencing — a legacy push, or an MCP payload predating the field —+ // so the cached link stands. Anything else is the current snapshot:+ // replace it, or clear it to null when the meeting no longer has one.+ // Without this gate an older client silently drops a working Join action.+ if (event.meetingUrl !== undefined) existing.meetingUrl = event.meetingUrl;+ existing.syncedAt = event.syncedAt;+ updatedCount++;+ } else {+ // A newly cached event always carries the key, so `meetingUrl` is absent+ // from the cache only for records written before this shipped.+ const retained = { ...event, meetingUrl: event.meetingUrl ?? null };+ cache.events.push(retained);+ existingMap.set(event.externalId, retained);+ newCount++;+ }}- }- // Prune events for this subcalendar that are no longer present. Skipped when- // the caller can't vouch that `rawEvents` is complete (see options.prune).- let pruned = 0;- if (shouldPrune) {- const before = cache.events.length;- cache.events = cache.events.filter(e =>- e.subcalendarId !== calendarId || incomingIds.has(e.externalId)- );- pruned = before - cache.events.length;- }+ // Prune events for this subcalendar that are no longer present. Skipped when+ // the caller can't vouch that `rawEvents` is complete (see options.prune).+ let pruned = 0;+ if (shouldPrune) {+ const before = cache.events.length;+ cache.events = cache.events.filter(e =>+ e.subcalendarId !== calendarId || incomingIds.has(e.externalId)+ );+ pruned = before - cache.events.length;+ }- await saveCache(accountId, cache);+ return { newCount, updatedCount, pruned, total: cache.events.length };+ });await updateSyncStatus(accountId, status);// Auto-log Tribe touchpoints from this subcalendar batch (#2033) — secondary@@ -181,7 +186,7 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEve});console.log(`📅 Google push sync for ${calendarName}: ${newCount} new, ${updatedCount} updated, ${pruned} pruned${shouldPrune ? '' : ' (prune skipped — partial payload)'}`);- return { newEvents: newCount, updated: updatedCount, pruned, total: cache.events.length, status };+ return { newEvents: newCount, updated: updatedCount, pruned, total, status };}/**@@ -210,6 +215,15 @@ const mcpSyncLock = new Map();export async function mcpSyncAccount(accountId, io) {if (mcpSyncLock.has(accountId)) throw new ServerError('MCP sync already in progress', { status: 409 });+ mcpSyncLock.set(accountId, true);+ try {+ return await runMcpSyncAccount(accountId, io);+ } finally {+ mcpSyncLock.delete(accountId);+ }+}++async function runMcpSyncAccount(accountId, io) {const account = await getAccount(accountId);if (!account) throw new ServerError('Account not found', { status: 404 });if (account.type !== 'google-calendar') throw new ServerError('Not a Google Calendar account', { status: 400 });@@ -217,7 +231,6 @@ export async function mcpSyncAccount(accountId, io) {const enabledCalendars = (account.subcalendars || []).filter(sc => sc.enabled && !sc.dormant);if (enabledCalendars.length === 0) throw new ServerError('No enabled subcalendars', { status: 400 });- mcpSyncLock.set(accountId, true);io?.emit('calendar:sync:started', { accountId, method: 'mcp' });console.log(`📅 Starting MCP sync for ${account.name} (${enabledCalendars.length} calendars)`);@@ -309,8 +322,6 @@ Include the full events arrays as returned by gcal_list_events, with every fieldio?.emit('calendar:sync:failed', { accountId, error: error.message, method: 'mcp' });await updateSyncStatus(accountId, 'error').catch(() => {});throw error instanceof ServerError ? error : new ServerError(error.message, { status: 502 });- }).finally(() => {- mcpSyncLock.delete(accountId);});}diff --git a/server/services/calendarGoogleSync.test.js b/server/services/calendarGoogleSync.test.jsindex b66079cd85..7386769a92 100644--- a/server/services/calendarGoogleSync.test.js+++ b/server/services/calendarGoogleSync.test.js@@ -20,6 +20,12 @@ vi.mock('./calendarAccounts.js', () => ({vi.mock('./calendarSync.js', () => ({loadCache: vi.fn(),saveCache: vi.fn(async () => {}),+ mutateCache: vi.fn(async (id, mutate) => {+ const cache = await loadCache(id);+ const result = await mutate(cache, await getAccount(id));+ await saveCache(id, cache);+ return result;+ }),logCalendarTouchpoints: vi.fn(async () => {}),recordCalendarActivity: vi.fn(async () => {}),}));diff --git a/server/services/calendarSync.js b/server/services/calendarSync.jsindex ad8df64ccc..1d92c16bad 100644--- a/server/services/calendarSync.js+++ b/server/services/calendarSync.js@@ -1,12 +1,14 @@import { readdir, unlink } from 'fs/promises';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 { getUserTimezone } from './userTimezone.js';import { getAccount, updateSyncStatus } from './calendarAccounts.js';export const CACHE_DIR = join(PATHS.calendar, 'cache');const syncLocks = new Map();+const queueCacheWrite = createKeyedFileWriteQueue();const CALENDAR_SEARCH_FIELDS = ['title', 'description', 'location', 'organizer.name'];function filterBySearch(events, search) {@@ -31,17 +33,31 @@ const DEFAULT_CACHE = { syncCursor: null, events: [] };export async function loadCache(accountId) {if (!UUID_RE.test(accountId)) throw new Error(`Invalid accountId: ${accountId}`);await ensureDir(CACHE_DIR);- const parsed = await readJSONFile(join(CACHE_DIR, `${accountId}.json`), DEFAULT_CACHE);- if (!parsed || !Array.isArray(parsed.events)) return { ...DEFAULT_CACHE };+ const parsed = await readJSONFile(join(CACHE_DIR, `${accountId}.json`), { ...DEFAULT_CACHE, events: [] });+ if (!parsed || !Array.isArray(parsed.events)) return { ...DEFAULT_CACHE, events: [] };return parsed;}-export async function saveCache(accountId, cache) {+async function saveCache(accountId, cache) {await ensureDir(CACHE_DIR);const filePath = join(CACHE_DIR, `${accountId}.json`);await atomicWrite(filePath, cache);}+// One file per account: load, mutate and persist under the same queue. Account+// deletion removes metadata BEFORE queueing deleteCache; earlier writes drain+// before unlink, and later/provider-delayed writes reject instead of resurrecting.+export function mutateCache(accountId, mutate) {+ return queueCacheWrite(accountId, async () => {+ const account = await getAccount(accountId);+ if (!account) throw new ServerError('Account not found', { status: 404 });+ const cache = await loadCache(accountId);+ const result = await mutate(cache, account);+ await saveCache(accountId, cache);+ return result;+ });+}+function filterDeclinedAndCancelled(events) {return events.filter(e =>e.myStatus !== 'declined' &&@@ -110,21 +126,20 @@ export async function getEvents(options = {}) {}export async function purgeDisabledSubcalendars(accountId) {- const account = await getAccount(accountId);- if (!account?.subcalendars?.length) return { purged: 0 };-- const enabledIds = new Set(- account.subcalendars.filter(sc => sc.enabled && !sc.dormant).map(sc => sc.calendarId)- );- const cache = await loadCache(accountId);- const before = cache.events.length;- cache.events = cache.events.filter(e => !e.subcalendarId || enabledIds.has(e.subcalendarId));- const purged = before - cache.events.length;- if (purged > 0) {- await saveCache(accountId, cache);- console.log(`🧹 Purged ${purged} events from disabled subcalendars for account ${accountId}`);- }- return { purged, remaining: cache.events.length };+ return mutateCache(accountId, (cache, account) => {+ if (!account?.subcalendars?.length) return { purged: 0 };++ const enabledIds = new Set(+ account.subcalendars.filter(sc => sc.enabled && !sc.dormant).map(sc => sc.calendarId)+ );+ const before = cache.events.length;+ cache.events = cache.events.filter(e => !e.subcalendarId || enabledIds.has(e.subcalendarId));+ const purged = before - cache.events.length;+ if (purged > 0) {+ console.log(`🧹 Purged ${purged} events from disabled subcalendars for account ${accountId}`);+ }+ return { purged, remaining: cache.events.length };+ });}export async function getEvent(accountId, eventId) {@@ -136,27 +151,37 @@ export async function getEvent(accountId, eventId) {export async function deleteCache(accountId) {if (!UUID_RE.test(accountId)) return;- const filePath = join(CACHE_DIR, `${accountId}.json`);- try {- await unlink(filePath);- console.log(`🗑️ Calendar cache deleted for account ${accountId}`);- } catch (err) {- if (err.code === 'ENOENT') {- console.log(`🗑️ No calendar cache to delete for account ${accountId}`);- } else {- console.error(`❌ Failed to delete calendar cache for account ${accountId}: ${err.message}`);+ return queueCacheWrite(accountId, async () => {+ const filePath = join(CACHE_DIR, `${accountId}.json`);+ try {+ await unlink(filePath);+ console.log(`🗑️ Calendar cache deleted for account ${accountId}`);+ } catch (err) {+ if (err.code === 'ENOENT') {+ console.log(`🗑️ No calendar cache to delete for account ${accountId}`);+ } else {+ console.error(`❌ Failed to delete calendar cache for account ${accountId}: ${err.message}`);+ }}- }+ });}export async function syncAccount(accountId, io, options = {}) {if (syncLocks.has(accountId)) throw new ServerError('Sync already in progress', { status: 409 });+ syncLocks.set(accountId, true);+ try {+ return await runAccountSync(accountId, io, options);+ } finally {+ syncLocks.delete(accountId);+ }+}++async function runAccountSync(accountId, io, options) {const account = await getAccount(accountId);if (!account) throw new ServerError('Account not found', { status: 404 });if (!account.enabled) throw new ServerError('Account is disabled', { status: 400 });- syncLocks.set(accountId, true);io?.emit('calendar:sync:started', { accountId });console.log(`📅 Starting calendar sync for ${account.name} (${account.type})`);@@ -180,49 +205,51 @@ export async function syncAccount(accountId, io, options = {}) {const newEvents = Array.isArray(providerResult) ? providerResult : providerResult?.events ?? [];const providerStatus = Array.isArray(providerResult) ? 'success' : providerResult?.status ?? 'success';- // Deduplicate by externalId; update fields on existing events- const existingMap = new Map();- cache.events = cache.events.filter(event => {- if (!event.externalId) return true;- if (existingMap.has(event.externalId)) return false;- existingMap.set(event.externalId, event);- return true;- });- const uniqueNew = [];- for (const event of newEvents) {- if (!event.externalId || !existingMap.has(event.externalId)) {- uniqueNew.push(event);- if (event.externalId) existingMap.set(event.externalId, event);- } else {- const existing = existingMap.get(event.externalId);- // Update mutable fields- if (event.title !== undefined) existing.title = event.title;- if (event.description !== undefined) existing.description = event.description;- if (event.location !== undefined) existing.location = event.location;- if (event.startTime !== undefined) existing.startTime = event.startTime;- if (event.endTime !== undefined) existing.endTime = event.endTime;- if (event.isAllDay !== undefined) existing.isAllDay = event.isAllDay;- if (event.isCancelled !== undefined) existing.isCancelled = event.isCancelled;- if (event.organizer !== undefined) existing.organizer = event.organizer;- if (event.attendees !== undefined) existing.attendees = event.attendees;- if (event.myStatus !== undefined) existing.myStatus = event.myStatus;- if (event.categories !== undefined) existing.categories = event.categories;- if (event.importance !== undefined) existing.importance = event.importance;+ const { newCount, pruned, total } = await mutateCache(accountId, cache => {+ // Deduplicate by externalId; update fields on existing events+ const existingMap = new Map();+ cache.events = cache.events.filter(event => {+ if (!event.externalId) return true;+ if (existingMap.has(event.externalId)) return false;+ existingMap.set(event.externalId, event);+ return true;+ });+ const uniqueNew = [];+ for (const event of newEvents) {+ if (!event.externalId || !existingMap.has(event.externalId)) {+ uniqueNew.push(event);+ if (event.externalId) existingMap.set(event.externalId, event);+ } else {+ const existing = existingMap.get(event.externalId);+ // Update mutable fields+ if (event.title !== undefined) existing.title = event.title;+ if (event.description !== undefined) existing.description = event.description;+ if (event.location !== undefined) existing.location = event.location;+ if (event.startTime !== undefined) existing.startTime = event.startTime;+ if (event.endTime !== undefined) existing.endTime = event.endTime;+ if (event.isAllDay !== undefined) existing.isAllDay = event.isAllDay;+ if (event.isCancelled !== undefined) existing.isCancelled = event.isCancelled;+ if (event.organizer !== undefined) existing.organizer = event.organizer;+ if (event.attendees !== undefined) existing.attendees = event.attendees;+ if (event.myStatus !== undefined) existing.myStatus = event.myStatus;+ if (event.categories !== undefined) existing.categories = event.categories;+ if (event.importance !== undefined) existing.importance = event.importance;+ }+ }+ cache.events.push(...uniqueNew);++ // Reconcile: remove cached events no longer present+ let pruned = 0;+ if (providerStatus === 'success') {+ const fetchedIds = new Set(newEvents.filter(e => e.externalId).map(e => e.externalId));+ const before = cache.events.length;+ cache.events = cache.events.filter(e => !e.externalId || fetchedIds.has(e.externalId));+ pruned = before - cache.events.length;+ if (pruned > 0) console.log(`🧹 Pruned ${pruned} stale calendar events from ${account.name}`);}- }- cache.events.push(...uniqueNew);-- // Reconcile: remove cached events no longer present- let pruned = 0;- if (providerStatus === 'success') {- const fetchedIds = new Set(newEvents.filter(e => e.externalId).map(e => e.externalId));- const before = cache.events.length;- cache.events = cache.events.filter(e => !e.externalId || fetchedIds.has(e.externalId));- pruned = before - cache.events.length;- if (pruned > 0) console.log(`🧹 Pruned ${pruned} stale calendar events from ${account.name}`);- }- await saveCache(accountId, cache);+ return { newCount: uniqueNew.length, pruned, total: cache.events.length };+ });await updateSyncStatus(accountId, providerStatus === 'success' ? 'success' : providerStatus);// Auto-log Tribe touchpoints from this batch (secondary effect — must not@@ -235,10 +262,10 @@ export async function syncAccount(accountId, io, options = {}) {await recordCalendarActivity(account, newEvents).catch((err) =>console.error(`🗓️ Activity ingest 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}`);+ io?.emit('calendar:sync:completed', { accountId, newEvents: newCount, pruned, status: providerStatus });+ console.log(`📅 Sync complete for ${account.name}: ${newCount} new, ${pruned} pruned, status=${providerStatus}`);- return { newEvents: uniqueNew.length, pruned, total: cache.events.length, status: providerStatus };+ return { newEvents: newCount, pruned, total, status: providerStatus };};const result = await providerSync().catch(async (error) => {@@ -246,8 +273,6 @@ export async function syncAccount(accountId, io, options = {}) {await updateSyncStatus(accountId, 'error').catch(() => {});io?.emit('calendar:sync:failed', { accountId, error: error.message });throw error instanceof ServerError ? error : new ServerError(error.message, { status: 502 });- }).finally(() => {- syncLocks.delete(accountId);});return result;