import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify' import { execFile } from 'node:child_process' import { access, stat } from 'node:fs/promises' import { constants as fsConstants } from 'node:fs' import { platform } from 'node:os' import { basename, extname } from 'node:path' import { promisify } from 'node:util' import { db, sqlite } from '../db' import { tasks, statusDefinitions, activityLog, projects, workspaces, taskAttachments } from '../db/schema' import { eq, asc, desc, and, isNull, inArray } from 'drizzle-orm' import { hydrateTaskWithTags, hydrateTasksWithTags, replaceTaskTags } from '../lib/taskTags' const execFileAsync = promisify(execFile) const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i const COMMENT_MAX_LENGTH = 1000 const DESCRIPTION_MAX_LENGTH = 10000 const ATTACHMENT_NAME_MAX_LENGTH = 200 const ATTACHMENT_URI_MAX_LENGTH = 2000 const ATTACHMENT_KINDS = new Set(['file', 'image', 'pdf', 'folder']) const IMAGE_EXTENSIONS = new Set(['.apng', '.avif', '.gif', '.heic', '.jpeg', '.jpg', '.png', '.svg', '.webp']) const BLOCKED_OPEN_EXTENSIONS = new Set(['.app', '.command', '.scpt', '.terminal', '.workflow']) type SearchableTask = { id: string parentId: string | null title: string description: string | null tags?: Array<{ name: string }> } type TaskListQuery = { sort?: 'manual' | 'priority' | 'dueDate' | 'createdAt' order?: 'asc' | 'desc' filter?: 'all' | 'dueToday' | 'dueTomorrow' | 'dueThisWeek' | 'dueNextWeek' | 'pastDue' | 'noDate' | 'archived' includeArchived?: string q?: string } function isValidUUID(s: string): boolean { return UUID_REGEX.test(s) } function deleteTasksByIds(taskIds: string[]): number { const uniqueIds = [...new Set(taskIds)] if (uniqueIds.length === 0) return 0 const placeholders = uniqueIds.map(() => '?').join(', ') const countSelectedTasks = sqlite.prepare(`SELECT COUNT(*) AS count FROM tasks WHERE id IN (${placeholders})`) const deleteTasks = sqlite.prepare(` WITH RECURSIVE task_tree(id) AS ( SELECT id FROM tasks WHERE id IN (${placeholders}) UNION SELECT child.id FROM tasks child JOIN task_tree parent ON child.parent_id = parent.id ) DELETE FROM tasks WHERE id IN (SELECT id FROM task_tree) `) const transaction = sqlite.transaction(() => { const { count } = countSelectedTasks.get(...uniqueIds) as { count: number } deleteTasks.run(...uniqueIds) return count }) return transaction() } function addSubtaskCounts(taskRows: T[], allProjectTasks: Array<{ parentId: string | null; archived: boolean }>): T[] { const counts = new Map() for (const task of allProjectTasks) { if (!task.parentId) continue const current = counts.get(task.parentId) || { total: 0, completed: 0 } current.total += 1 if (task.archived) current.completed += 1 counts.set(task.parentId, current) } return taskRows.map((task) => { const count = counts.get(task.id) return { ...task, subtaskTotal: count?.total ?? 0, subtaskCompleted: count?.completed ?? 0, } }) } async function addAttachmentCounts(taskRows: T[]): Promise> { const taskIds = taskRows.map((task) => task.id) if (taskIds.length === 0) return taskRows.map((task) => ({ ...task, attachmentTotal: 0 })) const attachmentRows = await db.select({ taskId: taskAttachments.taskId }).from(taskAttachments) .where(inArray(taskAttachments.taskId, taskIds)) const counts = new Map() for (const attachment of attachmentRows) { counts.set(attachment.taskId, (counts.get(attachment.taskId) || 0) + 1) } return taskRows.map((task) => ({ ...task, attachmentTotal: counts.get(task.id) || 0, })) } function isTooLong(value: string | undefined, maxLength: number): boolean { return value !== undefined && value.length > maxLength } function normalizeAttachmentKind(kind: string | undefined): string { const normalized = kind?.trim().toLowerCase() || 'file' return ATTACHMENT_KINDS.has(normalized) ? normalized : 'file' } function isSupportedAttachmentKind(kind: string | undefined): boolean { if (!kind) return true return ATTACHMENT_KINDS.has(kind.trim().toLowerCase()) } function localPathToFileUri(localPath: string): string { return `file://${localPath.split('/').map(encodeURIComponent).join('/')}` } function inferAttachmentKind(localPath: string, requestedKind?: string): string { const normalized = normalizeAttachmentKind(requestedKind) if (localPath.endsWith('/')) return 'folder' if (normalized === 'folder') return 'folder' const extension = extname(localPath).toLowerCase() if (extension === '.pdf') return 'pdf' if (IMAGE_EXTENSIONS.has(extension)) return 'image' return normalized } function normalizeAttachmentUri(uri: string, kind?: string): string { const normalizedKind = normalizeAttachmentKind(kind) if (normalizedKind !== 'folder' && uri.startsWith('/')) return localPathToFileUri(uri) if (normalizedKind === 'folder' && uri.startsWith('/')) return localPathToFileUri(uri.replace(/\/$/, '')) return uri } function attachmentPathExtension(uri: string): string { let path = uri if (uri.startsWith('file://')) { try { path = decodeURIComponent(new URL(uri).pathname) } catch { return '' } } return extname(path).toLowerCase() } function attachmentUriToLocalPath(uri: string): string | null { if (!uri.startsWith('file://')) return null try { return decodeURIComponent(new URL(uri).pathname) } catch { return null } } function validateAttachmentReference(kind: string, uri: string): string | null { if (!uri.startsWith('file://')) return 'Attachments must reference a local file or folder' const extension = attachmentPathExtension(uri) if (kind === 'pdf' && extension !== '.pdf') return 'PDF attachments must be .pdf files' if (kind === 'image' && !IMAGE_EXTENSIONS.has(extension)) return 'Image attachments must be an image file' return null } async function openLocalAttachment(uri: string) { const localPath = attachmentUriToLocalPath(uri) if (!localPath) throw new Error('Attachment is not a local file or folder') const extension = extname(localPath.replace(/\/$/, '')).toLowerCase() if (BLOCKED_OPEN_EXTENSIONS.has(extension)) { const error = new Error('This attachment type cannot be opened from FocusClaw.') ;(error as Error & { statusCode?: number }).statusCode = 400 throw error } let fileStat try { await access(localPath) fileStat = await stat(localPath) } catch { const error = new Error('File not found. It may have been moved or deleted.') ;(error as Error & { statusCode?: number }).statusCode = 404 throw error } if (fileStat.isFile()) { try { await access(localPath, fsConstants.X_OK) const error = new Error('Executable attachments cannot be opened from FocusClaw.') ;(error as Error & { statusCode?: number }).statusCode = 400 throw error } catch (error) { if (error instanceof Error && 'statusCode' in error) throw error } } if (platform() !== 'darwin') { throw new Error('Opening local attachments is currently available on macOS only') } await execFileAsync('open', [localPath], { timeout: 15000 }) } async function pickLocalAttachment(kind?: string) { if (platform() !== 'darwin') { throw new Error('Local file picking is currently available on macOS only') } const requestedKind = kind?.trim().toLowerCase() const normalizedKind = normalizeAttachmentKind(kind) const script = !requestedKind ? 'POSIX path of (choose file with prompt "Choose a file to attach to FocusClaw")' : normalizedKind === 'folder' ? 'POSIX path of (choose folder with prompt "Choose a folder to attach to FocusClaw")' : normalizedKind === 'pdf' ? 'POSIX path of (choose file with prompt "Choose a PDF to attach to FocusClaw" of type {"com.adobe.pdf", "PDF"})' : normalizedKind === 'image' ? 'POSIX path of (choose file with prompt "Choose an image to attach to FocusClaw" of type {"public.image"})' : 'POSIX path of (choose file with prompt "Choose a file to attach to FocusClaw")' const { stdout } = await execFileAsync('osascript', ['-e', script], { timeout: 120000 }) const localPath = stdout.trim() if (!localPath) return null return { name: basename(localPath.replace(/\/$/, '')) || localPath, kind: inferAttachmentKind(localPath, normalizedKind), uri: localPathToFileUri(localPath), } } function localDateKey(date = new Date()): string { return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}` } function startOfNextMondayFirstWeek(today: Date): Date { const start = new Date(today) start.setHours(0, 0, 0, 0) const dayOffset = (8 - start.getDay()) % 7 || 7 start.setDate(start.getDate() + dayOffset) return start } function parseDueDateInput(input: string): Date { const dateOnlyMatch = input.match(/^(\d{4})-(\d{2})-(\d{2})$/) if (dateOnlyMatch) { const [, year, month, day] = dateOnlyMatch return new Date(Number(year), Number(month) - 1, Number(day), 23, 59, 59, 999) } return new Date(input) } function taskDueDateKey(dueDate: Date | string | null): string | null { if (!dueDate) return null const date = dueDate instanceof Date ? dueDate : new Date(dueDate) if (Number.isNaN(date.getTime())) return null // Older date-picker tasks were saved from YYYY-MM-DD as UTC midnight. // Preserve the intended calendar day for those records. const isUtcMidnight = date.getUTCHours() === 0 && date.getUTCMinutes() === 0 && date.getUTCSeconds() === 0 && date.getUTCMilliseconds() === 0 return isUtcMidnight ? date.toISOString().slice(0, 10) : localDateKey(date) } async function rotateHighlightsToToday(projectIds: string[]): Promise { if (projectIds.length === 0) return const highlighted = await db.select().from(tasks).where(and( inArray(tasks.projectId, projectIds), eq(tasks.highlight, true), eq(tasks.archived, false), )) const todayKey = localDateKey() const staleIds = highlighted .filter((task) => taskDueDateKey(task.dueDate) !== todayKey) .map((task) => task.id) if (staleIds.length === 0) return await db.update(tasks) .set({ dueDate: parseDueDateInput(todayKey), updatedAt: new Date() }) .where(inArray(tasks.id, staleIds)) } function readActivityChanges(raw: string | null): Record { if (!raw) return {} try { const parsed = JSON.parse(raw) return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {} } catch { return {} } } function textMatchesSearch(value: unknown, query: string): boolean { return typeof value === 'string' && value.toLowerCase().includes(query) } function taskMatchesSearch( task: SearchableTask, query: string, projectName: string, commentsByTaskId: Map, subtasksByParentId: Map, ): boolean { if (textMatchesSearch(task.title, query)) return true if (textMatchesSearch(task.description, query)) return true if (textMatchesSearch(projectName, query)) return true if (task.tags?.some((tag) => textMatchesSearch(tag.name, query))) return true if (commentsByTaskId.get(task.id)?.some((content) => textMatchesSearch(content, query))) return true const subtasks = subtasksByParentId.get(task.id) || [] return subtasks.some((subtask) => textMatchesSearch(subtask.title, query) || textMatchesSearch(subtask.description, query) || subtask.tags?.some((tag) => textMatchesSearch(tag.name, query)) || commentsByTaskId.get(subtask.id)?.some((content) => textMatchesSearch(content, query)), ) } // ───────────────────────────────────────────── // Natural Language Date Parser // ───────────────────────────────────────────── // Lightweight parser for common date expressions — no external deps needed. // Handles: "today", "tomorrow", "next [day]", "in X days", "next week", "monday-sunday" (standalone or as next X) function parseNaturalDate(input: string): { dueDate: Date | null; reasoning: string } { const now = new Date() const lower = input.toLowerCase().trim() // today if (/\btoday\b/.test(lower)) { return { dueDate: new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59), reasoning: 'Parsed "today"' } } // tomorrow if (/\btomorrow\b/.test(lower)) { const d = new Date(now); d.setDate(d.getDate() + 1) return { dueDate: new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59), reasoning: 'Parsed "tomorrow"' } } // in X days / in X weeks const inDaysMatch = lower.match(/\bin\s+(\d+)\s+(days?|weeks?)\b/) if (inDaysMatch) { const num = parseInt(inDaysMatch[1]) const unit = inDaysMatch[2] const d = new Date(now) if (unit.startsWith('day')) d.setDate(d.getDate() + num) else d.setDate(d.getDate() + num * 7) return { dueDate: new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59), reasoning: `Parsed "in ${num} ${unit}"` } } // next week if (/\bnext\s+week\b/.test(lower)) { const d = new Date(now); d.setDate(d.getDate() + 7) return { dueDate: new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59), reasoning: 'Parsed "next week"' } } // next [day name] — find the next occurrence of that day const dayNames = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday'] const nextDayMatch = lower.match(/\bnext\s+(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\b/) if (nextDayMatch) { const targetDay = dayNames.indexOf(nextDayMatch[1]) if (targetDay !== -1) { const d = new Date(now) const diff = (targetDay - d.getDay() + 7) % 7 || 7 // if same day, go to next week d.setDate(d.getDate() + diff) return { dueDate: new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59), reasoning: `Parsed "next ${nextDayMatch[1]}"` } } } // standalone day names: "monday", "friday" → next occurrence const singleDayMatch = lower.match(/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)$/) if (singleDayMatch) { const targetDay = dayNames.indexOf(singleDayMatch[0]) const d = new Date(now) const diff = (targetDay - d.getDay() + 7) % 7 || 7 d.setDate(d.getDate() + diff) return { dueDate: new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59), reasoning: `Parsed "${singleDayMatch[0]}"` } } // priority keywords if (/\b(critical|urgent|asap)\b/.test(lower)) { return { dueDate: null, reasoning: 'Detected critical priority keyword' } } return { dueDate: null, reasoning: 'No natural date detected' } } // Smart priority detection from keywords function detectPriorityFromText(input: string): number { const lower = input.toLowerCase() if (/\b(critical|urgent|asap|p0)\b/.test(lower)) return 1 if (/\b(high|important|p1)\b/.test(lower)) return 2 if (/\b(medium|normal|p2)\b/.test(lower)) return 3 if (/\b(low|p3)\b/.test(lower)) return 4 return 2 // default high } export async function taskRoutes(fastify: FastifyInstance) { // Create task — with natural language support fastify.post('/', async (request: FastifyRequest, reply: FastifyReply) => { const { projectId, title, description, statusId, priority, dueDate, assignee, labels, parentId, recurring, recurringEnd, dependsOn, } = request.body as { projectId: string title: string description?: string statusId?: string priority?: number dueDate?: string assignee?: string | null labels?: string[] parentId?: string recurring?: string recurringEnd?: string dependsOn?: string[] } if (!projectId || !title) { return reply.status(400).send({ error: 'projectId and title are required' }) } if (isTooLong(description, DESCRIPTION_MAX_LENGTH)) { return reply.status(400).send({ error: `Description must be ${DESCRIPTION_MAX_LENGTH} chars or less` }) } // ── Natural Language Parsing ────────────────────────────────────────── const combinedText = `${title} ${description || ''}` const { dueDate: nlDueDate, reasoning: dateReasoning } = parseNaturalDate(combinedText) const nlPriority = priority ?? detectPriorityFromText(combinedText) const explicitRecurring = recurring?.trim() || null // Use NL-parsed date if no explicit dueDate provided const finalDueDate = dueDate ? (dueDate ? parseDueDateInput(dueDate) : undefined) : (nlDueDate || undefined) const aiReasoning = [ dateReasoning, nlPriority !== 2 ? `Priority detected: ${nlPriority}` : '', explicitRecurring ? `Recurring selected: ${explicitRecurring}` : '', ].filter(Boolean).join('; ') // ── Position (for root tasks, or subtasks) ───────────────────────────── let position = 0 if (parentId) { // Subtasks get appended to end of parent const siblings = await db.select({ maxPos: tasks.position }) .from(tasks) .where(and(eq(tasks.projectId, projectId), eq(tasks.parentId, parentId))) .orderBy(desc(tasks.position)) .limit(1) position = siblings.length > 0 ? siblings[0].maxPos + 1 : 0 } else { const rootTaskPosition = sqlite.prepare(` SELECT COALESCE(MAX(task.position), -1) AS max_pos FROM tasks task JOIN projects task_project ON task_project.id = task.project_id WHERE task_project.workspace_id = ( SELECT workspace_id FROM projects WHERE id = ? ) AND task.parent_id IS NULL `).get(projectId) as { max_pos: number } position = rootTaskPosition.max_pos + 1 } // ── Dependencies ──────────────────────────────────────────────────────── const dependsOnJson = dependsOn && dependsOn.length > 0 ? JSON.stringify(dependsOn) : '[]' const [task] = await db.insert(tasks).values({ projectId, title, description: description ?? null, statusId: statusId ?? null, priority: nlPriority, dueDate: finalDueDate || null, assignee: assignee?.trim() || null, labels: '[]', position, parentId: parentId ?? null, recurring: explicitRecurring, recurringEnd: recurringEnd ? new Date(recurringEnd) : null, dependsOn: dependsOnJson, dueDateNatural: nlDueDate ? combinedText.match(/\b(next\s+\w+|today|tomorrow|\w+)\b/i)?.[0] ?? null : null, aiReasoning: aiReasoning || null }).returning() if (!task) return reply.status(500).send({ error: 'Failed to create task' }) const canonicalTags = replaceTaskTags(task.id, projectId, labels || []) // Log activity await db.insert(activityLog).values({ taskId: task.id, action: 'created', changes: JSON.stringify({ title, priority: nlPriority, statusId, aiReasoning }), userId: undefined }) return reply.status(201).send({ ...task, tags: canonicalTags, labels: JSON.stringify(canonicalTags.map((tag) => tag.name)), subtaskTotal: 0, subtaskCompleted: 0, attachmentTotal: 0, }) }) async function listTasksForProjects(projectIds: string[], projectNameById: Map, query: TaskListQuery) { if (projectIds.length === 0) return [] await rotateHighlightsToToday(projectIds) const { sort, order, filter, includeArchived, q } = query const sortField = sort === 'dueDate' ? tasks.dueDate : sort === 'createdAt' ? tasks.createdAt : tasks.priority const sortDirection = order === 'desc' ? desc(sortField) : asc(sortField) const allProjectTasks = await db.select().from(tasks) .where(inArray(tasks.projectId, projectIds)) .orderBy( asc(tasks.archived), desc(tasks.highlight), ...(sort === 'manual' ? [asc(tasks.priority), asc(tasks.position)] : [asc(tasks.projectId), sortDirection]), ) let result = allProjectTasks const hydratedProjectTasks = hydrateTasksWithTags(allProjectTasks) const hydratedTaskById = new Map(hydratedProjectTasks.map((task) => [task.id, task])) const today = new Date() today.setHours(0, 0, 0, 0) const todayKey = localDateKey(today) const tomorrow = new Date(today) tomorrow.setDate(tomorrow.getDate() + 1) const tomorrowKey = localDateKey(tomorrow) const dayAfterTomorrow = new Date(tomorrow) dayAfterTomorrow.setDate(tomorrow.getDate() + 1) const dayAfterTomorrowKey = localDateKey(dayAfterTomorrow) const nextWeek = new Date(today) nextWeek.setDate(nextWeek.getDate() + 7) const nextWeekKey = localDateKey(nextWeek) const nextCalendarWeekStart = startOfNextMondayFirstWeek(today) const nextCalendarWeekEnd = new Date(nextCalendarWeekStart) nextCalendarWeekEnd.setDate(nextCalendarWeekEnd.getDate() + 7) const nextCalendarWeekStartKey = localDateKey(nextCalendarWeekStart) const nextCalendarWeekEndKey = localDateKey(nextCalendarWeekEnd) const shouldIncludeArchived = includeArchived === 'true' const isVisibleForDateFilter = (task: typeof result[number]) => shouldIncludeArchived || !task.archived if (filter === 'dueToday') { result = result.filter(t => isVisibleForDateFilter(t) && taskDueDateKey(t.dueDate) === todayKey) } else if (filter === 'dueTomorrow') { result = result.filter(t => { const dueKey = taskDueDateKey(t.dueDate) return isVisibleForDateFilter(t) && dueKey !== null && dueKey >= tomorrowKey && dueKey < dayAfterTomorrowKey }) } else if (filter === 'dueThisWeek') { result = result.filter(t => { const dueKey = taskDueDateKey(t.dueDate) return isVisibleForDateFilter(t) && dueKey !== null && dueKey >= todayKey && dueKey < nextWeekKey }) } else if (filter === 'dueNextWeek') { result = result.filter(t => { const dueKey = taskDueDateKey(t.dueDate) return isVisibleForDateFilter(t) && dueKey !== null && dueKey >= nextCalendarWeekStartKey && dueKey < nextCalendarWeekEndKey }) } else if (filter === 'pastDue') { result = result.filter(t => { const dueKey = taskDueDateKey(t.dueDate) return isVisibleForDateFilter(t) && dueKey !== null && dueKey < todayKey }) } else if (filter === 'noDate') { result = result.filter(t => (shouldIncludeArchived || !t.archived) && !t.dueDate) } else if (filter === 'archived') { result = result.filter(t => t.archived) } else if (!shouldIncludeArchived) { result = result.filter(t => !t.archived) } const searchQuery = q?.trim().toLowerCase() if (searchQuery) { const taskIds = allProjectTasks.map((task) => task.id) const commentRows = taskIds.length > 0 ? await db.select().from(activityLog).where(and(inArray(activityLog.taskId, taskIds), eq(activityLog.action, 'comment'))) : [] const commentsByTaskId = new Map() for (const row of commentRows) { const content = readActivityChanges(row.changes).content if (typeof content !== 'string') continue const current = commentsByTaskId.get(row.taskId) || [] current.push(content) commentsByTaskId.set(row.taskId, current) } const subtasksByParentId = new Map() for (const task of hydratedProjectTasks) { if (!task.parentId) continue const current = subtasksByParentId.get(task.parentId) || [] current.push(task) subtasksByParentId.set(task.parentId, current) } result = result.filter((task) => { const hydratedTask = hydratedTaskById.get(task.id) return hydratedTask ? taskMatchesSearch(hydratedTask, searchQuery, projectNameById.get(task.projectId) || '', commentsByTaskId, subtasksByParentId) : false }) } return addAttachmentCounts(addSubtaskCounts(hydrateTasksWithTags(result), allProjectTasks)) } // List tasks across all projects, a workspace, or a single project. fastify.get('/', async (request: FastifyRequest, reply: FastifyReply) => { const { projectId, workspaceId, ...query } = request.query as TaskListQuery & { projectId?: string workspaceId?: string } if (projectId) { if (!isValidUUID(projectId)) return reply.send([]) const projectRows = await db.select().from(projects).where(eq(projects.id, projectId)).limit(1) if (projectRows.length === 0) return reply.send([]) return reply.send(await listTasksForProjects([projectId], new Map([[projectId, projectRows[0].name]]), query)) } const projectRows = workspaceId ? await db.select().from(projects).where(eq(projects.workspaceId, workspaceId)).orderBy(asc(projects.createdAt)) : await db.select().from(projects).orderBy(asc(projects.createdAt)) const projectIds = projectRows.map((project) => project.id) const projectNameById = new Map(projectRows.map((project) => [project.id, project.name])) return reply.send(await listTasksForProjects(projectIds, projectNameById, query)) }) // List tasks by project fastify.get('/project/:projectId', async (request: FastifyRequest, reply: FastifyReply) => { const { projectId } = request.params as { projectId: string } const { sort, order, filter, includeArchived, q } = request.query as { sort?: 'manual' | 'priority' | 'dueDate' | 'createdAt' order?: 'asc' | 'desc' filter?: 'all' | 'dueToday' | 'dueTomorrow' | 'dueThisWeek' | 'dueNextWeek' | 'pastDue' | 'noDate' | 'archived' includeArchived?: string q?: string } // Validate UUID format before querying if (!isValidUUID(projectId)) { return reply.send([]) } // Validate project exists const projectExists = await db.select().from(projects).where(eq(projects.id, projectId)).limit(1) if (projectExists.length === 0) { return reply.send([]) } await rotateHighlightsToToday([projectId]) // Open tasks stay above completed tasks, with the Highlight first; selected sort applies within each group. const sortField = sort === 'dueDate' ? tasks.dueDate : sort === 'createdAt' ? tasks.createdAt : tasks.priority const sortDirection = order === 'desc' ? desc(sortField) : asc(sortField) const allProjectTasks = await db.select().from(tasks) .where(eq(tasks.projectId, projectId)) .orderBy( asc(tasks.archived), desc(tasks.highlight), ...(sort === 'manual' ? [asc(tasks.priority), asc(tasks.position)] : [sortDirection]), ) let result = allProjectTasks const hydratedProjectTasks = hydrateTasksWithTags(allProjectTasks) const hydratedTaskById = new Map(hydratedProjectTasks.map((task) => [task.id, task])) const today = new Date() today.setHours(0, 0, 0, 0) const todayKey = localDateKey(today) const tomorrow = new Date(today) tomorrow.setDate(tomorrow.getDate() + 1) const tomorrowKey = localDateKey(tomorrow) const dayAfterTomorrow = new Date(tomorrow) dayAfterTomorrow.setDate(tomorrow.getDate() + 1) const dayAfterTomorrowKey = localDateKey(dayAfterTomorrow) const nextWeek = new Date(today) nextWeek.setDate(nextWeek.getDate() + 7) const nextWeekKey = localDateKey(nextWeek) const nextCalendarWeekStart = startOfNextMondayFirstWeek(today) const nextCalendarWeekEnd = new Date(nextCalendarWeekStart) nextCalendarWeekEnd.setDate(nextCalendarWeekEnd.getDate() + 7) const nextCalendarWeekStartKey = localDateKey(nextCalendarWeekStart) const nextCalendarWeekEndKey = localDateKey(nextCalendarWeekEnd) const shouldIncludeArchived = includeArchived === 'true' const isVisibleForDateFilter = (task: typeof result[number]) => shouldIncludeArchived || !task.archived // Apply filters in JS (simpler than SQL date math) // NOTE: 'all' is the default — excludes archived tasks unless includeArchived=true. // Date filters include completed tasks only when includeArchived=true. // 'noDate' returns active tasks without a due date unless includeArchived=true. // 'archived' explicitly returns only archived tasks (completed tasks). if (filter === 'dueToday') { result = result.filter(t => isVisibleForDateFilter(t) && taskDueDateKey(t.dueDate) === todayKey) } else if (filter === 'dueTomorrow') { result = result.filter(t => { const dueKey = taskDueDateKey(t.dueDate) return isVisibleForDateFilter(t) && dueKey !== null && dueKey >= tomorrowKey && dueKey < dayAfterTomorrowKey }) } else if (filter === 'dueThisWeek') { result = result.filter(t => { const dueKey = taskDueDateKey(t.dueDate) return isVisibleForDateFilter(t) && dueKey !== null && dueKey >= todayKey && dueKey < nextWeekKey }) } else if (filter === 'dueNextWeek') { result = result.filter(t => { const dueKey = taskDueDateKey(t.dueDate) return isVisibleForDateFilter(t) && dueKey !== null && dueKey >= nextCalendarWeekStartKey && dueKey < nextCalendarWeekEndKey }) } else if (filter === 'pastDue') { result = result.filter(t => { const dueKey = taskDueDateKey(t.dueDate) return isVisibleForDateFilter(t) && dueKey !== null && dueKey < todayKey }) } else if (filter === 'noDate') { result = result.filter(t => (shouldIncludeArchived || !t.archived) && !t.dueDate) } else if (filter === 'archived') { result = result.filter(t => t.archived) } else if (!shouldIncludeArchived) { // 'all' or undefined — default to active tasks only (exclude archived) result = result.filter(t => !t.archived) } const searchQuery = q?.trim().toLowerCase() if (searchQuery) { const projectTaskIds = allProjectTasks.map((task) => task.id) const commentRows = projectTaskIds.length > 0 ? await db.select().from(activityLog).where(and(inArray(activityLog.taskId, projectTaskIds), eq(activityLog.action, 'comment'))) : [] const commentsByTaskId = new Map() for (const row of commentRows) { const content = readActivityChanges(row.changes).content if (typeof content !== 'string') continue const current = commentsByTaskId.get(row.taskId) || [] current.push(content) commentsByTaskId.set(row.taskId, current) } const subtasksByParentId = new Map() for (const task of hydratedProjectTasks) { if (!task.parentId) continue const current = subtasksByParentId.get(task.parentId) || [] current.push(task) subtasksByParentId.set(task.parentId, current) } result = result.filter((task) => { const hydratedTask = hydratedTaskById.get(task.id) return hydratedTask ? taskMatchesSearch(hydratedTask, searchQuery, projectExists[0].name, commentsByTaskId, subtasksByParentId) : false }) } const hydrated = await addAttachmentCounts(addSubtaskCounts(hydrateTasksWithTags(result), allProjectTasks)) return reply.send(hydrated) }) // Change selected tasks only; never run completion, recurrence, or project-move logic. fastify.post('/bulk-reschedule', async (request: FastifyRequest, reply: FastifyReply) => { const { taskIds, dueDate } = (request.body ?? {}) as { taskIds?: unknown; dueDate?: unknown } if (!Array.isArray(taskIds) || taskIds.length === 0 || taskIds.length > 5000) { return reply.status(400).send({ error: 'taskIds must contain 1-5000 task IDs' }) } if (!taskIds.every((id) => typeof id === 'string' && isValidUUID(id))) { return reply.status(400).send({ error: 'Every task ID must be a valid UUID' }) } if (typeof dueDate !== 'string' || !/^[1-9]\d{3}-\d{2}-\d{2}$/.test(dueDate)) { return reply.status(400).send({ error: 'dueDate must be a calendar date in YYYY-MM-DD format (1000-9999)' }) } const parsed = parseDueDateInput(dueDate) if (!Number.isFinite(parsed.getTime()) || localDateKey(parsed) !== dueDate) { return reply.status(400).send({ error: 'dueDate must be an actual calendar date' }) } const ids = [...new Set(taskIds)] const placeholders = ids.map(() => '?').join(', ') const offToday = dueDate !== localDateKey() const reschedule = sqlite.transaction(() => { const rows = sqlite.prepare(`SELECT id, highlight FROM tasks WHERE id IN (${placeholders})`) .all(...ids) as Array<{ id: string; highlight: number }> if (rows.length !== ids.length) return null sqlite.prepare(`UPDATE tasks SET due_date = ?, updated_at = unixepoch(), highlight = CASE WHEN ? THEN 0 ELSE highlight END WHERE id IN (${placeholders})`) .run(Math.floor(parsed.getTime() / 1000), offToday ? 1 : 0, ...ids) return { rescheduledCount: ids.length, clearedHighlightCount: offToday ? rows.filter((row) => row.highlight).length : 0 } }) const result = reschedule() if (!result) return reply.status(404).send({ error: 'One or more selected tasks no longer exist; no tasks were changed' }) return reply.send({ ...result, dueDate: new Date(Math.floor(parsed.getTime() / 1000) * 1000).toISOString() }) }) // Delete multiple tasks in one transaction. Related task metadata cascades with each task. fastify.post('/bulk-delete', async (request: FastifyRequest, reply: FastifyReply) => { const { taskIds } = (request.body || {}) as { taskIds?: unknown } if (!Array.isArray(taskIds) || taskIds.length === 0) { return reply.status(400).send({ error: 'taskIds must be a non-empty array' }) } if (taskIds.length > 5000) { return reply.status(400).send({ error: 'A maximum of 5000 tasks can be deleted at once' }) } if (!taskIds.every((taskId) => typeof taskId === 'string' && isValidUUID(taskId))) { return reply.status(400).send({ error: 'Every task ID must be a valid UUID' }) } const deletedCount = deleteTasksByIds(taskIds) return reply.send({ deletedCount }) }) fastify.post('/attachments/pick-local', async (request: FastifyRequest, reply: FastifyReply) => { const { kind } = (request.body ?? {}) as { kind?: string } try { const picked = await pickLocalAttachment(kind) if (!picked) return reply.status(204).send() return reply.send(picked) } catch (error) { const message = error instanceof Error ? error.message : 'Could not open the local file picker' if (/user canceled/i.test(message)) return reply.status(204).send() return reply.status(501).send({ error: message }) } }) // List attachment metadata for a task. Files are not uploaded into FocusClaw. fastify.get('/:id/attachments', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } if (!isValidUUID(id)) return reply.status(400).send({ error: 'Invalid task ID' }) const existingTask = await db.select({ id: tasks.id }).from(tasks).where(eq(tasks.id, id)).limit(1) if (existingTask.length === 0) return reply.status(404).send({ error: 'Task not found' }) const result = await db.select().from(taskAttachments) .where(eq(taskAttachments.taskId, id)) .orderBy(asc(taskAttachments.createdAt)) return reply.send(result) }) // Add attachment metadata for a task. fastify.post('/:id/attachments', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const { name, kind, uri, mimeType, sizeBytes } = request.body as { name?: string kind?: string uri?: string mimeType?: string | null sizeBytes?: number | null } if (!isValidUUID(id)) return reply.status(400).send({ error: 'Invalid task ID' }) const existingTask = await db.select({ id: tasks.id }).from(tasks).where(eq(tasks.id, id)).limit(1) if (existingTask.length === 0) return reply.status(404).send({ error: 'Task not found' }) const nextName = name?.trim() if (!isSupportedAttachmentKind(kind)) { return reply.status(400).send({ error: 'Attachment type must be file, image, PDF, or folder' }) } const nextUri = uri ? normalizeAttachmentUri(uri.trim(), kind) : undefined if (!nextName || !nextUri) return reply.status(400).send({ error: 'Attachment name and local path are required' }) if (nextName.length > ATTACHMENT_NAME_MAX_LENGTH) { return reply.status(400).send({ error: `Attachment name must be ${ATTACHMENT_NAME_MAX_LENGTH} chars or less` }) } if (nextUri.length > ATTACHMENT_URI_MAX_LENGTH) { return reply.status(400).send({ error: `Attachment path must be ${ATTACHMENT_URI_MAX_LENGTH} chars or less` }) } const nextKind = normalizeAttachmentKind(kind) const attachmentError = validateAttachmentReference(nextKind, nextUri) if (attachmentError) { return reply.status(400).send({ error: attachmentError }) } if (sizeBytes !== undefined && sizeBytes !== null && (!Number.isFinite(sizeBytes) || sizeBytes < 0)) { return reply.status(400).send({ error: 'Attachment size must be a positive number' }) } const [attachment] = await db.insert(taskAttachments).values({ taskId: id, name: nextName, kind: nextKind, uri: nextUri, mimeType: mimeType?.trim() || null, sizeBytes: sizeBytes ?? null, }).returning() await db.insert(activityLog).values({ taskId: id, action: 'attachment_added', changes: JSON.stringify({ attachmentId: attachment.id, name: attachment.name, kind: attachment.kind }), }) return reply.status(201).send(attachment) }) // Rename attachment metadata. The original file path is intentionally immutable. fastify.patch('/:id/attachments/:attachmentId', async (request: FastifyRequest, reply: FastifyReply) => { const { id, attachmentId } = request.params as { id: string; attachmentId: string } const { name } = request.body as { name?: string } if (!isValidUUID(id) || !isValidUUID(attachmentId)) return reply.status(400).send({ error: 'Invalid attachment ID' }) const nextName = name?.trim() if (!nextName) return reply.status(400).send({ error: 'Attachment name is required' }) if (nextName.length > ATTACHMENT_NAME_MAX_LENGTH) { return reply.status(400).send({ error: `Attachment name must be ${ATTACHMENT_NAME_MAX_LENGTH} chars or less` }) } const existing = await db.select().from(taskAttachments) .where(and(eq(taskAttachments.id, attachmentId), eq(taskAttachments.taskId, id))) .limit(1) if (existing.length === 0) return reply.status(404).send({ error: 'Attachment not found' }) const [attachment] = await db.update(taskAttachments) .set({ name: nextName }) .where(eq(taskAttachments.id, attachmentId)) .returning() await db.insert(activityLog).values({ taskId: id, action: 'attachment_renamed', changes: JSON.stringify({ attachmentId, from: existing[0].name, to: attachment.name }), }) return reply.send(attachment) }) // Open an attachment on the local machine running the FocusClaw API. fastify.post('/:id/attachments/:attachmentId/open', async (request: FastifyRequest, reply: FastifyReply) => { const { id, attachmentId } = request.params as { id: string; attachmentId: string } if (!isValidUUID(id) || !isValidUUID(attachmentId)) return reply.status(400).send({ error: 'Invalid attachment ID' }) const existing = await db.select().from(taskAttachments) .where(and(eq(taskAttachments.id, attachmentId), eq(taskAttachments.taskId, id))) .limit(1) if (existing.length === 0) return reply.status(404).send({ error: 'Attachment not found' }) try { await openLocalAttachment(existing[0].uri) } catch (error) { const message = error instanceof Error ? error.message : 'Could not open attachment' const statusCode = error && typeof error === 'object' && 'statusCode' in error && typeof (error as { statusCode?: unknown }).statusCode === 'number' ? (error as { statusCode: number }).statusCode : 501 return reply.status(statusCode).send({ error: message }) } return reply.status(204).send() }) // Delete attachment metadata from a task. The referenced file or folder is not deleted. fastify.delete('/:id/attachments/:attachmentId', async (request: FastifyRequest, reply: FastifyReply) => { const { id, attachmentId } = request.params as { id: string; attachmentId: string } if (!isValidUUID(id) || !isValidUUID(attachmentId)) return reply.status(400).send({ error: 'Invalid attachment ID' }) const existing = await db.select().from(taskAttachments) .where(and(eq(taskAttachments.id, attachmentId), eq(taskAttachments.taskId, id))) .limit(1) if (existing.length === 0) return reply.status(404).send({ error: 'Attachment not found' }) await db.delete(taskAttachments).where(eq(taskAttachments.id, attachmentId)) await db.insert(activityLog).values({ taskId: id, action: 'attachment_deleted', changes: JSON.stringify({ attachmentId, name: existing[0].name }), }) return reply.status(204).send() }) // Get single task fastify.get('/:id', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } let result = await db.select().from(tasks).where(eq(tasks.id, id)).limit(1) if (result.length === 0) { return reply.status(404).send({ error: 'Task not found' }) } if (result[0].highlight && !result[0].archived && taskDueDateKey(result[0].dueDate) !== localDateKey()) { await db.update(tasks) .set({ dueDate: parseDueDateInput(localDateKey()), updatedAt: new Date() }) .where(eq(tasks.id, id)) result = await db.select().from(tasks).where(eq(tasks.id, id)).limit(1) } const [task] = await addAttachmentCounts(addSubtaskCounts([hydrateTaskWithTags(result[0])], result)) return reply.send(task) }) // Update task fastify.patch('/:id', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const updates = request.body as Partial<{ title: string description: string statusId: string | null priority: number dueDate: string | null assignee: string | null labels: string[] archived: boolean position: number projectId: string recurring: string | null recurringEnd: string | null highlight: boolean }> const existingTask = await db.select().from(tasks).where(eq(tasks.id, id)).limit(1) if (existingTask.length === 0) { return reply.status(404).send({ error: 'Task not found' }) } if (isTooLong(updates.description, DESCRIPTION_MAX_LENGTH)) { return reply.status(400).send({ error: `Description must be ${DESCRIPTION_MAX_LENGTH} chars or less` }) } const setObj: Record = { ...updates } const nextLabels = updates.labels delete setObj.labels if (updates.labels !== undefined) { setObj.labels = JSON.stringify(updates.labels) } if (updates.dueDate !== undefined) { setObj.dueDate = updates.dueDate ? parseDueDateInput(updates.dueDate) : null } if (updates.assignee !== undefined) { setObj.assignee = updates.assignee?.trim() || null } if (updates.recurring !== undefined) { setObj.recurring = updates.recurring?.trim() || null } if (updates.recurringEnd !== undefined) { setObj.recurringEnd = updates.recurringEnd ? new Date(updates.recurringEnd) : null } const willBeArchived = updates.archived ?? existingTask[0].archived const willBeHighlight = !willBeArchived && (updates.highlight ?? existingTask[0].highlight) if (willBeHighlight && existingTask[0].parentId) { return reply.status(400).send({ error: 'Only top-level tasks can be highlighted' }) } if (willBeHighlight) { const targetProjectId = updates.projectId ?? existingTask[0].projectId const targetProject = await db.select().from(projects).where(eq(projects.id, targetProjectId)).limit(1) if (targetProject.length === 0) return reply.status(400).send({ error: 'Project not found' }) const workspaceProjects = await db.select({ id: projects.id }).from(projects) .where(eq(projects.workspaceId, targetProject[0].workspaceId)) const workspaceProjectIds = workspaceProjects.map((project) => project.id) if (workspaceProjectIds.length > 0) { await db.update(tasks) .set({ highlight: false, updatedAt: new Date() }) .where(and(inArray(tasks.projectId, workspaceProjectIds), eq(tasks.highlight, true))) } setObj.highlight = true setObj.dueDate = parseDueDateInput(localDateKey()) } else if (willBeArchived || updates.highlight === false) { setObj.highlight = false } setObj.updatedAt = new Date() const result = await db.update(tasks) .set(setObj) .where(eq(tasks.id, id)) .returning() const movedToProject = updates.projectId !== undefined && updates.projectId !== existingTask[0].projectId if (nextLabels !== undefined) { replaceTaskTags(id, result[0].projectId, nextLabels) } else if (movedToProject) { const existingTagNames = hydrateTaskWithTags(existingTask[0]).tags.map((tag) => tag.name) replaceTaskTags(id, result[0].projectId, existingTagNames) } // Log activity await db.insert(activityLog).values({ taskId: id, action: 'updated', changes: JSON.stringify(updates) }) const allProjectTasks = await db.select().from(tasks).where(eq(tasks.projectId, result[0].projectId)) const [task] = await addAttachmentCounts(addSubtaskCounts([hydrateTaskWithTags(result[0])], allProjectTasks)) return reply.send(task) }) // Delete task permanently. Completion is handled by POST /:id/complete. fastify.delete('/:id', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const existingTask = await db.select({ id: tasks.id }).from(tasks).where(eq(tasks.id, id)).limit(1) if (existingTask.length === 0) { return reply.status(404).send({ error: 'Task not found' }) } deleteTasksByIds([id]) return reply.status(204).send() }) // Get task activity fastify.get('/:id/activity', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const result = await db.select().from(activityLog) .where(eq(activityLog.taskId, id)) .orderBy(asc(activityLog.createdAt)) return reply.send(result) }) // GET /tasks/:id/comments — get comments for a task fastify.get('/:id/comments', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const result = await db.select().from(activityLog) .where(eq(activityLog.taskId, id)) .orderBy(asc(activityLog.createdAt)) return reply.send(result) }) // POST /tasks/:id/comments — add comment to a task fastify.post('/:id/comments', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const { content } = request.body as { content: string } const nextContent = content?.trim() if (!nextContent || nextContent.length > COMMENT_MAX_LENGTH) { return reply.status(400).send({ error: `Comment must be 1-${COMMENT_MAX_LENGTH} chars` }) } await db.insert(activityLog).values({ taskId: id, action: 'comment', changes: JSON.stringify({ content: nextContent }), userId: undefined }) return reply.status(201).send({ success: true }) }) // PATCH /tasks/:id/comments/:commentId — edit an existing comment fastify.patch('/:id/comments/:commentId', async (request: FastifyRequest, reply: FastifyReply) => { const { id, commentId } = request.params as { id: string; commentId: string } const { content } = request.body as { content: string } const nextContent = content?.trim() if (!isValidUUID(id) || !isValidUUID(commentId)) return reply.status(400).send({ error: 'Invalid comment ID' }) if (!nextContent || nextContent.length > COMMENT_MAX_LENGTH) { return reply.status(400).send({ error: `Comment must be 1-${COMMENT_MAX_LENGTH} chars` }) } const existing = await db.select().from(activityLog) .where(and(eq(activityLog.id, commentId), eq(activityLog.taskId, id), eq(activityLog.action, 'comment'))) .limit(1) if (existing.length === 0) return reply.status(404).send({ error: 'Comment not found' }) const [updated] = await db.update(activityLog) .set({ changes: JSON.stringify({ ...readActivityChanges(existing[0].changes), content: nextContent }) }) .where(eq(activityLog.id, commentId)) .returning() return reply.send(updated) }) // DELETE /tasks/:id/comments/:commentId — delete an existing comment fastify.delete('/:id/comments/:commentId', async (request: FastifyRequest, reply: FastifyReply) => { const { id, commentId } = request.params as { id: string; commentId: string } if (!isValidUUID(id) || !isValidUUID(commentId)) return reply.status(400).send({ error: 'Invalid comment ID' }) const existing = await db.select({ id: activityLog.id }).from(activityLog) .where(and(eq(activityLog.id, commentId), eq(activityLog.taskId, id), eq(activityLog.action, 'comment'))) .limit(1) if (existing.length === 0) return reply.status(404).send({ error: 'Comment not found' }) await db.delete(activityLog).where(eq(activityLog.id, commentId)) return reply.status(204).send() }) // Reorder a visible subset of root tasks within one workspace. fastify.post('/reorder', async (request: FastifyRequest, reply: FastifyReply) => { const { taskIds } = request.body as { projectId?: string; taskIds?: string[] } if (!Array.isArray(taskIds) || taskIds.length < 2 || taskIds.length > 2000) { return reply.status(400).send({ error: 'taskIds must contain 2-2000 tasks' }) } const orderedIds = [...new Set(taskIds)] if (orderedIds.length !== taskIds.length || orderedIds.some((id) => !isValidUUID(id))) { return reply.status(400).send({ error: 'taskIds must contain unique valid task IDs' }) } const placeholders = orderedIds.map(() => '?').join(', ') const selectedRows = sqlite.prepare(` SELECT task.id, task.parent_id, task.priority, task.archived, project.workspace_id FROM tasks task JOIN projects project ON project.id = task.project_id WHERE task.id IN (${placeholders}) `).all(...orderedIds) as Array<{ id: string; parent_id: string | null; priority: number; archived: number; workspace_id: string }> if (selectedRows.length !== orderedIds.length || selectedRows.some((task) => task.parent_id !== null)) { return reply.status(400).send({ error: 'Manual ordering supports root tasks only' }) } const workspaceIds = new Set(selectedRows.map((task) => task.workspace_id)) if (workspaceIds.size !== 1) { return reply.status(400).send({ error: 'Tasks must belong to one workspace' }) } const priorityGroups = new Set(selectedRows.map((task) => `${task.archived}:${task.priority}`)) if (priorityGroups.size !== 1) { return reply.status(400).send({ error: 'Manual ordering works within one priority group' }) } const workspaceId = selectedRows[0].workspace_id const priority = selectedRows[0].priority const archived = selectedRows[0].archived const workspaceTasks = sqlite.prepare(` SELECT task.id FROM tasks task JOIN projects project ON project.id = task.project_id WHERE project.workspace_id = ? AND task.parent_id IS NULL AND task.priority = ? AND task.archived = ? ORDER BY task.position ASC, task.created_at ASC, task.id ASC `).all(workspaceId, priority, archived) as Array<{ id: string }> const selectedSet = new Set(orderedIds) const selectedSlots = workspaceTasks .map((task, index) => selectedSet.has(task.id) ? index : -1) .filter((index) => index >= 0) if (selectedSlots.length !== orderedIds.length) { return reply.status(409).send({ error: 'Task order changed; refresh and try again' }) } const normalizedOrder = workspaceTasks.map((task) => task.id) selectedSlots.forEach((slot, index) => { normalizedOrder[slot] = orderedIds[index] }) const updatePosition = sqlite.prepare('UPDATE tasks SET position = ?, updated_at = unixepoch() WHERE id = ?') const persistOrder = sqlite.transaction(() => { normalizedOrder.forEach((taskId, index) => updatePosition.run(index, taskId)) }) persistOrder() return reply.send({ success: true, reorderedCount: orderedIds.length }) }) // Status definitions fastify.post('/statuses', async (request: FastifyRequest, reply: FastifyReply) => { const { workspaceId, name, order, color } = request.body as { workspaceId: string name: string order?: number color?: string } const result = await db.insert(statusDefinitions).values({ workspaceId, name, order: order || 0, color: color || '#6B7280' }).returning() return reply.status(201).send(result[0]) }) fastify.get('/statuses/:workspaceId', async (request: FastifyRequest, reply: FastifyReply) => { const { workspaceId } = request.params as { workspaceId: string } const result = await db.select().from(statusDefinitions) .where(eq(statusDefinitions.workspaceId, workspaceId)) .orderBy(asc(statusDefinitions.order)) return reply.send(result) }) // Resolve the workspace's canonical In Progress status, creating it on first use. // This reuses existing status definitions instead of introducing a parallel task field. fastify.post('/statuses/:workspaceId/in-progress', async (request: FastifyRequest, reply: FastifyReply) => { const { workspaceId } = request.params as { workspaceId: string } const workspace = await db.select({ id: workspaces.id }).from(workspaces).where(eq(workspaces.id, workspaceId)).limit(1) if (workspace.length === 0) return reply.status(404).send({ error: 'Workspace not found' }) const existing = await db.select().from(statusDefinitions) .where(eq(statusDefinitions.workspaceId, workspaceId)) .orderBy(asc(statusDefinitions.order)) const inProgress = existing.find((status) => status.name.trim().toLowerCase() === 'in progress') if (inProgress) return reply.send(inProgress) const [created] = await db.insert(statusDefinitions).values({ workspaceId, name: 'In Progress', order: existing.length, color: '#3B82F6', }).returning() return reply.status(201).send(created) }) // ── Subtasks ────────────────────────────────────────────────────────────── // GET /tasks/:id/subtasks — get all subtasks of a task fastify.get('/:id/subtasks', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } if (!isValidUUID(id)) return reply.send([]) const result = await db.select().from(tasks) .where(eq(tasks.parentId, id)) .orderBy(asc(tasks.position)) return reply.send(result) }) // POST /tasks/:id/subtasks/reorder — persist the complete order for one parent. fastify.post('/:id/subtasks/reorder', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const { subtaskIds } = (request.body ?? {}) as { subtaskIds?: string[] } if (!isValidUUID(id) || !Array.isArray(subtaskIds) || subtaskIds.length < 2 || subtaskIds.length > 2000 || subtaskIds.some((subtaskId) => !isValidUUID(subtaskId)) || new Set(subtaskIds).size !== subtaskIds.length) { return reply.status(400).send({ error: 'subtaskIds must contain 2-2000 unique valid IDs' }) } const siblings = sqlite.prepare(` SELECT id FROM tasks WHERE parent_id = ? ORDER BY position ASC, created_at ASC, id ASC `).all(id) as Array<{ id: string }> const expected = new Set(siblings.map((subtask) => subtask.id)) if (siblings.length !== subtaskIds.length || subtaskIds.some((subtaskId) => !expected.has(subtaskId))) { return reply.status(409).send({ error: 'Subtask list changed; refresh and try again' }) } const updatePosition = sqlite.prepare('UPDATE tasks SET position = ?, updated_at = unixepoch() WHERE id = ?') sqlite.transaction(() => { subtaskIds.forEach((subtaskId, position) => updatePosition.run(position, subtaskId)) })() return reply.send({ success: true, reorderedCount: subtaskIds.length }) }) // POST /tasks/:id/subtasks — add a subtask to a task fastify.post('/:id/subtasks', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const { title, description, priority } = request.body as { title: string description?: string priority?: number } if (!title) return reply.status(400).send({ error: 'title is required' }) if (isTooLong(description, DESCRIPTION_MAX_LENGTH)) { return reply.status(400).send({ error: `Description must be ${DESCRIPTION_MAX_LENGTH} chars or less` }) } // Get the parent task to find its projectId const parent = await db.select().from(tasks).where(eq(tasks.id, id)).limit(1) if (parent.length === 0) return reply.status(404).send({ error: 'Parent task not found' }) const { projectId } = parent[0] // Siblings const siblings = await db.select({ maxPos: tasks.position }) .from(tasks) .where(eq(tasks.parentId, id)) .orderBy(desc(tasks.position)) .limit(1) const position = siblings.length > 0 ? siblings[0].maxPos + 1 : 0 const [subtask] = await db.insert(tasks).values({ projectId, parentId: id, title, description: description ?? null, priority: priority ?? 2, position, }).returning() if (!subtask) return reply.status(500).send({ error: 'Failed to create subtask' }) return reply.status(201).send(hydrateTaskWithTags(subtask)) }) // PATCH /subtasks/:id — update a subtask fastify.patch('/subtasks/:id', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const updates = request.body as Partial<{ title: string description: string priority: number archived: boolean }> if (!isValidUUID(id)) return reply.status(400).send({ error: 'Invalid subtask ID' }) const existing = await db.select().from(tasks).where(eq(tasks.id, id)).limit(1) if (existing.length === 0 || !existing[0].parentId) return reply.status(404).send({ error: 'Subtask not found' }) if (updates.title !== undefined && !updates.title.trim()) return reply.status(400).send({ error: 'title is required' }) if (isTooLong(updates.description, DESCRIPTION_MAX_LENGTH)) { return reply.status(400).send({ error: `Description must be ${DESCRIPTION_MAX_LENGTH} chars or less` }) } const setObj: Record = { updatedAt: new Date() } if (updates.title !== undefined) setObj.title = updates.title.trim() if (updates.description !== undefined) setObj.description = updates.description || null if (updates.priority !== undefined) setObj.priority = updates.priority if (updates.archived !== undefined) setObj.archived = updates.archived const [subtask] = await db.update(tasks) .set(setObj) .where(eq(tasks.id, id)) .returning() return reply.send(hydrateTaskWithTags(subtask)) }) // DELETE /subtasks/:id — delete a subtask fastify.delete('/subtasks/:id', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } if (!isValidUUID(id)) return reply.status(400).send({ error: 'Invalid subtask ID' }) const existing = await db.select().from(tasks).where(eq(tasks.id, id)).limit(1) if (existing.length === 0) return reply.status(404).send({ error: 'Subtask not found' }) await db.delete(tasks).where(eq(tasks.id, id)) return reply.status(204).send() }) // ── Recurring Tasks ─────────────────────────────────────────────────────── // POST /tasks/:id/complete — marks a task complete and creates next recurring instance if applicable fastify.post('/:id/complete', async (request: FastifyRequest, reply: FastifyReply) => { const { id } = request.params as { id: string } const task = await db.select().from(tasks).where(eq(tasks.id, id)).limit(1) if (!task.length) return reply.status(404).send({ error: 'Task not found' }) const currentTask = task[0] // Archive the current instance await db.update(tasks) .set({ archived: true, highlight: false, updatedAt: new Date() }) .where(eq(tasks.id, id)) // Log completion await db.insert(activityLog).values({ taskId: id, action: 'completed', changes: JSON.stringify({ title: currentTask.title }), userId: undefined }) // If recurring, create the next instance if (currentTask.recurring) { const nextDue = calculateNextRecurringDate(currentTask.recurring, currentTask.dueDate as Date | null) const [nextTask] = await db.insert(tasks).values({ projectId: currentTask.projectId, title: currentTask.title, description: currentTask.description, priority: currentTask.priority, dueDate: nextDue, recurring: currentTask.recurring, position: currentTask.position }).returning() if (nextTask) { replaceTaskTags(nextTask.id, nextTask.projectId, hydrateTaskWithTags(currentTask).tags.map((tag) => tag.name)) } } return reply.send({ success: true, recurring: currentTask.recurring ? true : false }) }) // ── CSV Export ──────────────────────────────────────────────────────────── const priorityLabels: Record = { 1: 'Critical', 2: 'High', 3: 'Medium', 4: 'Low' } const csvEscape = (value: unknown): string => { const raw = value == null ? '' : String(value) return `"${raw.replace(/"/g, '""')}"` } const csvHeaders = ['id', 'project', 'title', 'description', 'priority', 'due_date', 'highlight', 'assignee', 'tags', 'status', 'created_at', 'updated_at'] const buildTasksCsv = (taskRows: Array, projectNameById: Map) => { const rows = taskRows.map((t: any) => [ csvEscape(t.id), csvEscape(projectNameById.get(t.projectId) || ''), csvEscape(t.title || ''), csvEscape(t.description || ''), csvEscape(priorityLabels[t.priority] || 'Unknown'), t.dueDate ? csvEscape(new Date(t.dueDate).toISOString().split('T')[0]) : '', csvEscape(t.highlight ? 'yes' : 'no'), csvEscape(t.assignee || ''), csvEscape(Array.isArray(t.tags) ? t.tags.map((tag: any) => tag.name).join('; ') : ''), csvEscape(t.archived ? 'completed' : 'active'), csvEscape(t.createdAt ? new Date(t.createdAt).toISOString() : ''), csvEscape(t.updatedAt ? new Date(t.updatedAt).toISOString() : '') ]) return [ csvHeaders.join(','), ...rows.map((r: string[]) => r.join(',')) ].join('\n') } // GET /tasks/export — download all tasks across all projects as CSV fastify.get('/export', async (_request: FastifyRequest, reply: FastifyReply) => { const allProjects = await db.select().from(projects) const projectNameById = new Map(allProjects.map((project) => [project.id, project.name])) const allTasks = hydrateTasksWithTags(await db.select().from(tasks) .orderBy(asc(tasks.projectId), asc(tasks.archived), asc(tasks.priority), asc(tasks.dueDate))) const csvContent = buildTasksCsv(allTasks, projectNameById) reply.header('Content-Type', 'text/csv') const exportedDate = new Date().toISOString().split('T')[0] reply.header('Content-Disposition', `attachment; filename="focusclaw-tasks-all-${exportedDate}.csv"`) return reply.send(csvContent) }) // GET /tasks/export/:projectId — download project tasks as CSV fastify.get('/export/:projectId', async (request: FastifyRequest, reply: FastifyReply) => { const { projectId } = request.params as { projectId: string } if (!isValidUUID(projectId)) { return reply.status(400).send({ error: 'Invalid project ID' }) } const projectExists = await db.select().from(projects).where(eq(projects.id, projectId)).limit(1) if (projectExists.length === 0) { return reply.status(404).send({ error: 'Project not found' }) } // Fetch all tasks for the project, including completed tasks const allTasks = hydrateTasksWithTags(await db.select().from(tasks) .where(eq(tasks.projectId, projectId)) .orderBy(asc(tasks.archived), asc(tasks.priority), asc(tasks.dueDate))) const csvContent = buildTasksCsv(allTasks, new Map([[projectId, projectExists[0].name]])) reply.header('Content-Type', 'text/csv') reply.header('Content-Disposition', `attachment; filename="focusclaw-tasks-${projectId.slice(0, 8)}.csv"`) return reply.send(csvContent) }) } // Helper: calculate next due date from a recurring pattern function calculateNextRecurringDate(recurring: string, currentDue: Date | null): Date { const from = currentDue ? new Date(currentDue) : new Date() const lower = recurring.toLowerCase() if (lower === 'daily') { return new Date(from.getFullYear(), from.getMonth(), from.getDate() + 1, 23, 59, 59) } if (lower === 'weekly') { return new Date(from.getFullYear(), from.getMonth(), from.getDate() + 7, 23, 59, 59) } if (lower === 'biweekly') { return new Date(from.getFullYear(), from.getMonth(), from.getDate() + 14, 23, 59, 59) } if (lower === 'monthly') { return new Date(from.getFullYear(), from.getMonth() + 1, from.getDate(), 23, 59, 59) } // every X days const daysMatch = lower.match(/every\s+(\d+)\s+days?/) if (daysMatch) { const num = parseInt(daysMatch[1]) return new Date(from.getFullYear(), from.getMonth(), from.getDate() + num, 23, 59, 59) } // every [day name] const dayNames = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday'] for (let i = 0; i < dayNames.length; i++) { if (lower.includes(dayNames[i])) { const d = new Date(from) const diff = ((i - d.getDay()) + 7) % 7 || 7 d.setDate(d.getDate() + diff) return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59) } } // Default: daily return new Date(from.getFullYear(), from.getMonth(), from.getDate() + 1, 23, 59, 59) }