import { z } from 'zod'; import { FileManager } from '../utils/file-manager.js'; import { TaskParser } from '../utils/task-parser.js'; const createTaskSchema = z.object({ action: z.literal('create'), projectPath: z.string().min(1, 'projectPath is required and must be absolute'), title: z.string().min(1, 'title is required'), description: z.string().min(1, 'description is required'), number: z.string().min(1, 'number is required') }); const createBatchTaskSchema = z.object({ action: z.literal('createBatch'), projectPath: z.string().min(1, 'projectPath is required and must be absolute'), tasks: z.array(z.object({ title: z.string().min(1, 'title is required'), description: z.string().min(1, 'description is required'), number: z.string().min(1, 'number is required') })) }); const updateTaskSchema = z.object({ action: z.literal('update'), projectPath: z.string().min(1, 'projectPath is required and must be absolute'), taskId: z.string().min(1, 'taskId is required'), status: z.enum(['pending', 'in-progress', 'completed']) }); const listTaskSchema = z.object({ action: z.literal('list'), projectPath: z.string().min(1, 'projectPath is required and must be absolute') }); const addSubtaskSchema = z.object({ action: z.literal('add-subtask'), projectPath: z.string().min(1, 'projectPath is required and must be absolute'), parentId: z.string().min(1, 'parentId is required'), title: z.string().min(1, 'title is required'), description: z.string().min(1, 'description is required') }); const reorderTaskSchema = z.object({ action: z.literal('reorder'), projectPath: z.string().min(1, 'projectPath is required and must be absolute') }); const taskSchema = z.union([ createTaskSchema, createBatchTaskSchema, updateTaskSchema, listTaskSchema, addSubtaskSchema, reorderTaskSchema ]); export async function handleSpecTasks(args: any) { try { const validatedArgs = taskSchema.parse(args); const { action, projectPath } = validatedArgs; const fileManager = new FileManager(projectPath); switch (action) { case 'create': { const { title, description, number } = validatedArgs; // Validate task number format if (!isValidTaskNumber(number)) { throw new Error(`Invalid number format: ${number}. Must be in format: x.0.0 or x.y.z`); } // Read current tasks let tasks: any[] = []; try { const currentContent = await fileManager.readFile('tasks.md'); if (currentContent && currentContent.trim().length > 0) { tasks = TaskParser.parseMarkdownTasks(currentContent); } } catch (error) { // File doesn't exist yet, start with empty tasks } // Check if task already exists if (taskExists(tasks, number)) { throw new Error(`Task with number ${number} already exists`); } const newTask = { id: number, description: description, status: 'pending' as const, children: [], level: number.split('.').length - 1, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; tasks.push(newTask); // Sort tasks by number tasks.sort((a, b) => { const aParts = a.id.split('.').map(Number); const bParts = b.id.split('.').map(Number); for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) { const aNum = aParts[i] || 0; const bNum = bParts[i] || 0; if (aNum !== bNum) return aNum - bNum; } return 0; }); // Generate markdown const markdown = TaskParser.toMarkdown(tasks); await fileManager.writeFile('tasks.md', markdown); return { content: [{ type: "text", text: `✅ Task ${number} created: ${title}\nDescription: ${description}` }] }; } case 'createBatch': { const { tasks: tasksArray } = validatedArgs; if (!tasksArray || tasksArray.length === 0) { throw new Error('tasks array is required for createBatch action'); } // Read current tasks let existingTasks: any[] = []; try { const currentContent = await fileManager.readFile('tasks.md'); if (currentContent && currentContent.trim().length > 0) { existingTasks = TaskParser.parseMarkdownTasks(currentContent); } } catch (error) { // File doesn't exist yet, start with empty tasks } const newTasks = []; const errors = []; // Process each task for (const taskParams of tasksArray) { const { title, description, number } = taskParams; if (!title || !description || !number) { errors.push(`Task missing required fields: title, description, or number`); continue; } if (!isValidTaskNumber(number)) { errors.push(`Invalid number format: ${number}. Must be in format: x.0.0 or x.y.z`); continue; } if (taskExists(existingTasks, number)) { errors.push(`Task with number ${number} already exists`); continue; } const newTask = { id: number, description: description, status: 'pending' as const, children: [], level: number.split('.').length - 1, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; existingTasks.push(newTask); newTasks.push({ number, title }); } if (errors.length > 0) { throw new Error(`Batch creation errors:\n${errors.join('\n')}`); } // Sort tasks by number existingTasks.sort((a, b) => { const aParts = a.id.split('.').map(Number); const bParts = b.id.split('.').map(Number); for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) { const aNum = aParts[i] || 0; const bNum = bParts[i] || 0; if (aNum !== bNum) return aNum - bNum; } return 0; }); // Generate markdown const markdown = TaskParser.toMarkdown(existingTasks); await fileManager.writeFile('tasks.md', markdown); return { content: [{ type: "text", text: `✅ Batch creation completed!\n\nCreated ${newTasks.length} tasks:\n${newTasks.map(t => `• ${t.number} - ${t.title}`).join('\n')}` }] }; } case 'update': { const { taskId, status } = validatedArgs; // Read current tasks let tasks: any[] = []; try { const currentContent = await fileManager.readFile('tasks.md'); tasks = TaskParser.parseMarkdownTasks(currentContent); } catch (error) { throw new Error('No tasks found to update'); } // Find and update task const taskFound = updateTaskStatus(tasks, taskId, status); if (!taskFound) { throw new Error(`Task with ID ${taskId} not found`); } // Generate markdown const markdown = TaskParser.toMarkdown(tasks); await fileManager.writeFile('tasks.md', markdown); return { content: [{ type: "text", text: `✅ Task ${taskId} updated to status: ${status}` }] }; } case 'list': { // Read current tasks let tasks: any[] = []; try { const currentContent = await fileManager.readFile('tasks.md'); tasks = TaskParser.parseMarkdownTasks(currentContent); } catch (error) { return { content: [{ type: "text", text: "No tasks found. Create tasks using 'create' or 'createBatch' actions." }] }; } const taskList = tasks.map(task => { const status = task.status === 'completed' ? '✅' : task.status === 'in-progress' ? '🔄' : '⏳'; return `${status} ${task.id} ${task.description}`; }).join('\n'); return { content: [{ type: "text", text: `📋 Current Tasks:\n\n${taskList}` }] }; } case 'add-subtask': { const { parentId, title, description } = validatedArgs; // Read current tasks let tasks: any[] = []; try { const currentContent = await fileManager.readFile('tasks.md'); tasks = TaskParser.parseMarkdownTasks(currentContent); } catch (error) { throw new Error('No tasks found to add subtask to'); } // Find parent task recursively const parentTask = findTaskRecursively(tasks, parentId); if (!parentTask) { throw new Error(`Parent task with ID ${parentId} not found`); } // Generate next subtask number const subtaskNumber = generateNextSubtaskNumber(parentTask); // Check if subtask already exists if (taskExists(tasks, subtaskNumber)) { throw new Error(`Subtask with number ${subtaskNumber} already exists`); } const newSubtask = { id: subtaskNumber, description: description, status: 'pending' as const, children: [], level: parentTask.level + 1, parentId: parentId, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; // Add subtask to parent's children parentTask.children.push(newSubtask); // Also add to main tasks array for sorting tasks.push(newSubtask); // Sort tasks by number tasks.sort((a, b) => { const aParts = a.id.split('.').map(Number); const bParts = b.id.split('.').map(Number); for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) { const aNum = aParts[i] || 0; const bNum = bParts[i] || 0; if (aNum !== bNum) return aNum - bNum; } return 0; }); // Generate markdown const markdown = TaskParser.toMarkdown(tasks); await fileManager.writeFile('tasks.md', markdown); return { content: [{ type: "text", text: `✅ Subtask ${subtaskNumber} created under ${parentId}: ${title}\nDescription: ${description}` }] }; } case 'reorder': { // Read current tasks let tasks: any[] = []; try { const currentContent = await fileManager.readFile('tasks.md'); tasks = TaskParser.parseMarkdownTasks(currentContent); } catch (error) { throw new Error('No tasks found to reorder'); } // Sort tasks by number tasks.sort((a, b) => { const aParts = a.id.split('.').map(Number); const bParts = b.id.split('.').map(Number); for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) { const aNum = aParts[i] || 0; const bNum = bParts[i] || 0; if (aNum !== bNum) return aNum - bNum; } return 0; }); // Generate markdown const markdown = TaskParser.toMarkdown(tasks); await fileManager.writeFile('tasks.md', markdown); return { content: [{ type: "text", text: `✅ Tasks reordered successfully` }] }; } default: throw new Error(`Unknown action: ${action}`); } } catch (error: any) { return { content: [{ type: "text", text: `❌ Error in spec-tasks: ${error.message}` }] }; } } // Helper functions function isValidTaskNumber(number: string): boolean { // Must be in format: x.0.0 or x.y.z (semantic versioning style) const pattern = /^\d+(\.\d+)*$/; return pattern.test(number); } function taskExists(tasks: any[], taskId: string): boolean { return tasks.some(task => task.id === taskId); } function updateTaskStatus(tasks: any[], taskId: string, newStatus: string): boolean { const task = tasks.find(t => t.id === taskId); if (task) { task.status = newStatus; task.updatedAt = new Date().toISOString(); return true; } return false; } function findTaskRecursively(tasks: any[], taskId: string): any { for (const task of tasks) { if (task.id === taskId) { return task; } if (task.children && task.children.length > 0) { const found = findTaskRecursively(task.children, taskId); if (found) return found; } } return null; } function generateNextSubtaskNumber(parentTask: any): string { const parentId = parentTask.id; const children = parentTask.children || []; // Find the highest subtask number let maxNumber = 0; for (const child of children) { const childNumber = parseInt(child.id.split('.').pop() || '0'); if (childNumber > maxNumber) { maxNumber = childNumber; } } // Generate next subtask number based on parent level const parentParts = parentId.split('.'); if (parentParts.length === 3) { // Parent is x.y.z, create x.y.(z+1) return `${parentParts[0]}.${parseInt(parentParts[1]) + 1}.0`; } else if (parentParts.length === 2) { // Parent is x.y, create x.y.1 return `${parentId}.1`; } else { // Parent is x, create x.1.0 return `${parentId}.1.0`; } } // Export the tool function export const specTasksTool = { name: "spec-tasks", description: "Create and manage hierarchical tasks.md (1., 1.1, 1.2, 2., etc.)", inputSchema: { type: "object", properties: { action: { type: "string", enum: ["create", "createBatch", "update", "list", "add-subtask", "reorder"], description: "Action to perform: create new task, create multiple tasks (batch), update progress, add subtasks, or reorder" }, projectPath: { type: "string", description: "Absolute path to the project directory (must be full path, not relative)" }, title: { type: "string", description: "Task title (for single create)" }, description: { type: "string", description: "Task description (for single create)" }, number: { type: "string", description: "Task number (e.g., '1.', '1.2', '2.3.1') (for single create)" }, tasks: { type: "array", items: { type: "object", properties: { title: { type: "string", description: "Task title" }, description: { type: "string", description: "Task description" }, number: { type: "string", description: "Task number (e.g., '1.', '1.2')" } }, required: ["title", "description", "number"] }, description: "Array of tasks to create (for createBatch)" }, taskId: { type: "string", description: "Task ID (e.g., '1.2') for updates" }, status: { type: "string", enum: ["pending", "in-progress", "completed"], description: "New status for task update" }, parentId: { type: "string", description: "Parent task ID for new subtask" } }, required: ["action", "projectPath"] }, handler: handleSpecTasks };