import type { LocalTask, ServerTask } from '../task-store'; import { DOGFOOD_OWNER } from './owner'; const isLocalOwner = (ownerId: string | null): boolean => ownerId === null || ownerId === DOGFOOD_OWNER; function inferLegacyOwner(tasks: LocalTask[]): string | null { const accountRows = tasks.filter((task) => !isLocalOwner(task.ownerId)); const candidates = accountRows.some((task) => task.deletedAt === undefined) ? accountRows.filter((task) => task.deletedAt === undefined) : accountRows; if (candidates.length === 0) return null; return candidates.reduce((latest, task) => { if (task.updatedAt !== latest.updatedAt) return task.updatedAt > latest.updatedAt ? task : latest; return (task.ownerId ?? '') > (latest.ownerId ?? '') ? task : latest; }).ownerId; } /** * Resolve provenance for stores written before `workspace.ownerId` existed. * Returning this from hydration makes the one-time inference stable across offline edits. */ export function resolvePersistedWorkspaceOwner( tasks: LocalTask[], workspaceOwnerId: string | null ): string | null { if (workspaceOwnerId !== null) return workspaceOwnerId; const accountOwners = new Set( tasks.map((task) => task.ownerId).filter((ownerId) => !isLocalOwner(ownerId)) ); if (accountOwners.size === 0) return null; if (accountOwners.size === 1) return [...accountOwners][0] ?? null; const hasLiveLocalRows = tasks.some( (task) => isLocalOwner(task.ownerId) && task.deletedAt === undefined ); return hasLiveLocalRows ? null : inferLegacyOwner(tasks); } /** All rows belonging to the one persisted workspace, including deletion tombstones. */ export function persistedWorkspaceTasks( tasks: LocalTask[], workspaceOwnerId: string | null ): LocalTask[] { const resolvedOwnerId = resolvePersistedWorkspaceOwner(tasks, workspaceOwnerId); if (resolvedOwnerId !== null) { return tasks.filter((task) => isLocalOwner(task.ownerId) || task.ownerId === resolvedOwnerId); } const localRows = tasks.filter((task) => isLocalOwner(task.ownerId)); // Multiple legacy owners plus live genuinely-local rows means the local rows are the only // unambiguous workspace. Account caches stay isolated until a target account is known. return localRows; } /** The single on-device workspace is visible regardless of sync/auth readiness. */ export function visibleWorkspaceTasks( tasks: LocalTask[], workspaceOwnerId: string | null = null ): LocalTask[] { return persistedWorkspaceTasks(tasks, workspaceOwnerId).filter( (task) => task.deletedAt === undefined ); } /** Include the target account's legacy cache while collapsing an ambiguous old multi-owner store. */ export function workspaceRowsForReconciliation( tasks: LocalTask[], workspaceOwnerId: string | null, targetOwnerId: string ): LocalTask[] { if (workspaceOwnerId !== null) return persistedWorkspaceTasks(tasks, workspaceOwnerId); const accountOwners = new Set(tasks.map((task) => task.ownerId).filter((ownerId) => !isLocalOwner(ownerId))); if (accountOwners.size <= 1) return tasks; return tasks.filter((task) => isLocalOwner(task.ownerId) || task.ownerId === targetOwnerId); } export function serverTaskToLocal(task: ServerTask): LocalTask { return { id: task.clientId, ownerId: task.ownerId, title: task.title, status: task.status, resistance: task.resistance, exposureCount: task.exposureCount, createdAt: task.createdAt, updatedAt: task.updatedAt, statusChangedAt: task.statusChangedAt, order: task.order, deferCount: task.deferCount, lastDecision: task.lastDecision, completedAt: task.completedAt, deletedAt: task.deletedAt, syncedAt: task.updatedAt, }; } /** * Combine the one local workspace with an account snapshot. * * Moving a row between accounts resets only its sync acknowledgement. Its content timestamp * stays untouched so account adoption cannot falsely beat a genuinely newer remote edit. * Tombstones from another account are omitted: they cannot delete a row that never existed * in the destination account. */ export function mergeWorkspace( localTasks: LocalTask[], serverTasks: ServerTask[], ownerId: string ): LocalTask[] { const merged = new Map(); for (const task of localTasks) { const changingOwner = task.ownerId !== ownerId; if (changingOwner && task.deletedAt !== undefined) continue; merged.set(task.id, { ...task, ownerId, syncedAt: changingOwner ? null : task.syncedAt, }); } for (const serverTask of serverTasks) { const incoming = serverTaskToLocal(serverTask); const local = merged.get(incoming.id); if (!local || incoming.updatedAt >= local.updatedAt) merged.set(incoming.id, incoming); } return [...merged.values()]; } export function replaceWorkspace(serverTasks: ServerTask[]): LocalTask[] { return serverTasks.map(serverTaskToLocal); } export type AuthIntent = 'signIn' | 'signUp' | null; export type WorkspaceReconciliationPlan = 'merge' | 'replace' | 'prompt'; type ReconciliationTask = Pick; /** * Decide whether authenticated startup is an automatic resume or needs the user's intent. * A cached Clerk session has no auth intent, while Glide's explicit sign-in/up forms persist * one immediately before finalizing the new session. */ export function planWorkspaceReconciliation({ authIntent, localTasks, workspaceOwnerId, remoteOwnerId, }: { authIntent: AuthIntent; localTasks: ReconciliationTask[]; workspaceOwnerId: string | null; remoteOwnerId: string; }): WorkspaceReconciliationPlan { const liveTasks = localTasks.filter((task) => task.deletedAt === undefined); if (liveTasks.length === 0) { // Preserve same-account tombstones on a returning session so pending deletes can drain. return localTasks.length > 0 && workspaceOwnerId === remoteOwnerId ? 'merge' : 'replace'; } if (authIntent === 'signUp') return 'merge'; if (authIntent === 'signIn') return 'prompt'; if (workspaceOwnerId === remoteOwnerId) return 'merge'; // One-time migration for stores created before workspace provenance was persisted. const compatibleLegacyRows = localTasks.every( (task) => task.ownerId === null || task.ownerId === DOGFOOD_OWNER || task.ownerId === remoteOwnerId ); return workspaceOwnerId === null && compatibleLegacyRows ? 'merge' : 'prompt'; }