{
  "tasks": [
    {
      "id": 1,
      "title": "Implement Task Data Structure",
      "description": "Design and implement the core tasks.json structure that will serve as the single source of truth for the system.",
      "status": "done",
      "dependencies": [],
      "priority": "high",
      "details": "Create the foundational data structure including:\n- JSON schema for tasks.json\n- Task model with all required fields (id, title, description, status, dependencies, priority, details, testStrategy, subtasks)\n- Validation functions for the task model\n- Basic file system operations for reading/writing tasks.json\n- Error handling for file operations",
      "testStrategy": "Verify that the tasks.json structure can be created, read, and validated. Test with sample data to ensure all fields are properly handled and that validation correctly identifies invalid structures.",
      "subtasks": [],
      "previousStatus": "in-progress"
    },
    {
      "id": 2,
      "title": "Develop Command Line Interface Foundation",
      "description": "Create the basic CLI structure using Commander.js with command parsing and help documentation.",
      "status": "done",
      "dependencies": [
        1
      ],
      "priority": "high",
      "details": "Implement the CLI foundation including:\n- Set up Commander.js for command parsing\n- Create help documentation for all commands\n- Implement colorized console output for better readability\n- Add logging system with configurable levels\n- Handle global options (--help, --version, --file, --quiet, --debug, --json)",
      "testStrategy": "Test each command with various parameters to ensure proper parsing. Verify help documentation is comprehensive and accurate. Test logging at different verbosity levels.",
      "subtasks": []
    },
    {
      "id": 3,
      "title": "Implement Basic Task Operations",
      "description": "Create core functionality for managing tasks including listing, creating, updating, and deleting tasks.",
      "status": "done",
      "dependencies": [
        1
      ],
      "priority": "high",
      "details": "Implement the following task operations:\n- List tasks with filtering options\n- Create new tasks with required fields\n- Update existing task properties\n- Delete tasks\n- Change task status (pending/done/deferred)\n- Handle dependencies between tasks\n- Manage task priorities",
      "testStrategy": "Test each operation with valid and invalid inputs. Verify that dependencies are properly tracked and that status changes are reflected correctly in the tasks.json file.",
      "subtasks": []
    },
    {
      "id": 4,
      "title": "Create Task File Generation System",
      "description": "Implement the system for generating individual task files from the tasks.json data structure.",
      "status": "done",
      "dependencies": [
        1,
        3
      ],
      "priority": "medium",
      "details": "Build the task file generation system including:\n- Create task file templates\n- Implement generation of task files from tasks.json\n- Add bi-directional synchronization between task files and tasks.json\n- Implement proper file naming and organization\n- Handle updates to task files reflecting back to tasks.json",
      "testStrategy": "Generate task files from sample tasks.json data and verify the content matches the expected format. Test synchronization by modifying task files and ensuring changes are reflected in tasks.json.",
      "subtasks": [
        {
          "id": 1,
          "title": "Design Task File Template Structure",
          "description": "Create the template structure for individual task files that will be generated from tasks.json. This includes defining the format with sections for task ID, title, status, dependencies, priority, description, details, test strategy, and subtasks. Implement a template engine or string formatting system that can populate these templates with task data. The template should follow the format specified in the PRD's Task File Format section.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Template structure matches the specification in the PRD\n- Template includes all required sections (ID, title, status, dependencies, etc.)\n- Template supports proper formatting of multi-line content like details and test strategy\n- Template handles subtasks correctly, including proper indentation and formatting\n- Template system is modular and can be easily modified if requirements change"
        },
        {
          "id": 2,
          "title": "Implement Task File Generation Logic",
          "description": "Develop the core functionality to generate individual task files from the tasks.json data structure. This includes reading the tasks.json file, iterating through each task, applying the template to each task's data, and writing the resulting content to appropriately named files in the tasks directory. Ensure proper error handling for file operations and data validation.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- Successfully reads tasks from tasks.json\n- Correctly applies template to each task's data\n- Generates files with proper naming convention (e.g., task_001.txt)\n- Creates the tasks directory if it doesn't exist\n- Handles errors gracefully (file not found, permission issues, etc.)\n- Validates task data before generation to prevent errors\n- Logs generation process with appropriate verbosity levels"
        },
        {
          "id": 3,
          "title": "Implement File Naming and Organization System",
          "description": "Create a consistent system for naming and organizing task files. Implement a function that generates standardized filenames based on task IDs (e.g., task_001.txt for task ID 1). Design the directory structure for storing task files according to the PRD specification. Ensure the system handles task ID formatting consistently and prevents filename collisions.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- Generates consistent filenames based on task IDs with proper zero-padding\n- Creates and maintains the correct directory structure as specified in the PRD\n- Handles special characters or edge cases in task IDs appropriately\n- Prevents filename collisions between different tasks\n- Provides utility functions for converting between task IDs and filenames\n- Maintains backward compatibility if the naming scheme needs to evolve"
        },
        {
          "id": 4,
          "title": "Implement Task File to JSON Synchronization",
          "description": "Develop functionality to read modified task files and update the corresponding entries in tasks.json. This includes parsing the task file format, extracting structured data, validating the changes, and updating the tasks.json file accordingly. Ensure the system can handle concurrent modifications and resolve conflicts appropriately.",
          "status": "done",
          "dependencies": [
            1,
            3,
            2
          ],
          "acceptanceCriteria": "- Successfully parses task files to extract structured data\n- Validates parsed data against the task model schema\n- Updates tasks.json with changes from task files\n- Handles conflicts when the same task is modified in both places\n- Preserves task relationships and dependencies during synchronization\n- Provides clear error messages for parsing or validation failures\n- Updates the \"updatedAt\" timestamp in tasks.json metadata"
        },
        {
          "id": 5,
          "title": "Implement Change Detection and Update Handling",
          "description": "Create a system to detect changes in task files and tasks.json, and handle updates bidirectionally. This includes implementing file watching or comparison mechanisms, determining which version is newer, and applying changes in the appropriate direction. Ensure the system handles edge cases like deleted files, new tasks, and conflicting changes.",
          "status": "done",
          "dependencies": [
            1,
            3,
            4,
            2
          ],
          "acceptanceCriteria": "- Detects changes in both task files and tasks.json\n- Determines which version is newer based on modification timestamps or content\n- Applies changes in the appropriate direction (file to JSON or JSON to file)\n- Handles edge cases like deleted files, new tasks, and renamed tasks\n- Provides options for manual conflict resolution when necessary\n- Maintains data integrity during the synchronization process\n- Includes a command to force synchronization in either direction\n- Logs all synchronization activities for troubleshooting\n\nEach of these subtasks addresses a specific component of the task file generation system, following a logical progression from template design to bidirectional synchronization. The dependencies ensure that prerequisites are completed before dependent work begins, and the acceptance criteria provide clear guidelines for verifying each subtask's completion.",
          "details": "\n\n<info added on 2025-05-01T21:59:10.551Z>\n{\n  \"id\": 5,\n  \"title\": \"Implement Change Detection and Update Handling\",\n  \"description\": \"Create a system to detect changes in task files and tasks.json, and handle updates bidirectionally. This includes implementing file watching or comparison mechanisms, determining which version is newer, and applying changes in the appropriate direction. Ensure the system handles edge cases like deleted files, new tasks, and conflicting changes.\",\n  \"status\": \"done\",\n  \"dependencies\": [\n    1,\n    3,\n    4,\n    2\n  ],\n  \"acceptanceCriteria\": \"- Detects changes in both task files and tasks.json\\n- Determines which version is newer based on modification timestamps or content\\n- Applies changes in the appropriate direction (file to JSON or JSON to file)\\n- Handles edge cases like deleted files, new tasks, and renamed tasks\\n- Provides options for manual conflict resolution when necessary\\n- Maintains data integrity during the synchronization process\\n- Includes a command to force synchronization in either direction\\n- Logs all synchronization activities for troubleshooting\\n\\nEach of these subtasks addresses a specific component of the task file generation system, following a logical progression from template design to bidirectional synchronization. The dependencies ensure that prerequisites are completed before dependent work begins, and the acceptance criteria provide clear guidelines for verifying each subtask's completion.\",\n  \"details\": \"[2025-05-01 21:59:07] Adding another note via MCP test.\"\n}\n</info added on 2025-05-01T21:59:10.551Z>"
        }
      ]
    },
    {
      "id": 5,
      "title": "Integrate Anthropic Claude API",
      "description": "Set up the integration with Claude API for AI-powered task generation and expansion.",
      "status": "done",
      "dependencies": [
        1
      ],
      "priority": "high",
      "details": "Implement Claude API integration including:\n- API authentication using environment variables\n- Create prompt templates for various operations\n- Implement response handling and parsing\n- Add error management with retries and exponential backoff\n- Implement token usage tracking\n- Create configurable model parameters",
      "testStrategy": "Test API connectivity with sample prompts. Verify authentication works correctly with different API keys. Test error handling by simulating API failures.",
      "subtasks": [
        {
          "id": 1,
          "title": "Configure API Authentication System",
          "description": "Create a dedicated module for Anthropic API authentication. Implement a secure system to load API keys from environment variables using dotenv. Include validation to ensure API keys are properly formatted and present. Create a configuration object that will store all Claude-related settings including API keys, base URLs, and default parameters.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Environment variables are properly loaded from .env file\n- API key validation is implemented with appropriate error messages\n- Configuration object includes all necessary Claude API parameters\n- Authentication can be tested with a simple API call\n- Documentation is added for required environment variables"
        },
        {
          "id": 2,
          "title": "Develop Prompt Template System",
          "description": "Create a flexible prompt template system for Claude API interactions. Implement a PromptTemplate class that can handle variable substitution, system and user messages, and proper formatting according to Claude's requirements. Include templates for different operations (task generation, task expansion, etc.) with appropriate instructions and constraints for each use case.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- PromptTemplate class supports variable substitution\n- System and user message separation is properly implemented\n- Templates exist for all required operations (task generation, expansion, etc.)\n- Templates include appropriate constraints and formatting instructions\n- Template system is unit tested with various inputs"
        },
        {
          "id": 3,
          "title": "Implement Response Handling and Parsing",
          "description": "Create a response handling system that processes Claude API responses. Implement JSON parsing for structured outputs, error detection in responses, and extraction of relevant information. Build utility functions to transform Claude's responses into the application's data structures. Include validation to ensure responses meet expected formats.",
          "status": "done",
          "dependencies": [
            1,
            2
          ],
          "acceptanceCriteria": "- Response parsing functions handle both JSON and text formats\n- Error detection identifies malformed or unexpected responses\n- Utility functions transform responses into task data structures\n- Validation ensures responses meet expected schemas\n- Edge cases like empty or partial responses are handled gracefully"
        },
        {
          "id": 4,
          "title": "Build Error Management with Retry Logic",
          "description": "Implement a robust error handling system for Claude API interactions. Create middleware that catches API errors, network issues, and timeout problems. Implement exponential backoff retry logic that increases wait time between retries. Add configurable retry limits and timeout settings. Include detailed logging for troubleshooting API issues.",
          "status": "done",
          "dependencies": [
            1,
            3
          ],
          "acceptanceCriteria": "- All API errors are caught and handled appropriately\n- Exponential backoff retry logic is implemented\n- Retry limits and timeouts are configurable\n- Detailed error logging provides actionable information\n- System degrades gracefully when API is unavailable\n- Unit tests verify retry behavior with mocked API failures"
        },
        {
          "id": 5,
          "title": "Implement Token Usage Tracking",
          "description": "Create a token tracking system to monitor Claude API usage. Implement functions to count tokens in prompts and responses. Build a logging system that records token usage per operation. Add reporting capabilities to show token usage trends and costs. Implement configurable limits to prevent unexpected API costs.",
          "status": "done",
          "dependencies": [
            1,
            3
          ],
          "acceptanceCriteria": "- Token counting functions accurately estimate usage\n- Usage logging records tokens per operation type\n- Reporting functions show usage statistics and estimated costs\n- Configurable limits can prevent excessive API usage\n- Warning system alerts when approaching usage thresholds\n- Token tracking data is persisted between application runs"
        },
        {
          "id": 6,
          "title": "Create Model Parameter Configuration System",
          "description": "Implement a flexible system for configuring Claude model parameters. Create a configuration module that manages model selection, temperature, top_p, max_tokens, and other parameters. Build functions to customize parameters based on operation type. Add validation to ensure parameters are within acceptable ranges. Include preset configurations for different use cases (creative, precise, etc.).",
          "status": "done",
          "dependencies": [
            1,
            5
          ],
          "acceptanceCriteria": "- Configuration module manages all Claude model parameters\n- Parameter customization functions exist for different operations\n- Validation ensures parameters are within acceptable ranges\n- Preset configurations exist for different use cases\n- Parameters can be overridden at runtime when needed\n- Documentation explains parameter effects and recommended values\n- Unit tests verify parameter validation and configuration loading"
        }
      ]
    },
    {
      "id": 6,
      "title": "Build PRD Parsing System",
      "description": "Create the system for parsing Product Requirements Documents into structured task lists.",
      "status": "done",
      "dependencies": [
        1,
        5
      ],
      "priority": "high",
      "details": "Implement PRD parsing functionality including:\n- PRD file reading from specified path\n- Prompt engineering for effective PRD parsing\n- Convert PRD content to task structure via Claude API\n- Implement intelligent dependency inference\n- Add priority assignment logic\n- Handle large PRDs by chunking if necessary",
      "testStrategy": "Test with sample PRDs of varying complexity. Verify that generated tasks accurately reflect the requirements in the PRD. Check that dependencies and priorities are logically assigned.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement PRD File Reading Module",
          "description": "Create a module that can read PRD files from a specified file path. The module should handle different file formats (txt, md, docx) and extract the text content. Implement error handling for file not found, permission issues, and invalid file formats. Add support for encoding detection and proper text extraction to ensure the content is correctly processed regardless of the source format.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Function accepts a file path and returns the PRD content as a string\n- Supports at least .txt and .md file formats (with extensibility for others)\n- Implements robust error handling with meaningful error messages\n- Successfully reads files of various sizes (up to 10MB)\n- Preserves formatting where relevant for parsing (headings, lists, code blocks)"
        },
        {
          "id": 2,
          "title": "Design and Engineer Effective PRD Parsing Prompts",
          "description": "Create a set of carefully engineered prompts for Claude API that effectively extract structured task information from PRD content. Design prompts that guide Claude to identify tasks, dependencies, priorities, and implementation details from unstructured PRD text. Include system prompts, few-shot examples, and output format specifications to ensure consistent results.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- At least 3 different prompt templates optimized for different PRD styles/formats\n- Prompts include clear instructions for identifying tasks, dependencies, and priorities\n- Output format specification ensures Claude returns structured, parseable data\n- Includes few-shot examples to guide Claude's understanding\n- Prompts are optimized for token efficiency while maintaining effectiveness"
        },
        {
          "id": 3,
          "title": "Implement PRD to Task Conversion System",
          "description": "Develop the core functionality that sends PRD content to Claude API and converts the response into the task data structure. This includes sending the engineered prompts with PRD content to Claude, parsing the structured response, and transforming it into valid task objects that conform to the task model. Implement validation to ensure the generated tasks meet all requirements.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- Successfully sends PRD content to Claude API with appropriate prompts\n- Parses Claude's response into structured task objects\n- Validates generated tasks against the task model schema\n- Handles API errors and response parsing failures gracefully\n- Generates unique and sequential task IDs"
        },
        {
          "id": 4,
          "title": "Build Intelligent Dependency Inference System",
          "description": "Create an algorithm that analyzes the generated tasks and infers logical dependencies between them. The system should identify which tasks must be completed before others based on the content and context of each task. Implement both explicit dependency detection (from Claude's output) and implicit dependency inference (based on task relationships and logical ordering).",
          "status": "done",
          "dependencies": [
            1,
            3
          ],
          "acceptanceCriteria": "- Correctly identifies explicit dependencies mentioned in task descriptions\n- Infers implicit dependencies based on task context and relationships\n- Prevents circular dependencies in the task graph\n- Provides confidence scores for inferred dependencies\n- Allows for manual override/adjustment of detected dependencies"
        },
        {
          "id": 5,
          "title": "Implement Priority Assignment Logic",
          "description": "Develop a system that assigns appropriate priorities (high, medium, low) to tasks based on their content, dependencies, and position in the PRD. Create algorithms that analyze task descriptions, identify critical path tasks, and consider factors like technical risk and business value. Implement both automated priority assignment and manual override capabilities.",
          "status": "done",
          "dependencies": [
            1,
            3
          ],
          "acceptanceCriteria": "- Assigns priorities based on multiple factors (dependencies, critical path, risk)\n- Identifies foundation/infrastructure tasks as high priority\n- Balances priorities across the project (not everything is high priority)\n- Provides justification for priority assignments\n- Allows for manual adjustment of priorities"
        },
        {
          "id": 6,
          "title": "Implement PRD Chunking for Large Documents",
          "description": "Create a system that can handle large PRDs by breaking them into manageable chunks for processing. Implement intelligent document segmentation that preserves context across chunks, tracks section relationships, and maintains coherence in the generated tasks. Develop a mechanism to reassemble and deduplicate tasks generated from different chunks into a unified task list.",
          "status": "done",
          "dependencies": [
            1,
            5,
            3
          ],
          "acceptanceCriteria": "- Successfully processes PRDs larger than Claude's context window\n- Intelligently splits documents at logical boundaries (sections, chapters)\n- Preserves context when processing individual chunks\n- Reassembles tasks from multiple chunks into a coherent task list\n- Detects and resolves duplicate or overlapping tasks\n- Maintains correct dependency relationships across chunks"
        }
      ]
    },
    {
      "id": 7,
      "title": "Implement Task Expansion with Claude",
      "description": "Create functionality to expand tasks into subtasks using Claude's AI capabilities.",
      "status": "done",
      "dependencies": [
        3,
        5
      ],
      "priority": "medium",
      "details": "Build task expansion functionality including:\n- Create subtask generation prompts\n- Implement workflow for expanding a task into subtasks\n- Add context-aware expansion capabilities\n- Implement parent-child relationship management\n- Allow specification of number of subtasks to generate\n- Provide mechanism to regenerate unsatisfactory subtasks",
      "testStrategy": "Test expanding various types of tasks into subtasks. Verify that subtasks are properly linked to parent tasks. Check that context is properly incorporated into generated subtasks.",
      "subtasks": [
        {
          "id": 1,
          "title": "Design and Implement Subtask Generation Prompts",
          "description": "Create optimized prompt templates for Claude to generate subtasks from parent tasks. Design the prompts to include task context, project information, and formatting instructions that ensure consistent, high-quality subtask generation. Implement a prompt template system that allows for dynamic insertion of task details, configurable number of subtasks, and additional context parameters.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- At least two prompt templates are created (standard and detailed)\n- Prompts include clear instructions for formatting subtask output\n- Prompts dynamically incorporate task title, description, details, and context\n- Prompts include parameters for specifying the number of subtasks to generate\n- Prompt system allows for easy modification and extension of templates"
        },
        {
          "id": 2,
          "title": "Develop Task Expansion Workflow and UI",
          "description": "Implement the command-line interface and workflow for expanding tasks into subtasks. Create a new command that allows users to select a task, specify the number of subtasks, and add optional context. Design the interaction flow to handle the API request, process the response, and update the tasks.json file with the newly generated subtasks.",
          "status": "done",
          "dependencies": [
            5
          ],
          "acceptanceCriteria": "- Command `node scripts/dev.js expand --id=<task_id> --count=<number>` is implemented\n- Optional parameters for additional context (`--context=\"...\"`) are supported\n- User is shown progress indicators during API calls\n- Generated subtasks are displayed for review before saving\n- Command handles errors gracefully with helpful error messages\n- Help documentation for the expand command is comprehensive"
        },
        {
          "id": 3,
          "title": "Implement Context-Aware Expansion Capabilities",
          "description": "Enhance the task expansion functionality to incorporate project context when generating subtasks. Develop a system to gather relevant information from the project, such as related tasks, dependencies, and previously completed work. Implement logic to include this context in the Claude prompts to improve the relevance and quality of generated subtasks.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- System automatically gathers context from related tasks and dependencies\n- Project metadata is incorporated into expansion prompts\n- Implementation details from dependent tasks are included in context\n- Context gathering is configurable (amount and type of context)\n- Generated subtasks show awareness of existing project structure and patterns\n- Context gathering has reasonable performance even with large task collections"
        },
        {
          "id": 4,
          "title": "Build Parent-Child Relationship Management",
          "description": "Implement the data structure and operations for managing parent-child relationships between tasks and subtasks. Create functions to establish these relationships in the tasks.json file, update the task model to support subtask arrays, and develop utilities to navigate, filter, and display task hierarchies. Ensure all basic task operations (update, delete, etc.) properly handle subtask relationships.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- Task model is updated to include subtasks array\n- Subtasks have proper ID format (parent.sequence)\n- Parent tasks track their subtasks with proper references\n- Task listing command shows hierarchical structure\n- Completing all subtasks automatically updates parent task status\n- Deleting a parent task properly handles orphaned subtasks\n- Task file generation includes subtask information"
        },
        {
          "id": 5,
          "title": "Implement Subtask Regeneration Mechanism",
          "description": "Create functionality that allows users to regenerate unsatisfactory subtasks. Implement a command that can target specific subtasks for regeneration, preserve satisfactory subtasks, and incorporate feedback to improve the new generation. Design the system to maintain proper parent-child relationships and task IDs during regeneration.",
          "status": "done",
          "dependencies": [
            1,
            2,
            4
          ],
          "acceptanceCriteria": "- Command `node scripts/dev.js regenerate --id=<subtask_id>` is implemented\n- Option to regenerate all subtasks for a parent (`--all`)\n- Feedback parameter allows user to guide regeneration (`--feedback=\"...\"`)\n- Original subtask details are preserved in prompt context\n- Regenerated subtasks maintain proper ID sequence\n- Task relationships remain intact after regeneration\n- Command provides clear before/after comparison of subtasks"
        }
      ]
    },
    {
      "id": 8,
      "title": "Develop Implementation Drift Handling",
      "description": "Create system to handle changes in implementation that affect future tasks.",
      "status": "done",
      "dependencies": [
        3,
        5,
        7
      ],
      "priority": "medium",
      "details": "Implement drift handling including:\n- Add capability to update future tasks based on completed work\n- Implement task rewriting based on new context\n- Create dependency chain updates when tasks change\n- Preserve completed work while updating future tasks\n- Add command to analyze and suggest updates to future tasks",
      "testStrategy": "Simulate implementation changes and test the system's ability to update future tasks appropriately. Verify that completed tasks remain unchanged while pending tasks are updated correctly.",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Task Update Mechanism Based on Completed Work",
          "description": "Implement a system that can identify pending tasks affected by recently completed tasks and update them accordingly. This requires analyzing the dependency chain and determining which future tasks need modification based on implementation decisions made in completed tasks. Create a function that takes a completed task ID as input, identifies dependent tasks, and prepares them for potential updates.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Function implemented to identify all pending tasks that depend on a specified completed task\n- System can extract relevant implementation details from completed tasks\n- Mechanism to flag tasks that need updates based on implementation changes\n- Unit tests that verify the correct tasks are identified for updates\n- Command-line interface to trigger the update analysis process"
        },
        {
          "id": 2,
          "title": "Implement AI-Powered Task Rewriting",
          "description": "Develop functionality to use Claude API to rewrite pending tasks based on new implementation context. This involves creating specialized prompts that include the original task description, the implementation details of completed dependency tasks, and instructions to update the pending task to align with the actual implementation. The system should generate updated task descriptions, details, and test strategies.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Specialized Claude prompt template for task rewriting\n- Function to gather relevant context from completed dependency tasks\n- Implementation of task rewriting logic that preserves task ID and dependencies\n- Proper error handling for API failures\n- Mechanism to preview changes before applying them\n- Unit tests with mock API responses"
        },
        {
          "id": 3,
          "title": "Build Dependency Chain Update System",
          "description": "Create a system to update task dependencies when task implementations change. This includes adding new dependencies that weren't initially identified, removing dependencies that are no longer relevant, and reordering dependencies based on implementation decisions. The system should maintain the integrity of the dependency graph while reflecting the actual implementation requirements.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Function to analyze and update the dependency graph\n- Capability to add new dependencies to tasks\n- Capability to remove obsolete dependencies\n- Validation to prevent circular dependencies\n- Preservation of dependency chain integrity\n- CLI command to visualize dependency changes\n- Unit tests for dependency graph modifications"
        },
        {
          "id": 4,
          "title": "Implement Completed Work Preservation",
          "description": "Develop a mechanism to ensure that updates to future tasks don't affect completed work. This includes creating a versioning system for tasks, tracking task history, and implementing safeguards to prevent modifications to completed tasks. The system should maintain a record of task changes while ensuring that completed work remains stable.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- Implementation of task versioning to track changes\n- Safeguards that prevent modifications to tasks marked as \"done\"\n- System to store and retrieve task history\n- Clear visual indicators in the CLI for tasks that have been modified\n- Ability to view the original version of a modified task\n- Unit tests for completed work preservation"
        },
        {
          "id": 5,
          "title": "Create Update Analysis and Suggestion Command",
          "description": "Implement a CLI command that analyzes the current state of tasks, identifies potential drift between completed and pending tasks, and suggests updates. This command should provide a comprehensive report of potential inconsistencies and offer recommendations for task updates without automatically applying them. It should include options to apply all suggested changes, select specific changes to apply, or ignore suggestions.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- New CLI command \"analyze-drift\" implemented\n- Comprehensive analysis of potential implementation drift\n- Detailed report of suggested task updates\n- Interactive mode to select which suggestions to apply\n- Batch mode to apply all suggested changes\n- Option to export suggestions to a file for review\n- Documentation of the command usage and options\n- Integration tests that verify the end-to-end workflow"
        }
      ]
    },
    {
      "id": 9,
      "title": "Integrate Perplexity API",
      "description": "Add integration with Perplexity API for research-backed task generation.",
      "status": "done",
      "dependencies": [
        5
      ],
      "priority": "low",
      "details": "Implement Perplexity integration including:\n- API authentication via OpenAI client\n- Create research-oriented prompt templates\n- Implement response handling for Perplexity\n- Add fallback to Claude when Perplexity is unavailable\n- Implement response quality comparison logic\n- Add configuration for model selection",
      "testStrategy": "Test connectivity to Perplexity API. Verify research-oriented prompts return useful information. Test fallback mechanism by simulating Perplexity API unavailability.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Perplexity API Authentication Module",
          "description": "Create a dedicated module for authenticating with the Perplexity API using the OpenAI client library. This module should handle API key management, connection setup, and basic error handling. Implement environment variable support for the PERPLEXITY_API_KEY and PERPLEXITY_MODEL variables with appropriate defaults as specified in the PRD. Include a connection test function to verify API access.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Authentication module successfully connects to Perplexity API using OpenAI client\n- Environment variables for API key and model selection are properly handled\n- Connection test function returns appropriate success/failure responses\n- Basic error handling for authentication failures is implemented\n- Documentation for required environment variables is added to .env.example"
        },
        {
          "id": 2,
          "title": "Develop Research-Oriented Prompt Templates",
          "description": "Design and implement specialized prompt templates optimized for research tasks with Perplexity. Create a template system that can generate contextually relevant research prompts based on task information. These templates should be structured to leverage Perplexity's online search capabilities and should follow the Research-Backed Expansion Prompt Structure defined in the PRD. Include mechanisms to control prompt length and focus.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- At least 3 different research-oriented prompt templates are implemented\n- Templates can be dynamically populated with task context and parameters\n- Prompts are optimized for Perplexity's capabilities and response format\n- Template system is extensible to allow for future additions\n- Templates include appropriate system instructions to guide Perplexity's responses"
        },
        {
          "id": 3,
          "title": "Create Perplexity Response Handler",
          "description": "Implement a specialized response handler for Perplexity API responses. This should parse and process the JSON responses from Perplexity, extract relevant information, and transform it into the task data structure format. Include validation to ensure responses meet quality standards and contain the expected information. Implement streaming response handling if supported by the API client.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Response handler successfully parses Perplexity API responses\n- Handler extracts structured task information from free-text responses\n- Validation logic identifies and handles malformed or incomplete responses\n- Response streaming is properly implemented if supported\n- Handler includes appropriate error handling for various response scenarios\n- Unit tests verify correct parsing of sample responses"
        },
        {
          "id": 4,
          "title": "Implement Claude Fallback Mechanism",
          "description": "Create a fallback system that automatically switches to the Claude API when Perplexity is unavailable or returns errors. This system should detect API failures, rate limiting, or quality issues with Perplexity responses and seamlessly transition to using Claude with appropriate prompt modifications. Implement retry logic with exponential backoff before falling back to Claude. Log all fallback events for monitoring.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- System correctly detects Perplexity API failures and availability issues\n- Fallback to Claude is triggered automatically when needed\n- Prompts are appropriately modified when switching to Claude\n- Retry logic with exponential backoff is implemented before fallback\n- All fallback events are logged with relevant details\n- Configuration option allows setting the maximum number of retries"
        },
        {
          "id": 5,
          "title": "Develop Response Quality Comparison and Model Selection",
          "description": "Implement a system to compare response quality between Perplexity and Claude, and provide configuration options for model selection. Create metrics for evaluating response quality (e.g., specificity, relevance, actionability). Add configuration options that allow users to specify which model to use for different types of tasks. Implement a caching mechanism to reduce API calls and costs when appropriate.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Quality comparison logic evaluates responses based on defined metrics\n- Configuration system allows selection of preferred models for different operations\n- Model selection can be controlled via environment variables and command-line options\n- Response caching mechanism reduces duplicate API calls\n- System logs quality metrics for later analysis\n- Documentation clearly explains model selection options and quality metrics\n\nThese subtasks provide a comprehensive breakdown of the Perplexity API integration task, covering all the required aspects mentioned in the original task description while ensuring each subtask is specific, actionable, and technically relevant."
        }
      ]
    },
    {
      "id": 10,
      "title": "Create Research-Backed Subtask Generation",
      "description": "Enhance subtask generation with research capabilities from Perplexity API.",
      "status": "done",
      "dependencies": [
        7,
        9
      ],
      "priority": "low",
      "details": "Implement research-backed generation including:\n- Create specialized research prompts for different domains\n- Implement context enrichment from research results\n- Add domain-specific knowledge incorporation\n- Create more detailed subtask generation with best practices\n- Include references to relevant libraries and tools",
      "testStrategy": "Compare subtasks generated with and without research backing. Verify that research-backed subtasks include more specific technical details and best practices.",
      "subtasks": [
        {
          "id": 1,
          "title": "Design Domain-Specific Research Prompt Templates",
          "description": "Create a set of specialized prompt templates for different software development domains (e.g., web development, mobile, data science, DevOps). Each template should be structured to extract relevant best practices, libraries, tools, and implementation patterns from Perplexity API. Implement a prompt template selection mechanism based on the task context and domain.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- At least 5 domain-specific prompt templates are created and stored in a dedicated templates directory\n- Templates include specific sections for querying best practices, tools, libraries, and implementation patterns\n- A prompt selection function is implemented that can determine the appropriate template based on task metadata\n- Templates are parameterized to allow dynamic insertion of task details and context\n- Documentation is added explaining each template's purpose and structure"
        },
        {
          "id": 2,
          "title": "Implement Research Query Execution and Response Processing",
          "description": "Build a module that executes research queries using the Perplexity API integration. This should include sending the domain-specific prompts, handling the API responses, and parsing the results into a structured format that can be used for context enrichment. Implement error handling, rate limiting, and fallback to Claude when Perplexity is unavailable.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Function to execute research queries with proper error handling and retries\n- Response parser that extracts structured data from Perplexity's responses\n- Fallback mechanism that uses Claude when Perplexity fails or is unavailable\n- Caching system to avoid redundant API calls for similar research queries\n- Logging system for tracking API usage and response quality\n- Unit tests verifying correct handling of successful and failed API calls"
        },
        {
          "id": 3,
          "title": "Develop Context Enrichment Pipeline",
          "description": "Create a pipeline that processes research results and enriches the task context with relevant information. This should include filtering irrelevant information, organizing research findings by category (tools, libraries, best practices, etc.), and formatting the enriched context for use in subtask generation. Implement a scoring mechanism to prioritize the most relevant research findings.",
          "status": "done",
          "dependencies": [
            2
          ],
          "acceptanceCriteria": "- Context enrichment function that takes raw research results and task details as input\n- Filtering system to remove irrelevant or low-quality information\n- Categorization of research findings into distinct sections (tools, libraries, patterns, etc.)\n- Relevance scoring algorithm to prioritize the most important findings\n- Formatted output that can be directly used in subtask generation prompts\n- Tests comparing enriched context quality against baseline"
        },
        {
          "id": 4,
          "title": "Implement Domain-Specific Knowledge Incorporation",
          "description": "Develop a system to incorporate domain-specific knowledge into the subtask generation process. This should include identifying key domain concepts, technical requirements, and industry standards from the research results. Create a knowledge base structure that organizes domain information and can be referenced during subtask generation.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- Domain knowledge extraction function that identifies key technical concepts\n- Knowledge base structure for organizing domain-specific information\n- Integration with the subtask generation prompt to incorporate relevant domain knowledge\n- Support for technical terminology and concept explanation in generated subtasks\n- Mechanism to link domain concepts to specific implementation recommendations\n- Tests verifying improved technical accuracy in generated subtasks"
        },
        {
          "id": 5,
          "title": "Enhance Subtask Generation with Technical Details",
          "description": "Extend the existing subtask generation functionality to incorporate research findings and produce more technically detailed subtasks. This includes modifying the Claude prompt templates to leverage the enriched context, implementing specific sections for technical approach, implementation notes, and potential challenges. Ensure generated subtasks include concrete technical details rather than generic steps.",
          "status": "done",
          "dependencies": [
            3,
            4
          ],
          "acceptanceCriteria": "- Enhanced prompt templates for Claude that incorporate research-backed context\n- Generated subtasks include specific technical approaches and implementation details\n- Each subtask contains references to relevant tools, libraries, or frameworks\n- Implementation notes section with code patterns or architectural recommendations\n- Potential challenges and mitigation strategies are included where appropriate\n- Comparative tests showing improvement over baseline subtask generation"
        },
        {
          "id": 6,
          "title": "Implement Reference and Resource Inclusion",
          "description": "Create a system to include references to relevant libraries, tools, documentation, and other resources in generated subtasks. This should extract specific references from research results, validate their relevance, and format them as actionable links or citations within subtasks. Implement a verification step to ensure referenced resources are current and applicable.",
          "status": "done",
          "dependencies": [
            3,
            5
          ],
          "acceptanceCriteria": "- Reference extraction function that identifies tools, libraries, and resources from research\n- Validation mechanism to verify reference relevance and currency\n- Formatting system for including references in subtask descriptions\n- Support for different reference types (GitHub repos, documentation, articles, etc.)\n- Optional version specification for referenced libraries and tools\n- Tests verifying that included references are relevant and accessible"
        }
      ]
    },
    {
      "id": 11,
      "title": "Implement Batch Operations",
      "description": "Add functionality for performing operations on multiple tasks simultaneously.",
      "status": "done",
      "dependencies": [
        3
      ],
      "priority": "medium",
      "details": "Create batch operations including:\n- Implement multi-task status updates\n- Add bulk subtask generation\n- Create task filtering and querying capabilities\n- Implement advanced dependency management\n- Add batch prioritization\n- Create commands for operating on filtered task sets",
      "testStrategy": "Test batch operations with various filters and operations. Verify that operations are applied correctly to all matching tasks. Test with large task sets to ensure performance.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Multi-Task Status Update Functionality",
          "description": "Create a command-line interface command that allows users to update the status of multiple tasks simultaneously. Implement the backend logic to process batch status changes, validate the requested changes, and update the tasks.json file accordingly. The implementation should include options for filtering tasks by various criteria (ID ranges, status, priority, etc.) and applying status changes to the filtered set.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- Command accepts parameters for filtering tasks (e.g., `--status=pending`, `--priority=high`, `--id=1,2,3-5`)\n- Command accepts a parameter for the new status value (e.g., `--new-status=done`)\n- All matching tasks are updated in the tasks.json file\n- Command provides a summary of changes made (e.g., \"Updated 5 tasks from 'pending' to 'done'\")\n- Command handles errors gracefully (e.g., invalid status values, no matching tasks)\n- Changes are persisted correctly to tasks.json"
        },
        {
          "id": 2,
          "title": "Develop Bulk Subtask Generation System",
          "description": "Create functionality to generate multiple subtasks across several parent tasks at once. This should include a command-line interface that accepts filtering parameters to select parent tasks and either a template for subtasks or an AI-assisted generation option. The system should validate parent tasks, generate appropriate subtasks with proper ID assignments, and update the tasks.json file.",
          "status": "done",
          "dependencies": [
            3,
            4
          ],
          "acceptanceCriteria": "- Command accepts parameters for filtering parent tasks\n- Command supports template-based subtask generation with variable substitution\n- Command supports AI-assisted subtask generation using Claude API\n- Generated subtasks have proper IDs following the parent.sequence format (e.g., 1.1, 1.2)\n- Subtasks inherit appropriate properties from parent tasks (e.g., dependencies)\n- Generated subtasks are added to the tasks.json file\n- Task files are regenerated to include the new subtasks\n- Command provides a summary of subtasks created"
        },
        {
          "id": 3,
          "title": "Implement Advanced Task Filtering and Querying",
          "description": "Create a robust filtering and querying system that can be used across all batch operations. Implement a query syntax that allows for complex filtering based on task properties, including status, priority, dependencies, ID ranges, and text search within titles and descriptions. Design the system to be reusable across different batch operation commands.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Support for filtering by task properties (status, priority, dependencies)\n- Support for ID-based filtering (individual IDs, ranges, exclusions)\n- Support for text search within titles and descriptions\n- Support for logical operators (AND, OR, NOT) in filters\n- Query parser that converts command-line arguments to filter criteria\n- Reusable filtering module that can be imported by other commands\n- Comprehensive test cases covering various filtering scenarios\n- Documentation of the query syntax for users"
        },
        {
          "id": 4,
          "title": "Create Advanced Dependency Management System",
          "description": "Implement batch operations for managing dependencies between tasks. This includes commands for adding, removing, and updating dependencies across multiple tasks simultaneously. The system should validate dependency changes to prevent circular dependencies, update the tasks.json file, and regenerate task files to reflect the changes.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- Command for adding dependencies to multiple tasks at once\n- Command for removing dependencies from multiple tasks\n- Command for replacing dependencies across multiple tasks\n- Validation to prevent circular dependencies\n- Validation to ensure referenced tasks exist\n- Automatic update of affected task files\n- Summary report of dependency changes made\n- Error handling for invalid dependency operations"
        },
        {
          "id": 5,
          "title": "Implement Batch Task Prioritization and Command System",
          "description": "Create a system for batch prioritization of tasks and a command framework for operating on filtered task sets. This includes commands for changing priorities of multiple tasks at once and a generic command execution system that can apply custom operations to filtered task sets. The implementation should include a plugin architecture that allows for extending the system with new batch operations.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- Command for changing priorities of multiple tasks at once\n- Support for relative priority changes (e.g., increase/decrease priority)\n- Generic command execution framework that works with the filtering system\n- Plugin architecture for registering new batch operations\n- At least three example plugins (e.g., batch tagging, batch assignment, batch export)\n- Command for executing arbitrary operations on filtered task sets\n- Documentation for creating new batch operation plugins\n- Performance testing with large task sets (100+ tasks)"
        }
      ]
    },
    {
      "id": 12,
      "title": "Develop Project Initialization System",
      "description": "Create functionality for initializing new projects with task structure and configuration.",
      "status": "done",
      "dependencies": [
        1,
        3,
        4,
        6
      ],
      "priority": "medium",
      "details": "Implement project initialization including:\n- Create project templating system\n- Implement interactive setup wizard\n- Add environment configuration generation\n- Create initial directory structure\n- Generate example tasks.json\n- Set up default configuration",
      "testStrategy": "Test project initialization in empty directories. Verify that all required files and directories are created correctly. Test the interactive setup with various inputs.",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Project Template Structure",
          "description": "Design and implement a flexible project template system that will serve as the foundation for new project initialization. This should include creating a base directory structure, template files (e.g., default tasks.json, .env.example), and a configuration file to define customizable aspects of the template.",
          "status": "done",
          "dependencies": [
            4
          ],
          "acceptanceCriteria": "- A `templates` directory is created with at least one default project template"
        },
        {
          "id": 2,
          "title": "Implement Interactive Setup Wizard",
          "description": "Develop an interactive command-line wizard using a library like Inquirer.js to guide users through the project initialization process. The wizard should prompt for project name, description, initial task structure, and other configurable options defined in the template configuration.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- Interactive wizard prompts for essential project information"
        },
        {
          "id": 3,
          "title": "Generate Environment Configuration",
          "description": "Create functionality to generate environment-specific configuration files based on user input and template defaults. This includes creating a .env file with necessary API keys and configuration values, and updating the tasks.json file with project-specific metadata.",
          "status": "done",
          "dependencies": [
            2
          ],
          "acceptanceCriteria": "- .env file is generated with placeholders for required API keys"
        },
        {
          "id": 4,
          "title": "Implement Directory Structure Creation",
          "description": "Develop the logic to create the initial directory structure for new projects based on the selected template and user inputs. This should include creating necessary subdirectories (e.g., tasks/, scripts/, .cursor/rules/) and copying template files to appropriate locations.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- Directory structure is created according to the template specification"
        },
        {
          "id": 5,
          "title": "Generate Example Tasks.json",
          "description": "Create functionality to generate an initial tasks.json file with example tasks based on the project template and user inputs from the setup wizard. This should include creating a set of starter tasks that demonstrate the task structure and provide a starting point for the project.",
          "status": "done",
          "dependencies": [
            6
          ],
          "acceptanceCriteria": "- An initial tasks.json file is generated with at least 3 example tasks"
        },
        {
          "id": 6,
          "title": "Implement Default Configuration Setup",
          "description": "Develop the system for setting up default configurations for the project, including initializing the .cursor/rules/ directory with dev_workflow.mdc, cursor_rules.mdc, and self_improve.mdc files. Also, create a default package.json with necessary dependencies and scripts for the project.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- .cursor/rules/ directory is created with required .mdc files"
        }
      ]
    },
    {
      "id": 13,
      "title": "Create Cursor Rules Implementation",
      "description": "Develop the Cursor AI integration rules and documentation.",
      "status": "done",
      "dependencies": [
        1,
        3
      ],
      "priority": "medium",
      "details": "Implement Cursor rules including:\n- Create dev_workflow.mdc documentation\n- Implement cursor_rules.mdc\n- Add self_improve.mdc\n- Design rule integration documentation\n- Set up .cursor directory structure\n- Document how Cursor AI should interact with the system",
      "testStrategy": "Review rules documentation for clarity and completeness. Test with Cursor AI to verify the rules are properly interpreted and followed.",
      "subtasks": [
        {
          "id": 1,
          "title": "Set up .cursor Directory Structure",
          "description": "Create the required directory structure for Cursor AI integration, including the .cursor folder and rules subfolder. This provides the foundation for storing all Cursor-related configuration files and rule documentation. Ensure proper permissions and gitignore settings are configured to maintain these files correctly.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- .cursor directory created at the project root\n- .cursor/rules subdirectory created\n- Directory structure matches the specification in the PRD\n- Appropriate entries added to .gitignore to handle .cursor directory correctly\n- README documentation updated to mention the .cursor directory purpose"
        },
        {
          "id": 2,
          "title": "Create dev_workflow.mdc Documentation",
          "description": "Develop the dev_workflow.mdc file that documents the development workflow for Cursor AI. This file should outline how Cursor AI should assist with task discovery, implementation, and verification within the project. Include specific examples of commands and interactions that demonstrate the optimal workflow.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- dev_workflow.mdc file created in .cursor/rules directory\n- Document clearly explains the development workflow with Cursor AI\n- Workflow documentation includes task discovery process\n- Implementation guidance for Cursor AI is detailed\n- Verification procedures are documented\n- Examples of typical interactions are provided"
        },
        {
          "id": 3,
          "title": "Implement cursor_rules.mdc",
          "description": "Create the cursor_rules.mdc file that defines specific rules and guidelines for how Cursor AI should interact with the codebase. This should include code style preferences, architectural patterns to follow, documentation requirements, and any project-specific conventions that Cursor AI should adhere to when generating or modifying code.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- cursor_rules.mdc file created in .cursor/rules directory\n- Rules document clearly defines code style guidelines\n- Architectural patterns and principles are specified\n- Documentation requirements for generated code are outlined\n- Project-specific naming conventions are documented\n- Rules for handling dependencies and imports are defined\n- Guidelines for test implementation are included"
        },
        {
          "id": 4,
          "title": "Add self_improve.mdc Documentation",
          "description": "Develop the self_improve.mdc file that instructs Cursor AI on how to continuously improve its assistance capabilities within the project context. This document should outline how Cursor AI should learn from feedback, adapt to project evolution, and enhance its understanding of the codebase over time.",
          "status": "done",
          "dependencies": [
            1,
            2,
            3
          ],
          "acceptanceCriteria": "- self_improve.mdc file created in .cursor/rules directory\n- Document outlines feedback incorporation mechanisms\n- Guidelines for adapting to project evolution are included\n- Instructions for enhancing codebase understanding over time\n- Strategies for improving code suggestions based on past interactions\n- Methods for refining prompt responses based on user feedback\n- Approach for maintaining consistency with evolving project patterns"
        },
        {
          "id": 5,
          "title": "Create Cursor AI Integration Documentation",
          "description": "Develop comprehensive documentation on how Cursor AI integrates with the task management system. This should include detailed instructions on how Cursor AI should interpret tasks.json, individual task files, and how it should assist with implementation. Document the specific commands and workflows that Cursor AI should understand and support.",
          "status": "done",
          "dependencies": [
            1,
            2,
            3,
            4
          ],
          "acceptanceCriteria": "- Integration documentation created and stored in an appropriate location\n- Documentation explains how Cursor AI should interpret tasks.json structure\n- Guidelines for Cursor AI to understand task dependencies and priorities\n- Instructions for Cursor AI to assist with task implementation\n- Documentation of specific commands Cursor AI should recognize\n- Examples of effective prompts for working with the task system\n- Troubleshooting section for common Cursor AI integration issues\n- Documentation references all created rule files and explains their purpose"
        }
      ]
    },
    {
      "id": 14,
      "title": "Develop Agent Workflow Guidelines",
      "description": "Create comprehensive guidelines for how AI agents should interact with the task system.",
      "status": "done",
      "dependencies": [
        13
      ],
      "priority": "medium",
      "details": "Create agent workflow guidelines including:\n- Document task discovery workflow\n- Create task selection guidelines\n- Implement implementation guidance\n- Add verification procedures\n- Define how agents should prioritize work\n- Create guidelines for handling dependencies",
      "testStrategy": "Review guidelines with actual AI agents to verify they can follow the procedures. Test various scenarios to ensure the guidelines cover all common workflows.",
      "subtasks": [
        {
          "id": 1,
          "title": "Document Task Discovery Workflow",
          "description": "Create a comprehensive document outlining how AI agents should discover and interpret new tasks within the system. This should include steps for parsing the tasks.json file, interpreting task metadata, and understanding the relationships between tasks and subtasks. Implement example code snippets in Node.js demonstrating how to traverse the task structure and extract relevant information.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Detailed markdown document explaining the task discovery process"
        },
        {
          "id": 2,
          "title": "Implement Task Selection Algorithm",
          "description": "Develop an algorithm for AI agents to select the most appropriate task to work on based on priority, dependencies, and current project status. This should include logic for evaluating task urgency, managing blocked tasks, and optimizing workflow efficiency. Implement the algorithm in JavaScript and integrate it with the existing task management system.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- JavaScript module implementing the task selection algorithm"
        },
        {
          "id": 3,
          "title": "Create Implementation Guidance Generator",
          "description": "Develop a system that generates detailed implementation guidance for AI agents based on task descriptions and project context. This should leverage the Anthropic Claude API to create step-by-step instructions, suggest relevant libraries or tools, and provide code snippets or pseudocode where appropriate. Implement caching to reduce API calls and improve performance.",
          "status": "done",
          "dependencies": [
            5
          ],
          "acceptanceCriteria": "- Node.js module for generating implementation guidance using Claude API"
        },
        {
          "id": 4,
          "title": "Develop Verification Procedure Framework",
          "description": "Create a flexible framework for defining and executing verification procedures for completed tasks. This should include a DSL (Domain Specific Language) for specifying acceptance criteria, automated test generation where possible, and integration with popular testing frameworks. Implement hooks for both automated and manual verification steps.",
          "status": "done",
          "dependencies": [
            1,
            2
          ],
          "acceptanceCriteria": "- JavaScript module implementing the verification procedure framework"
        },
        {
          "id": 5,
          "title": "Implement Dynamic Task Prioritization System",
          "description": "Develop a system that dynamically adjusts task priorities based on project progress, dependencies, and external factors. This should include an algorithm for recalculating priorities, a mechanism for propagating priority changes through dependency chains, and an API for external systems to influence priorities. Implement this as a background process that periodically updates the tasks.json file.",
          "status": "done",
          "dependencies": [
            1,
            2,
            3
          ],
          "acceptanceCriteria": "- Node.js module implementing the dynamic prioritization system"
        }
      ]
    },
    {
      "id": 15,
      "title": "Optimize Agent Integration with Cursor and dev.js Commands",
      "description": "Document and enhance existing agent interaction patterns through Cursor rules and dev.js commands.",
      "status": "done",
      "dependencies": [
        14
      ],
      "priority": "medium",
      "details": "Optimize agent integration including:\n- Document and improve existing agent interaction patterns in Cursor rules\n- Enhance integration between Cursor agent capabilities and dev.js commands\n- Improve agent workflow documentation in cursor rules (dev_workflow.mdc, cursor_rules.mdc)\n- Add missing agent-specific features to existing commands\n- Leverage existing infrastructure rather than building a separate system",
      "testStrategy": "Test the enhanced commands with AI agents to verify they can correctly interpret and use them. Verify that agents can effectively interact with the task system using the documented patterns in Cursor rules.",
      "subtasks": [
        {
          "id": 1,
          "title": "Document Existing Agent Interaction Patterns",
          "description": "Review and document the current agent interaction patterns in Cursor rules (dev_workflow.mdc, cursor_rules.mdc). Create comprehensive documentation that explains how agents should interact with the task system using existing commands and patterns.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Comprehensive documentation of existing agent interaction patterns in Cursor rules"
        },
        {
          "id": 2,
          "title": "Enhance Integration Between Cursor Agents and dev.js Commands",
          "description": "Improve the integration between Cursor's built-in agent capabilities and the dev.js command system. Ensure that agents can effectively use all task management commands and that the command outputs are optimized for agent consumption.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Enhanced integration between Cursor agents and dev.js commands"
        },
        {
          "id": 3,
          "title": "Optimize Command Responses for Agent Consumption",
          "description": "Refine the output format of existing commands to ensure they are easily parseable by AI agents. Focus on consistent, structured outputs that agents can reliably interpret without requiring a separate parsing system.",
          "status": "done",
          "dependencies": [
            2
          ],
          "acceptanceCriteria": "- Command outputs optimized for agent consumption"
        },
        {
          "id": 4,
          "title": "Improve Agent Workflow Documentation in Cursor Rules",
          "description": "Enhance the agent workflow documentation in dev_workflow.mdc and cursor_rules.mdc to provide clear guidance on how agents should interact with the task system. Include example interactions and best practices for agents.",
          "status": "done",
          "dependencies": [
            1,
            3
          ],
          "acceptanceCriteria": "- Enhanced agent workflow documentation in Cursor rules"
        },
        {
          "id": 5,
          "title": "Add Agent-Specific Features to Existing Commands",
          "description": "Identify and implement any missing agent-specific features in the existing command system. This may include additional flags, parameters, or output formats that are particularly useful for agent interactions.",
          "status": "done",
          "dependencies": [
            2
          ],
          "acceptanceCriteria": "- Agent-specific features added to existing commands"
        },
        {
          "id": 6,
          "title": "Create Agent Usage Examples and Patterns",
          "description": "Develop a set of example interactions and usage patterns that demonstrate how agents should effectively use the task system. Include these examples in the documentation to guide future agent implementations.",
          "status": "done",
          "dependencies": [
            3,
            4
          ],
          "acceptanceCriteria": "- Comprehensive set of agent usage examples and patterns"
        }
      ]
    },
    {
      "id": 16,
      "title": "Create Configuration Management System",
      "description": "Implement robust configuration handling with environment variables and .env files.",
      "status": "done",
      "dependencies": [
        1
      ],
      "priority": "high",
      "details": "Build configuration management including:\n- Environment variable handling\n- .env file support\n- Configuration validation\n- Sensible defaults with overrides\n- Create .env.example template\n- Add configuration documentation\n- Implement secure handling of API keys",
      "testStrategy": "Test configuration loading from various sources (environment variables, .env files). Verify that validation correctly identifies invalid configurations. Test that defaults are applied when values are missing.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Environment Variable Loading",
          "description": "Create a module that loads environment variables from process.env and makes them accessible throughout the application. Implement a hierarchical structure for configuration values with proper typing. Include support for required vs. optional variables and implement a validation mechanism to ensure critical environment variables are present.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Function created to access environment variables with proper TypeScript typing\n- Support for required variables with validation\n- Default values provided for optional variables\n- Error handling for missing required variables\n- Unit tests verifying environment variable loading works correctly"
        },
        {
          "id": 2,
          "title": "Implement .env File Support",
          "description": "Add support for loading configuration from .env files using dotenv or a similar library. Implement file detection, parsing, and merging with existing environment variables. Handle multiple environments (.env.development, .env.production, etc.) and implement proper error handling for file reading issues.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- Integration with dotenv or equivalent library\n- Support for multiple environment-specific .env files (.env.development, .env.production)\n- Proper error handling for missing or malformed .env files\n- Priority order established (process.env overrides .env values)\n- Unit tests verifying .env file loading and overriding behavior"
        },
        {
          "id": 3,
          "title": "Implement Configuration Validation",
          "description": "Create a validation system for configuration values using a schema validation library like Joi, Zod, or Ajv. Define schemas for all configuration categories (API keys, file paths, feature flags, etc.). Implement validation that runs at startup and provides clear error messages for invalid configurations.",
          "status": "done",
          "dependencies": [
            1,
            2
          ],
          "acceptanceCriteria": "- Schema validation implemented for all configuration values\n- Type checking and format validation for different value types\n- Comprehensive error messages that clearly identify validation failures\n- Support for custom validation rules for complex configuration requirements\n- Unit tests covering validation of valid and invalid configurations"
        },
        {
          "id": 4,
          "title": "Create Configuration Defaults and Override System",
          "description": "Implement a system of sensible defaults for all configuration values with the ability to override them via environment variables or .env files. Create a unified configuration object that combines defaults, .env values, and environment variables with proper precedence. Implement a caching mechanism to avoid repeated environment lookups.",
          "status": "done",
          "dependencies": [
            1,
            2,
            3
          ],
          "acceptanceCriteria": "- Default configuration values defined for all settings\n- Clear override precedence (env vars > .env files > defaults)\n- Configuration object accessible throughout the application\n- Caching mechanism to improve performance\n- Unit tests verifying override behavior works correctly"
        },
        {
          "id": 5,
          "title": "Create .env.example Template",
          "description": "Generate a comprehensive .env.example file that documents all supported environment variables, their purpose, format, and default values. Include comments explaining the purpose of each variable and provide examples. Ensure sensitive values are not included but have clear placeholders.",
          "status": "done",
          "dependencies": [
            1,
            2,
            3,
            4
          ],
          "acceptanceCriteria": "- Complete .env.example file with all supported variables\n- Detailed comments explaining each variable's purpose and format\n- Clear placeholders for sensitive values (API_KEY=your-api-key-here)\n- Categorization of variables by function (API, logging, features, etc.)\n- Documentation on how to use the .env.example file"
        },
        {
          "id": 6,
          "title": "Implement Secure API Key Handling",
          "description": "Create a secure mechanism for handling sensitive configuration values like API keys. Implement masking of sensitive values in logs and error messages. Add validation for API key formats and implement a mechanism to detect and warn about insecure storage of API keys (e.g., committed to git). Add support for key rotation and refresh.",
          "status": "done",
          "dependencies": [
            1,
            2,
            3,
            4
          ],
          "acceptanceCriteria": "- Secure storage of API keys and sensitive configuration\n- Masking of sensitive values in logs and error messages\n- Validation of API key formats (length, character set, etc.)\n- Warning system for potentially insecure configuration practices\n- Support for key rotation without application restart\n- Unit tests verifying secure handling of sensitive configuration\n\nThese subtasks provide a comprehensive approach to implementing the configuration management system with a focus on security, validation, and developer experience. The tasks are sequenced to build upon each other logically, starting with basic environment variable support and progressing to more advanced features like secure API key handling."
        }
      ]
    },
    {
      "id": 17,
      "title": "Implement Comprehensive Logging System",
      "description": "Create a flexible logging system with configurable levels and output formats.",
      "status": "done",
      "dependencies": [
        16
      ],
      "priority": "medium",
      "details": "Implement logging system including:\n- Multiple log levels (debug, info, warn, error)\n- Configurable output destinations\n- Command execution logging\n- API interaction logging\n- Error tracking\n- Performance metrics\n- Log file rotation",
      "testStrategy": "Test logging at different verbosity levels. Verify that logs contain appropriate information for debugging. Test log file rotation with large volumes of logs.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Core Logging Framework with Log Levels",
          "description": "Create a modular logging framework that supports multiple log levels (debug, info, warn, error). Implement a Logger class that handles message formatting, timestamp addition, and log level filtering. The framework should allow for global log level configuration through the configuration system and provide a clean API for logging messages at different levels.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Logger class with methods for each log level (debug, info, warn, error)\n- Log level filtering based on configuration settings\n- Consistent log message format including timestamp, level, and context\n- Unit tests for each log level and filtering functionality\n- Documentation for logger usage in different parts of the application"
        },
        {
          "id": 2,
          "title": "Implement Configurable Output Destinations",
          "description": "Extend the logging framework to support multiple output destinations simultaneously. Implement adapters for console output, file output, and potentially other destinations (like remote logging services). Create a configuration system that allows specifying which log levels go to which destinations. Ensure thread-safe writing to prevent log corruption.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- Abstract destination interface that can be implemented by different output types\n- Console output adapter with color-coding based on log level\n- File output adapter with proper file handling and path configuration\n- Configuration options to route specific log levels to specific destinations\n- Ability to add custom output destinations through the adapter pattern\n- Tests verifying logs are correctly routed to configured destinations"
        },
        {
          "id": 3,
          "title": "Implement Command and API Interaction Logging",
          "description": "Create specialized logging functionality for command execution and API interactions. For commands, log the command name, arguments, options, and execution status. For API interactions, log request details (URL, method, headers), response status, and timing information. Implement sanitization to prevent logging sensitive data like API keys or passwords.",
          "status": "done",
          "dependencies": [
            1,
            2
          ],
          "acceptanceCriteria": "- Command logger that captures command execution details\n- API logger that records request/response details with timing information\n- Data sanitization to mask sensitive information in logs\n- Configuration options to control verbosity of command and API logs\n- Integration with existing command execution flow\n- Tests verifying proper logging of commands and API calls"
        },
        {
          "id": 4,
          "title": "Implement Error Tracking and Performance Metrics",
          "description": "Enhance the logging system to provide detailed error tracking and performance metrics. For errors, capture stack traces, error codes, and contextual information. For performance metrics, implement timing utilities to measure execution duration of key operations. Create a consistent format for these specialized log types to enable easier analysis.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- Error logging with full stack trace capture and error context\n- Performance timer utility for measuring operation duration\n- Standard format for error and performance log entries\n- Ability to track related errors through correlation IDs\n- Configuration options for performance logging thresholds\n- Unit tests for error tracking and performance measurement"
        },
        {
          "id": 5,
          "title": "Implement Log File Rotation and Management",
          "description": "Create a log file management system that handles rotation based on file size or time intervals. Implement compression of rotated logs, automatic cleanup of old logs, and configurable retention policies. Ensure that log rotation happens without disrupting the application and that no log messages are lost during rotation.",
          "status": "done",
          "dependencies": [
            2
          ],
          "acceptanceCriteria": "- Log rotation based on configurable file size or time interval\n- Compressed archive creation for rotated logs\n- Configurable retention policy for log archives\n- Zero message loss during rotation operations\n- Proper file locking to prevent corruption during rotation\n- Configuration options for rotation settings\n- Tests verifying rotation functionality with large log volumes\n- Documentation for log file location and naming conventions"
        }
      ]
    },
    {
      "id": 18,
      "title": "Create Comprehensive User Documentation",
      "description": "Develop complete user documentation including README, examples, and troubleshooting guides.",
      "status": "done",
      "dependencies": [
        1,
        3,
        4,
        5,
        6,
        7,
        11,
        12,
        16
      ],
      "priority": "medium",
      "details": "Create user documentation including:\n- Detailed README with installation and usage instructions\n- Command reference documentation\n- Configuration guide\n- Example workflows\n- Troubleshooting guides\n- API integration documentation\n- Best practices\n- Advanced usage scenarios",
      "testStrategy": "Review documentation for clarity and completeness. Have users unfamiliar with the system attempt to follow the documentation and note any confusion or issues.",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Detailed README with Installation and Usage Instructions",
          "description": "Develop a comprehensive README.md file that serves as the primary documentation entry point. Include project overview, installation steps for different environments, basic usage examples, and links to other documentation sections. Structure the README with clear headings, code blocks for commands, and screenshots where helpful.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- README includes project overview, features list, and system requirements\n- Installation instructions cover all supported platforms with step-by-step commands\n- Basic usage examples demonstrate core functionality with command syntax\n- Configuration section explains environment variables and .env file usage\n- Documentation includes badges for version, license, and build status\n- All sections are properly formatted with Markdown for readability"
        },
        {
          "id": 2,
          "title": "Develop Command Reference Documentation",
          "description": "Create detailed documentation for all CLI commands, their options, arguments, and examples. Organize commands by functionality category, include syntax diagrams, and provide real-world examples for each command. Document all global options and environment variables that affect command behavior.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- All commands are documented with syntax, options, and arguments\n- Each command includes at least 2 practical usage examples\n- Commands are organized into logical categories (task management, AI integration, etc.)\n- Global options are documented with their effects on command execution\n- Exit codes and error messages are documented for troubleshooting\n- Documentation includes command output examples"
        },
        {
          "id": 3,
          "title": "Create Configuration and Environment Setup Guide",
          "description": "Develop a comprehensive guide for configuring the application, including environment variables, .env file setup, API keys management, and configuration best practices. Include security considerations for API keys and sensitive information. Document all configuration options with their default values and effects.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- All environment variables are documented with purpose, format, and default values\n- Step-by-step guide for setting up .env file with examples\n- Security best practices for managing API keys\n- Configuration troubleshooting section with common issues and solutions\n- Documentation includes example configurations for different use cases\n- Validation rules for configuration values are clearly explained"
        },
        {
          "id": 4,
          "title": "Develop Example Workflows and Use Cases",
          "description": "Create detailed documentation of common workflows and use cases, showing how to use the tool effectively for different scenarios. Include step-by-step guides with command sequences, expected outputs, and explanations. Cover basic to advanced workflows, including PRD parsing, task expansion, and implementation drift handling.",
          "status": "done",
          "dependencies": [
            3,
            6
          ],
          "acceptanceCriteria": "- At least 5 complete workflow examples from initialization to completion\n- Each workflow includes all commands in sequence with expected outputs\n- Screenshots or terminal recordings illustrate the workflows\n- Explanation of decision points and alternatives within workflows\n- Advanced use cases demonstrate integration with development processes\n- Examples show how to handle common edge cases and errors"
        },
        {
          "id": 5,
          "title": "Create Troubleshooting Guide and FAQ",
          "description": "Develop a comprehensive troubleshooting guide that addresses common issues, error messages, and their solutions. Include a FAQ section covering common questions about usage, configuration, and best practices. Document known limitations and workarounds for edge cases.",
          "status": "done",
          "dependencies": [
            1,
            2,
            3
          ],
          "acceptanceCriteria": "- All error messages are documented with causes and solutions\n- Common issues are organized by category (installation, configuration, execution)\n- FAQ covers at least 15 common questions with detailed answers\n- Troubleshooting decision trees help users diagnose complex issues\n- Known limitations and edge cases are clearly documented\n- Recovery procedures for data corruption or API failures are included"
        },
        {
          "id": 6,
          "title": "Develop API Integration and Extension Documentation",
          "description": "Create technical documentation for API integrations (Claude, Perplexity) and extension points. Include details on prompt templates, response handling, token optimization, and custom integrations. Document the internal architecture to help developers extend the tool with new features or integrations.",
          "status": "done",
          "dependencies": [
            5
          ],
          "acceptanceCriteria": "- Detailed documentation of all API integrations with authentication requirements\n- Prompt templates are documented with variables and expected responses\n- Token usage optimization strategies are explained\n- Extension points are documented with examples\n- Internal architecture diagrams show component relationships\n- Custom integration guide includes step-by-step instructions and code examples"
        }
      ]
    },
    {
      "id": 19,
      "title": "Implement Error Handling and Recovery",
      "description": "Create robust error handling throughout the system with helpful error messages and recovery options.",
      "status": "done",
      "dependencies": [
        1,
        3,
        5,
        9,
        16,
        17
      ],
      "priority": "high",
      "details": "Implement error handling including:\n- Consistent error message format\n- Helpful error messages with recovery suggestions\n- API error handling with retries\n- File system error recovery\n- Data validation errors with specific feedback\n- Command syntax error guidance\n- System state recovery after failures",
      "testStrategy": "Deliberately trigger various error conditions and verify that the system handles them gracefully. Check that error messages are helpful and provide clear guidance on how to resolve issues.",
      "subtasks": [
        {
          "id": 1,
          "title": "Define Error Message Format and Structure",
          "description": "Create a standardized error message format that includes error codes, descriptive messages, and recovery suggestions. Implement a centralized ErrorMessage class or module that enforces this structure across the application. This should include methods for generating consistent error messages and translating error codes to user-friendly descriptions.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- ErrorMessage class/module is implemented with methods for creating structured error messages"
        },
        {
          "id": 2,
          "title": "Implement API Error Handling with Retry Logic",
          "description": "Develop a robust error handling system for API calls, including automatic retries with exponential backoff. Create a wrapper for API requests that catches common errors (e.g., network timeouts, rate limiting) and implements appropriate retry logic. This should be integrated with both the Claude and Perplexity API calls.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- API request wrapper is implemented with configurable retry logic"
        },
        {
          "id": 3,
          "title": "Develop File System Error Recovery Mechanisms",
          "description": "Implement error handling and recovery mechanisms for file system operations, focusing on tasks.json and individual task files. This should include handling of file not found errors, permission issues, and data corruption scenarios. Implement automatic backups and recovery procedures to ensure data integrity.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- File system operations are wrapped with comprehensive error handling"
        },
        {
          "id": 4,
          "title": "Enhance Data Validation with Detailed Error Feedback",
          "description": "Improve the existing data validation system to provide more specific and actionable error messages. Implement detailed validation checks for all user inputs and task data, with clear error messages that pinpoint the exact issue and how to resolve it. This should cover task creation, updates, and any data imported from external sources.",
          "status": "done",
          "dependencies": [
            1,
            3
          ],
          "acceptanceCriteria": "- Enhanced validation checks are implemented for all task properties and user inputs"
        },
        {
          "id": 5,
          "title": "Implement Command Syntax Error Handling and Guidance",
          "description": "Enhance the CLI to provide more helpful error messages and guidance when users input invalid commands or options. Implement a \"did you mean?\" feature for close matches to valid commands, and provide context-sensitive help for command syntax errors. This should integrate with the existing Commander.js setup.",
          "status": "done",
          "dependencies": [
            2
          ],
          "acceptanceCriteria": "- Invalid commands trigger helpful error messages with suggestions for valid alternatives"
        },
        {
          "id": 6,
          "title": "Develop System State Recovery After Critical Failures",
          "description": "Implement a system state recovery mechanism to handle critical failures that could leave the task management system in an inconsistent state. This should include creating periodic snapshots of the system state, implementing a recovery procedure to restore from these snapshots, and providing tools for manual intervention if automatic recovery fails.",
          "status": "done",
          "dependencies": [
            1,
            3
          ],
          "acceptanceCriteria": "- Periodic snapshots of the tasks.json and related state are automatically created"
        }
      ]
    },
    {
      "id": 20,
      "title": "Create Token Usage Tracking and Cost Management",
      "description": "Implement system for tracking API token usage and managing costs.",
      "status": "done",
      "dependencies": [
        5,
        9,
        17
      ],
      "priority": "medium",
      "details": "Implement token tracking including:\n- Track token usage for all API calls\n- Implement configurable usage limits\n- Add reporting on token consumption\n- Create cost estimation features\n- Implement caching to reduce API calls\n- Add token optimization for prompts\n- Create usage alerts when approaching limits",
      "testStrategy": "Track token usage across various operations and verify accuracy. Test that limits properly prevent excessive usage. Verify that caching reduces token consumption for repeated operations.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Token Usage Tracking for API Calls",
          "description": "Create a middleware or wrapper function that intercepts all API calls to OpenAI, Anthropic, and Perplexity. This function should count the number of tokens used in both the request and response, storing this information in a persistent data store (e.g., SQLite database). Implement a caching mechanism to reduce redundant API calls and token usage.",
          "status": "done",
          "dependencies": [
            5
          ],
          "acceptanceCriteria": "- Token usage is accurately tracked for all API calls"
        },
        {
          "id": 2,
          "title": "Develop Configurable Usage Limits",
          "description": "Create a configuration system that allows setting token usage limits at the project, user, and API level. Implement a mechanism to enforce these limits by checking the current usage against the configured limits before making API calls. Add the ability to set different limit types (e.g., daily, weekly, monthly) and actions to take when limits are reached (e.g., block calls, send notifications).",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Configuration file or database table for storing usage limits"
        },
        {
          "id": 3,
          "title": "Implement Token Usage Reporting and Cost Estimation",
          "description": "Develop a reporting module that generates detailed token usage reports. Include breakdowns by API, user, and time period. Implement cost estimation features by integrating current pricing information for each API. Create both command-line and programmatic interfaces for generating reports and estimates.",
          "status": "done",
          "dependencies": [
            1,
            2
          ],
          "acceptanceCriteria": "- CLI command for generating usage reports with various filters"
        },
        {
          "id": 4,
          "title": "Optimize Token Usage in Prompts",
          "description": "Implement a prompt optimization system that analyzes and refines prompts to reduce token usage while maintaining effectiveness. Use techniques such as prompt compression, removing redundant information, and leveraging efficient prompting patterns. Integrate this system into the existing prompt generation and API call processes.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Prompt optimization function reduces average token usage by at least 10%"
        },
        {
          "id": 5,
          "title": "Develop Token Usage Alert System",
          "description": "Create an alert system that monitors token usage in real-time and sends notifications when usage approaches or exceeds defined thresholds. Implement multiple notification channels (e.g., email, Slack, system logs) and allow for customizable alert rules. Integrate this system with the existing logging and reporting modules.",
          "status": "done",
          "dependencies": [
            2,
            3
          ],
          "acceptanceCriteria": "- Real-time monitoring of token usage against configured limits"
        }
      ]
    },
    {
      "id": 21,
      "title": "Refactor dev.js into Modular Components",
      "description": "Restructure the monolithic dev.js file into separate modular components to improve code maintainability, readability, and testability while preserving all existing functionality.",
      "status": "done",
      "dependencies": [
        3,
        16,
        17
      ],
      "priority": "high",
      "details": "This task involves breaking down the current dev.js file into logical modules with clear responsibilities:\n\n1. Create the following module files:\n   - commands.js: Handle all CLI command definitions and execution logic\n   - ai-services.js: Encapsulate all AI service interactions (OpenAI, etc.)\n   - task-manager.js: Manage task operations (create, read, update, delete)\n   - ui.js: Handle all console output formatting, colors, and user interaction\n   - utils.js: Contain helper functions, utilities, and shared code\n\n2. Refactor dev.js to serve as the entry point that:\n   - Imports and initializes all modules\n   - Handles command-line argument parsing\n   - Sets up the execution environment\n   - Orchestrates the flow between modules\n\n3. Ensure proper dependency injection between modules to avoid circular dependencies\n\n4. Maintain consistent error handling across modules\n\n5. Update import/export statements throughout the codebase\n\n6. Document each module with clear JSDoc comments explaining purpose and usage\n\n7. Ensure configuration and logging systems are properly integrated into each module\n\nThe refactoring should not change any existing functionality - this is purely a code organization task.",
      "testStrategy": "Testing should verify that functionality remains identical after refactoring:\n\n1. Automated Testing:\n   - Create unit tests for each new module to verify individual functionality\n   - Implement integration tests that verify modules work together correctly\n   - Test each command to ensure it works exactly as before\n\n2. Manual Testing:\n   - Execute all existing CLI commands and verify outputs match pre-refactoring behavior\n   - Test edge cases like error handling and invalid inputs\n   - Verify that configuration options still work as expected\n\n3. Code Quality Verification:\n   - Run linting tools to ensure code quality standards are maintained\n   - Check for any circular dependencies between modules\n   - Verify that each module has a single, clear responsibility\n\n4. Performance Testing:\n   - Compare execution time before and after refactoring to ensure no performance regression\n\n5. Documentation Check:\n   - Verify that each module has proper documentation\n   - Ensure README is updated if necessary to reflect architectural changes",
      "subtasks": [
        {
          "id": 1,
          "title": "Analyze Current dev.js Structure and Plan Module Boundaries",
          "description": "Perform a comprehensive analysis of the existing dev.js file to identify logical boundaries for the new modules. Create a detailed mapping document that outlines which functions, variables, and code blocks will move to which module files. Identify shared dependencies, potential circular references, and determine the appropriate interfaces between modules.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- Complete inventory of all functions, variables, and code blocks in dev.js"
        },
        {
          "id": 2,
          "title": "Create Core Module Structure and Entry Point Refactoring",
          "description": "Create the skeleton structure for all module files (commands.js, ai-services.js, task-manager.js, ui.js, utils.js) with proper export statements. Refactor dev.js to serve as the entry point that imports and orchestrates these modules. Implement the basic initialization flow and command-line argument parsing in the new structure.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- All module files created with appropriate JSDoc headers explaining purpose"
        },
        {
          "id": 3,
          "title": "Implement Core Module Functionality with Dependency Injection",
          "description": "Migrate the core functionality from dev.js into the appropriate modules following the mapping document. Implement proper dependency injection to avoid circular dependencies. Ensure each module has a clear API and properly encapsulates its internal state. Focus on the critical path functionality first.",
          "status": "done",
          "dependencies": [
            2
          ],
          "acceptanceCriteria": "- All core functionality migrated to appropriate modules"
        },
        {
          "id": 4,
          "title": "Implement Error Handling and Complete Module Migration",
          "description": "Establish a consistent error handling pattern across all modules. Complete the migration of remaining functionality from dev.js to the appropriate modules. Ensure all edge cases, error scenarios, and helper functions are properly moved and integrated. Update all import/export statements throughout the codebase to reference the new module structure.",
          "status": "done",
          "dependencies": [
            3
          ],
          "acceptanceCriteria": "- Consistent error handling pattern implemented across all modules"
        },
        {
          "id": 5,
          "title": "Test, Document, and Finalize Modular Structure",
          "description": "Perform comprehensive testing of the refactored codebase to ensure all functionality works as expected. Add detailed JSDoc comments to all modules, functions, and significant code blocks. Create or update developer documentation explaining the new modular structure, module responsibilities, and how they interact. Perform a final code review to ensure code quality, consistency, and adherence to best practices.",
          "status": "done",
          "dependencies": [
            "21.4"
          ],
          "acceptanceCriteria": "- All existing functionality works exactly as before"
        }
      ]
    },
    {
      "id": 22,
      "title": "Create Comprehensive Test Suite for Task Master CLI",
      "description": "Develop a complete testing infrastructure for the Task Master CLI that includes unit, integration, and end-to-end tests to verify all core functionality and error handling.",
      "status": "done",
      "dependencies": [
        21
      ],
      "priority": "high",
      "details": "Implement a comprehensive test suite using Jest as the testing framework. The test suite should be organized into three main categories:\n\n1. Unit Tests:\n   - Create tests for all utility functions and core logic components\n   - Test task creation, parsing, and manipulation functions\n   - Test data storage and retrieval functions\n   - Test formatting and display functions\n\n2. Integration Tests:\n   - Test all CLI commands (create, expand, update, list, etc.)\n   - Verify command options and parameters work correctly\n   - Test interactions between different components\n   - Test configuration loading and application settings\n\n3. End-to-End Tests:\n   - Test complete workflows (e.g., creating a task, expanding it, updating status)\n   - Test error scenarios and recovery\n   - Test edge cases like handling large numbers of tasks\n\nImplement proper mocking for:\n- Claude API interactions (using Jest mock functions)\n- File system operations (using mock-fs or similar)\n- User input/output (using mock stdin/stdout)\n\nEnsure tests cover both successful operations and error handling paths. Set up continuous integration to run tests automatically. Create fixtures for common test data and scenarios. Include test coverage reporting to identify untested code paths.",
      "testStrategy": "Verification will involve:\n\n1. Code Review:\n   - Verify test organization follows the unit/integration/end-to-end structure\n   - Check that all major functions have corresponding tests\n   - Verify mocks are properly implemented for external dependencies\n\n2. Test Coverage Analysis:\n   - Run test coverage tools to ensure at least 80% code coverage\n   - Verify critical paths have 100% coverage\n   - Identify any untested code paths\n\n3. Test Quality Verification:\n   - Manually review test cases to ensure they test meaningful behavior\n   - Verify both positive and negative test cases exist\n   - Check that tests are deterministic and don't have false positives/negatives\n\n4. CI Integration:\n   - Verify tests run successfully in the CI environment\n   - Ensure tests run in a reasonable amount of time\n   - Check that test failures provide clear, actionable information\n\nThe task will be considered complete when all tests pass consistently, coverage meets targets, and the test suite can detect intentionally introduced bugs.",
      "subtasks": [
        {
          "id": 1,
          "title": "Set Up Jest Testing Environment",
          "description": "Configure Jest for the project, including setting up the jest.config.js file, adding necessary dependencies, and creating the initial test directory structure. Implement proper mocking for Claude API interactions, file system operations, and user input/output. Set up test coverage reporting and configure it to run in the CI pipeline.",
          "status": "done",
          "dependencies": [],
          "acceptanceCriteria": "- jest.config.js is properly configured for the project"
        },
        {
          "id": 2,
          "title": "Implement Unit Tests for Core Components",
          "description": "Create a comprehensive set of unit tests for all utility functions, core logic components, and individual modules of the Task Master CLI. This includes tests for task creation, parsing, manipulation, data storage, retrieval, and formatting functions. Ensure all edge cases and error scenarios are covered.",
          "status": "done",
          "dependencies": [
            1
          ],
          "acceptanceCriteria": "- Unit tests are implemented for all utility functions in the project"
        },
        {
          "id": 3,
          "title": "Develop Integration and End-to-End Tests",
          "description": "Create integration tests that verify the correct interaction between different components of the CLI, including command execution, option parsing, and data flow. Implement end-to-end tests that simulate complete user workflows, such as creating a task, expanding it, and updating its status. Include tests for error scenarios, recovery processes, and handling large numbers of tasks.",
          "status": "deferred",
          "dependencies": [
            1,
            2
          ],
          "acceptanceCriteria": "- Integration tests cover all CLI commands (create, expand, update, list, etc.)"
        }
      ]
    },
    {
      "id": 23,
      "title": "Complete MCP Server Implementation for Task Master using FastMCP",
      "description": "Finalize the MCP server functionality for Task Master by leveraging FastMCP's capabilities, transitioning from CLI-based execution to direct function imports, and optimizing performance, authentication, and context management. Ensure the server integrates seamlessly with Cursor via `mcp.json` and supports proper tool registration, efficient context handling, and transport type handling (focusing on stdio). Additionally, ensure the server can be instantiated properly when installed via `npx` or `npm i -g`. Evaluate and address gaps in the current implementation, including function imports, context management, caching, tool registration, and adherence to FastMCP best practices.",
      "status": "done",
      "dependencies": [
        22
      ],
      "priority": "medium",
      "details": "This task involves completing the Model Context Protocol (MCP) server implementation for Task Master using FastMCP. Key updates include:\n\n1. Transition from CLI-based execution (currently using `child_process.spawnSync`) to direct Task Master function imports for improved performance and reliability.\n2. Implement caching mechanisms for frequently accessed contexts to enhance performance, leveraging FastMCP's efficient transport mechanisms (e.g., stdio).\n3. Refactor context management to align with best practices for handling large context windows, metadata, and tagging.\n4. Refactor tool registration in `tools/index.js` to include clear descriptions and parameter definitions, leveraging FastMCP's decorator-based patterns for better integration.\n5. Enhance transport type handling to ensure proper stdio communication and compatibility with FastMCP.\n6. Ensure the MCP server can be instantiated and run correctly when installed globally via `npx` or `npm i -g`.\n7. Integrate the ModelContextProtocol SDK directly to streamline resource and tool registration, ensuring compatibility with FastMCP's transport mechanisms.\n8. Identify and address missing components or functionalities to meet FastMCP best practices, such as robust error handling, monitoring endpoints, and concurrency support.\n9. Update documentation to include examples of using the MCP server with FastMCP, detailed setup instructions, and client integration guides.\n10. Organize direct function implementations in a modular structure within the mcp-server/src/core/direct-functions/ directory for improved maintainability and organization.\n11. Follow consistent naming conventions: file names use kebab-case (like-this.js), direct functions use camelCase with Direct suffix (functionNameDirect), tool registration functions use camelCase with Tool suffix (registerToolNameTool), and MCP tool names exposed to clients use snake_case (tool_name).\n\nThe implementation must ensure compatibility with existing MCP clients and follow RESTful API design principles, while supporting concurrent requests and maintaining robust error handling.",
      "testStrategy": "Testing for the MCP server implementation will follow a comprehensive approach based on our established testing guidelines:\n\n## Test Organization\n\n1. **Unit Tests** (`tests/unit/mcp-server/`):\n   - Test individual MCP server components in isolation\n   - Mock all external dependencies including FastMCP SDK\n   - Test each tool implementation separately\n   - Test each direct function implementation in the direct-functions directory\n   - Verify direct function imports work correctly\n   - Test context management and caching mechanisms\n   - Example files: `context-manager.test.js`, `tool-registration.test.js`, `direct-functions/list-tasks.test.js`\n\n2. **Integration Tests** (`tests/integration/mcp-server/`):\n   - Test interactions between MCP server components\n   - Verify proper tool registration with FastMCP\n   - Test context flow between components\n   - Validate error handling across module boundaries\n   - Test the integration between direct functions and their corresponding MCP tools\n   - Example files: `server-tool-integration.test.js`, `context-flow.test.js`\n\n3. **End-to-End Tests** (`tests/e2e/mcp-server/`):\n   - Test complete MCP server workflows\n   - Verify server instantiation via different methods (direct, npx, global install)\n   - Test actual stdio communication with mock clients\n   - Example files: `server-startup.e2e.test.js`, `client-communication.e2e.test.js`\n\n4. **Test Fixtures** (`tests/fixtures/mcp-server/`):\n   - Sample context data\n   - Mock tool definitions\n   - Sample MCP requests and responses\n\n## Testing Approach\n\n### Module Mocking Strategy\n```javascript\n// Mock the FastMCP SDK\njest.mock('@model-context-protocol/sdk', () => ({\n  MCPServer: jest.fn().mockImplementation(() => ({\n    registerTool: jest.fn(),\n    registerResource: jest.fn(),\n    start: jest.fn().mockResolvedValue(undefined),\n    stop: jest.fn().mockResolvedValue(undefined)\n  })),\n  MCPError: jest.fn().mockImplementation(function(message, code) {\n    this.message = message;\n    this.code = code;\n  })\n}));\n\n// Import modules after mocks\nimport { MCPServer, MCPError } from '@model-context-protocol/sdk';\nimport { initMCPServer } from '../../scripts/mcp-server.js';\n```\n\n### Direct Function Testing\n- Test each direct function in isolation\n- Verify proper error handling and return formats\n- Test with various input parameters and edge cases\n- Verify integration with the task-master-core.js export hub\n\n### Context Management Testing\n- Test context creation, retrieval, and manipulation\n- Verify caching mechanisms work correctly\n- Test context windowing and metadata handling\n- Validate context persistence across server restarts\n\n### Direct Function Import Testing\n- Verify Task Master functions are imported correctly\n- Test performance improvements compared to CLI execution\n- Validate error handling with direct imports\n\n### Tool Registration Testing\n- Verify tools are registered with proper descriptions and parameters\n- Test decorator-based registration patterns\n- Validate tool execution with different input types\n\n### Error Handling Testing\n- Test all error paths with appropriate MCPError types\n- Verify error propagation to clients\n- Test recovery from various error conditions\n\n### Performance Testing\n- Benchmark response times with and without caching\n- Test memory usage under load\n- Verify concurrent request handling\n\n## Test Quality Guidelines\n\n- Follow TDD approach when possible\n- Maintain test independence and isolation\n- Use descriptive test names explaining expected behavior\n- Aim for 80%+ code coverage, with critical paths at 100%\n- Follow the mock-first-then-import pattern for all Jest mocks\n- Avoid testing implementation details that might change\n- Ensure tests don't depend on execution order\n\n## Specific Test Cases\n\n1. **Server Initialization**\n   - Test server creation with various configuration options\n   - Verify proper tool and resource registration\n   - Test server startup and shutdown procedures\n\n2. **Context Operations**\n   - Test context creation, retrieval, update, and deletion\n   - Verify context windowing and truncation\n   - Test context metadata and tagging\n\n3. **Tool Execution**\n   - Test each tool with various input parameters\n   - Verify proper error handling for invalid inputs\n   - Test tool execution performance\n\n4. **MCP.json Integration**\n   - Test creation and updating of .cursor/mcp.json\n   - Verify proper server registration in mcp.json\n   - Test handling of existing mcp.json files\n\n5. **Transport Handling**\n   - Test stdio communication\n   - Verify proper message formatting\n   - Test error handling in transport layer\n\n6. **Direct Function Structure**\n   - Test the modular organization of direct functions\n   - Verify proper import/export through task-master-core.js\n   - Test utility functions in the utils directory\n\nAll tests will be automated and integrated into the CI/CD pipeline to ensure consistent quality.",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Core MCP Server Module and Basic Structure",
          "description": "Create the foundation for the MCP server implementation by setting up the core module structure, configuration, and server initialization.",
          "dependencies": [],
          "details": "Implementation steps:\n1. Create a new module `mcp-server.js` with the basic server structure\n2. Implement configuration options to enable/disable the MCP server\n3. Set up Express.js routes for the required MCP endpoints (/context, /models, /execute)\n4. Create middleware for request validation and response formatting\n5. Implement basic error handling according to MCP specifications\n6. Add logging infrastructure for MCP operations\n7. Create initialization and shutdown procedures for the MCP server\n8. Set up integration with the main Task Master application\n\nTesting approach:\n- Unit tests for configuration loading and validation\n- Test server initialization and shutdown procedures\n- Verify that routes are properly registered\n- Test basic error handling with invalid requests",
          "status": "done",
          "parentTaskId": 23
        },
        {
          "id": 2,
          "title": "Implement Context Management System",
          "description": "Develop a robust context management system that can efficiently store, retrieve, and manipulate context data according to the MCP specification.",
          "dependencies": [
            1
          ],
          "details": "Implementation steps:\n1. Design and implement data structures for context storage\n2. Create methods for context creation, retrieval, updating, and deletion\n3. Implement context windowing and truncation algorithms for handling size limits\n4. Add support for context metadata and tagging\n5. Create utilities for context serialization and deserialization\n6. Implement efficient indexing for quick context lookups\n7. Add support for context versioning and history\n8. Develop mechanisms for context persistence (in-memory, disk-based, or database)\n\nTesting approach:\n- Unit tests for all context operations (CRUD)\n- Performance tests for context retrieval with various sizes\n- Test context windowing and truncation with edge cases\n- Verify metadata handling and tagging functionality\n- Test persistence mechanisms with simulated failures",
          "status": "done",
          "parentTaskId": 23
        },
        {
          "id": 3,
          "title": "Implement MCP Endpoints and API Handlers",
          "description": "Develop the complete API handlers for all required MCP endpoints, ensuring they follow the protocol specification and integrate with the context management system.",
          "dependencies": [
            1,
            2
          ],
          "details": "Implementation steps:\n1. Implement the `/context` endpoint for:\n   - GET: retrieving existing context\n   - POST: creating new context\n   - PUT: updating existing context\n   - DELETE: removing context\n2. Implement the `/models` endpoint to list available models\n3. Develop the `/execute` endpoint for performing operations with context\n4. Create request validators for each endpoint\n5. Implement response formatters according to MCP specifications\n6. Add detailed error handling for each endpoint\n7. Set up proper HTTP status codes for different scenarios\n8. Implement pagination for endpoints that return lists\n\nTesting approach:\n- Unit tests for each endpoint handler\n- Integration tests with mock context data\n- Test various request formats and edge cases\n- Verify response formats match MCP specifications\n- Test error handling with invalid inputs\n- Benchmark endpoint performance",
          "status": "done",
          "parentTaskId": 23
        },
        {
          "id": 6,
          "title": "Refactor MCP Server to Leverage ModelContextProtocol SDK",
          "description": "Integrate the ModelContextProtocol SDK directly into the MCP server implementation to streamline tool registration and resource handling.",
          "dependencies": [
            1,
            2,
            3
          ],
          "details": "Implementation steps:\n1. Replace manual tool registration with ModelContextProtocol SDK methods.\n2. Use SDK utilities to simplify resource and template management.\n3. Ensure compatibility with FastMCP's transport mechanisms.\n4. Update server initialization to include SDK-based configurations.\n\nTesting approach:\n- Verify SDK integration with all MCP endpoints.\n- Test resource and template registration using SDK methods.\n- Validate compatibility with existing MCP clients.\n- Benchmark performance improvements from SDK integration.\n\n<info added on 2025-03-31T18:49:14.439Z>\nThe subtask is being cancelled because FastMCP already serves as a higher-level abstraction over the Model Context Protocol SDK. Direct integration with the MCP SDK would be redundant and potentially counterproductive since:\n\n1. FastMCP already encapsulates the necessary SDK functionality for tool registration and resource handling\n2. The existing FastMCP abstractions provide a more streamlined developer experience\n3. Adding another layer of SDK integration would increase complexity without clear benefits\n4. The transport mechanisms in FastMCP are already optimized for the current architecture\n\nInstead, we should focus on extending and enhancing the existing FastMCP abstractions where needed, rather than attempting to bypass them with direct SDK integration.\n</info added on 2025-03-31T18:49:14.439Z>",
          "status": "done",
          "parentTaskId": 23
        },
        {
          "id": 8,
          "title": "Implement Direct Function Imports and Replace CLI-based Execution",
          "description": "Refactor the MCP server implementation to use direct Task Master function imports instead of the current CLI-based execution using child_process.spawnSync. This will improve performance, reliability, and enable better error handling.",
          "dependencies": [
            "23.13"
          ],
          "details": "\n\n<info added on 2025-03-30T00:14:10.040Z>\n```\n# Refactoring Strategy for Direct Function Imports\n\n## Core Approach\n1. Create a clear separation between data retrieval/processing and presentation logic\n2. Modify function signatures to accept `outputFormat` parameter ('cli'|'json', default: 'cli')\n3. Implement early returns for JSON format to bypass CLI-specific code\n\n## Implementation Details for `listTasks`\n```javascript\nfunction listTasks(tasksPath, statusFilter, withSubtasks = false, outputFormat = 'cli') {\n  try {\n    // Existing data retrieval logic\n    const filteredTasks = /* ... */;\n    \n    // Early return for JSON format\n    if (outputFormat === 'json') return filteredTasks;\n    \n    // Existing CLI output logic\n  } catch (error) {\n    if (outputFormat === 'json') {\n      throw {\n        code: 'TASK_LIST_ERROR',\n        message: error.message,\n        details: error.stack\n      };\n    } else {\n      console.error(error);\n      process.exit(1);\n    }\n  }\n}\n```\n\n## Testing Strategy\n- Create integration tests in `tests/integration/mcp-server/`\n- Use FastMCP InMemoryTransport for direct client-server testing\n- Test both JSON and CLI output formats\n- Verify structure consistency with schema validation\n\n## Additional Considerations\n- Update JSDoc comments to document new parameters and return types\n- Ensure backward compatibility with default CLI behavior\n- Add JSON schema validation for consistent output structure\n- Apply similar pattern to other core functions (expandTask, updateTaskById, etc.)\n\n## Error Handling Improvements\n- Standardize error format for JSON returns:\n```javascript\n{\n  code: 'ERROR_CODE',\n  message: 'Human-readable message',\n  details: {}, // Additional context when available\n  stack: process.env.NODE_ENV === 'development' ? error.stack : undefined\n}\n```\n- Enrich JSON errors with error codes and debug info\n- Ensure validation failures return proper objects in JSON mode\n```\n</info added on 2025-03-30T00:14:10.040Z>",
          "status": "done",
          "parentTaskId": 23
        },
        {
          "id": 9,
          "title": "Implement Context Management and Caching Mechanisms",
          "description": "Enhance the MCP server with proper context management and caching to improve performance and user experience, especially for frequently accessed data and contexts.",
          "dependencies": [
            1
          ],
          "details": "1. Implement a context manager class that leverages FastMCP's Context object\n2. Add caching for frequently accessed task data with configurable TTL settings\n3. Implement context tagging for better organization of context data\n4. Add methods to efficiently handle large context windows\n5. Create helper functions for storing and retrieving context data\n6. Implement cache invalidation strategies for task updates\n7. Add cache statistics for monitoring performance\n8. Create unit tests for context management and caching functionality",
          "status": "done",
          "parentTaskId": 23
        },
        {
          "id": 10,
          "title": "Enhance Tool Registration and Resource Management",
          "description": "Refactor tool registration to follow FastMCP best practices, using decorators and improving the overall structure. Implement proper resource management for task templates and other shared resources.",
          "dependencies": [
            1,
            "23.8"
          ],
          "details": "1. Update registerTaskMasterTools function to use FastMCP's decorator pattern\n2. Implement @mcp.tool() decorators for all existing tools\n3. Add proper type annotations and documentation for all tools\n4. Create resource handlers for task templates using @mcp.resource()\n5. Implement resource templates for common task patterns\n6. Update the server initialization to properly register all tools and resources\n7. Add validation for tool inputs using FastMCP's built-in validation\n8. Create comprehensive tests for tool registration and resource access\n\n<info added on 2025-03-31T18:35:21.513Z>\nHere is additional information to enhance the subtask regarding resources and resource templates in FastMCP:\n\nResources in FastMCP are used to expose static or dynamic data to LLM clients. For the Task Master MCP server, we should implement resources to provide:\n\n1. Task templates: Predefined task structures that can be used as starting points\n2. Workflow definitions: Reusable workflow patterns for common task sequences\n3. User preferences: Stored user settings for task management\n4. Project metadata: Information about active projects and their attributes\n\nResource implementation should follow this structure:\n\n```python\n@mcp.resource(\"tasks://templates/{template_id}\")\ndef get_task_template(template_id: str) -> dict:\n    # Fetch and return the specified task template\n    ...\n\n@mcp.resource(\"workflows://definitions/{workflow_id}\")\ndef get_workflow_definition(workflow_id: str) -> dict:\n    # Fetch and return the specified workflow definition\n    ...\n\n@mcp.resource(\"users://{user_id}/preferences\")\ndef get_user_preferences(user_id: str) -> dict:\n    # Fetch and return user preferences\n    ...\n\n@mcp.resource(\"projects://metadata\")\ndef get_project_metadata() -> List[dict]:\n    # Fetch and return metadata for all active projects\n    ...\n```\n\nResource templates in FastMCP allow for dynamic generation of resources based on patterns. For Task Master, we can implement:\n\n1. Dynamic task creation templates\n2. Customizable workflow templates\n3. User-specific resource views\n\nExample implementation:\n\n```python\n@mcp.resource(\"tasks://create/{task_type}\")\ndef get_task_creation_template(task_type: str) -> dict:\n    # Generate and return a task creation template based on task_type\n    ...\n\n@mcp.resource(\"workflows://custom/{user_id}/{workflow_name}\")\ndef get_custom_workflow_template(user_id: str, workflow_name: str) -> dict:\n    # Generate and return a custom workflow template for the user\n    ...\n\n@mcp.resource(\"users://{user_id}/dashboard\")\ndef get_user_dashboard(user_id: str) -> dict:\n    # Generate and return a personalized dashboard view for the user\n    ...\n```\n\nBest practices for integrating resources with Task Master functionality:\n\n1. Use resources to provide context and data for tools\n2. Implement caching for frequently accessed resources\n3. Ensure proper error handling and not-found cases for all resources\n4. Use resource templates to generate dynamic, personalized views of data\n5. Implement access control to ensure users only access authorized resources\n\nBy properly implementing these resources and resource templates, we can provide rich, contextual data to LLM clients, enhancing the Task Master's capabilities and user experience.\n</info added on 2025-03-31T18:35:21.513Z>",
          "status": "done",
          "parentTaskId": 23
        },
        {
          "id": 11,
          "title": "Implement Comprehensive Error Handling",
          "description": "Implement robust error handling using FastMCP's MCPError, including custom error types for different categories and standardized error responses.",
          "details": "1. Create custom error types extending MCPError for different categories (validation, auth, etc.)\\n2. Implement standardized error responses following MCP protocol\\n3. Add error handling middleware for all MCP endpoints\\n4. Ensure proper error propagation from tools to client\\n5. Add debug mode with detailed error information\\n6. Document error types and handling patterns",
          "status": "done",
          "dependencies": [
            "23.1",
            "23.3"
          ],
          "parentTaskId": 23
        },
        {
          "id": 12,
          "title": "Implement Structured Logging System",
          "description": "Implement a comprehensive logging system for the MCP server with different log levels, structured logging format, and request/response tracking.",
          "details": "1. Design structured log format for consistent parsing\\n2. Implement different log levels (debug, info, warn, error)\\n3. Add request/response logging middleware\\n4. Implement correlation IDs for request tracking\\n5. Add performance metrics logging\\n6. Configure log output destinations (console, file)\\n7. Document logging patterns and usage",
          "status": "done",
          "dependencies": [
            "23.1",
            "23.3"
          ],
          "parentTaskId": 23
        },
        {
          "id": 13,
          "title": "Create Testing Framework and Test Suite",
          "description": "Implement a comprehensive testing framework for the MCP server, including unit tests, integration tests, and end-to-end tests.",
          "details": "1. Set up Jest testing framework with proper configuration\\n2. Create MCPTestClient for testing FastMCP server interaction\\n3. Implement unit tests for individual tool functions\\n4. Create integration tests for end-to-end request/response cycles\\n5. Set up test fixtures and mock data\\n6. Implement test coverage reporting\\n7. Document testing guidelines and examples",
          "status": "done",
          "dependencies": [
            "23.1",
            "23.3"
          ],
          "parentTaskId": 23
        },
        {
          "id": 14,
          "title": "Add MCP.json to the Init Workflow",
          "description": "Implement functionality to create or update .cursor/mcp.json during project initialization, handling cases where: 1) If there's no mcp.json, create it with the appropriate configuration; 2) If there is an mcp.json, intelligently append to it without syntax errors like trailing commas",
          "details": "1. Create functionality to detect if .cursor/mcp.json exists in the project\\n2. Implement logic to create a new mcp.json file with proper structure if it doesn't exist\\n3. Add functionality to read and parse existing mcp.json if it exists\\n4. Create method to add a new taskmaster-ai server entry to the mcpServers object\\n5. Implement intelligent JSON merging that avoids trailing commas and syntax errors\\n6. Ensure proper formatting and indentation in the generated/updated JSON\\n7. Add validation to verify the updated configuration is valid JSON\\n8. Include this functionality in the init workflow\\n9. Add error handling for file system operations and JSON parsing\\n10. Document the mcp.json structure and integration process",
          "status": "done",
          "dependencies": [
            "23.1",
            "23.3"
          ],
          "parentTaskId": 23
        },
        {
          "id": 15,
          "title": "Implement SSE Support for Real-time Updates",
          "description": "Add Server-Sent Events (SSE) capabilities to the MCP server to enable real-time updates and streaming of task execution progress, logs, and status changes to clients",
          "details": "1. Research and implement SSE protocol for the MCP server\\n2. Create dedicated SSE endpoints for event streaming\\n3. Implement event emitter pattern for internal event management\\n4. Add support for different event types (task status, logs, errors)\\n5. Implement client connection management with proper keep-alive handling\\n6. Add filtering capabilities to allow subscribing to specific event types\\n7. Create in-memory event buffer for clients reconnecting\\n8. Document SSE endpoint usage and client implementation examples\\n9. Add robust error handling for dropped connections\\n10. Implement rate limiting and backpressure mechanisms\\n11. Add authentication for SSE connections",
          "status": "done",
          "dependencies": [
            "23.1",
            "23.3",
            "23.11"
          ],
          "parentTaskId": 23
        },
        {
          "id": 16,
          "title": "Implement parse-prd MCP command",
          "description": "Create direct function wrapper and MCP tool for parsing PRD documents to generate tasks.",
          "details": "Following MCP implementation standards:\\n\\n1. Create parsePRDDirect function in task-master-core.js:\\n   - Import parsePRD from task-manager.js\\n   - Handle file paths using findTasksJsonPath utility\\n   - Process arguments: input file, output path, numTasks\\n   - Validate inputs and handle errors with try/catch\\n   - Return standardized { success, data/error } object\\n   - Add to directFunctions map\\n\\n2. Create parse-prd.js MCP tool in mcp-server/src/tools/:\\n   - Import z from zod for parameter schema\\n   - Import executeMCPToolAction from ./utils.js\\n   - Import parsePRDDirect from task-master-core.js\\n   - Define parameters matching CLI options using zod schema\\n   - Implement registerParsePRDTool(server) with server.addTool\\n   - Use executeMCPToolAction in execute method\\n\\n3. Register in tools/index.js\\n\\n4. Add to .cursor/mcp.json with appropriate schema\\n\\n5. Write tests following testing guidelines:\\n   - Unit test for parsePRDDirect\\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 17,
          "title": "Implement update MCP command",
          "description": "Create direct function wrapper and MCP tool for updating multiple tasks based on prompt.",
          "details": "Following MCP implementation standards:\\n\\n1. Create updateTasksDirect function in task-master-core.js:\\n   - Import updateTasks from task-manager.js\\n   - Handle file paths using findTasksJsonPath utility\\n   - Process arguments: fromId, prompt, useResearch\\n   - Validate inputs and handle errors with try/catch\\n   - Return standardized { success, data/error } object\\n   - Add to directFunctions map\\n\\n2. Create update.js MCP tool in mcp-server/src/tools/:\\n   - Import z from zod for parameter schema\\n   - Import executeMCPToolAction from ./utils.js\\n   - Import updateTasksDirect from task-master-core.js\\n   - Define parameters matching CLI options using zod schema\\n   - Implement registerUpdateTool(server) with server.addTool\\n   - Use executeMCPToolAction in execute method\\n\\n3. Register in tools/index.js\\n\\n4. Add to .cursor/mcp.json with appropriate schema\\n\\n5. Write tests following testing guidelines:\\n   - Unit test for updateTasksDirect\\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 18,
          "title": "Implement update-task MCP command",
          "description": "Create direct function wrapper and MCP tool for updating a single task by ID with new information.",
          "details": "Following MCP implementation standards:\n\n1. Create updateTaskByIdDirect.js in mcp-server/src/core/direct-functions/:\n   - Import updateTaskById from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: taskId, prompt, useResearch\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create update-task.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import updateTaskByIdDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerUpdateTaskTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for updateTaskByIdDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 19,
          "title": "Implement update-subtask MCP command",
          "description": "Create direct function wrapper and MCP tool for appending information to a specific subtask.",
          "details": "Following MCP implementation standards:\n\n1. Create updateSubtaskByIdDirect.js in mcp-server/src/core/direct-functions/:\n   - Import updateSubtaskById from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: subtaskId, prompt, useResearch\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create update-subtask.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import updateSubtaskByIdDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerUpdateSubtaskTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for updateSubtaskByIdDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 20,
          "title": "Implement generate MCP command",
          "description": "Create direct function wrapper and MCP tool for generating task files from tasks.json.",
          "details": "Following MCP implementation standards:\n\n1. Create generateTaskFilesDirect.js in mcp-server/src/core/direct-functions/:\n   - Import generateTaskFiles from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: tasksPath, outputDir\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create generate.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import generateTaskFilesDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerGenerateTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for generateTaskFilesDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 21,
          "title": "Implement set-status MCP command",
          "description": "Create direct function wrapper and MCP tool for setting task status.",
          "details": "Following MCP implementation standards:\n\n1. Create setTaskStatusDirect.js in mcp-server/src/core/direct-functions/:\n   - Import setTaskStatus from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: taskId, status\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create set-status.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import setTaskStatusDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerSetStatusTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for setTaskStatusDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 22,
          "title": "Implement show-task MCP command",
          "description": "Create direct function wrapper and MCP tool for showing task details.",
          "details": "Following MCP implementation standards:\n\n1. Create showTaskDirect.js in mcp-server/src/core/direct-functions/:\n   - Import showTask from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: taskId\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create show-task.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import showTaskDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerShowTaskTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'show_task'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for showTaskDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 23,
          "title": "Implement next-task MCP command",
          "description": "Create direct function wrapper and MCP tool for finding the next task to work on.",
          "details": "Following MCP implementation standards:\n\n1. Create nextTaskDirect.js in mcp-server/src/core/direct-functions/:\n   - Import nextTask from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments (no specific args needed except projectRoot/file)\n   - Handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create next-task.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import nextTaskDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerNextTaskTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'next_task'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for nextTaskDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 24,
          "title": "Implement expand-task MCP command",
          "description": "Create direct function wrapper and MCP tool for expanding a task into subtasks.",
          "details": "Following MCP implementation standards:\n\n1. Create expandTaskDirect.js in mcp-server/src/core/direct-functions/:\n   - Import expandTask from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: taskId, prompt, num, force, research\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create expand-task.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import expandTaskDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerExpandTaskTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'expand_task'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for expandTaskDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 25,
          "title": "Implement add-task MCP command",
          "description": "Create direct function wrapper and MCP tool for adding new tasks.",
          "details": "Following MCP implementation standards:\n\n1. Create addTaskDirect.js in mcp-server/src/core/direct-functions/:\n   - Import addTask from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: prompt, priority, dependencies\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create add-task.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import addTaskDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerAddTaskTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'add_task'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for addTaskDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 26,
          "title": "Implement add-subtask MCP command",
          "description": "Create direct function wrapper and MCP tool for adding subtasks to existing tasks.",
          "details": "Following MCP implementation standards:\n\n1. Create addSubtaskDirect.js in mcp-server/src/core/direct-functions/:\n   - Import addSubtask from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: parentTaskId, title, description, details\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create add-subtask.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import addSubtaskDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerAddSubtaskTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'add_subtask'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for addSubtaskDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 27,
          "title": "Implement remove-subtask MCP command",
          "description": "Create direct function wrapper and MCP tool for removing subtasks from tasks.",
          "details": "Following MCP implementation standards:\n\n1. Create removeSubtaskDirect.js in mcp-server/src/core/direct-functions/:\n   - Import removeSubtask from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: parentTaskId, subtaskId\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create remove-subtask.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import removeSubtaskDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerRemoveSubtaskTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'remove_subtask'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for removeSubtaskDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 28,
          "title": "Implement analyze MCP command",
          "description": "Create direct function wrapper and MCP tool for analyzing task complexity.",
          "details": "Following MCP implementation standards:\n\n1. Create analyzeTaskComplexityDirect.js in mcp-server/src/core/direct-functions/:\n   - Import analyzeTaskComplexity from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: taskId\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create analyze.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import analyzeTaskComplexityDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerAnalyzeTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'analyze'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for analyzeTaskComplexityDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 29,
          "title": "Implement clear-subtasks MCP command",
          "description": "Create direct function wrapper and MCP tool for clearing subtasks from a parent task.",
          "details": "Following MCP implementation standards:\n\n1. Create clearSubtasksDirect.js in mcp-server/src/core/direct-functions/:\n   - Import clearSubtasks from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: taskId\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create clear-subtasks.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import clearSubtasksDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerClearSubtasksTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'clear_subtasks'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for clearSubtasksDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 30,
          "title": "Implement expand-all MCP command",
          "description": "Create direct function wrapper and MCP tool for expanding all tasks into subtasks.",
          "details": "Following MCP implementation standards:\n\n1. Create expandAllTasksDirect.js in mcp-server/src/core/direct-functions/:\n   - Import expandAllTasks from task-manager.js\n   - Handle file paths using findTasksJsonPath utility\n   - Process arguments: prompt, num, force, research\n   - Validate inputs and handle errors with try/catch\n   - Return standardized { success, data/error } object\n\n2. Export from task-master-core.js:\n   - Import the function from its file\n   - Add to directFunctions map\n\n3. Create expand-all.js MCP tool in mcp-server/src/tools/:\n   - Import z from zod for parameter schema\n   - Import executeMCPToolAction from ./utils.js\n   - Import expandAllTasksDirect from task-master-core.js\n   - Define parameters matching CLI options using zod schema\n   - Implement registerExpandAllTool(server) with server.addTool\n   - Use executeMCPToolAction in execute method\n\n4. Register in tools/index.js with tool name 'expand_all'\n\n5. Add to .cursor/mcp.json with appropriate schema\n\n6. Write tests following testing guidelines:\n   - Unit test for expandAllTasksDirect.js\n   - Integration test for MCP tool",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 31,
          "title": "Create Core Direct Function Structure",
          "description": "Set up the modular directory structure for direct functions and update task-master-core.js to act as an import/export hub.",
          "details": "1. Create the mcp-server/src/core/direct-functions/ directory structure\n2. Update task-master-core.js to import and re-export functions from individual files\n3. Create a utils directory for shared utility functions\n4. Implement a standard template for direct function files\n5. Create documentation for the new modular structure\n6. Update existing imports in MCP tools to use the new structure\n7. Create unit tests for the import/export hub functionality\n8. Ensure backward compatibility with any existing code using the old structure",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 32,
          "title": "Refactor Existing Direct Functions to Modular Structure",
          "description": "Move existing direct function implementations from task-master-core.js to individual files in the new directory structure.",
          "details": "1. Identify all existing direct functions in task-master-core.js\n2. Create individual files for each function in mcp-server/src/core/direct-functions/\n3. Move the implementation to the new files, ensuring consistent error handling\n4. Update imports/exports in task-master-core.js\n5. Create unit tests for each individual function file\n6. Update documentation to reflect the new structure\n7. Ensure all MCP tools reference the functions through task-master-core.js\n8. Verify backward compatibility with existing code",
          "status": "done",
          "dependencies": [
            "23.31"
          ],
          "parentTaskId": 23
        },
        {
          "id": 33,
          "title": "Implement Naming Convention Standards",
          "description": "Update all MCP server components to follow the standardized naming conventions for files, functions, and tools.",
          "details": "1. Audit all existing MCP server files and update file names to use kebab-case (like-this.js)\n2. Refactor direct function names to use camelCase with Direct suffix (functionNameDirect)\n3. Update tool registration functions to use camelCase with Tool suffix (registerToolNameTool)\n4. Ensure all MCP tool names exposed to clients use snake_case (tool_name)\n5. Create a naming convention documentation file for future reference\n6. Update imports/exports in all files to reflect the new naming conventions\n7. Verify that all tools are properly registered with the correct naming pattern\n8. Update tests to reflect the new naming conventions\n9. Create a linting rule to enforce naming conventions in future development",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 34,
          "title": "Review functionality of all MCP direct functions",
          "description": "Verify that all implemented MCP direct functions work correctly with edge cases",
          "details": "Perform comprehensive testing of all MCP direct function implementations to ensure they handle various input scenarios correctly and return appropriate responses. Check edge cases, error handling, and parameter validation.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 35,
          "title": "Review commands.js to ensure all commands are available via MCP",
          "description": "Verify that all CLI commands have corresponding MCP implementations",
          "details": "Compare the commands defined in scripts/modules/commands.js with the MCP tools implemented in mcp-server/src/tools/. Create a list of any commands missing MCP implementations and ensure all command options are properly represented in the MCP parameter schemas.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 36,
          "title": "Finish setting up addResearch in index.js",
          "description": "Complete the implementation of addResearch functionality in the MCP server",
          "details": "Implement the addResearch function in the MCP server's index.js file to enable research-backed functionality. This should include proper integration with Perplexity AI and ensure that all MCP tools requiring research capabilities have access to this functionality.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 37,
          "title": "Finish setting up addTemplates in index.js",
          "description": "Complete the implementation of addTemplates functionality in the MCP server",
          "details": "Implement the addTemplates function in the MCP server's index.js file to enable template-based generation. Configure proper loading of templates from the appropriate directory and ensure they're accessible to all MCP tools that need to generate formatted content.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 38,
          "title": "Implement robust project root handling for file paths",
          "description": "Create a consistent approach for handling project root paths across MCP tools",
          "details": "Analyze and refactor the project root handling mechanism to ensure consistent file path resolution across all MCP direct functions. This should properly handle relative and absolute paths, respect the projectRoot parameter when provided, and have appropriate fallbacks when not specified. Document the approach in a comment within path-utils.js for future maintainers.\n\n<info added on 2025-04-01T02:21:57.137Z>\nHere's additional information addressing the request for research on npm package path handling:\n\n## Path Handling Best Practices for npm Packages\n\n### Distinguishing Package and Project Paths\n\n1. **Package Installation Path**: \n   - Use `require.resolve()` to find paths relative to your package\n   - For global installs, use `process.execPath` to locate the Node.js executable\n\n2. **Project Path**:\n   - Use `process.cwd()` as a starting point\n   - Search upwards for `package.json` or `.git` to find project root\n   - Consider using packages like `find-up` or `pkg-dir` for robust root detection\n\n### Standard Approaches\n\n1. **Detecting Project Root**:\n   - Recursive search for `package.json` or `.git` directory\n   - Use `path.resolve()` to handle relative paths\n   - Fall back to `process.cwd()` if no root markers found\n\n2. **Accessing Package Files**:\n   - Use `__dirname` for paths relative to current script\n   - For files in `node_modules`, use `require.resolve('package-name/path/to/file')`\n\n3. **Separating Package and Project Files**:\n   - Store package-specific files in a dedicated directory (e.g., `.task-master`)\n   - Use environment variables to override default paths\n\n### Cross-Platform Compatibility\n\n1. Use `path.join()` and `path.resolve()` for cross-platform path handling\n2. Avoid hardcoded forward/backslashes in paths\n3. Use `os.homedir()` for user home directory references\n\n### Best Practices for Path Resolution\n\n1. **Absolute vs Relative Paths**:\n   - Always convert relative paths to absolute using `path.resolve()`\n   - Use `path.isAbsolute()` to check if a path is already absolute\n\n2. **Handling Different Installation Scenarios**:\n   - Local dev: Use `process.cwd()` as fallback project root\n   - Local dependency: Resolve paths relative to consuming project\n   - Global install: Use `process.execPath` to locate global `node_modules`\n\n3. **Configuration Options**:\n   - Allow users to specify custom project root via CLI option or config file\n   - Implement a clear precedence order for path resolution (e.g., CLI option > config file > auto-detection)\n\n4. **Error Handling**:\n   - Provide clear error messages when critical paths cannot be resolved\n   - Implement retry logic with alternative methods if primary path detection fails\n\n5. **Documentation**:\n   - Clearly document path handling behavior in README and inline comments\n   - Provide examples for common scenarios and edge cases\n\nBy implementing these practices, the MCP tools can achieve consistent and robust path handling across various npm installation and usage scenarios.\n</info added on 2025-04-01T02:21:57.137Z>\n\n<info added on 2025-04-01T02:25:01.463Z>\nHere's additional information addressing the request for clarification on path handling challenges for npm packages:\n\n## Advanced Path Handling Challenges and Solutions\n\n### Challenges to Avoid\n\n1. **Relying solely on process.cwd()**:\n   - Global installs: process.cwd() could be any directory\n   - Local installs as dependency: points to parent project's root\n   - Users may run commands from subdirectories\n\n2. **Dual Path Requirements**:\n   - Package Path: Where task-master code is installed\n   - Project Path: Where user's tasks.json resides\n\n3. **Specific Edge Cases**:\n   - Non-project directory execution\n   - Deeply nested project structures\n   - Yarn/pnpm workspaces\n   - Monorepos with multiple tasks.json files\n   - Commands invoked from scripts in different directories\n\n### Advanced Solutions\n\n1. **Project Marker Detection**:\n   - Implement recursive search for package.json or .git\n   - Use `find-up` package for efficient directory traversal\n   ```javascript\n   const findUp = require('find-up');\n   const projectRoot = await findUp(dir => findUp.sync('package.json', { cwd: dir }));\n   ```\n\n2. **Package Path Resolution**:\n   - Leverage `import.meta.url` with `fileURLToPath`:\n   ```javascript\n   import { fileURLToPath } from 'url';\n   import path from 'path';\n   \n   const __filename = fileURLToPath(import.meta.url);\n   const __dirname = path.dirname(__filename);\n   const packageRoot = path.resolve(__dirname, '..');\n   ```\n\n3. **Workspace-Aware Resolution**:\n   - Detect Yarn/pnpm workspaces:\n   ```javascript\n   const findWorkspaceRoot = require('find-yarn-workspace-root');\n   const workspaceRoot = findWorkspaceRoot(process.cwd());\n   ```\n\n4. **Monorepo Handling**:\n   - Implement cascading configuration search\n   - Allow multiple tasks.json files with clear precedence rules\n\n5. **CLI Tool Inspiration**:\n   - ESLint: Uses `eslint-find-rule-files` for config discovery\n   - Jest: Implements `jest-resolve` for custom module resolution\n   - Next.js: Uses `find-up` to locate project directories\n\n6. **Robust Path Resolution Algorithm**:\n   ```javascript\n   function resolveProjectRoot(startDir) {\n     const projectMarkers = ['package.json', '.git', 'tasks.json'];\n     let currentDir = startDir;\n     while (currentDir !== path.parse(currentDir).root) {\n       if (projectMarkers.some(marker => fs.existsSync(path.join(currentDir, marker)))) {\n         return currentDir;\n       }\n       currentDir = path.dirname(currentDir);\n     }\n     return startDir; // Fallback to original directory\n   }\n   ```\n\n7. **Environment Variable Overrides**:\n   - Allow users to explicitly set paths:\n   ```javascript\n   const projectRoot = process.env.TASK_MASTER_PROJECT_ROOT || resolveProjectRoot(process.cwd());\n   ```\n\nBy implementing these advanced techniques, task-master can achieve robust path handling across various npm scenarios without requiring manual specification.\n</info added on 2025-04-01T02:25:01.463Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 39,
          "title": "Implement add-dependency MCP command",
          "description": "Create MCP tool implementation for the add-dependency command",
          "details": "",
          "status": "done",
          "dependencies": [
            "23.31"
          ],
          "parentTaskId": 23
        },
        {
          "id": 40,
          "title": "Implement remove-dependency MCP command",
          "description": "Create MCP tool implementation for the remove-dependency command",
          "details": "",
          "status": "done",
          "dependencies": [
            "23.31"
          ],
          "parentTaskId": 23
        },
        {
          "id": 41,
          "title": "Implement validate-dependencies MCP command",
          "description": "Create MCP tool implementation for the validate-dependencies command",
          "details": "",
          "status": "done",
          "dependencies": [
            "23.31",
            "23.39",
            "23.40"
          ],
          "parentTaskId": 23
        },
        {
          "id": 42,
          "title": "Implement fix-dependencies MCP command",
          "description": "Create MCP tool implementation for the fix-dependencies command",
          "details": "",
          "status": "done",
          "dependencies": [
            "23.31",
            "23.41"
          ],
          "parentTaskId": 23
        },
        {
          "id": 43,
          "title": "Implement complexity-report MCP command",
          "description": "Create MCP tool implementation for the complexity-report command",
          "details": "",
          "status": "done",
          "dependencies": [
            "23.31"
          ],
          "parentTaskId": 23
        },
        {
          "id": 44,
          "title": "Implement init MCP command",
          "description": "Create MCP tool implementation for the init command",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 45,
          "title": "Support setting env variables through mcp server",
          "description": "currently we need to access the env variables through the env file present in the project (that we either create or find and append to). we could abstract this by allowing users to define the env vars in the mcp.json directly as folks currently do. mcp.json should then be in gitignore if thats the case. but for this i think in fastmcp all we need is to access ENV in a specific way. we need to find that way and then implement it",
          "details": "\n\n<info added on 2025-04-01T01:57:24.160Z>\nTo access environment variables defined in the mcp.json config file when using FastMCP, you can utilize the `Config` class from the `fastmcp` module. Here's how to implement this:\n\n1. Import the necessary module:\n```python\nfrom fastmcp import Config\n```\n\n2. Access environment variables:\n```python\nconfig = Config()\nenv_var = config.env.get(\"VARIABLE_NAME\")\n```\n\nThis approach allows you to retrieve environment variables defined in the mcp.json file directly in your code. The `Config` class automatically loads the configuration, including environment variables, from the mcp.json file.\n\nFor security, ensure that sensitive information in mcp.json is not committed to version control. You can add mcp.json to your .gitignore file to prevent accidental commits.\n\nIf you need to access multiple environment variables, you can do so like this:\n```python\ndb_url = config.env.get(\"DATABASE_URL\")\napi_key = config.env.get(\"API_KEY\")\ndebug_mode = config.env.get(\"DEBUG_MODE\", False)  # With a default value\n```\n\nThis method provides a clean and consistent way to access environment variables defined in the mcp.json configuration file within your FastMCP project.\n</info added on 2025-04-01T01:57:24.160Z>\n\n<info added on 2025-04-01T01:57:49.848Z>\nTo access environment variables defined in the mcp.json config file when using FastMCP in a JavaScript environment, you can use the `fastmcp` npm package. Here's how to implement this:\n\n1. Install the `fastmcp` package:\n```bash\nnpm install fastmcp\n```\n\n2. Import the necessary module:\n```javascript\nconst { Config } = require('fastmcp');\n```\n\n3. Access environment variables:\n```javascript\nconst config = new Config();\nconst envVar = config.env.get('VARIABLE_NAME');\n```\n\nThis approach allows you to retrieve environment variables defined in the mcp.json file directly in your JavaScript code. The `Config` class automatically loads the configuration, including environment variables, from the mcp.json file.\n\nYou can access multiple environment variables like this:\n```javascript\nconst dbUrl = config.env.get('DATABASE_URL');\nconst apiKey = config.env.get('API_KEY');\nconst debugMode = config.env.get('DEBUG_MODE', false); // With a default value\n```\n\nThis method provides a consistent way to access environment variables defined in the mcp.json configuration file within your FastMCP project in a JavaScript environment.\n</info added on 2025-04-01T01:57:49.848Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        },
        {
          "id": 46,
          "title": "adjust rules so it prioritizes mcp commands over script",
          "description": "",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 23
        }
      ]
    },
    {
      "id": 24,
      "title": "Implement AI-Powered Test Generation Command",
      "description": "Create a new 'generate-test' command in Task Master that leverages AI to automatically produce Jest test files for tasks based on their descriptions and subtasks, utilizing Claude API for AI integration.",
      "status": "pending",
      "dependencies": [
        22
      ],
      "priority": "high",
      "details": "Implement a new command in the Task Master CLI that generates comprehensive Jest test files for tasks. The command should be callable as 'task-master generate-test --id=1' and should:\n\n1. Accept a task ID parameter to identify which task to generate tests for\n2. Retrieve the task and its subtasks from the task store\n3. Analyze the task description, details, and subtasks to understand implementation requirements\n4. Construct an appropriate prompt for the AI service using Claude API\n5. Process the AI response to create a well-formatted test file named 'task_XXX.test.ts' where XXX is the zero-padded task ID\n6. Include appropriate test cases that cover the main functionality described in the task\n7. Generate mocks for external dependencies identified in the task description\n8. Create assertions that validate the expected behavior\n9. Handle both parent tasks and subtasks appropriately (for subtasks, name the file 'task_XXX_YYY.test.ts' where YYY is the subtask ID)\n10. Include error handling for API failures, invalid task IDs, etc.\n11. Add appropriate documentation for the command in the help system\n\nThe implementation should utilize the Claude API for AI service integration and maintain consistency with the current command structure and error handling patterns. Consider using TypeScript for better type safety and integration with the Claude API.",
      "testStrategy": "Testing for this feature should include:\n\n1. Unit tests for the command handler function to verify it correctly processes arguments and options\n2. Mock tests for the Claude API integration to ensure proper prompt construction and response handling\n3. Integration tests that verify the end-to-end flow using a mock Claude API response\n4. Tests for error conditions including:\n   - Invalid task IDs\n   - Network failures when contacting the AI service\n   - Malformed AI responses\n   - File system permission issues\n5. Verification that generated test files follow Jest conventions and can be executed\n6. Tests for both parent task and subtask handling\n7. Manual verification of the quality of generated tests by running them against actual task implementations\n\nCreate a test fixture with sample tasks of varying complexity to evaluate the test generation capabilities across different scenarios. The tests should verify that the command outputs appropriate success/error messages to the console and creates files in the expected location with proper content structure.",
      "subtasks": [
        {
          "id": 1,
          "title": "Create command structure for 'generate-test'",
          "description": "Implement the basic structure for the 'generate-test' command, including command registration, parameter validation, and help documentation.",
          "dependencies": [],
          "details": "Implementation steps:\n1. Create a new file `src/commands/generate-test.ts`\n2. Implement the command structure following the pattern of existing commands\n3. Register the new command in the CLI framework\n4. Add command options for task ID (--id=X) parameter\n5. Implement parameter validation to ensure a valid task ID is provided\n6. Add help documentation for the command\n7. Create the basic command flow that retrieves the task from the task store\n8. Implement error handling for invalid task IDs and other basic errors\n\nTesting approach:\n- Test command registration\n- Test parameter validation (missing ID, invalid ID format)\n- Test error handling for non-existent task IDs\n- Test basic command flow with a mock task store\n<info added on 2025-05-23T21:02:03.909Z>\n## Updated Implementation Approach\n\nBased on code review findings, the implementation approach needs to be revised:\n\n1. Implement the command in `scripts/modules/commands.js` instead of creating a new file\n2. Add command registration in the `registerCommands()` function (around line 482)\n3. Follow existing command structure pattern:\n   ```javascript\n   programInstance\n       .command('generate-test')\n       .description('Generate test cases for a task using AI')\n       .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')\n       .option('-i, --id <id>', 'Task ID parameter')\n       .option('-p, --prompt <text>', 'Additional prompt context')\n       .option('-r, --research', 'Use research model')\n       .action(async (options) => {\n           // Implementation\n       });\n   ```\n\n4. Use the following utilities:\n   - `findProjectRoot()` for resolving project paths\n   - `findTaskById()` for retrieving task data\n   - `chalk` for formatted console output\n\n5. Implement error handling following the pattern:\n   ```javascript\n   try {\n       // Implementation\n   } catch (error) {\n       console.error(chalk.red(`Error generating test: ${error.message}`));\n       if (error.details) {\n           console.error(chalk.red(error.details));\n       }\n       process.exit(1);\n   }\n   ```\n\n6. Required imports:\n   - chalk for colored output\n   - path for file path operations\n   - findProjectRoot and findTaskById from './utils.js'\n</info added on 2025-05-23T21:02:03.909Z>",
          "status": "pending",
          "parentTaskId": 24
        },
        {
          "id": 2,
          "title": "Implement AI prompt construction and FastMCP integration",
          "description": "Develop the logic to analyze tasks, construct appropriate AI prompts, and interact with the AI service using FastMCP to generate test content.",
          "dependencies": [
            1
          ],
          "details": "Implementation steps:\n1. Create a utility function to analyze task descriptions and subtasks for test requirements\n2. Implement a prompt builder that formats task information into an effective AI prompt\n3. Use FastMCP to send the prompt and receive the response\n4. Process the FastMCP response to extract the generated test code\n5. Implement error handling for FastMCP failures, rate limits, and malformed responses\n6. Add appropriate logging for the FastMCP interaction process\n\nTesting approach:\n- Test prompt construction with various task types\n- Test FastMCP integration with mocked responses\n- Test error handling for FastMCP failures\n- Test response processing with sample FastMCP outputs\n<info added on 2025-05-23T21:04:33.890Z>\n## AI Integration Implementation\n\n### AI Service Integration\n- Use the unified AI service layer, not FastMCP directly\n- Implement with `generateObjectService` from '../ai-services-unified.js'\n- Define Zod schema for structured test generation output:\n  - testContent: Complete Jest test file content\n  - fileName: Suggested filename for the test file\n  - mockRequirements: External dependencies that need mocking\n\n### Prompt Construction\n- Create system prompt defining AI's role as test generator\n- Build user prompt with task context (ID, title, description, details)\n- Include test strategy and subtasks context in the prompt\n- Follow patterns from add-task.js for prompt structure\n\n### Task Analysis\n- Retrieve task data using `findTaskById()` from utils.js\n- Build context by analyzing task description, details, and testStrategy\n- Examine project structure for import patterns\n- Parse specific testing requirements from task.testStrategy field\n\n### File System Operations\n- Determine output path in same directory as tasks.json\n- Generate standardized filename based on task ID\n- Use fs.writeFileSync for writing test content to file\n\n### Error Handling & UI\n- Implement try/catch blocks for AI service calls\n- Display user-friendly error messages with chalk\n- Use loading indicators during AI processing\n- Support both research and main AI models\n\n### Telemetry\n- Pass through telemetryData from AI service response\n- Display AI usage summary for CLI output\n\n### Required Dependencies\n- generateObjectService from ai-services-unified.js\n- UI components (loading indicators, display functions)\n- Zod for schema validation\n- Chalk for formatted console output\n</info added on 2025-05-23T21:04:33.890Z>",
          "status": "pending",
          "parentTaskId": 24
        },
        {
          "id": 3,
          "title": "Implement test file generation and output",
          "description": "Create functionality to format AI-generated tests into proper Jest test files and save them to the appropriate location.",
          "dependencies": [
            2
          ],
          "details": "Implementation steps:\n1. Create a utility to format the FastMCP response into a well-structured Jest test file\n2. Implement naming logic for test files (task_XXX.test.ts for parent tasks, task_XXX_YYY.test.ts for subtasks)\n3. Add logic to determine the appropriate file path for saving the test\n4. Implement file system operations to write the test file\n5. Add validation to ensure the generated test follows Jest conventions\n6. Implement formatting of the test file for consistency with project coding standards\n7. Add user feedback about successful test generation and file location\n8. Implement handling for both parent tasks and subtasks\n\nTesting approach:\n- Test file naming logic for various task/subtask combinations\n- Test file content formatting with sample FastMCP outputs\n- Test file system operations with mocked fs module\n- Test the complete flow from command input to file output\n- Verify generated tests can be executed by Jest\n<info added on 2025-05-23T21:06:32.457Z>\n## Detailed Implementation Guidelines\n\n### File Naming Convention Implementation\n```javascript\nfunction generateTestFileName(taskId, isSubtask = false) {\n  if (isSubtask) {\n    // For subtasks like \"24.1\", generate \"task_024_001.test.js\"\n    const [parentId, subtaskId] = taskId.split('.');\n    return `task_${parentId.padStart(3, '0')}_${subtaskId.padStart(3, '0')}.test.js`;\n  } else {\n    // For parent tasks like \"24\", generate \"task_024.test.js\"\n    return `task_${taskId.toString().padStart(3, '0')}.test.js`;\n  }\n}\n```\n\n### File Location Strategy\n- Place generated test files in the `tasks/` directory alongside task files\n- This ensures co-location with task documentation and simplifies implementation\n\n### File Content Structure Template\n```javascript\n/**\n * Test file for Task ${taskId}: ${taskTitle}\n * Generated automatically by Task Master\n */\n\nimport { jest } from '@jest/globals';\n// Additional imports based on task requirements\n\ndescribe('Task ${taskId}: ${taskTitle}', () => {\n  beforeEach(() => {\n    // Setup code\n  });\n\n  afterEach(() => {\n    // Cleanup code\n  });\n\n  test('should ${testDescription}', () => {\n    // Test implementation\n  });\n});\n```\n\n### Code Formatting Standards\n- Follow project's .prettierrc configuration:\n  - Tab width: 2 spaces (useTabs: true)\n  - Print width: 80 characters\n  - Semicolons: Required (semi: true)\n  - Quotes: Single quotes (singleQuote: true)\n  - Trailing commas: None (trailingComma: \"none\")\n  - Bracket spacing: True\n  - Arrow parens: Always\n\n### File System Operations Implementation\n```javascript\nimport fs from 'fs';\nimport path from 'path';\n\n// Determine output path\nconst tasksDir = path.dirname(tasksPath); // Same directory as tasks.json\nconst fileName = generateTestFileName(task.id, isSubtask);\nconst filePath = path.join(tasksDir, fileName);\n\n// Ensure directory exists\nif (!fs.existsSync(tasksDir)) {\n  fs.mkdirSync(tasksDir, { recursive: true });\n}\n\n// Write test file with proper error handling\ntry {\n  fs.writeFileSync(filePath, formattedTestContent, 'utf8');\n} catch (error) {\n  throw new Error(`Failed to write test file: ${error.message}`);\n}\n```\n\n### Error Handling for File Operations\n```javascript\ntry {\n  // File writing operation\n  fs.writeFileSync(filePath, testContent, 'utf8');\n} catch (error) {\n  if (error.code === 'ENOENT') {\n    throw new Error(`Directory does not exist: ${path.dirname(filePath)}`);\n  } else if (error.code === 'EACCES') {\n    throw new Error(`Permission denied writing to: ${filePath}`);\n  } else if (error.code === 'ENOSPC') {\n    throw new Error('Insufficient disk space to write test file');\n  } else {\n    throw new Error(`Failed to write test file: ${error.message}`);\n  }\n}\n```\n\n### User Feedback Implementation\n```javascript\n// Success feedback\nconsole.log(chalk.green('✅ Test file generated successfully:'));\nconsole.log(chalk.cyan(`   File: ${fileName}`));\nconsole.log(chalk.cyan(`   Location: ${filePath}`));\nconsole.log(chalk.gray(`   Size: ${testContent.length} characters`));\n\n// Additional info\nif (mockRequirements && mockRequirements.length > 0) {\n  console.log(chalk.yellow(`   Mocks needed: ${mockRequirements.join(', ')}`));\n}\n```\n\n### Content Validation Requirements\n1. Jest Syntax Validation:\n   - Ensure proper describe/test structure\n   - Validate import statements\n   - Check for balanced brackets and parentheses\n\n2. Code Quality Checks:\n   - Verify no syntax errors\n   - Ensure proper indentation\n   - Check for required imports\n\n3. Test Completeness:\n   - At least one test case\n   - Proper test descriptions\n   - Appropriate assertions\n\n### Required Dependencies\n```javascript\nimport fs from 'fs';\nimport path from 'path';\nimport chalk from 'chalk';\nimport { log } from '../utils.js';\n```\n\n### Integration with Existing Patterns\nFollow the pattern from `generate-task-files.js`:\n1. Read task data using existing utilities\n2. Process content with proper formatting\n3. Write files with error handling\n4. Provide feedback to user\n5. Return success data for MCP integration\n</info added on 2025-05-23T21:06:32.457Z>\n<info added on 2025-05-23T21:18:25.369Z>\n## Corrected Implementation Approach\n\n### Updated File Location Strategy\n\n**CORRECTION**: Tests should go in `/tests/` directory, not `/tasks/` directory.\n\nBased on Jest configuration analysis:\n- Jest is configured with `roots: ['<rootDir>/tests']`\n- Test pattern: `**/?(*.)+(spec|test).js`\n- Current test structure has `/tests/unit/`, `/tests/integration/`, etc.\n\n### Recommended Directory Structure:\n```\ntests/\n├── unit/                    # Manual unit tests\n├── integration/             # Manual integration tests  \n├── generated/               # AI-generated tests\n│   ├── tasks/              # Generated task tests\n│   │   ├── task_024.test.js\n│   │   └── task_024_001.test.js\n│   └── README.md           # Explains generated tests\n└── fixtures/               # Test fixtures\n```\n\n### Updated File Path Logic:\n```javascript\n// Determine output path - place in tests/generated/tasks/\nconst projectRoot = findProjectRoot() || '.';\nconst testsDir = path.join(projectRoot, 'tests', 'generated', 'tasks');\nconst fileName = generateTestFileName(task.id, isSubtask);\nconst filePath = path.join(testsDir, fileName);\n\n// Ensure directory structure exists\nif (!fs.existsSync(testsDir)) {\n    fs.mkdirSync(testsDir, { recursive: true });\n}\n```\n\n### Testing Framework Configuration\n\nThe generate-test command should read the configured testing framework from `.taskmasterconfig`:\n\n```javascript\n// Read testing framework from config\nconst config = getConfig(projectRoot);\nconst testingFramework = config.testingFramework || 'jest'; // Default to Jest\n\n// Generate different templates based on framework\nswitch (testingFramework) {\n    case 'jest':\n        return generateJestTest(task, context);\n    case 'mocha':\n        return generateMochaTest(task, context);\n    case 'vitest':\n        return generateVitestTest(task, context);\n    default:\n        throw new Error(`Unsupported testing framework: ${testingFramework}`);\n}\n```\n\n### Framework-Specific Templates\n\n**Jest Template** (current):\n```javascript\n/**\n * Test file for Task ${taskId}: ${taskTitle}\n * Generated automatically by Task Master\n */\n\nimport { jest } from '@jest/globals';\n// Task-specific imports\n\ndescribe('Task ${taskId}: ${taskTitle}', () => {\n    beforeEach(() => {\n        jest.clearAllMocks();\n    });\n\n    test('should ${testDescription}', () => {\n        // Test implementation\n    });\n});\n```\n\n**Mocha Template**:\n```javascript\n/**\n * Test file for Task ${taskId}: ${taskTitle}\n * Generated automatically by Task Master\n */\n\nimport { expect } from 'chai';\nimport sinon from 'sinon';\n// Task-specific imports\n\ndescribe('Task ${taskId}: ${taskTitle}', () => {\n    beforeEach(() => {\n        sinon.restore();\n    });\n\n    it('should ${testDescription}', () => {\n        // Test implementation\n    });\n});\n```\n\n**Vitest Template**:\n```javascript\n/**\n * Test file for Task ${taskId}: ${taskTitle}\n * Generated automatically by Task Master\n */\n\nimport { describe, test, expect, vi, beforeEach } from 'vitest';\n// Task-specific imports\n\ndescribe('Task ${taskId}: ${taskTitle}', () => {\n    beforeEach(() => {\n        vi.clearAllMocks();\n    });\n\n    test('should ${testDescription}', () => {\n        // Test implementation\n    });\n});\n```\n\n### AI Prompt Enhancement for Mocking\n\nTo address the mocking challenge, enhance the AI prompt with project context:\n\n```javascript\nconst systemPrompt = `You are an expert at generating comprehensive test files. When generating tests, pay special attention to mocking external dependencies correctly.\n\nCRITICAL MOCKING GUIDELINES:\n1. Analyze the task requirements to identify external dependencies (APIs, databases, file system, etc.)\n2. Mock external dependencies at the module level, not inline\n3. Use the testing framework's mocking utilities (jest.mock(), sinon.stub(), vi.mock())\n4. Create realistic mock data that matches the expected API responses\n5. Test both success and error scenarios for mocked dependencies\n6. Ensure mocks are cleared between tests to prevent test pollution\n\nTesting Framework: ${testingFramework}\nProject Structure: ${projectStructureContext}\n`;\n```\n\n### Integration with Future Features\n\nThis primitive command design enables:\n1. **Automatic test generation**: `task-master add-task --with-test`\n2. **Batch test generation**: `task-master generate-tests --all`\n3. **Framework-agnostic**: Support multiple testing frameworks\n4. **Smart mocking**: LLM analyzes dependencies and generates appropriate mocks\n\n### Updated Implementation Requirements:\n\n1. **Read testing framework** from `.taskmasterconfig`\n2. **Create tests directory structure** if it doesn't exist\n3. **Generate framework-specific templates** based on configuration\n4. **Enhanced AI prompts** with mocking best practices\n5. **Project structure analysis** for better import resolution\n6. **Mock dependency detection** from task requirements\n</info added on 2025-05-23T21:18:25.369Z>",
          "status": "pending",
          "parentTaskId": 24
        },
        {
          "id": 4,
          "title": "Implement MCP tool integration for generate-test command",
          "description": "Create MCP server tool support for the generate-test command to enable integration with Claude Code and other MCP clients.",
          "details": "Implementation steps:\n1. Create direct function wrapper in mcp-server/src/core/direct-functions/\n2. Create MCP tool registration in mcp-server/src/tools/\n3. Add tool to the main tools index\n4. Implement proper parameter validation and error handling\n5. Ensure telemetry data is properly passed through\n6. Add tool to MCP server registration\n\nThe MCP tool should support the same parameters as the CLI command:\n- id: Task ID to generate tests for\n- file: Path to tasks.json file\n- research: Whether to use research model\n- prompt: Additional context for test generation\n\nFollow the existing pattern from other MCP tools like add-task.js and expand-task.js.",
          "status": "pending",
          "dependencies": [
            3
          ],
          "parentTaskId": 24
        },
        {
          "id": 5,
          "title": "Add testing framework configuration to project initialization",
          "description": "Enhance the init.js process to let users choose their preferred testing framework (Jest, Mocha, Vitest, etc.) and store this choice in .taskmasterconfig for use by the generate-test command.",
          "details": "Implementation requirements:\n\n1. **Add Testing Framework Prompt to init.js**:\n   - Add interactive prompt asking users to choose testing framework\n   - Support Jest (default), Mocha + Chai, Vitest, Ava, Jasmine\n   - Include brief descriptions of each framework\n   - Allow --testing-framework flag for non-interactive mode\n\n2. **Update .taskmasterconfig Template**:\n   - Add testingFramework field to configuration file\n   - Include default dependencies for each framework\n   - Store framework-specific configuration options\n\n3. **Framework-Specific Setup**:\n   - Generate appropriate config files (jest.config.js, vitest.config.ts, etc.)\n   - Add framework dependencies to package.json suggestions\n   - Create sample test file for the chosen framework\n\n4. **Integration Points**:\n   - Ensure generate-test command reads testingFramework from config\n   - Add validation to prevent conflicts between framework choices\n   - Support switching frameworks later via models command or separate config command\n\nThis makes the generate-test command truly framework-agnostic and sets up the foundation for --with-test flags in other commands.\n<info added on 2025-05-23T21:22:02.048Z>\n# Implementation Plan for Testing Framework Integration\n\n## Code Structure\n\n### 1. Update init.js\n- Add testing framework prompt after addAliases prompt\n- Implement framework selection with descriptions\n- Support non-interactive mode with --testing-framework flag\n- Create setupTestingFramework() function to handle framework-specific setup\n\n### 2. Create New Module Files\n- Create `scripts/modules/testing-frameworks.js` for framework templates and setup\n- Add sample test generators for each supported framework\n- Implement config file generation for each framework\n\n### 3. Update Configuration Templates\n- Modify `assets/.taskmasterconfig` to include testing fields:\n  ```json\n  \"testingFramework\": \"{{testingFramework}}\",\n  \"testingConfig\": {\n    \"framework\": \"{{testingFramework}}\",\n    \"setupFiles\": [],\n    \"testDirectory\": \"tests\",\n    \"testPattern\": \"**/*.test.js\",\n    \"coverage\": {\n      \"enabled\": false,\n      \"threshold\": 80\n    }\n  }\n  ```\n\n### 4. Create Framework-Specific Templates\n- `assets/jest.config.template.js`\n- `assets/vitest.config.template.ts`\n- `assets/.mocharc.template.json`\n- `assets/ava.config.template.js`\n- `assets/jasmine.json.template`\n\n### 5. Update commands.js\n- Add `--testing-framework <framework>` option to init command\n- Add validation for supported frameworks\n\n## Error Handling\n- Validate selected framework against supported list\n- Handle existing config files gracefully with warning/overwrite prompt\n- Provide recovery options if framework setup fails\n- Add conflict detection for multiple testing frameworks\n\n## Integration Points\n- Ensure generate-test command reads testingFramework from config\n- Prepare for future --with-test flag in other commands\n- Support framework switching via config command\n\n## Testing Requirements\n- Unit tests for framework selection logic\n- Integration tests for config file generation\n- Validation tests for each supported framework\n</info added on 2025-05-23T21:22:02.048Z>",
          "status": "pending",
          "dependencies": [
            3
          ],
          "parentTaskId": 24
        }
      ]
    },
    {
      "id": 25,
      "title": "Implement 'add-subtask' Command for Task Hierarchy Management",
      "description": "Create a command-line interface command that allows users to manually add subtasks to existing tasks, establishing a parent-child relationship between tasks.",
      "status": "done",
      "dependencies": [
        3
      ],
      "priority": "medium",
      "details": "Implement the 'add-subtask' command that enables users to create hierarchical relationships between tasks. The command should:\n\n1. Accept parameters for the parent task ID and either the details for a new subtask or the ID of an existing task to convert to a subtask\n2. Validate that the parent task exists before proceeding\n3. If creating a new subtask, collect all necessary task information (title, description, due date, etc.)\n4. If converting an existing task, ensure it's not already a subtask of another task\n5. Update the data model to support parent-child relationships between tasks\n6. Modify the task storage mechanism to persist these relationships\n7. Ensure that when a parent task is marked complete, there's appropriate handling of subtasks (prompt user or provide options)\n8. Update the task listing functionality to display subtasks with appropriate indentation or visual hierarchy\n9. Implement proper error handling for cases like circular dependencies (a task cannot be a subtask of its own subtask)\n10. Document the command syntax and options in the help system",
      "testStrategy": "Testing should verify both the functionality and edge cases of the subtask implementation:\n\n1. Unit tests:\n   - Test adding a new subtask to an existing task\n   - Test converting an existing task to a subtask\n   - Test validation logic for parent task existence\n   - Test prevention of circular dependencies\n   - Test error handling for invalid inputs\n\n2. Integration tests:\n   - Verify subtask relationships are correctly persisted to storage\n   - Verify subtasks appear correctly in task listings\n   - Test the complete workflow from adding a subtask to viewing it in listings\n\n3. Edge cases:\n   - Attempt to add a subtask to a non-existent parent\n   - Attempt to make a task a subtask of itself\n   - Attempt to create circular dependencies (A → B → A)\n   - Test with a deep hierarchy of subtasks (A → B → C → D)\n   - Test handling of subtasks when parent tasks are deleted\n   - Verify behavior when marking parent tasks as complete\n\n4. Manual testing:\n   - Verify command usability and clarity of error messages\n   - Test the command with various parameter combinations",
      "subtasks": [
        {
          "id": 1,
          "title": "Update Data Model to Support Parent-Child Task Relationships",
          "description": "Modify the task data structure to support hierarchical relationships between tasks",
          "dependencies": [],
          "details": "1. Examine the current task data structure in scripts/modules/task-manager.js\n2. Add a 'parentId' field to the task object schema to reference parent tasks\n3. Add a 'subtasks' array field to store references to child tasks\n4. Update any relevant validation functions to account for these new fields\n5. Ensure serialization and deserialization of tasks properly handles these new fields\n6. Update the storage mechanism to persist these relationships\n7. Test by manually creating tasks with parent-child relationships and verifying they're saved correctly\n8. Write unit tests to verify the updated data model works as expected",
          "status": "done",
          "parentTaskId": 25
        },
        {
          "id": 2,
          "title": "Implement Core addSubtask Function in task-manager.js",
          "description": "Create the core function that handles adding subtasks to parent tasks",
          "dependencies": [
            1
          ],
          "details": "1. Create a new addSubtask function in scripts/modules/task-manager.js\n2. Implement logic to validate that the parent task exists\n3. Add functionality to handle both creating new subtasks and converting existing tasks\n4. For new subtasks: collect task information and create a new task with parentId set\n5. For existing tasks: validate it's not already a subtask and update its parentId\n6. Add validation to prevent circular dependencies (a task cannot be a subtask of its own subtask)\n7. Update the parent task's subtasks array\n8. Ensure proper error handling with descriptive error messages\n9. Export the function for use by the command handler\n10. Write unit tests to verify all scenarios (new subtask, converting task, error cases)",
          "status": "done",
          "parentTaskId": 25
        },
        {
          "id": 3,
          "title": "Implement add-subtask Command in commands.js",
          "description": "Create the command-line interface for the add-subtask functionality",
          "dependencies": [
            2
          ],
          "details": "1. Add a new command registration in scripts/modules/commands.js following existing patterns\n2. Define command syntax: 'add-subtask <parentId> [--task-id=<taskId> | --title=<title>]'\n3. Implement command handler that calls the addSubtask function from task-manager.js\n4. Add interactive prompts to collect required information when not provided as arguments\n5. Implement validation for command arguments\n6. Add appropriate success and error messages\n7. Document the command syntax and options in the help system\n8. Test the command with various input combinations\n9. Ensure the command follows the same patterns as other commands like add-dependency",
          "status": "done",
          "parentTaskId": 25
        },
        {
          "id": 4,
          "title": "Create Unit Test for add-subtask",
          "description": "Develop comprehensive unit tests for the add-subtask functionality",
          "dependencies": [
            2,
            3
          ],
          "details": "1. Create a test file in tests/unit/ directory for the add-subtask functionality\n2. Write tests for the addSubtask function in task-manager.js\n3. Test all key scenarios: adding new subtasks, converting existing tasks to subtasks\n4. Test error cases: non-existent parent task, circular dependencies, invalid input\n5. Use Jest mocks to isolate the function from file system operations\n6. Test the command handler in isolation using mock functions\n7. Ensure test coverage for all branches and edge cases\n8. Document the testing approach for future reference",
          "status": "done",
          "parentTaskId": 25
        },
        {
          "id": 5,
          "title": "Implement remove-subtask Command",
          "description": "Create functionality to remove a subtask from its parent, following the same approach as add-subtask",
          "dependencies": [
            2,
            3
          ],
          "details": "1. Create a removeSubtask function in scripts/modules/task-manager.js\n2. Implement logic to validate the subtask exists and is actually a subtask\n3. Add options to either delete the subtask completely or convert it to a standalone task\n4. Update the parent task's subtasks array to remove the reference\n5. If converting to standalone task, clear the parentId reference\n6. Implement the remove-subtask command in scripts/modules/commands.js following patterns from add-subtask\n7. Add appropriate validation and error messages\n8. Document the command in the help system\n9. Export the function in task-manager.js\n10. Ensure proper error handling for all scenarios",
          "status": "done",
          "parentTaskId": 25
        }
      ]
    },
    {
      "id": 26,
      "title": "Implement Context Foundation for AI Operations",
      "description": "Implement the foundation for context integration in Task Master, enabling AI operations to leverage file-based context, cursor rules, and basic code context to improve generated outputs.",
      "status": "pending",
      "dependencies": [
        5,
        6,
        7
      ],
      "priority": "high",
      "details": "Create a Phase 1 foundation for context integration in Task Master that provides immediate practical value:\n\n1. Add `--context-file` Flag to AI Commands:\n   - Add a consistent `--context-file <file>` option to all AI-related commands (expand, update, add-task, etc.)\n   - Implement file reading functionality that loads content from the specified file\n   - Add content integration into Claude API prompts with appropriate formatting\n   - Handle error conditions such as file not found gracefully\n   - Update help documentation to explain the new option\n\n2. Implement Cursor Rules Integration for Context:\n   - Create a `--context-rules <rules>` option for all AI commands\n   - Implement functionality to extract content from specified .cursor/rules/*.mdc files\n   - Support comma-separated lists of rule names and \"all\" option\n   - Add validation and error handling for non-existent rules\n   - Include helpful examples in command help output\n\n3. Implement Basic Context File Extraction Utility:\n   - Create utility functions in utils.js for reading context from files\n   - Add proper error handling and logging\n   - Implement content validation to ensure reasonable size limits\n   - Add content truncation if files exceed token limits\n   - Create helper functions for formatting context additions properly\n\n4. Update Command Handler Logic:\n   - Modify command handlers to support the new context options\n   - Update prompt construction to incorporate context content\n   - Ensure backwards compatibility with existing commands\n   - Add logging for context inclusion to aid troubleshooting\n\nThe focus of this phase is to provide immediate value with straightforward implementations that enable users to include relevant context in their AI operations.",
      "testStrategy": "Testing should verify that the context foundation works as expected and adds value:\n\n1. Functional Tests:\n   - Verify `--context-file` flag correctly reads and includes content from specified files\n   - Test that `--context-rules` correctly extracts and formats content from cursor rules\n   - Test with both existing and non-existent files/rules to verify error handling\n   - Verify content truncation works appropriately for large files\n\n2. Integration Tests:\n   - Test each AI-related command with context options\n   - Verify context is properly included in API calls to Claude\n   - Test combinations of multiple context options\n   - Verify help documentation includes the new options\n\n3. Usability Testing:\n   - Create test scenarios that show clear improvement in AI output quality with context\n   - Compare outputs with and without context to measure impact\n   - Document examples of effective context usage for the user documentation\n\n4. Error Handling:\n   - Test invalid file paths and rule names\n   - Test oversized context files\n   - Verify appropriate error messages guide users to correct usage\n\nThe testing focus should be on proving immediate value to users while ensuring robust error handling.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement --context-file Flag for AI Commands",
          "description": "Add the --context-file <file> option to all AI-related commands and implement file reading functionality",
          "details": "1. Update the contextOptions array in commands.js to include the --context-file option\\n2. Modify AI command action handlers to check for the context-file option\\n3. Implement file reading functionality that loads content from the specified file\\n4. Add content integration into Claude API prompts with appropriate formatting\\n5. Add error handling for file not found or permission issues\\n6. Update help documentation to explain the new option with examples",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 26
        },
        {
          "id": 2,
          "title": "Implement --context Flag for AI Commands",
          "description": "Add support for directly passing context in the command line",
          "details": "1. Update AI command options to include a --context option\\n2. Modify action handlers to process context from command line\\n3. Sanitize and truncate long context inputs\\n4. Add content integration into Claude API prompts\\n5. Update help documentation to explain the new option with examples",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 26
        },
        {
          "id": 3,
          "title": "Implement Cursor Rules Integration for Context",
          "description": "Create a --context-rules option for all AI commands that extracts content from specified .cursor/rules/*.mdc files",
          "details": "1. Add --context-rules <rules> option to all AI-related commands\\n2. Implement functionality to extract content from specified .cursor/rules/*.mdc files\\n3. Support comma-separated lists of rule names and 'all' option\\n4. Add validation and error handling for non-existent rules\\n5. Include helpful examples in command help output",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 26
        },
        {
          "id": 4,
          "title": "Implement Basic Context File Extraction Utility",
          "description": "Create utility functions for reading context from files with error handling and content validation",
          "details": "1. Create utility functions in utils.js for reading context from files\\n2. Add proper error handling and logging for file access issues\\n3. Implement content validation to ensure reasonable size limits\\n4. Add content truncation if files exceed token limits\\n5. Create helper functions for formatting context additions properly\\n6. Document the utility functions with clear examples",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 26
        }
      ]
    },
    {
      "id": 27,
      "title": "Implement Context Enhancements for AI Operations",
      "description": "Enhance the basic context integration with more sophisticated code context extraction, task history awareness, and PRD integration to provide richer context for AI operations.",
      "status": "pending",
      "dependencies": [
        26
      ],
      "priority": "high",
      "details": "Building upon the foundational context implementation in Task #26, implement Phase 2 context enhancements:\n\n1. Add Code Context Extraction Feature:\n   - Create a `--context-code <pattern>` option for all AI commands\n   - Implement glob-based file matching to extract code from specified patterns\n   - Create intelligent code parsing to extract most relevant sections (function signatures, classes, exports)\n   - Implement token usage optimization by selecting key structural elements\n   - Add formatting for code context with proper file paths and syntax indicators\n\n2. Implement Task History Context:\n   - Add a `--context-tasks <ids>` option for AI commands\n   - Support comma-separated task IDs and a \"similar\" option to find related tasks\n   - Create functions to extract context from specified tasks or find similar tasks\n   - Implement formatting for task context with clear section markers\n   - Add validation and error handling for non-existent task IDs\n\n3. Add PRD Context Integration:\n   - Create a `--context-prd <file>` option for AI commands\n   - Implement PRD text extraction and intelligent summarization\n   - Add formatting for PRD context with appropriate section markers\n   - Integrate with the existing PRD parsing functionality from Task #6\n\n4. Improve Context Formatting and Integration:\n   - Create a standardized context formatting system\n   - Implement type-based sectioning for different context sources\n   - Add token estimation for different context types to manage total prompt size\n   - Enhance prompt templates to better integrate various context types\n\nThese enhancements will provide significantly richer context for AI operations, resulting in more accurate and relevant outputs while remaining practical to implement.",
      "testStrategy": "Testing should verify the enhanced context functionality:\n\n1. Code Context Testing:\n   - Verify pattern matching works for different glob patterns\n   - Test code extraction with various file types and sizes\n   - Verify intelligent parsing correctly identifies important code elements\n   - Test token optimization by comparing full file extraction vs. optimized extraction\n   - Check code formatting in prompts sent to Claude API\n\n2. Task History Testing:\n   - Test with different combinations of task IDs\n   - Verify \"similar\" option correctly identifies relevant tasks\n   - Test with non-existent task IDs to ensure proper error handling\n   - Verify formatting and integration in prompts\n\n3. PRD Context Testing:\n   - Test with various PRD files of different sizes\n   - Verify summarization functions correctly when PRDs are too large\n   - Test integration with prompts and formatting\n\n4. Performance Testing:\n   - Measure the impact of context enrichment on command execution time\n   - Test with large code bases to ensure reasonable performance\n   - Verify token counting and optimization functions work as expected\n\n5. Quality Assessment:\n   - Compare AI outputs with Phase 1 vs. Phase 2 context to measure improvements\n   - Create test cases that specifically benefit from code context\n   - Create test cases that benefit from task history context\n\nFocus testing on practical use cases that demonstrate clear improvements in AI-generated outputs.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Code Context Extraction Feature",
          "description": "Create a --context-code <pattern> option for AI commands and implement glob-based file matching to extract relevant code sections",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 27
        },
        {
          "id": 2,
          "title": "Implement Task History Context Integration",
          "description": "Add a --context-tasks option for AI commands that supports finding and extracting context from specified or similar tasks",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 27
        },
        {
          "id": 3,
          "title": "Add PRD Context Integration",
          "description": "Implement a --context-prd option for AI commands that extracts and formats content from PRD files",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 27
        },
        {
          "id": 4,
          "title": "Create Standardized Context Formatting System",
          "description": "Implement a consistent formatting system for different context types with section markers and token optimization",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 27
        }
      ]
    },
    {
      "id": 28,
      "title": "Implement Advanced ContextManager System",
      "description": "Create a comprehensive ContextManager class to unify context handling with advanced features like context optimization, prioritization, and intelligent context selection.",
      "status": "pending",
      "dependencies": [
        26,
        27
      ],
      "priority": "high",
      "details": "Building on Phase 1 and Phase 2 context implementations, develop Phase 3 advanced context management:\n\n1. Implement the ContextManager Class:\n   - Create a unified `ContextManager` class that encapsulates all context functionality\n   - Implement methods for gathering context from all supported sources\n   - Create a configurable context priority system to favor more relevant context types\n   - Add token management to ensure context fits within API limits\n   - Implement caching for frequently used context to improve performance\n\n2. Create Context Optimization Pipeline:\n   - Develop intelligent context optimization algorithms\n   - Implement type-based truncation strategies (code vs. text)\n   - Create relevance scoring to prioritize most useful context portions\n   - Add token budget allocation that divides available tokens among context types\n   - Implement dynamic optimization based on operation type\n\n3. Add Command Interface Enhancements:\n   - Create the `--context-all` flag to include all available context\n   - Add the `--context-max-tokens <tokens>` option to control token allocation\n   - Implement unified context options across all AI commands\n   - Add intelligent default values for different command types\n\n4. Integrate with AI Services:\n   - Update the AI service integration to use the ContextManager\n   - Create specialized context assembly for different AI operations\n   - Add post-processing to capture new context from AI responses\n   - Implement adaptive context selection based on operation success\n\n5. Add Performance Monitoring:\n   - Create context usage statistics tracking\n   - Implement logging for context selection decisions\n   - Add warnings for context token limits\n   - Create troubleshooting utilities for context-related issues\n\nThe ContextManager system should provide a powerful but easy-to-use interface for both users and developers, maintaining backward compatibility with earlier phases while adding substantial new capabilities.",
      "testStrategy": "Testing should verify both the functionality and performance of the advanced context management:\n\n1. Unit Testing:\n   - Test all ContextManager class methods with various inputs\n   - Verify optimization algorithms maintain critical information\n   - Test caching mechanisms for correctness and efficiency\n   - Verify token allocation and budgeting functions\n   - Test each context source integration separately\n\n2. Integration Testing:\n   - Verify ContextManager integration with AI services\n   - Test with all AI-related commands\n   - Verify backward compatibility with existing context options\n   - Test context prioritization across multiple context types\n   - Verify logging and error handling\n\n3. Performance Testing:\n   - Benchmark context gathering and optimization times\n   - Test with large and complex context sources\n   - Measure impact of caching on repeated operations\n   - Verify memory usage remains acceptable\n   - Test with token limits of different sizes\n\n4. Quality Assessment:\n   - Compare AI outputs using Phase 3 vs. earlier context handling\n   - Measure improvements in context relevance and quality\n   - Test complex scenarios requiring multiple context types\n   - Quantify the impact on token efficiency\n\n5. User Experience Testing:\n   - Verify CLI options are intuitive and well-documented\n   - Test error messages are helpful for troubleshooting\n   - Ensure log output provides useful insights\n   - Test all convenience options like `--context-all`\n\nCreate automated test suites for regression testing of the complete context system.",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Core ContextManager Class Structure",
          "description": "Create a unified ContextManager class that encapsulates all context functionality with methods for gathering context from supported sources",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 28
        },
        {
          "id": 2,
          "title": "Develop Context Optimization Pipeline",
          "description": "Create intelligent algorithms for context optimization including type-based truncation, relevance scoring, and token budget allocation",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 28
        },
        {
          "id": 3,
          "title": "Create Command Interface Enhancements",
          "description": "Add unified context options to all AI commands including --context-all flag and --context-max-tokens for controlling allocation",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 28
        },
        {
          "id": 4,
          "title": "Integrate ContextManager with AI Services",
          "description": "Update AI service integration to use the ContextManager with specialized context assembly for different operations",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 28
        },
        {
          "id": 5,
          "title": "Implement Performance Monitoring and Metrics",
          "description": "Create a system for tracking context usage statistics, logging selection decisions, and providing troubleshooting utilities",
          "details": "",
          "status": "pending",
          "dependencies": [],
          "parentTaskId": 28
        }
      ]
    },
    {
      "id": 29,
      "title": "Update Claude 3.7 Sonnet Integration with Beta Header for 128k Token Output",
      "description": "Modify the ai-services.js file to include the beta header 'output-128k-2025-02-19' in Claude 3.7 Sonnet API requests to increase the maximum output token length to 128k tokens.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "The task involves updating the Claude 3.7 Sonnet integration in the ai-services.js file to take advantage of the new 128k token output capability. Specifically:\n\n1. Locate the Claude 3.7 Sonnet API request configuration in ai-services.js\n2. Add the beta header 'output-128k-2025-02-19' to the request headers\n3. Update any related configuration parameters that might need adjustment for the increased token limit\n4. Ensure that token counting and management logic is updated to account for the new 128k token output limit\n5. Update any documentation comments in the code to reflect the new capability\n6. Consider implementing a configuration option to enable/disable this feature, as it may be a beta feature subject to change\n7. Verify that the token management logic correctly handles the increased limit without causing unexpected behavior\n8. Ensure backward compatibility with existing code that might assume lower token limits\n\nThe implementation should be clean and maintainable, with appropriate error handling for cases where the beta header might not be supported in the future.",
      "testStrategy": "Testing should verify that the beta header is correctly included and that the system properly handles the increased token limit:\n\n1. Unit test: Verify that the API request to Claude 3.7 Sonnet includes the 'output-128k-2025-02-19' header\n2. Integration test: Make an actual API call to Claude 3.7 Sonnet with the beta header and confirm a successful response\n3. Test with a prompt designed to generate a very large response (>20k tokens but <128k tokens) and verify it completes successfully\n4. Test the token counting logic with mock responses of various sizes to ensure it correctly handles responses approaching the 128k limit\n5. Verify error handling by simulating API errors related to the beta header\n6. Test any configuration options for enabling/disabling the feature\n7. Performance test: Measure any impact on response time or system resources when handling very large responses\n8. Regression test: Ensure existing functionality using Claude 3.7 Sonnet continues to work as expected\n\nDocument all test results, including any limitations or edge cases discovered during testing."
    },
    {
      "id": 30,
      "title": "Enhance parse-prd Command to Support Default PRD Path",
      "description": "Modify the parse-prd command to automatically use a default PRD path when no path is explicitly provided, improving user experience by reducing the need for manual path specification.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "Currently, the parse-prd command requires users to explicitly specify the path to the PRD document. This enhancement should:\n\n1. Implement a default PRD path configuration that can be set in the application settings or configuration file.\n2. Update the parse-prd command to check for this default path when no path argument is provided.\n3. Add a configuration option that allows users to set/update the default PRD path through a command like `config set default-prd-path <path>`.\n4. Ensure backward compatibility by maintaining support for explicit path specification.\n5. Add appropriate error handling for cases where the default path is not set or the file doesn't exist.\n6. Update the command's help text to indicate that a default path will be used if none is specified.\n7. Consider implementing path validation to ensure the default path points to a valid PRD document.\n8. If multiple PRD formats are supported (Markdown, PDF, etc.), ensure the default path handling works with all supported formats.\n9. Add logging for default path usage to help with debugging and usage analytics.",
      "testStrategy": "1. Unit tests:\n   - Test that the command correctly uses the default path when no path is provided\n   - Test that explicit paths override the default path\n   - Test error handling when default path is not set\n   - Test error handling when default path is set but file doesn't exist\n\n2. Integration tests:\n   - Test the full workflow of setting a default path and then using the parse-prd command without arguments\n   - Test with various file formats if multiple are supported\n\n3. Manual testing:\n   - Verify the command works in a real environment with actual PRD documents\n   - Test the user experience of setting and using default paths\n   - Verify help text correctly explains the default path behavior\n\n4. Edge cases to test:\n   - Relative vs. absolute paths for default path setting\n   - Path with special characters or spaces\n   - Very long paths approaching system limits\n   - Permissions issues with the default path location"
    },
    {
      "id": 31,
      "title": "Add Config Flag Support to task-master init Command",
      "description": "Enhance the 'task-master init' command to accept configuration flags that allow users to bypass the interactive CLI questions and directly provide configuration values.",
      "status": "done",
      "dependencies": [],
      "priority": "low",
      "details": "Currently, the 'task-master init' command prompts users with a series of questions to set up the configuration. This task involves modifying the init command to accept command-line flags that can pre-populate these configuration values, allowing for a non-interactive setup process.\n\nImplementation steps:\n1. Identify all configuration options that are currently collected through CLI prompts during initialization\n2. Create corresponding command-line flags for each configuration option (e.g., --project-name, --ai-provider, etc.)\n3. Modify the init command handler to check for these flags before starting the interactive prompts\n4. If a flag is provided, skip the corresponding prompt and use the provided value instead\n5. If all required configuration values are provided via flags, skip the interactive process entirely\n6. Update the command's help text to document all available flags and their usage\n7. Ensure backward compatibility so the command still works with the interactive approach when no flags are provided\n8. Consider adding a --non-interactive flag that will fail if any required configuration is missing rather than prompting for it (useful for scripts and CI/CD)\n\nThe implementation should follow the existing command structure and use the same configuration file format. Make sure to validate flag values with the same validation logic used for interactive inputs.",
      "testStrategy": "Testing should verify both the interactive and non-interactive paths work correctly:\n\n1. Unit tests:\n   - Test each flag individually to ensure it correctly overrides the corresponding prompt\n   - Test combinations of flags to ensure they work together properly\n   - Test validation of flag values to ensure invalid values are rejected\n   - Test the --non-interactive flag to ensure it fails when required values are missing\n\n2. Integration tests:\n   - Test a complete initialization with all flags provided\n   - Test partial initialization with some flags and some interactive prompts\n   - Test initialization with no flags (fully interactive)\n\n3. Manual testing scenarios:\n   - Run 'task-master init --project-name=\"Test Project\" --ai-provider=\"openai\"' and verify it skips those prompts\n   - Run 'task-master init --help' and verify all flags are documented\n   - Run 'task-master init --non-interactive' without required flags and verify it fails with a helpful error message\n   - Run a complete non-interactive initialization and verify the resulting configuration file matches expectations\n\nEnsure the command's documentation is updated to reflect the new functionality, and verify that the help text accurately describes all available options."
    },
    {
      "id": 32,
      "title": "Implement \"learn\" Command for Automatic Cursor Rule Generation",
      "description": "Create a new \"learn\" command that analyzes Cursor's chat history and code changes to automatically generate or update rule files in the .cursor/rules directory, following the cursor_rules.mdc template format. This command will help Cursor autonomously improve its ability to follow development standards by learning from successful implementations.",
      "status": "deferred",
      "dependencies": [],
      "priority": "high",
      "details": "Implement a new command in the task-master CLI that enables Cursor to learn from successful coding patterns and chat interactions:\n\nKey Components:\n1. Cursor Data Analysis\n   - Access and parse Cursor's chat history from ~/Library/Application Support/Cursor/User/History\n   - Extract relevant patterns, corrections, and successful implementations\n   - Track file changes and their associated chat context\n\n2. Rule Management\n   - Use cursor_rules.mdc as the template for all rule file formatting\n   - Manage rule files in .cursor/rules directory\n   - Support both creation and updates of rule files\n   - Categorize rules based on context (testing, components, API, etc.)\n\n3. AI Integration\n   - Utilize ai-services.js to interact with Claude\n   - Provide comprehensive context including:\n     * Relevant chat history showing the evolution of solutions\n     * Code changes and their outcomes\n     * Existing rules and template structure\n   - Generate or update rules while maintaining template consistency\n\n4. Implementation Requirements:\n   - Automatic triggering after task completion (configurable)\n   - Manual triggering via CLI command\n   - Proper error handling for missing or corrupt files\n   - Validation against cursor_rules.mdc template\n   - Performance optimization for large histories\n   - Clear logging and progress indication\n\n5. Key Files:\n   - commands/learn.js: Main command implementation\n   - rules/cursor-rules-manager.js: Rule file management\n   - utils/chat-history-analyzer.js: Cursor chat analysis\n   - index.js: Command registration\n\n6. Security Considerations:\n   - Safe file system operations\n   - Proper error handling for inaccessible files\n   - Validation of generated rules\n   - Backup of existing rules before updates",
      "testStrategy": "1. Unit Tests:\n   - Test each component in isolation:\n     * Chat history extraction and analysis\n     * Rule file management and validation\n     * Pattern detection and categorization\n     * Template validation logic\n   - Mock file system operations and AI responses\n   - Test error handling and edge cases\n\n2. Integration Tests:\n   - End-to-end command execution\n   - File system interactions\n   - AI service integration\n   - Rule generation and updates\n   - Template compliance validation\n\n3. Manual Testing:\n   - Test after completing actual development tasks\n   - Verify rule quality and usefulness\n   - Check template compliance\n   - Validate performance with large histories\n   - Test automatic and manual triggering\n\n4. Validation Criteria:\n   - Generated rules follow cursor_rules.mdc format\n   - Rules capture meaningful patterns\n   - Performance remains acceptable\n   - Error handling works as expected\n   - Generated rules improve Cursor's effectiveness",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Initial File Structure",
          "description": "Set up the basic file structure for the learn command implementation",
          "details": "Create the following files with basic exports:\n- commands/learn.js\n- rules/cursor-rules-manager.js\n- utils/chat-history-analyzer.js\n- utils/cursor-path-helper.js",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement Cursor Path Helper",
          "description": "Create utility functions to handle Cursor's application data paths",
          "details": "In utils/cursor-path-helper.js implement:\n- getCursorAppDir(): Returns ~/Library/Application Support/Cursor\n- getCursorHistoryDir(): Returns User/History path\n- getCursorLogsDir(): Returns logs directory path\n- validatePaths(): Ensures required directories exist",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Create Chat History Analyzer Base",
          "description": "Create the base structure for analyzing Cursor's chat history",
          "details": "In utils/chat-history-analyzer.js create:\n- ChatHistoryAnalyzer class\n- readHistoryDir(): Lists all history directories\n- readEntriesJson(): Parses entries.json files\n- parseHistoryEntry(): Extracts relevant data from .js files",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Implement Chat History Extraction",
          "description": "Add core functionality to extract relevant chat history",
          "details": "In ChatHistoryAnalyzer add:\n- extractChatHistory(startTime): Gets history since task start\n- parseFileChanges(): Extracts code changes\n- parseAIInteractions(): Extracts AI responses\n- filterRelevantHistory(): Removes irrelevant entries",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Create CursorRulesManager Base",
          "description": "Set up the base structure for managing Cursor rules",
          "details": "In rules/cursor-rules-manager.js create:\n- CursorRulesManager class\n- readTemplate(): Reads cursor_rules.mdc\n- listRuleFiles(): Lists all .mdc files\n- readRuleFile(): Reads specific rule file",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Implement Template Validation",
          "description": "Add validation logic for rule files against cursor_rules.mdc",
          "details": "In CursorRulesManager add:\n- validateRuleFormat(): Checks against template\n- parseTemplateStructure(): Extracts template sections\n- validateAgainstTemplate(): Validates content structure\n- getRequiredSections(): Lists mandatory sections",
          "status": "pending"
        },
        {
          "id": 7,
          "title": "Add Rule Categorization Logic",
          "description": "Implement logic to categorize changes into rule files",
          "details": "In CursorRulesManager add:\n- categorizeChanges(): Maps changes to rule files\n- detectRuleCategories(): Identifies relevant categories\n- getRuleFileForPattern(): Maps patterns to files\n- createNewRuleFile(): Initializes new rule files",
          "status": "pending"
        },
        {
          "id": 8,
          "title": "Implement Pattern Analysis",
          "description": "Create functions to analyze implementation patterns",
          "details": "In ChatHistoryAnalyzer add:\n- extractPatterns(): Finds success patterns\n- extractCorrections(): Finds error corrections\n- findSuccessfulPaths(): Tracks successful implementations\n- analyzeDecisions(): Extracts key decisions",
          "status": "pending"
        },
        {
          "id": 9,
          "title": "Create AI Prompt Builder",
          "description": "Implement prompt construction for Claude",
          "details": "In learn.js create:\n- buildRuleUpdatePrompt(): Builds Claude prompt\n- formatHistoryContext(): Formats chat history\n- formatRuleContext(): Formats current rules\n- buildInstructions(): Creates specific instructions",
          "status": "pending"
        },
        {
          "id": 10,
          "title": "Implement Learn Command Core",
          "description": "Create the main learn command implementation",
          "details": "In commands/learn.js implement:\n- learnCommand(): Main command function\n- processRuleUpdates(): Handles rule updates\n- generateSummary(): Creates learning summary\n- handleErrors(): Manages error cases",
          "status": "pending"
        },
        {
          "id": 11,
          "title": "Add Auto-trigger Support",
          "description": "Implement automatic learning after task completion",
          "details": "Update task-manager.js:\n- Add autoLearnConfig handling\n- Modify completeTask() to trigger learning\n- Add learning status tracking\n- Implement learning queue",
          "status": "pending"
        },
        {
          "id": 12,
          "title": "Implement CLI Integration",
          "description": "Add the learn command to the CLI",
          "details": "Update index.js to:\n- Register learn command\n- Add command options\n- Handle manual triggers\n- Process command flags",
          "status": "pending"
        },
        {
          "id": 13,
          "title": "Add Progress Logging",
          "description": "Implement detailed progress logging",
          "details": "Create utils/learn-logger.js with:\n- logLearningProgress(): Tracks overall progress\n- logRuleUpdates(): Tracks rule changes\n- logErrors(): Handles error logging\n- createSummary(): Generates final report",
          "status": "pending"
        },
        {
          "id": 14,
          "title": "Implement Error Recovery",
          "description": "Add robust error handling throughout the system",
          "details": "Create utils/error-handler.js with:\n- handleFileErrors(): Manages file system errors\n- handleParsingErrors(): Manages parsing failures\n- handleAIErrors(): Manages Claude API errors\n- implementRecoveryStrategies(): Adds recovery logic",
          "status": "pending"
        },
        {
          "id": 15,
          "title": "Add Performance Optimization",
          "description": "Optimize performance for large histories",
          "details": "Add to utils/performance-optimizer.js:\n- implementCaching(): Adds result caching\n- optimizeFileReading(): Improves file reading\n- addProgressiveLoading(): Implements lazy loading\n- addMemoryManagement(): Manages memory usage",
          "status": "pending"
        }
      ]
    },
    {
      "id": 33,
      "title": "Create and Integrate Windsurf Rules Document from MDC Files",
      "description": "Develop functionality to generate a .windsurfrules document by combining and refactoring content from three primary .mdc files used for Cursor Rules, ensuring it's properly integrated into the initialization pipeline.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves creating a mechanism to generate a Windsurf-specific rules document by combining three existing MDC (Markdown Content) files that are currently used for Cursor Rules. The implementation should:\n\n1. Identify and locate the three primary .mdc files used for Cursor Rules\n2. Extract content from these files and merge them into a single document\n3. Refactor the content to make it Windsurf-specific, replacing Cursor-specific terminology and adapting guidelines as needed\n4. Create a function that generates a .windsurfrules document from this content\n5. Integrate this function into the initialization pipeline\n6. Implement logic to check if a .windsurfrules document already exists:\n   - If it exists, append the new content to it\n   - If it doesn't exist, create a new document\n7. Ensure proper error handling for file operations\n8. Add appropriate logging to track the generation and modification of the .windsurfrules document\n\nThe implementation should be modular and maintainable, with clear separation of concerns between content extraction, refactoring, and file operations.",
      "testStrategy": "Testing should verify both the content generation and the integration with the initialization pipeline:\n\n1. Unit Tests:\n   - Test the content extraction function with mock .mdc files\n   - Test the content refactoring function to ensure Cursor-specific terms are properly replaced\n   - Test the file operation functions with mock filesystem\n\n2. Integration Tests:\n   - Test the creation of a new .windsurfrules document when none exists\n   - Test appending to an existing .windsurfrules document\n   - Test the complete initialization pipeline with the new functionality\n\n3. Manual Verification:\n   - Inspect the generated .windsurfrules document to ensure content is properly combined and refactored\n   - Verify that Cursor-specific terminology has been replaced with Windsurf-specific terminology\n   - Run the initialization process multiple times to verify idempotence (content isn't duplicated on multiple runs)\n\n4. Edge Cases:\n   - Test with missing or corrupted .mdc files\n   - Test with an existing but empty .windsurfrules document\n   - Test with an existing .windsurfrules document that already contains some of the content"
    },
    {
      "id": 34,
      "title": "Implement updateTask Command for Single Task Updates",
      "description": "Create a new command that allows updating a specific task by ID using AI-driven refinement while preserving completed subtasks and supporting all existing update command options.",
      "status": "done",
      "dependencies": [],
      "priority": "high",
      "details": "Implement a new command called 'updateTask' that focuses on updating a single task rather than all tasks from an ID onwards. The implementation should:\n\n1. Accept a single task ID as a required parameter\n2. Use the same AI-driven approach as the existing update command to refine the task\n3. Preserve the completion status of any subtasks that were previously marked as complete\n4. Support all options from the existing update command including:\n   - The research flag for Perplexity integration\n   - Any formatting or refinement options\n   - Task context options\n5. Update the CLI help documentation to include this new command\n6. Ensure the command follows the same pattern as other commands in the codebase\n7. Add appropriate error handling for cases where the specified task ID doesn't exist\n8. Implement the ability to update task title, description, and details separately if needed\n9. Ensure the command returns appropriate success/failure messages\n10. Optimize the implementation to only process the single task rather than scanning through all tasks\n\nThe command should reuse existing AI prompt templates where possible but modify them to focus on refining a single task rather than multiple tasks.",
      "testStrategy": "Testing should verify the following aspects:\n\n1. **Basic Functionality Test**: Verify that the command successfully updates a single task when given a valid task ID\n2. **Preservation Test**: Create a task with completed subtasks, update it, and verify the completion status remains intact\n3. **Research Flag Test**: Test the command with the research flag and verify it correctly integrates with Perplexity\n4. **Error Handling Tests**:\n   - Test with non-existent task ID and verify appropriate error message\n   - Test with invalid parameters and verify helpful error messages\n5. **Integration Test**: Run a complete workflow that creates a task, updates it with updateTask, and then verifies the changes are persisted\n6. **Comparison Test**: Compare the results of updating a single task with updateTask versus using the original update command on the same task to ensure consistent quality\n7. **Performance Test**: Measure execution time compared to the full update command to verify efficiency gains\n8. **CLI Help Test**: Verify the command appears correctly in help documentation with appropriate descriptions\n\nCreate unit tests for the core functionality and integration tests for the complete workflow. Document any edge cases discovered during testing.",
      "subtasks": [
        {
          "id": 1,
          "title": "Create updateTaskById function in task-manager.js",
          "description": "Implement a new function in task-manager.js that focuses on updating a single task by ID using AI-driven refinement while preserving completed subtasks.",
          "dependencies": [],
          "details": "Implementation steps:\n1. Create a new `updateTaskById` function in task-manager.js that accepts parameters: taskId, options object (containing research flag, formatting options, etc.)\n2. Implement logic to find a specific task by ID in the tasks array\n3. Add appropriate error handling for cases where the task ID doesn't exist (throw a custom error)\n4. Reuse existing AI prompt templates but modify them to focus on refining a single task\n5. Implement logic to preserve completion status of subtasks that were previously marked as complete\n6. Add support for updating task title, description, and details separately based on options\n7. Optimize the implementation to only process the single task rather than scanning through all tasks\n8. Return the updated task and appropriate success/failure messages\n\nTesting approach:\n- Unit test the function with various scenarios including:\n  - Valid task ID with different update options\n  - Non-existent task ID\n  - Task with completed subtasks to verify preservation\n  - Different combinations of update options",
          "status": "done",
          "parentTaskId": 34
        },
        {
          "id": 2,
          "title": "Implement updateTask command in commands.js",
          "description": "Create a new command called 'updateTask' in commands.js that leverages the updateTaskById function to update a specific task by ID.",
          "dependencies": [
            1
          ],
          "details": "Implementation steps:\n1. Create a new command object for 'updateTask' in commands.js following the Command pattern\n2. Define command parameters including a required taskId parameter\n3. Support all options from the existing update command:\n   - Research flag for Perplexity integration\n   - Formatting and refinement options\n   - Task context options\n4. Implement the command handler function that calls the updateTaskById function from task-manager.js\n5. Add appropriate error handling to catch and display user-friendly error messages\n6. Ensure the command follows the same pattern as other commands in the codebase\n7. Implement proper validation of input parameters\n8. Format and return appropriate success/failure messages to the user\n\nTesting approach:\n- Unit test the command handler with various input combinations\n- Test error handling scenarios\n- Verify command options are correctly passed to the updateTaskById function",
          "status": "done",
          "parentTaskId": 34
        },
        {
          "id": 3,
          "title": "Add comprehensive error handling and validation",
          "description": "Implement robust error handling and validation for the updateTask command to ensure proper user feedback and system stability.",
          "dependencies": [
            1,
            2
          ],
          "details": "Implementation steps:\n1. Create custom error types for different failure scenarios (TaskNotFoundError, ValidationError, etc.)\n2. Implement input validation for the taskId parameter and all options\n3. Add proper error handling for AI service failures with appropriate fallback mechanisms\n4. Implement concurrency handling to prevent conflicts when multiple updates occur simultaneously\n5. Add comprehensive logging for debugging and auditing purposes\n6. Ensure all error messages are user-friendly and actionable\n7. Implement proper HTTP status codes for API responses if applicable\n8. Add validation to ensure the task exists before attempting updates\n\nTesting approach:\n- Test various error scenarios including invalid inputs, non-existent tasks, and API failures\n- Verify error messages are clear and helpful\n- Test concurrency scenarios with multiple simultaneous updates\n- Verify logging captures appropriate information for troubleshooting",
          "status": "done",
          "parentTaskId": 34
        },
        {
          "id": 4,
          "title": "Write comprehensive tests for updateTask command",
          "description": "Create a comprehensive test suite for the updateTask command to ensure it works correctly in all scenarios and maintains backward compatibility.",
          "dependencies": [
            1,
            2,
            3
          ],
          "details": "Implementation steps:\n1. Create unit tests for the updateTaskById function in task-manager.js\n   - Test finding and updating tasks with various IDs\n   - Test preservation of completed subtasks\n   - Test different update options combinations\n   - Test error handling for non-existent tasks\n2. Create unit tests for the updateTask command in commands.js\n   - Test command parameter parsing\n   - Test option handling\n   - Test error scenarios and messages\n3. Create integration tests that verify the end-to-end flow\n   - Test the command with actual AI service integration\n   - Test with mock AI responses for predictable testing\n4. Implement test fixtures and mocks for consistent testing\n5. Add performance tests to ensure the command is efficient\n6. Test edge cases such as empty tasks, tasks with many subtasks, etc.\n\nTesting approach:\n- Use Jest or similar testing framework\n- Implement mocks for external dependencies like AI services\n- Create test fixtures for consistent test data\n- Use snapshot testing for command output verification",
          "status": "done",
          "parentTaskId": 34
        },
        {
          "id": 5,
          "title": "Update CLI documentation and help text",
          "description": "Update the CLI help documentation to include the new updateTask command and ensure users understand its purpose and options.",
          "dependencies": [
            2
          ],
          "details": "Implementation steps:\n1. Add comprehensive help text for the updateTask command including:\n   - Command description\n   - Required and optional parameters\n   - Examples of usage\n   - Description of all supported options\n2. Update the main CLI help documentation to include the new command\n3. Add the command to any relevant command groups or categories\n4. Create usage examples that demonstrate common scenarios\n5. Update README.md and other documentation files to include information about the new command\n6. Add inline code comments explaining the implementation details\n7. Update any API documentation if applicable\n8. Create or update user guides with the new functionality\n\nTesting approach:\n- Verify help text is displayed correctly when running `--help`\n- Review documentation for clarity and completeness\n- Have team members review the documentation for usability\n- Test examples to ensure they work as documented",
          "status": "done",
          "parentTaskId": 34
        }
      ]
    },
    {
      "id": 35,
      "title": "Integrate Grok3 API for Research Capabilities",
      "description": "Replace the current Perplexity API integration with Grok3 API for all research-related functionalities while maintaining existing feature parity.",
      "status": "cancelled",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves migrating from Perplexity to Grok3 API for research capabilities throughout the application. Implementation steps include:\n\n1. Create a new API client module for Grok3 in `src/api/grok3.ts` that handles authentication, request formatting, and response parsing\n2. Update the research service layer to use the new Grok3 client instead of Perplexity\n3. Modify the request payload structure to match Grok3's expected format (parameters like temperature, max_tokens, etc.)\n4. Update response handling to properly parse and extract Grok3's response format\n5. Implement proper error handling for Grok3-specific error codes and messages\n6. Update environment variables and configuration files to include Grok3 API keys and endpoints\n7. Ensure rate limiting and quota management are properly implemented according to Grok3's specifications\n8. Update any UI components that display research provider information to show Grok3 instead of Perplexity\n9. Maintain backward compatibility for any stored research results from Perplexity\n10. Document the new API integration in the developer documentation\n\nGrok3 API has different parameter requirements and response formats compared to Perplexity, so careful attention must be paid to these differences during implementation.",
      "testStrategy": "Testing should verify that the Grok3 API integration works correctly and maintains feature parity with the previous Perplexity implementation:\n\n1. Unit tests:\n   - Test the Grok3 API client with mocked responses\n   - Verify proper error handling for various error scenarios (rate limits, authentication failures, etc.)\n   - Test the transformation of application requests to Grok3-compatible format\n\n2. Integration tests:\n   - Perform actual API calls to Grok3 with test credentials\n   - Verify that research results are correctly parsed and returned\n   - Test with various types of research queries to ensure broad compatibility\n\n3. End-to-end tests:\n   - Test the complete research flow from UI input to displayed results\n   - Verify that all existing research features work with the new API\n\n4. Performance tests:\n   - Compare response times between Perplexity and Grok3\n   - Ensure the application handles any differences in response time appropriately\n\n5. Regression tests:\n   - Verify that existing features dependent on research capabilities continue to work\n   - Test that stored research results from Perplexity are still accessible and displayed correctly\n\nCreate a test environment with both APIs available to compare results and ensure quality before fully replacing Perplexity with Grok3."
    },
    {
      "id": 36,
      "title": "Add Ollama Support for AI Services as Claude Alternative",
      "description": "Implement Ollama integration as an alternative to Claude for all main AI services, allowing users to run local language models instead of relying on cloud-based Claude API.",
      "status": "deferred",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves creating a comprehensive Ollama integration that can replace Claude across all main AI services in the application. Implementation should include:\n\n1. Create an OllamaService class that implements the same interface as the ClaudeService to ensure compatibility\n2. Add configuration options to specify Ollama endpoint URL (default: http://localhost:11434)\n3. Implement model selection functionality to allow users to choose which Ollama model to use (e.g., llama3, mistral, etc.)\n4. Handle prompt formatting specific to Ollama models, ensuring proper system/user message separation\n5. Implement proper error handling for cases where Ollama server is unavailable or returns errors\n6. Add fallback mechanism to Claude when Ollama fails or isn't configured\n7. Update the AI service factory to conditionally create either Claude or Ollama service based on configuration\n8. Ensure token counting and rate limiting are appropriately handled for Ollama models\n9. Add documentation for users explaining how to set up and use Ollama with the application\n10. Optimize prompt templates specifically for Ollama models if needed\n\nThe implementation should be toggled through a configuration option (useOllama: true/false) and should maintain all existing functionality currently provided by Claude.",
      "testStrategy": "Testing should verify that Ollama integration works correctly as a drop-in replacement for Claude:\n\n1. Unit tests:\n   - Test OllamaService class methods in isolation with mocked responses\n   - Verify proper error handling when Ollama server is unavailable\n   - Test fallback mechanism to Claude when configured\n\n2. Integration tests:\n   - Test with actual Ollama server running locally with at least two different models\n   - Verify all AI service functions work correctly with Ollama\n   - Compare outputs between Claude and Ollama for quality assessment\n\n3. Configuration tests:\n   - Verify toggling between Claude and Ollama works as expected\n   - Test with various model configurations\n\n4. Performance tests:\n   - Measure and compare response times between Claude and Ollama\n   - Test with different load scenarios\n\n5. Manual testing:\n   - Verify all main AI features work correctly with Ollama\n   - Test edge cases like very long inputs or specialized tasks\n\nCreate a test document comparing output quality between Claude and various Ollama models to help users understand the tradeoffs."
    },
    {
      "id": 37,
      "title": "Add Gemini Support for Main AI Services as Claude Alternative",
      "description": "Implement Google's Gemini API integration as an alternative to Claude for all main AI services, allowing users to switch between different LLM providers.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves integrating Google's Gemini API across all main AI services that currently use Claude:\n\n1. Create a new GeminiService class that implements the same interface as the existing ClaudeService\n2. Implement authentication and API key management for Gemini API\n3. Map our internal prompt formats to Gemini's expected input format\n4. Handle Gemini-specific parameters (temperature, top_p, etc.) and response parsing\n5. Update the AI service factory/provider to support selecting Gemini as an alternative\n6. Add configuration options in settings to allow users to select Gemini as their preferred provider\n7. Implement proper error handling for Gemini-specific API errors\n8. Ensure streaming responses are properly supported if Gemini offers this capability\n9. Update documentation to reflect the new Gemini option\n10. Consider implementing model selection if Gemini offers multiple models (e.g., Gemini Pro, Gemini Ultra)\n11. Ensure all existing AI capabilities (summarization, code generation, etc.) maintain feature parity when using Gemini\n\nThe implementation should follow the same pattern as the recent Ollama integration (Task #36) to maintain consistency in how alternative AI providers are supported.",
      "testStrategy": "Testing should verify Gemini integration works correctly across all AI services:\n\n1. Unit tests:\n   - Test GeminiService class methods with mocked API responses\n   - Verify proper error handling for common API errors\n   - Test configuration and model selection functionality\n\n2. Integration tests:\n   - Verify authentication and API connection with valid credentials\n   - Test each AI service with Gemini to ensure proper functionality\n   - Compare outputs between Claude and Gemini for the same inputs to verify quality\n\n3. End-to-end tests:\n   - Test the complete user flow of switching to Gemini and using various AI features\n   - Verify streaming responses work correctly if supported\n\n4. Performance tests:\n   - Measure and compare response times between Claude and Gemini\n   - Test with various input lengths to verify handling of context limits\n\n5. Manual testing:\n   - Verify the quality of Gemini responses across different use cases\n   - Test edge cases like very long inputs or specialized domain knowledge\n\nAll tests should pass with Gemini selected as the provider, and the user experience should be consistent regardless of which provider is selected."
    },
    {
      "id": 38,
      "title": "Implement Version Check System with Upgrade Notifications",
      "description": "Create a system that checks for newer package versions and displays upgrade notifications when users run any command, informing them to update to the latest version.",
      "status": "done",
      "dependencies": [],
      "priority": "high",
      "details": "Implement a version check mechanism that runs automatically with every command execution:\n\n1. Create a new module (e.g., `versionChecker.js`) that will:\n   - Fetch the latest version from npm registry using the npm registry API (https://registry.npmjs.org/task-master-ai/latest)\n   - Compare it with the current installed version (from package.json)\n   - Store the last check timestamp to avoid excessive API calls (check once per day)\n   - Cache the result to minimize network requests\n\n2. The notification should:\n   - Use colored text (e.g., yellow background with black text) to be noticeable\n   - Include the current version and latest version\n   - Show the exact upgrade command: 'npm i task-master-ai@latest'\n   - Be displayed at the beginning or end of command output, not interrupting the main content\n   - Include a small separator line to distinguish it from command output\n\n3. Implementation considerations:\n   - Handle network failures gracefully (don't block command execution if version check fails)\n   - Add a configuration option to disable update checks if needed\n   - Ensure the check is lightweight and doesn't significantly impact command performance\n   - Consider using a package like 'semver' for proper version comparison\n   - Implement a cooldown period (e.g., only check once per day) to avoid excessive API calls\n\n4. The version check should be integrated into the main command execution flow so it runs for all commands automatically.",
      "testStrategy": "1. Manual testing:\n   - Install an older version of the package\n   - Run various commands and verify the update notification appears\n   - Update to the latest version and confirm the notification no longer appears\n   - Test with network disconnected to ensure graceful handling of failures\n\n2. Unit tests:\n   - Mock the npm registry response to test different scenarios:\n     - When a newer version exists\n     - When using the latest version\n     - When the registry is unavailable\n   - Test the version comparison logic with various version strings\n   - Test the cooldown/caching mechanism works correctly\n\n3. Integration tests:\n   - Create a test that runs a command and verifies the notification appears in the expected format\n   - Test that the notification appears for all commands\n   - Verify the notification doesn't interfere with normal command output\n\n4. Edge cases to test:\n   - Pre-release versions (alpha/beta)\n   - Very old versions\n   - When package.json is missing or malformed\n   - When npm registry returns unexpected data"
    },
    {
      "id": 39,
      "title": "Update Project Licensing to Dual License Structure",
      "description": "Replace the current MIT license with a dual license structure that protects commercial rights for project owners while allowing non-commercial use under an open source license.",
      "status": "done",
      "dependencies": [],
      "priority": "high",
      "details": "This task requires implementing a comprehensive licensing update across the project:\n\n1. Remove all instances of the MIT license from the codebase, including any MIT license files, headers in source files, and references in documentation.\n\n2. Create a dual license structure with:\n   - Business Source License (BSL) 1.1 or similar for commercial use, explicitly stating that commercial rights are exclusively reserved for Ralph & Eyal\n   - Apache 2.0 for non-commercial use, allowing the community to use, modify, and distribute the code for non-commercial purposes\n\n3. Update the license field in package.json to reflect the dual license structure (e.g., \"BSL 1.1 / Apache 2.0\")\n\n4. Add a clear, concise explanation of the licensing terms in the README.md, including:\n   - A summary of what users can and cannot do with the code\n   - Who holds commercial rights\n   - How to obtain commercial use permission if needed\n   - Links to the full license texts\n\n5. Create a detailed LICENSE.md file that includes:\n   - Full text of both licenses\n   - Clear delineation between commercial and non-commercial use\n   - Specific definitions of what constitutes commercial use\n   - Any additional terms or clarifications specific to this project\n\n6. Create a CONTRIBUTING.md file that explicitly states:\n   - Contributors must agree that their contributions will be subject to the project's dual licensing\n   - Commercial rights for all contributions are assigned to Ralph & Eyal\n   - Guidelines for acceptable contributions\n\n7. Ensure all source code files include appropriate license headers that reference the dual license structure.",
      "testStrategy": "To verify correct implementation, perform the following checks:\n\n1. File verification:\n   - Confirm the MIT license file has been removed\n   - Verify LICENSE.md exists and contains both BSL and Apache 2.0 license texts\n   - Confirm README.md includes the license section with clear explanation\n   - Verify CONTRIBUTING.md exists with proper contributor guidelines\n   - Check package.json for updated license field\n\n2. Content verification:\n   - Review LICENSE.md to ensure it properly describes the dual license structure with clear terms\n   - Verify README.md license section is concise yet complete\n   - Check that commercial rights are explicitly reserved for Ralph & Eyal in all relevant documents\n   - Ensure CONTRIBUTING.md clearly explains the licensing implications for contributors\n\n3. Legal review:\n   - Have a team member not involved in the implementation review all license documents\n   - Verify that the chosen BSL terms properly protect commercial interests\n   - Confirm the Apache 2.0 implementation is correct and compatible with the BSL portions\n\n4. Source code check:\n   - Sample at least 10 source files to ensure they have updated license headers\n   - Verify no MIT license references remain in any source files\n\n5. Documentation check:\n   - Ensure any documentation that mentioned licensing has been updated to reflect the new structure",
      "subtasks": [
        {
          "id": 1,
          "title": "Remove MIT License and Create Dual License Files",
          "description": "Remove all MIT license references from the codebase and create the new license files for the dual license structure.",
          "dependencies": [],
          "details": "Implementation steps:\n1. Scan the entire codebase to identify all instances of MIT license references (license files, headers in source files, documentation mentions).\n2. Remove the MIT license file and all direct references to it.\n3. Create a LICENSE.md file containing:\n   - Full text of Business Source License (BSL) 1.1 with explicit commercial rights reservation for Ralph & Eyal\n   - Full text of Apache 2.0 license for non-commercial use\n   - Clear definitions of what constitutes commercial vs. non-commercial use\n   - Specific terms for obtaining commercial use permission\n4. Create a CONTRIBUTING.md file that explicitly states the contribution terms:\n   - Contributors must agree to the dual licensing structure\n   - Commercial rights for all contributions are assigned to Ralph & Eyal\n   - Guidelines for acceptable contributions\n\nTesting approach:\n- Verify all MIT license references have been removed using a grep or similar search tool\n- Have legal review of the LICENSE.md and CONTRIBUTING.md files to ensure they properly protect commercial rights\n- Validate that the license files are properly formatted and readable",
          "status": "done",
          "parentTaskId": 39
        },
        {
          "id": 2,
          "title": "Update Source Code License Headers and Package Metadata",
          "description": "Add appropriate dual license headers to all source code files and update package metadata to reflect the new licensing structure.",
          "dependencies": [
            1
          ],
          "details": "Implementation steps:\n1. Create a template for the new license header that references the dual license structure (BSL 1.1 / Apache 2.0).\n2. Systematically update all source code files to include the new license header, replacing any existing MIT headers.\n3. Update the license field in package.json to \"BSL 1.1 / Apache 2.0\".\n4. Update any other metadata files (composer.json, setup.py, etc.) that contain license information.\n5. Verify that any build scripts or tools that reference licensing information are updated.\n\nTesting approach:\n- Write a script to verify that all source files contain the new license header\n- Validate package.json and other metadata files have the correct license field\n- Ensure any build processes that depend on license information still function correctly\n- Run a sample build to confirm license information is properly included in any generated artifacts",
          "status": "done",
          "parentTaskId": 39
        },
        {
          "id": 3,
          "title": "Update Documentation and Create License Explanation",
          "description": "Update project documentation to clearly explain the dual license structure and create comprehensive licensing guidance.",
          "dependencies": [
            1,
            2
          ],
          "details": "Implementation steps:\n1. Update the README.md with a clear, concise explanation of the licensing terms:\n   - Summary of what users can and cannot do with the code\n   - Who holds commercial rights (Ralph & Eyal)\n   - How to obtain commercial use permission\n   - Links to the full license texts\n2. Create a dedicated LICENSING.md or similar document with detailed explanations of:\n   - The rationale behind the dual licensing approach\n   - Detailed examples of what constitutes commercial vs. non-commercial use\n   - FAQs addressing common licensing questions\n3. Update any other documentation references to licensing throughout the project.\n4. Create visual aids (if appropriate) to help users understand the licensing structure.\n5. Ensure all documentation links to licensing information are updated.\n\nTesting approach:\n- Have non-technical stakeholders review the documentation for clarity and understanding\n- Verify all links to license files work correctly\n- Ensure the explanation is comprehensive but concise enough for users to understand quickly\n- Check that the documentation correctly addresses the most common use cases and questions",
          "status": "done",
          "parentTaskId": 39
        }
      ]
    },
    {
      "id": 40,
      "title": "Implement 'plan' Command for Task Implementation Planning",
      "description": "Create a new 'plan' command that appends a structured implementation plan to tasks or subtasks, generating step-by-step instructions for execution based on the task content.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Implement a new 'plan' command that will append a structured implementation plan to existing tasks or subtasks. The implementation should:\n\n1. Accept an '--id' parameter that can reference either a task or subtask ID\n2. Determine whether the ID refers to a task or subtask and retrieve the appropriate content from tasks.json and/or individual task files\n3. Generate a step-by-step implementation plan using AI (Claude by default)\n4. Support a '--research' flag to use Perplexity instead of Claude when needed\n5. Format the generated plan within XML tags like `<implementation_plan as of timestamp>...</implementation_plan>`\n6. Append this plan to the implementation details section of the task/subtask\n7. Display a confirmation card indicating the implementation plan was successfully created\n\nThe implementation plan should be detailed and actionable, containing specific steps such as searching for files, creating new files, modifying existing files, etc. The goal is to frontload planning work into the task/subtask so execution can begin immediately.\n\nReference the existing 'update-subtask' command implementation as a starting point, as it uses a similar approach for appending content to tasks. Ensure proper error handling for cases where the specified ID doesn't exist or when API calls fail.",
      "testStrategy": "Testing should verify:\n\n1. Command correctly identifies and retrieves content for both task and subtask IDs\n2. Implementation plans are properly generated and formatted with XML tags and timestamps\n3. Plans are correctly appended to the implementation details section without overwriting existing content\n4. The '--research' flag successfully switches the backend from Claude to Perplexity\n5. Appropriate error messages are displayed for invalid IDs or API failures\n6. Confirmation card is displayed after successful plan creation\n\nTest cases should include:\n- Running 'plan --id 123' on an existing task\n- Running 'plan --id 123.1' on an existing subtask\n- Running 'plan --id 123 --research' to test the Perplexity integration\n- Running 'plan --id 999' with a non-existent ID to verify error handling\n- Running the command on tasks with existing implementation plans to ensure proper appending\n\nManually review the quality of generated plans to ensure they provide actionable, step-by-step guidance that accurately reflects the task requirements.",
      "subtasks": [
        {
          "id": 1,
          "title": "Retrieve Task Content",
          "description": "Fetch the content of the specified task from the task management system. This includes the task title, description, and any associated details.",
          "dependencies": [],
          "details": "Implement a function to retrieve task details based on a task ID. Handle cases where the task does not exist.",
          "status": "in-progress"
        },
        {
          "id": 2,
          "title": "Generate Implementation Plan with AI",
          "description": "Use an AI model (Claude or Perplexity) to generate an implementation plan based on the retrieved task content. The plan should outline the steps required to complete the task.",
          "dependencies": [
            1
          ],
          "details": "Implement logic to switch between Claude and Perplexity APIs. Handle API authentication and rate limiting. Prompt the AI model with the task content and request a detailed implementation plan.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Format Plan in XML",
          "description": "Format the generated implementation plan within XML tags. Each step in the plan should be represented as an XML element with appropriate attributes.",
          "dependencies": [
            2,
            "40.2"
          ],
          "details": "Define the XML schema for the implementation plan. Implement a function to convert the AI-generated plan into the defined XML format. Ensure proper XML syntax and validation.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Error Handling and Output",
          "description": "Implement error handling for all steps, including API failures and XML formatting errors. Output the formatted XML plan to the console or a file.",
          "dependencies": [
            3
          ],
          "details": "Add try-except blocks to handle potential exceptions. Log errors for debugging. Provide informative error messages to the user. Output the XML plan in a user-friendly format.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 41,
      "title": "Implement Visual Task Dependency Graph in Terminal",
      "description": "Create a feature that renders task dependencies as a visual graph using ASCII/Unicode characters in the terminal, with color-coded nodes representing tasks and connecting lines showing dependency relationships.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "This implementation should include:\n\n1. Create a new command `graph` or `visualize` that displays the dependency graph.\n\n2. Design an ASCII/Unicode-based graph rendering system that:\n   - Represents each task as a node with its ID and abbreviated title\n   - Shows dependencies as directional lines between nodes (→, ↑, ↓, etc.)\n   - Uses color coding for different task statuses (e.g., green for completed, yellow for in-progress, red for blocked)\n   - Handles complex dependency chains with proper spacing and alignment\n\n3. Implement layout algorithms to:\n   - Minimize crossing lines for better readability\n   - Properly space nodes to avoid overlapping\n   - Support both vertical and horizontal graph orientations (as a configurable option)\n\n4. Add detection and highlighting of circular dependencies with a distinct color/pattern\n\n5. Include a legend explaining the color coding and symbols used\n\n6. Ensure the graph is responsive to terminal width, with options to:\n   - Automatically scale to fit the current terminal size\n   - Allow zooming in/out of specific sections for large graphs\n   - Support pagination or scrolling for very large dependency networks\n\n7. Add options to filter the graph by:\n   - Specific task IDs or ranges\n   - Task status\n   - Dependency depth (e.g., show only direct dependencies or N levels deep)\n\n8. Ensure accessibility by using distinct patterns in addition to colors for users with color vision deficiencies\n\n9. Optimize performance for projects with many tasks and complex dependency relationships",
      "testStrategy": "1. Unit Tests:\n   - Test the graph generation algorithm with various dependency structures\n   - Verify correct node placement and connection rendering\n   - Test circular dependency detection\n   - Verify color coding matches task statuses\n\n2. Integration Tests:\n   - Test the command with projects of varying sizes (small, medium, large)\n   - Verify correct handling of different terminal sizes\n   - Test all filtering options\n\n3. Visual Verification:\n   - Create test cases with predefined dependency structures and verify the visual output matches expected patterns\n   - Test with terminals of different sizes, including very narrow terminals\n   - Verify readability of complex graphs\n\n4. Edge Cases:\n   - Test with no dependencies (single nodes only)\n   - Test with circular dependencies\n   - Test with very deep dependency chains\n   - Test with wide dependency networks (many parallel tasks)\n   - Test with the maximum supported number of tasks\n\n5. Usability Testing:\n   - Have team members use the feature and provide feedback on readability and usefulness\n   - Test in different terminal emulators to ensure compatibility\n   - Verify the feature works in terminals with limited color support\n\n6. Performance Testing:\n   - Measure rendering time for large projects\n   - Ensure reasonable performance with 100+ interconnected tasks",
      "subtasks": [
        {
          "id": 1,
          "title": "CLI Command Setup",
          "description": "Design and implement the command-line interface for the dependency graph tool, including argument parsing and help documentation.",
          "dependencies": [],
          "details": "Define commands for input file specification, output options, filtering, and other user-configurable parameters.\n<info added on 2025-05-23T21:02:26.442Z>\nImplement a new 'diagram' command (with 'graph' alias) in commands.js following the Commander.js pattern. The command should:\n\n1. Import diagram-generator.js module functions for generating visual representations\n2. Support multiple visualization types with --type option:\n   - dependencies: show task dependency relationships\n   - subtasks: show task/subtask hierarchy\n   - flow: show task workflow\n   - gantt: show timeline visualization\n\n3. Include the following options:\n   - --task <id>: Filter diagram to show only specified task and its relationships\n   - --mermaid: Output raw Mermaid markdown for external rendering\n   - --visual: Render diagram directly in terminal\n   - --format <format>: Output format (text, svg, png)\n\n4. Implement proper error handling and validation:\n   - Validate task IDs using existing taskExists() function\n   - Handle invalid option combinations\n   - Provide descriptive error messages\n\n5. Integrate with UI components:\n   - Use ui.js display functions for consistent output formatting\n   - Apply chalk coloring for terminal output\n   - Use boxen formatting consistent with other commands\n\n6. Handle file operations:\n   - Resolve file paths using findProjectRoot() pattern\n   - Support saving diagrams to files when appropriate\n\n7. Include comprehensive help text following the established pattern in other commands\n</info added on 2025-05-23T21:02:26.442Z>",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Graph Layout Algorithms",
          "description": "Develop or integrate algorithms to compute optimal node and edge placement for clear and readable graph layouts in a terminal environment.",
          "dependencies": [
            1
          ],
          "details": "Consider topological sorting, hierarchical, and force-directed layouts suitable for ASCII/Unicode rendering.\n<info added on 2025-05-23T21:02:49.434Z>\nCreate a new diagram-generator.js module in the scripts/modules/ directory following Task Master's module architecture pattern. The module should include:\n\n1. Core functions for generating Mermaid diagrams:\n   - generateDependencyGraph(tasks, options) - creates flowchart showing task dependencies\n   - generateSubtaskDiagram(task, options) - creates hierarchy diagram for subtasks\n   - generateProjectFlow(tasks, options) - creates overall project workflow\n   - generateGanttChart(tasks, options) - creates timeline visualization\n\n2. Integration with existing Task Master data structures:\n   - Use the same task object format from task-manager.js\n   - Leverage dependency analysis from dependency-manager.js\n   - Support complexity scores from analyze-complexity functionality\n   - Handle both main tasks and subtasks with proper ID notation (parentId.subtaskId)\n\n3. Layout algorithm considerations for Mermaid:\n   - Topological sorting for dependency flows\n   - Hierarchical layouts for subtask trees\n   - Circular dependency detection and highlighting\n   - Terminal width-aware formatting for ASCII fallback\n\n4. Export functions following the existing module pattern at the bottom of the file\n</info added on 2025-05-23T21:02:49.434Z>",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "ASCII/Unicode Rendering Engine",
          "description": "Implement rendering logic to display the dependency graph using ASCII and Unicode characters in the terminal.",
          "dependencies": [
            2
          ],
          "details": "Support for various node and edge styles, and ensure compatibility with different terminal types.\n<info added on 2025-05-23T21:03:10.001Z>\nExtend ui.js with diagram display functions that integrate with Task Master's existing UI patterns:\n\n1. Implement core diagram display functions:\n   - displayTaskDiagram(tasksPath, diagramType, options) as the main entry point\n   - displayMermaidCode(mermaidCode, title) for formatted code output with boxen\n   - displayDiagramLegend() to explain symbols and colors\n\n2. Ensure UI consistency by:\n   - Using established chalk color schemes (blue/green/yellow/red)\n   - Applying boxen for consistent component formatting\n   - Following existing display function patterns (displayTaskById, displayComplexityReport)\n   - Utilizing cli-table3 for any diagram metadata tables\n\n3. Address terminal rendering challenges:\n   - Implement ASCII/Unicode fallback when Mermaid rendering isn't available\n   - Respect terminal width constraints using process.stdout.columns\n   - Integrate with loading indicators via startLoadingIndicator/stopLoadingIndicator\n\n4. Update task file generation to include Mermaid diagram sections in individual task files\n\n5. Support both CLI and MCP output formats through the outputFormat parameter\n</info added on 2025-05-23T21:03:10.001Z>",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Color Coding Support",
          "description": "Add color coding to nodes and edges to visually distinguish types, statuses, or other attributes in the graph.",
          "dependencies": [
            3
          ],
          "details": "Use ANSI escape codes for color; provide options for colorblind-friendly palettes.\n<info added on 2025-05-23T21:03:35.762Z>\nIntegrate color coding with Task Master's existing status system:\n\n1. Extend getStatusWithColor() in ui.js to support diagram contexts:\n   - Add 'diagram' parameter to determine rendering context\n   - Modify color intensity for better visibility in graph elements\n\n2. Implement Task Master's established color scheme using ANSI codes:\n   - Green (\\x1b[32m) for 'done'/'completed' tasks\n   - Yellow (\\x1b[33m) for 'pending' tasks\n   - Orange (\\x1b[38;5;208m) for 'in-progress' tasks\n   - Red (\\x1b[31m) for 'blocked' tasks\n   - Gray (\\x1b[90m) for 'deferred'/'cancelled' tasks\n   - Magenta (\\x1b[35m) for 'review' tasks\n\n3. Create diagram-specific color functions:\n   - getDependencyLineColor(fromTaskStatus, toTaskStatus) - color dependency arrows based on relationship status\n   - getNodeBorderColor(task) - style node borders using priority/complexity indicators\n   - getSubtaskGroupColor(parentTask) - visually group related subtasks\n\n4. Integrate complexity visualization:\n   - Use getComplexityWithColor() for node background or border thickness\n   - Map complexity scores to visual weight in the graph\n\n5. Ensure accessibility:\n   - Add text-based indicators (symbols like ✓, ⚠, ⏳) alongside colors\n   - Implement colorblind-friendly palettes as user-selectable option\n   - Include shape variations for different statuses\n\n6. Follow existing ANSI patterns:\n   - Maintain consistency with terminal UI color usage\n   - Reuse color constants from the codebase\n\n7. Support graceful degradation:\n   - Check terminal capabilities using existing detection\n   - Provide monochrome fallbacks with distinctive patterns\n   - Use bold/underline as alternatives when colors unavailable\n</info added on 2025-05-23T21:03:35.762Z>",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Circular Dependency Detection",
          "description": "Implement algorithms to detect and highlight circular dependencies within the graph.",
          "dependencies": [
            2
          ],
          "details": "Clearly mark cycles in the rendered output and provide warnings or errors as appropriate.\n<info added on 2025-05-23T21:04:20.125Z>\nIntegrate with Task Master's existing circular dependency detection:\n\n1. Import the dependency detection logic from dependency-manager.js module\n2. Utilize the findCycles function from utils.js or dependency-manager.js\n3. Extend validateDependenciesCommand functionality to highlight cycles in diagrams\n\nVisual representation in Mermaid diagrams:\n- Apply red/bold styling to nodes involved in dependency cycles\n- Add warning annotations to cyclic edges\n- Implement cycle path highlighting with distinctive line styles\n\nIntegration with validation workflow:\n- Execute dependency validation before diagram generation\n- Display cycle warnings consistent with existing CLI error messaging\n- Utilize chalk.red and boxen for error highlighting following established patterns\n\nAdd diagram legend entries that explain cycle notation and warnings\n\nEnsure detection of cycles in both:\n- Main task dependencies\n- Subtask dependencies within parent tasks\n\nFollow Task Master's error handling patterns for graceful cycle reporting and user notification\n</info added on 2025-05-23T21:04:20.125Z>",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Filtering and Search Functionality",
          "description": "Enable users to filter nodes and edges by criteria such as name, type, or dependency depth.",
          "dependencies": [
            1,
            2
          ],
          "details": "Support command-line flags for filtering and interactive search if feasible.\n<info added on 2025-05-23T21:04:57.811Z>\nImplement MCP tool integration for task dependency visualization:\n\n1. Create task_diagram.js in mcp-server/src/tools/ following existing tool patterns\n2. Implement taskDiagramDirect.js in mcp-server/src/core/direct-functions/\n3. Use Zod schema for parameter validation:\n   - diagramType (dependencies, subtasks, flow, gantt)\n   - taskId (optional string)\n   - format (mermaid, text, json)\n   - includeComplexity (boolean)\n\n4. Structure response data with:\n   - mermaidCode for client-side rendering\n   - metadata (nodeCount, edgeCount, cycleWarnings)\n   - support for both task-specific and project-wide diagrams\n\n5. Integrate with session management and project root handling\n6. Implement error handling using handleApiResult pattern\n7. Register the tool in tools/index.js\n\nMaintain compatibility with existing command-line flags for filtering and interactive search.\n</info added on 2025-05-23T21:04:57.811Z>",
          "status": "pending"
        },
        {
          "id": 7,
          "title": "Accessibility Features",
          "description": "Ensure the tool is accessible, including support for screen readers, high-contrast modes, and keyboard navigation.",
          "dependencies": [
            3,
            4
          ],
          "details": "Provide alternative text output and ensure color is not the sole means of conveying information.\n<info added on 2025-05-23T21:05:54.584Z>\n# Accessibility and Export Integration\n\n## Accessibility Features\n- Provide alternative text output for visual elements\n- Ensure color is not the sole means of conveying information\n- Support keyboard navigation through the dependency graph\n- Add screen reader compatible node descriptions\n\n## Export Integration\n- Extend generateTaskFiles function in task-manager.js to include Mermaid diagram sections\n- Add Mermaid code blocks to task markdown files under ## Diagrams header\n- Follow existing task file generation patterns and markdown structure\n- Support multiple diagram types per task file:\n  * Task dependencies (prerequisite relationships)\n  * Subtask hierarchy visualization\n  * Task flow context in project workflow\n- Integrate with existing fs module file writing operations\n- Add diagram export options to the generate command in commands.js\n- Support SVG and PNG export using Mermaid CLI when available\n- Implement error handling for diagram generation failures\n- Reference exported diagrams in task markdown with proper paths\n- Update CLI generate command with options like --include-diagrams\n</info added on 2025-05-23T21:05:54.584Z>",
          "status": "pending"
        },
        {
          "id": 8,
          "title": "Performance Optimization",
          "description": "Profile and optimize the tool for large graphs to ensure responsive rendering and low memory usage.",
          "dependencies": [
            2,
            3,
            4,
            5,
            6
          ],
          "details": "Implement lazy loading, efficient data structures, and parallel processing where appropriate.\n<info added on 2025-05-23T21:06:14.533Z>\n# Mermaid Library Integration and Terminal-Specific Handling\n\n## Package Dependencies\n- Add mermaid package as an optional dependency in package.json for generating raw Mermaid diagram code\n- Consider mermaid-cli for SVG/PNG conversion capabilities\n- Evaluate terminal-image or similar libraries for terminals with image support\n- Explore ascii-art-ansi or box-drawing character libraries for text-only terminals\n\n## Terminal Capability Detection\n- Leverage existing terminal detection from ui.js to assess rendering capabilities\n- Implement detection for:\n  - iTerm2 and other terminals with image protocol support\n  - Terminals with Unicode/extended character support\n  - Basic terminals requiring pure ASCII output\n\n## Rendering Strategy with Fallbacks\n1. Primary: Generate raw Mermaid code for user copy/paste\n2. Secondary: Render simplified ASCII tree/flow representation using box characters\n3. Tertiary: Present dependencies in tabular format for minimal terminals\n\n## Implementation Approach\n- Use dynamic imports for optional rendering libraries to maintain lightweight core\n- Implement graceful degradation when optional packages aren't available\n- Follow Task Master's philosophy of minimal dependencies\n- Ensure performance optimization through lazy loading where appropriate\n- Design modular rendering components that can be swapped based on terminal capabilities\n</info added on 2025-05-23T21:06:14.533Z>",
          "status": "pending"
        },
        {
          "id": 9,
          "title": "Documentation",
          "description": "Write comprehensive user and developer documentation covering installation, usage, configuration, and extension.",
          "dependencies": [
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8
          ],
          "details": "Include examples, troubleshooting, and contribution guidelines.",
          "status": "pending"
        },
        {
          "id": 10,
          "title": "Testing and Validation",
          "description": "Develop automated tests for all major features, including CLI parsing, layout correctness, rendering, color coding, filtering, and cycle detection.",
          "dependencies": [
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9
          ],
          "details": "Include unit, integration, and regression tests; validate accessibility and performance claims.\n<info added on 2025-05-23T21:08:36.329Z>\n# Documentation Tasks for Visual Task Dependency Graph\n\n## User Documentation\n1. Update README.md with diagram command documentation following existing command reference format\n2. Add examples to CLI command help text in commands.js matching patterns from other commands\n3. Create docs/diagrams.md with detailed usage guide including:\n   - Command examples for each diagram type\n   - Mermaid code samples and output\n   - Terminal compatibility notes\n   - Integration with task workflow examples\n   - Troubleshooting section for common diagram rendering issues\n   - Accessibility features and terminal fallback options\n\n## Developer Documentation\n1. Update MCP tool documentation to include the new task_diagram tool\n2. Add JSDoc comments to all new functions following existing code standards\n3. Create contributor documentation for extending diagram types\n4. Update API documentation for any new MCP interface endpoints\n\n## Integration Documentation\n1. Document integration with existing commands (analyze-complexity, generate, etc.)\n2. Provide examples showing how diagrams complement other Task Master features\n</info added on 2025-05-23T21:08:36.329Z>",
          "status": "pending"
        }
      ]
    },
    {
      "id": 42,
      "title": "Implement MCP-to-MCP Communication Protocol",
      "description": "Design and implement a communication protocol that allows Taskmaster to interact with external MCP (Model Context Protocol) tools and servers, enabling programmatic operations across these tools without requiring custom integration code. The system should dynamically connect to MCP servers chosen by the user for task storage and management (e.g., GitHub-MCP or Postgres-MCP). This eliminates the need for separate APIs or SDKs for each service. The goal is to create a standardized, agnostic system that facilitates seamless task execution and interaction with external systems. Additionally, the system should support two operational modes: **solo/local mode**, where tasks are managed locally using a `tasks.json` file, and **multiplayer/remote mode**, where tasks are managed via external MCP integrations. The core modules of Taskmaster should dynamically adapt their operations based on the selected mode, with multiplayer/remote mode leveraging MCP servers for all task management operations.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves creating a standardized way for Taskmaster to communicate with external MCP implementations and tools. The implementation should:\n\n1. Define a standard protocol for communication with MCP servers, including authentication, request/response formats, and error handling.\n2. Leverage the existing `fastmcp` server logic to enable interaction with external MCP tools programmatically, focusing on creating a modular and reusable system.\n3. Implement an adapter pattern that allows Taskmaster to connect to any MCP-compliant tool or server.\n4. Build a client module capable of discovering, connecting to, and exchanging data with external MCP tools, ensuring compatibility with various implementations.\n5. Provide a reference implementation for interacting with a specific MCP tool (e.g., GitHub-MCP or Postgres-MCP) to demonstrate the protocol's functionality.\n6. Ensure the protocol supports versioning to maintain compatibility as MCP tools evolve.\n7. Implement rate limiting and backoff strategies to prevent overwhelming external MCP tools.\n8. Create a configuration system that allows users to specify connection details for external MCP tools and servers.\n9. Add support for two operational modes:\n   - **Solo/Local Mode**: Tasks are managed locally using a `tasks.json` file.\n   - **Multiplayer/Remote Mode**: Tasks are managed via external MCP integrations (e.g., GitHub-MCP or Postgres-MCP). The system should dynamically switch between these modes based on user configuration.\n10. Update core modules to perform task operations on the appropriate system (local or remote) based on the selected mode, with remote mode relying entirely on MCP servers for task management.\n11. Document the protocol thoroughly to enable other developers to implement it in their MCP tools.\n\nThe implementation should prioritize asynchronous communication where appropriate and handle network failures gracefully. Security considerations, including encryption and robust authentication mechanisms, should be integral to the design.",
      "testStrategy": "Testing should verify both the protocol design and implementation:\n\n1. Unit tests for the adapter pattern, ensuring it correctly translates between Taskmaster's internal models and the MCP protocol.\n2. Integration tests with a mock MCP tool or server to validate the full request/response cycle.\n3. Specific tests for the reference implementation (e.g., GitHub-MCP or Postgres-MCP), including authentication flows.\n4. Error handling tests that simulate network failures, timeouts, and malformed responses.\n5. Performance tests to ensure the communication does not introduce significant latency.\n6. Security tests to verify that authentication and encryption mechanisms are functioning correctly.\n7. End-to-end tests demonstrating Taskmaster's ability to programmatically interact with external MCP tools and execute tasks.\n8. Compatibility tests with different versions of the protocol to ensure backward compatibility.\n9. Tests for mode switching:\n   - Validate that Taskmaster correctly operates in solo/local mode using the `tasks.json` file.\n   - Validate that Taskmaster correctly operates in multiplayer/remote mode with external MCP integrations (e.g., GitHub-MCP or Postgres-MCP).\n   - Ensure seamless switching between modes without data loss or corruption.\n10. A test harness should be created to simulate an MCP tool or server for testing purposes without relying on external dependencies. Test cases should be documented thoroughly to serve as examples for other implementations.",
      "subtasks": [
        {
          "id": "42-1",
          "title": "Define MCP-to-MCP communication protocol",
          "status": "pending"
        },
        {
          "id": "42-2",
          "title": "Implement adapter pattern for MCP integration",
          "status": "pending"
        },
        {
          "id": "42-3",
          "title": "Develop client module for MCP tool discovery and interaction",
          "status": "pending"
        },
        {
          "id": "42-4",
          "title": "Provide reference implementation for GitHub-MCP integration",
          "status": "pending"
        },
        {
          "id": "42-5",
          "title": "Add support for solo/local and multiplayer/remote modes",
          "status": "pending"
        },
        {
          "id": "42-6",
          "title": "Update core modules to support dynamic mode-based operations",
          "status": "pending"
        },
        {
          "id": "42-7",
          "title": "Document protocol and mode-switching functionality",
          "status": "pending"
        },
        {
          "id": "42-8",
          "title": "Update terminology to reflect MCP server-based communication",
          "status": "pending"
        }
      ]
    },
    {
      "id": 43,
      "title": "Add Research Flag to Add-Task Command",
      "description": "Implement a '--research' flag for the add-task command that enables users to automatically generate research-related subtasks when creating a new task.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "Modify the add-task command to accept a new optional flag '--research'. When this flag is provided, the system should automatically generate and attach a set of research-oriented subtasks to the newly created task. These subtasks should follow a standard research methodology structure:\n\n1. Background Investigation: Research existing solutions and approaches\n2. Requirements Analysis: Define specific requirements and constraints\n3. Technology/Tool Evaluation: Compare potential technologies or tools for implementation\n4. Proof of Concept: Create a minimal implementation to validate approach\n5. Documentation: Document findings and recommendations\n\nThe implementation should:\n- Update the command-line argument parser to recognize the new flag\n- Create a dedicated function to generate the research subtasks with appropriate descriptions\n- Ensure subtasks are properly linked to the parent task\n- Update help documentation to explain the new flag\n- Maintain backward compatibility with existing add-task functionality\n\nThe research subtasks should be customized based on the main task's title and description when possible, rather than using generic templates.",
      "testStrategy": "Testing should verify both the functionality and usability of the new feature:\n\n1. Unit tests:\n   - Test that the '--research' flag is properly parsed\n   - Verify the correct number and structure of subtasks are generated\n   - Ensure subtask IDs are correctly assigned and linked to the parent task\n\n2. Integration tests:\n   - Create a task with the research flag and verify all subtasks appear in the task list\n   - Test that the research flag works with other existing flags (e.g., --priority, --depends-on)\n   - Verify the task and subtasks are properly saved to the storage backend\n\n3. Manual testing:\n   - Run 'taskmaster add-task \"Test task\" --research' and verify the output\n   - Check that the help documentation correctly describes the new flag\n   - Verify the research subtasks have meaningful descriptions\n   - Test the command with and without the flag to ensure backward compatibility\n\n4. Edge cases:\n   - Test with very short or very long task descriptions\n   - Verify behavior when maximum task/subtask limits are reached"
    },
    {
      "id": 44,
      "title": "Implement Task Automation with Webhooks and Event Triggers",
      "description": "Design and implement a system that allows users to automate task actions through webhooks and event triggers, enabling integration with external services and automated workflows.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "This feature will enable users to create automated workflows based on task events and external triggers. Implementation should include:\n\n1. A webhook registration system that allows users to specify URLs to be called when specific task events occur (creation, status change, completion, etc.)\n2. An event system that captures and processes all task-related events\n3. A trigger definition interface where users can define conditions for automation (e.g., 'When task X is completed, create task Y')\n4. Support for both incoming webhooks (external services triggering actions in Taskmaster) and outgoing webhooks (Taskmaster notifying external services)\n5. A secure authentication mechanism for webhook calls\n6. Rate limiting and retry logic for failed webhook deliveries\n7. Integration with the existing task management system\n8. Command-line interface for managing webhooks and triggers\n9. Payload templating system allowing users to customize the data sent in webhooks\n10. Logging system for webhook activities and failures\n\nThe implementation should be compatible with both the solo/local mode and the multiplayer/remote mode, with appropriate adaptations for each context. When operating in MCP mode, the system should leverage the MCP communication protocol implemented in Task #42.",
      "testStrategy": "Testing should verify both the functionality and security of the webhook system:\n\n1. Unit tests:\n   - Test webhook registration, modification, and deletion\n   - Verify event capturing for all task operations\n   - Test payload generation and templating\n   - Validate authentication logic\n\n2. Integration tests:\n   - Set up a mock server to receive webhooks and verify payload contents\n   - Test the complete flow from task event to webhook delivery\n   - Verify rate limiting and retry behavior with intentionally failing endpoints\n   - Test webhook triggers creating new tasks and modifying existing ones\n\n3. Security tests:\n   - Verify that authentication tokens are properly validated\n   - Test for potential injection vulnerabilities in webhook payloads\n   - Verify that sensitive information is not leaked in webhook payloads\n   - Test rate limiting to prevent DoS attacks\n\n4. Mode-specific tests:\n   - Verify correct operation in both solo/local and multiplayer/remote modes\n   - Test the interaction with MCP protocol when in multiplayer mode\n\n5. Manual verification:\n   - Set up integrations with common services (GitHub, Slack, etc.) to verify real-world functionality\n   - Verify that the CLI interface for managing webhooks works as expected",
      "subtasks": [
        {
          "id": 1,
          "title": "Design webhook registration API endpoints",
          "description": "Create API endpoints for registering, updating, and deleting webhook subscriptions",
          "dependencies": [],
          "details": "Implement RESTful API endpoints that allow clients to register webhook URLs, specify event types they want to subscribe to, and manage their subscriptions. Include validation for URL format, required parameters, and authentication requirements.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement webhook authentication and security measures",
          "description": "Develop security mechanisms for webhook verification and payload signing",
          "dependencies": [
            1
          ],
          "details": "Implement signature verification using HMAC, rate limiting to prevent abuse, IP whitelisting options, and webhook secret management. Create a secure token system for webhook verification and implement TLS for all webhook communications.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Create event trigger definition interface",
          "description": "Design and implement the interface for defining event triggers and conditions",
          "dependencies": [],
          "details": "Develop a user interface or API that allows defining what events should trigger webhooks. Include support for conditional triggers based on event properties, filtering options, and the ability to specify payload formats.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Build event processing and queuing system",
          "description": "Implement a robust system for processing and queuing events before webhook delivery",
          "dependencies": [
            1,
            3
          ],
          "details": "Create an event queue using a message broker (like RabbitMQ or Kafka) to handle high volumes of events. Implement event deduplication, prioritization, and persistence to ensure reliable delivery even during system failures.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Develop webhook delivery and retry mechanism",
          "description": "Create a reliable system for webhook delivery with retry logic and failure handling",
          "dependencies": [
            2,
            4
          ],
          "details": "Implement exponential backoff retry logic, configurable retry attempts, and dead letter queues for failed deliveries. Add monitoring for webhook delivery success rates and performance metrics. Include timeout handling for unresponsive webhook endpoints.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Implement comprehensive error handling and logging",
          "description": "Create robust error handling, logging, and monitoring for the webhook system",
          "dependencies": [
            5
          ],
          "details": "Develop detailed error logging for webhook failures, including response codes, error messages, and timing information. Implement alerting for critical failures and create a dashboard for monitoring system health. Add debugging tools for webhook delivery issues.",
          "status": "pending"
        },
        {
          "id": 7,
          "title": "Create webhook testing and simulation tools",
          "description": "Develop tools for testing webhook integrations and simulating event triggers",
          "dependencies": [
            3,
            5,
            6
          ],
          "details": "Build a webhook testing console that allows manual triggering of events, viewing delivery history, and replaying failed webhooks. Create a webhook simulator for developers to test their endpoint implementations without generating real system events.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 45,
      "title": "Implement GitHub Issue Import Feature",
      "description": "Add a '--from-github' flag to the add-task command that accepts a GitHub issue URL and automatically generates a corresponding task with relevant details.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Implement a new flag '--from-github' for the add-task command that allows users to create tasks directly from GitHub issues. The implementation should:\n\n1. Accept a GitHub issue URL as an argument (e.g., 'taskmaster add-task --from-github https://github.com/owner/repo/issues/123')\n2. Parse the URL to extract the repository owner, name, and issue number\n3. Use the GitHub API to fetch the issue details including:\n   - Issue title (to be used as task title)\n   - Issue description (to be used as task description)\n   - Issue labels (to be potentially used as tags)\n   - Issue assignees (for reference)\n   - Issue status (open/closed)\n4. Generate a well-formatted task with this information\n5. Include a reference link back to the original GitHub issue\n6. Handle authentication for private repositories using GitHub tokens from environment variables or config file\n7. Implement proper error handling for:\n   - Invalid URLs\n   - Non-existent issues\n   - API rate limiting\n   - Authentication failures\n   - Network issues\n8. Allow users to override or supplement the imported details with additional command-line arguments\n9. Add appropriate documentation in help text and user guide",
      "testStrategy": "Testing should cover the following scenarios:\n\n1. Unit tests:\n   - Test URL parsing functionality with valid and invalid GitHub issue URLs\n   - Test GitHub API response parsing with mocked API responses\n   - Test error handling for various failure cases\n\n2. Integration tests:\n   - Test with real GitHub public issues (use well-known repositories)\n   - Test with both open and closed issues\n   - Test with issues containing various elements (labels, assignees, comments)\n\n3. Error case tests:\n   - Invalid URL format\n   - Non-existent repository\n   - Non-existent issue number\n   - API rate limit exceeded\n   - Authentication failures for private repos\n\n4. End-to-end tests:\n   - Verify that a task created from a GitHub issue contains all expected information\n   - Verify that the task can be properly managed after creation\n   - Test the interaction with other flags and commands\n\nCreate mock GitHub API responses for testing to avoid hitting rate limits during development and testing. Use environment variables to configure test credentials if needed.",
      "subtasks": [
        {
          "id": 1,
          "title": "Design GitHub API integration architecture",
          "description": "Create a technical design document outlining the architecture for GitHub API integration, including authentication flow, rate limiting considerations, and error handling strategies.",
          "dependencies": [],
          "details": "Document should include: API endpoints to be used, authentication method (OAuth vs Personal Access Token), data flow diagrams, and security considerations. Research GitHub API rate limits and implement appropriate throttling mechanisms.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement GitHub URL parsing and validation",
          "description": "Create a module to parse and validate GitHub issue URLs, extracting repository owner, repository name, and issue number.",
          "dependencies": [
            1
          ],
          "details": "Handle various GitHub URL formats (e.g., github.com/owner/repo/issues/123, github.com/owner/repo/pull/123). Implement validation to ensure the URL points to a valid issue or pull request. Return structured data with owner, repo, and issue number for valid URLs.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Develop GitHub API client for issue fetching",
          "description": "Create a service to authenticate with GitHub and fetch issue details using the GitHub REST API.",
          "dependencies": [
            1,
            2
          ],
          "details": "Implement authentication using GitHub Personal Access Tokens or OAuth. Handle API responses, including error cases (rate limiting, authentication failures, not found). Extract relevant issue data: title, description, labels, assignees, and comments.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Create task formatter for GitHub issues",
          "description": "Develop a formatter to convert GitHub issue data into the application's task format.",
          "dependencies": [
            3
          ],
          "details": "Map GitHub issue fields to task fields (title, description, etc.). Convert GitHub markdown to the application's supported format. Handle special GitHub features like issue references and user mentions. Generate appropriate tags based on GitHub labels.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Implement end-to-end import flow with UI",
          "description": "Create the user interface and workflow for importing GitHub issues, including progress indicators and error handling.",
          "dependencies": [
            4
          ],
          "details": "Design and implement UI for URL input and import confirmation. Show loading states during API calls. Display meaningful error messages for various failure scenarios. Allow users to review and modify imported task details before saving. Add automated tests for the entire import flow.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 46,
      "title": "Implement ICE Analysis Command for Task Prioritization",
      "description": "Create a new command that analyzes and ranks tasks based on Impact, Confidence, and Ease (ICE) scoring methodology, generating a comprehensive prioritization report.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Develop a new command called `analyze-ice` that evaluates non-completed tasks (excluding those marked as done, cancelled, or deferred) and ranks them according to the ICE methodology:\n\n1. Core functionality:\n   - Calculate an Impact score (how much value the task will deliver)\n   - Calculate a Confidence score (how certain we are about the impact)\n   - Calculate an Ease score (how easy it is to implement)\n   - Compute a total ICE score (sum or product of the three components)\n\n2. Implementation details:\n   - Reuse the filtering logic from `analyze-complexity` to select relevant tasks\n   - Leverage the LLM to generate scores for each dimension on a scale of 1-10\n   - For each task, prompt the LLM to evaluate and justify each score based on task description and details\n   - Create an `ice_report.md` file similar to the complexity report\n   - Sort tasks by total ICE score in descending order\n\n3. CLI rendering:\n   - Implement a sister command `show-ice-report` that displays the report in the terminal\n   - Format the output with colorized scores and rankings\n   - Include options to sort by individual components (impact, confidence, or ease)\n\n4. Integration:\n   - If a complexity report exists, reference it in the ICE report for additional context\n   - Consider adding a combined view that shows both complexity and ICE scores\n\nThe command should follow the same design patterns as `analyze-complexity` for consistency and code reuse.",
      "testStrategy": "1. Unit tests:\n   - Test the ICE scoring algorithm with various mock task inputs\n   - Verify correct filtering of tasks based on status\n   - Test the sorting functionality with different ranking criteria\n\n2. Integration tests:\n   - Create a test project with diverse tasks and verify the generated ICE report\n   - Test the integration with existing complexity reports\n   - Verify that changes to task statuses correctly update the ICE analysis\n\n3. CLI tests:\n   - Verify the `analyze-ice` command generates the expected report file\n   - Test the `show-ice-report` command renders correctly in the terminal\n   - Test with various flag combinations and sorting options\n\n4. Validation criteria:\n   - The ICE scores should be reasonable and consistent\n   - The report should clearly explain the rationale behind each score\n   - The ranking should prioritize high-impact, high-confidence, easy-to-implement tasks\n   - Performance should be acceptable even with a large number of tasks\n   - The command should handle edge cases gracefully (empty projects, missing data)",
      "subtasks": [
        {
          "id": 1,
          "title": "Design ICE scoring algorithm",
          "description": "Create the algorithm for calculating Impact, Confidence, and Ease scores for tasks",
          "dependencies": [],
          "details": "Define the mathematical formula for ICE scoring (Impact × Confidence × Ease). Determine the scale for each component (e.g., 1-10). Create rules for how AI will evaluate each component based on task attributes like complexity, dependencies, and descriptions. Document the scoring methodology for future reference.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement AI integration for ICE scoring",
          "description": "Develop the AI component that will analyze tasks and generate ICE scores",
          "dependencies": [
            1
          ],
          "details": "Create prompts for the AI to evaluate Impact, Confidence, and Ease. Implement error handling for AI responses. Add caching to prevent redundant AI calls. Ensure the AI provides justification for each score component. Test with various task types to ensure consistent scoring.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Create report file generator",
          "description": "Build functionality to generate a structured report file with ICE analysis results",
          "dependencies": [
            2
          ],
          "details": "Design the report file format (JSON, CSV, or Markdown). Implement sorting of tasks by ICE score. Include task details, individual I/C/E scores, and final ICE score in the report. Add timestamp and project metadata. Create a function to save the report to the specified location.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Implement CLI rendering for ICE analysis",
          "description": "Develop the command-line interface for displaying ICE analysis results",
          "dependencies": [
            3
          ],
          "details": "Design a tabular format for displaying ICE scores in the terminal. Use color coding to highlight high/medium/low priority tasks. Implement filtering options (by score range, task type, etc.). Add sorting capabilities. Create a summary view that shows top N tasks by ICE score.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Integrate with existing complexity reports",
          "description": "Connect the ICE analysis functionality with the existing complexity reporting system",
          "dependencies": [
            3,
            4
          ],
          "details": "Modify the existing complexity report to include ICE scores. Ensure consistent formatting between complexity and ICE reports. Add cross-referencing between reports. Update the command-line help documentation. Test the integrated system with various project sizes and configurations.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 47,
      "title": "Enhance Task Suggestion Actions Card Workflow",
      "description": "Redesign the suggestion actions card to implement a structured workflow for task expansion, subtask creation, context addition, and task management.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Implement a new workflow for the suggestion actions card that guides users through a logical sequence when working with tasks and subtasks:\n\n1. Task Expansion Phase:\n   - Add a prominent 'Expand Task' button at the top of the suggestion card\n   - Implement an 'Add Subtask' button that becomes active after task expansion\n   - Allow users to add multiple subtasks sequentially\n   - Provide visual indication of the current phase (expansion phase)\n\n2. Context Addition Phase:\n   - After subtasks are created, transition to the context phase\n   - Implement an 'Update Subtask' action that allows appending context to each subtask\n   - Create a UI element showing which subtask is currently being updated\n   - Provide a progress indicator showing which subtasks have received context\n   - Include a mechanism to navigate between subtasks for context addition\n\n3. Task Management Phase:\n   - Once all subtasks have context, enable the 'Set as In Progress' button\n   - Add a 'Start Working' button that directs the agent to begin with the first subtask\n   - Implement an 'Update Task' action that consolidates all notes and reorganizes them into improved subtask details\n   - Provide a confirmation dialog when restructuring task content\n\n4. UI/UX Considerations:\n   - Use visual cues (colors, icons) to indicate the current phase\n   - Implement tooltips explaining each action's purpose\n   - Add a progress tracker showing completion status across all phases\n   - Ensure the UI adapts responsively to different screen sizes\n\nThe implementation should maintain all existing functionality while guiding users through this more structured approach to task management.",
      "testStrategy": "Testing should verify the complete workflow functions correctly:\n\n1. Unit Tests:\n   - Test each button/action individually to ensure it performs its specific function\n   - Verify state transitions between phases work correctly\n   - Test edge cases (e.g., attempting to set a task in progress before adding context)\n\n2. Integration Tests:\n   - Verify the complete workflow from task expansion to starting work\n   - Test that context added to subtasks is properly saved and displayed\n   - Ensure the 'Update Task' functionality correctly consolidates and restructures content\n\n3. UI/UX Testing:\n   - Verify visual indicators correctly show the current phase\n   - Test responsive design on various screen sizes\n   - Ensure tooltips and help text are displayed correctly\n\n4. User Acceptance Testing:\n   - Create test scenarios covering the complete workflow:\n     a. Expand a task and add 3 subtasks\n     b. Add context to each subtask\n     c. Set the task as in progress\n     d. Use update-task to restructure the content\n     e. Verify the agent correctly begins work on the first subtask\n   - Test with both simple and complex tasks to ensure scalability\n\n5. Regression Testing:\n   - Verify that existing functionality continues to work\n   - Ensure compatibility with keyboard shortcuts and accessibility features",
      "subtasks": [
        {
          "id": 1,
          "title": "Design Task Expansion UI Components",
          "description": "Create UI components for the expanded task suggestion actions card that allow for task breakdown and additional context input.",
          "dependencies": [],
          "details": "Design mockups for expanded card view, including subtask creation interface, context input fields, and task management controls. Ensure the design is consistent with existing UI patterns and responsive across different screen sizes. Include animations for card expansion/collapse.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement State Management for Task Expansion",
          "description": "Develop the state management logic to handle expanded task states, subtask creation, and context additions.",
          "dependencies": [
            1
          ],
          "details": "Create state handlers for expanded/collapsed states, subtask array management, and context data. Implement proper validation for user inputs and error handling. Ensure state persistence across user sessions and synchronization with backend services.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Build Context Addition Functionality",
          "description": "Create the functionality that allows users to add additional context to tasks and subtasks.",
          "dependencies": [
            2
          ],
          "details": "Implement context input fields with support for rich text, attachments, links, and references to other tasks. Add auto-save functionality for context changes and version history if applicable. Include context suggestion features based on task content.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Develop Task Management Controls",
          "description": "Implement controls for managing tasks within the expanded card view, including prioritization, scheduling, and assignment.",
          "dependencies": [
            2
          ],
          "details": "Create UI controls for task prioritization (drag-and-drop ranking), deadline setting with calendar integration, assignee selection with user search, and status updates. Implement notification triggers for task changes and deadline reminders.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Integrate with Existing Task Systems",
          "description": "Ensure the enhanced actions card workflow integrates seamlessly with existing task management functionality.",
          "dependencies": [
            3,
            4
          ],
          "details": "Connect the new UI components to existing backend APIs. Update data models if necessary to support new features. Ensure compatibility with existing task filters, search, and reporting features. Implement data migration plan for existing tasks if needed.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Test and Optimize User Experience",
          "description": "Conduct thorough testing of the enhanced workflow and optimize based on user feedback and performance metrics.",
          "dependencies": [
            5
          ],
          "details": "Perform usability testing with representative users. Collect metrics on task completion time, error rates, and user satisfaction. Optimize performance for large task lists and complex subtask hierarchies. Implement A/B testing for alternative UI approaches if needed.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 48,
      "title": "Refactor Prompts into Centralized Structure",
      "description": "Create a dedicated 'prompts' folder and move all prompt definitions from inline function implementations to individual files, establishing a centralized prompt management system.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves restructuring how prompts are managed in the codebase:\n\n1. Create a new 'prompts' directory at the appropriate level in the project structure\n2. For each existing prompt currently embedded in functions:\n   - Create a dedicated file with a descriptive name (e.g., 'task_suggestion_prompt.js')\n   - Extract the prompt text/object into this file\n   - Export the prompt using the appropriate module pattern\n3. Modify all functions that currently contain inline prompts to import them from the new centralized location\n4. Establish a consistent naming convention for prompt files (e.g., feature_action_prompt.js)\n5. Consider creating an index.js file in the prompts directory to provide a clean import interface\n6. Document the new prompt structure in the project documentation\n7. Ensure that any prompt that requires dynamic content insertion maintains this capability after refactoring\n\nThis refactoring will improve maintainability by making prompts easier to find, update, and reuse across the application.",
      "testStrategy": "Testing should verify that the refactoring maintains identical functionality while improving code organization:\n\n1. Automated Tests:\n   - Run existing test suite to ensure no functionality is broken\n   - Create unit tests for the new prompt import mechanism\n   - Verify that dynamically constructed prompts still receive their parameters correctly\n\n2. Manual Testing:\n   - Execute each feature that uses prompts and compare outputs before and after refactoring\n   - Verify that all prompts are properly loaded from their new locations\n   - Check that no prompt text is accidentally modified during the migration\n\n3. Code Review:\n   - Confirm all prompts have been moved to the new structure\n   - Verify consistent naming conventions are followed\n   - Check that no duplicate prompts exist\n   - Ensure imports are correctly implemented in all files that previously contained inline prompts\n\n4. Documentation:\n   - Verify documentation is updated to reflect the new prompt organization\n   - Confirm the index.js export pattern works as expected for importing prompts",
      "subtasks": [
        {
          "id": 1,
          "title": "Create prompts directory structure",
          "description": "Create a centralized 'prompts' directory with appropriate subdirectories for different prompt categories",
          "dependencies": [],
          "details": "Create a 'prompts' directory at the project root. Within this directory, create subdirectories based on functional categories (e.g., 'core', 'agents', 'utils'). Add an index.js file in each subdirectory to facilitate imports. Create a root index.js file that re-exports all prompts for easy access.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Extract prompts into individual files",
          "description": "Identify all hardcoded prompts in the codebase and extract them into individual files in the prompts directory",
          "dependencies": [
            1
          ],
          "details": "Search through the codebase for all hardcoded prompt strings. For each prompt, create a new file in the appropriate subdirectory with a descriptive name (e.g., 'taskBreakdownPrompt.js'). Format each file to export the prompt string as a constant. Add JSDoc comments to document the purpose and expected usage of each prompt.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Update functions to import prompts",
          "description": "Modify all functions that use hardcoded prompts to import them from the centralized structure",
          "dependencies": [
            1,
            2
          ],
          "details": "For each function that previously used a hardcoded prompt, add an import statement to pull in the prompt from the centralized structure. Test each function after modification to ensure it still works correctly. Update any tests that might be affected by the refactoring. Create a pull request with the changes and document the new prompt structure in the project documentation.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 49,
      "title": "Implement Code Quality Analysis Command",
      "description": "Create a command that analyzes the codebase to identify patterns and verify functions against current best practices, generating improvement recommendations and potential refactoring tasks.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Develop a new command called `analyze-code-quality` that performs the following functions:\n\n1. **Pattern Recognition**:\n   - Scan the codebase to identify recurring patterns in code structure, function design, and architecture\n   - Categorize patterns by frequency and impact on maintainability\n   - Generate a report of common patterns with examples from the codebase\n\n2. **Best Practice Verification**:\n   - For each function in specified files, extract its purpose, parameters, and implementation details\n   - Create a verification checklist for each function that includes:\n     - Function naming conventions\n     - Parameter handling\n     - Error handling\n     - Return value consistency\n     - Documentation quality\n     - Complexity metrics\n   - Use an API integration with Perplexity or similar AI service to evaluate each function against current best practices\n\n3. **Improvement Recommendations**:\n   - Generate specific refactoring suggestions for functions that don't align with best practices\n   - Include code examples of the recommended improvements\n   - Estimate the effort required for each refactoring suggestion\n\n4. **Task Integration**:\n   - Create a mechanism to convert high-value improvement recommendations into Taskmaster tasks\n   - Allow users to select which recommendations to convert to tasks\n   - Generate properly formatted task descriptions that include the current implementation, recommended changes, and justification\n\nThe command should accept parameters for targeting specific directories or files, setting the depth of analysis, and filtering by improvement impact level.",
      "testStrategy": "Testing should verify all aspects of the code analysis command:\n\n1. **Functionality Testing**:\n   - Create a test codebase with known patterns and anti-patterns\n   - Verify the command correctly identifies all patterns in the test codebase\n   - Check that function verification correctly flags issues in deliberately non-compliant functions\n   - Confirm recommendations are relevant and implementable\n\n2. **Integration Testing**:\n   - Test the AI service integration with mock responses to ensure proper handling of API calls\n   - Verify the task creation workflow correctly generates well-formed tasks\n   - Test integration with existing Taskmaster commands and workflows\n\n3. **Performance Testing**:\n   - Measure execution time on codebases of various sizes\n   - Ensure memory usage remains reasonable even on large codebases\n   - Test with rate limiting on API calls to ensure graceful handling\n\n4. **User Experience Testing**:\n   - Have developers use the command on real projects and provide feedback\n   - Verify the output is actionable and clear\n   - Test the command with different parameter combinations\n\n5. **Validation Criteria**:\n   - Command successfully analyzes at least 95% of functions in the codebase\n   - Generated recommendations are specific and actionable\n   - Created tasks follow the project's task format standards\n   - Analysis results are consistent across multiple runs on the same codebase",
      "subtasks": [
        {
          "id": 1,
          "title": "Design pattern recognition algorithm",
          "description": "Create an algorithm to identify common code patterns and anti-patterns in the codebase",
          "dependencies": [],
          "details": "Develop a system that can scan code files and identify common design patterns (Factory, Singleton, etc.) and anti-patterns (God objects, excessive coupling, etc.). Include detection for language-specific patterns and create a classification system for identified patterns.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement best practice verification",
          "description": "Build verification checks against established coding standards and best practices",
          "dependencies": [
            1
          ],
          "details": "Create a framework to compare code against established best practices for the specific language/framework. Include checks for naming conventions, function length, complexity metrics, comment coverage, and other industry-standard quality indicators.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Develop AI integration for code analysis",
          "description": "Integrate AI capabilities to enhance code analysis and provide intelligent recommendations",
          "dependencies": [
            1,
            2
          ],
          "details": "Connect to AI services (like OpenAI) to analyze code beyond rule-based checks. Configure the AI to understand context, project-specific patterns, and provide nuanced analysis that rule-based systems might miss.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Create recommendation generation system",
          "description": "Build a system to generate actionable improvement recommendations based on analysis results",
          "dependencies": [
            2,
            3
          ],
          "details": "Develop algorithms to transform analysis results into specific, actionable recommendations. Include priority levels, effort estimates, and potential impact assessments for each recommendation.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Implement task creation functionality",
          "description": "Add capability to automatically create tasks from code quality recommendations",
          "dependencies": [
            4
          ],
          "details": "Build functionality to convert recommendations into tasks in the project management system. Include appropriate metadata, assignee suggestions based on code ownership, and integration with existing workflow systems.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Create comprehensive reporting interface",
          "description": "Develop a user interface to display analysis results and recommendations",
          "dependencies": [
            4,
            5
          ],
          "details": "Build a dashboard showing code quality metrics, identified patterns, recommendations, and created tasks. Include filtering options, trend analysis over time, and the ability to drill down into specific issues with code snippets and explanations.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 50,
      "title": "Implement Test Coverage Tracking System by Task",
      "description": "Create a system that maps test coverage to specific tasks and subtasks, enabling targeted test generation and tracking of code coverage at the task level.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Develop a comprehensive test coverage tracking system with the following components:\n\n1. Create a `tests.json` file structure in the `tasks/` directory that associates test suites and individual tests with specific task IDs or subtask IDs.\n\n2. Build a generator that processes code coverage reports and updates the `tests.json` file to maintain an accurate mapping between tests and tasks.\n\n3. Implement a parser that can extract code coverage information from standard coverage tools (like Istanbul/nyc, Jest coverage reports) and convert it to the task-based format.\n\n4. Create CLI commands that can:\n   - Display test coverage for a specific task/subtask\n   - Identify untested code related to a particular task\n   - Generate test suggestions for uncovered code using LLMs\n\n5. Extend the MCP (Mission Control Panel) to visualize test coverage by task, showing percentage covered and highlighting areas needing tests.\n\n6. Develop an automated test generation system that uses LLMs to create targeted tests for specific uncovered code sections within a task.\n\n7. Implement a workflow that integrates with the existing task management system, allowing developers to see test requirements alongside implementation requirements.\n\nThe system should maintain bidirectional relationships: from tests to tasks and from tasks to the code they affect, enabling precise tracking of what needs testing for each development task.",
      "testStrategy": "Testing should verify all components of the test coverage tracking system:\n\n1. **File Structure Tests**: Verify the `tests.json` file is correctly created and follows the expected schema with proper task/test relationships.\n\n2. **Coverage Report Processing**: Create mock coverage reports and verify they are correctly parsed and integrated into the `tests.json` file.\n\n3. **CLI Command Tests**: Test each CLI command with various inputs:\n   - Test coverage display for existing tasks\n   - Edge cases like tasks with no tests\n   - Tasks with partial coverage\n\n4. **Integration Tests**: Verify the entire workflow from code changes to coverage reporting to task-based test suggestions.\n\n5. **LLM Test Generation**: Validate that generated tests actually cover the intended code paths by running them against the codebase.\n\n6. **UI/UX Tests**: Ensure the MCP correctly displays coverage information and that the interface for viewing and managing test coverage is intuitive.\n\n7. **Performance Tests**: Measure the performance impact of the coverage tracking system, especially for large codebases.\n\nCreate a test suite that can run in CI/CD to ensure the test coverage tracking system itself maintains high coverage and reliability.",
      "subtasks": [
        {
          "id": 1,
          "title": "Design and implement tests.json data structure",
          "description": "Create a comprehensive data structure that maps tests to tasks/subtasks and tracks coverage metrics. This structure will serve as the foundation for the entire test coverage tracking system.",
          "dependencies": [],
          "details": "1. Design a JSON schema for tests.json that includes: test IDs, associated task/subtask IDs, coverage percentages, test types (unit/integration/e2e), file paths, and timestamps.\n2. Implement bidirectional relationships by creating references between tests.json and tasks.json.\n3. Define fields for tracking statement coverage, branch coverage, and function coverage per task.\n4. Add metadata fields for test quality metrics beyond coverage (complexity, mutation score).\n5. Create utility functions to read/write/update the tests.json file.\n6. Implement validation logic to ensure data integrity between tasks and tests.\n7. Add version control compatibility by using relative paths and stable identifiers.\n8. Test the data structure with sample data representing various test scenarios.\n9. Document the schema with examples and usage guidelines.",
          "status": "pending",
          "parentTaskId": 50
        },
        {
          "id": 2,
          "title": "Develop coverage report parser and adapter system",
          "description": "Create a framework-agnostic system that can parse coverage reports from various testing tools and convert them to the standardized task-based format in tests.json.",
          "dependencies": [
            1
          ],
          "details": "1. Research and document output formats for major coverage tools (Istanbul/nyc, Jest, Pytest, JaCoCo).\n2. Design a normalized intermediate coverage format that any test tool can map to.\n3. Implement adapter classes for each major testing framework that convert their reports to the intermediate format.\n4. Create a parser registry that can automatically detect and use the appropriate parser based on input format.\n5. Develop a mapping algorithm that associates coverage data with specific tasks based on file paths and code blocks.\n6. Implement file path normalization to handle different operating systems and environments.\n7. Add error handling for malformed or incomplete coverage reports.\n8. Create unit tests for each adapter using sample coverage reports.\n9. Implement a command-line interface for manual parsing and testing.\n10. Document the extension points for adding custom coverage tool adapters.",
          "status": "pending",
          "parentTaskId": 50
        },
        {
          "id": 3,
          "title": "Build coverage tracking and update generator",
          "description": "Create a system that processes code coverage reports, maps them to tasks, and updates the tests.json file to maintain accurate coverage tracking over time.",
          "dependencies": [
            1,
            2
          ],
          "details": "1. Implement a coverage processor that takes parsed coverage data and maps it to task IDs.\n2. Create algorithms to calculate aggregate coverage metrics at the task and subtask levels.\n3. Develop a change detection system that identifies when tests or code have changed and require updates.\n4. Implement incremental update logic to avoid reprocessing unchanged tests.\n5. Create a task-code association system that maps specific code blocks to tasks for granular tracking.\n6. Add historical tracking to monitor coverage trends over time.\n7. Implement hooks for CI/CD integration to automatically update coverage after test runs.\n8. Create a conflict resolution strategy for when multiple tests cover the same code areas.\n9. Add performance optimizations for large codebases and test suites.\n10. Develop unit tests that verify correct aggregation and mapping of coverage data.\n11. Document the update workflow with sequence diagrams and examples.",
          "status": "pending",
          "parentTaskId": 50
        },
        {
          "id": 4,
          "title": "Implement CLI commands for coverage operations",
          "description": "Create a set of command-line interface tools that allow developers to view, analyze, and manage test coverage at the task level.",
          "dependencies": [
            1,
            2,
            3
          ],
          "details": "1. Design a cohesive CLI command structure with subcommands for different coverage operations.\n2. Implement 'coverage show' command to display test coverage for a specific task/subtask.\n3. Create 'coverage gaps' command to identify untested code related to a particular task.\n4. Develop 'coverage history' command to show how coverage has changed over time.\n5. Implement 'coverage generate' command that uses LLMs to suggest tests for uncovered code.\n6. Add filtering options to focus on specific test types or coverage thresholds.\n7. Create formatted output options (JSON, CSV, markdown tables) for integration with other tools.\n8. Implement colorized terminal output for better readability of coverage reports.\n9. Add batch processing capabilities for running operations across multiple tasks.\n10. Create comprehensive help documentation and examples for each command.\n11. Develop unit and integration tests for CLI commands.\n12. Document command usage patterns and example workflows.",
          "status": "pending",
          "parentTaskId": 50
        },
        {
          "id": 5,
          "title": "Develop AI-powered test generation system",
          "description": "Create an intelligent system that uses LLMs to generate targeted tests for uncovered code sections within tasks, integrating with the existing task management workflow.",
          "dependencies": [
            1,
            2,
            3,
            4
          ],
          "details": "1. Design prompt templates for different test types (unit, integration, E2E) that incorporate task descriptions and code context.\n2. Implement code analysis to extract relevant context from uncovered code sections.\n3. Create a test generation pipeline that combines task metadata, code context, and coverage gaps.\n4. Develop strategies for maintaining test context across task changes and updates.\n5. Implement test quality evaluation to ensure generated tests are meaningful and effective.\n6. Create a feedback mechanism to improve prompts based on acceptance or rejection of generated tests.\n7. Add support for different testing frameworks and languages through templating.\n8. Implement caching to avoid regenerating similar tests.\n9. Create a workflow that integrates with the task management system to suggest tests alongside implementation requirements.\n10. Develop specialized generation modes for edge cases, regression tests, and performance tests.\n11. Add configuration options for controlling test generation style and coverage goals.\n12. Create comprehensive documentation on how to use and extend the test generation system.\n13. Implement evaluation metrics to track the effectiveness of AI-generated tests.",
          "status": "pending",
          "parentTaskId": 50
        }
      ]
    },
    {
      "id": 51,
      "title": "Implement Perplexity Research Command",
      "description": "Create an interactive REPL-style chat interface for AI-powered research that maintains conversation context, integrates project information, and provides session management capabilities.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Develop an interactive REPL-style chat interface for AI-powered research that allows users to have ongoing research conversations with context awareness. The system should:\n\n1. Create an interactive REPL using inquirer that:\n   - Maintains conversation history and context\n   - Provides a natural chat-like experience\n   - Supports special commands with the '/' prefix\n\n2. Integrate with the existing ai-services-unified.js using research mode:\n   - Leverage our unified AI service architecture\n   - Configure appropriate system prompts for research context\n   - Handle streaming responses for real-time feedback\n\n3. Support multiple context sources:\n   - Task/subtask IDs for project context\n   - File paths for code or document context\n   - Custom prompts for specific research directions\n   - Project file tree for system context\n\n4. Implement chat commands including:\n   - `/save` - Save conversation to file\n   - `/task` - Associate with or load context from a task\n   - `/help` - Show available commands and usage\n   - `/exit` - End the research session\n   - `/copy` - Copy last response to clipboard\n   - `/summary` - Generate summary of conversation\n   - `/detail` - Adjust research depth level\n\n5. Create session management capabilities:\n   - Generate and track unique session IDs\n   - Save/load sessions automatically\n   - Browse and switch between previous sessions\n   - Export sessions to portable formats\n\n6. Design a consistent UI using ui.js patterns:\n   - Color-coded messages for user/AI distinction\n   - Support for markdown rendering in terminal\n   - Progressive display of AI responses\n   - Clear visual hierarchy and readability\n\n7. Follow the \"taskmaster way\":\n   - Create something new and exciting\n   - Focus on usefulness and practicality\n   - Avoid over-engineering\n   - Maintain consistency with existing patterns\n\nThe REPL should feel like a natural conversation while providing powerful research capabilities that integrate seamlessly with the rest of the system.",
      "testStrategy": "1. Unit tests:\n   - Test the REPL command parsing and execution\n   - Mock AI service responses to test different scenarios\n   - Verify context extraction and integration from various sources\n   - Test session serialization and deserialization\n\n2. Integration tests:\n   - Test actual AI service integration with the REPL\n   - Verify session persistence across application restarts\n   - Test conversation state management with long interactions\n   - Verify context switching between different tasks and files\n\n3. User acceptance testing:\n   - Have team members use the REPL for real research needs\n   - Test the conversation flow and command usability\n   - Verify the UI is intuitive and responsive\n   - Test with various terminal sizes and environments\n\n4. Performance testing:\n   - Measure and optimize response time for queries\n   - Test behavior with large conversation histories\n   - Verify performance with complex context sources\n   - Test under poor network conditions\n\n5. Specific test scenarios:\n   - Verify markdown rendering for complex formatting\n   - Test streaming display with various response lengths\n   - Verify export features create properly formatted files\n   - Test session recovery from simulated crashes\n   - Validate handling of special characters and unicode",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Perplexity API Client Service",
          "description": "Develop a service module that handles all interactions with the Perplexity AI API, including authentication, request formatting, and response handling.",
          "dependencies": [],
          "details": "Implementation details:\n1. Create a new service file `services/perplexityService.js`\n2. Implement authentication using the PERPLEXITY_API_KEY from environment variables\n3. Create functions for making API requests to Perplexity with proper error handling:\n   - `queryPerplexity(searchQuery, options)` - Main function to query the API\n   - `handleRateLimiting(response)` - Logic to handle rate limits with exponential backoff\n4. Implement response parsing and formatting functions\n5. Add proper error handling for network issues, authentication problems, and API limitations\n6. Create a simple caching mechanism using a Map or object to store recent query results\n7. Add configuration options for different detail levels (quick vs comprehensive)\n\nTesting approach:\n- Write unit tests using Jest to verify API client functionality with mocked responses\n- Test error handling with simulated network failures\n- Verify caching mechanism works correctly\n- Test with various query types and options\n<info added on 2025-05-23T21:06:45.726Z>\nDEPRECATION NOTICE: This subtask is no longer needed and has been marked for removal. Instead of creating a new Perplexity service, we will leverage the existing ai-services-unified.js with research mode. This approach allows us to maintain a unified architecture for AI services rather than implementing a separate service specifically for Perplexity.\n</info added on 2025-05-23T21:06:45.726Z>",
          "status": "cancelled",
          "parentTaskId": 51
        },
        {
          "id": 2,
          "title": "Implement Task Context Extraction Logic",
          "description": "Create utility functions to extract relevant context from tasks and subtasks to enhance research queries with project-specific information.",
          "dependencies": [],
          "details": "Implementation details:\n1. Create a new utility file `utils/contextExtractor.js`\n2. Implement a function `extractTaskContext(taskId)` that:\n   - Loads the task/subtask data from tasks.json\n   - Extracts relevant information (title, description, details)\n   - Formats the extracted information into a context string for research\n3. Add logic to handle both task and subtask IDs\n4. Implement a function to combine extracted context with the user's search query\n5. Create a function to identify and extract key terminology from tasks\n6. Add functionality to include parent task context when a subtask ID is provided\n7. Implement proper error handling for invalid task IDs\n\nTesting approach:\n- Write unit tests to verify context extraction from sample tasks\n- Test with various task structures and content types\n- Verify error handling for missing or invalid tasks\n- Test the quality of extracted context with sample queries\n<info added on 2025-05-23T21:11:44.560Z>\nUpdated Implementation Approach:\n\nREFACTORED IMPLEMENTATION:\n1. Extract the fuzzy search logic from add-task.js (lines ~240-400) into `utils/contextExtractor.js`\n2. Implement a reusable `TaskContextExtractor` class with the following methods:\n   - `extractTaskContext(taskId)` - Base context extraction\n   - `performFuzzySearch(query, options)` - Enhanced Fuse.js implementation\n   - `getRelevanceScore(task, query)` - Scoring mechanism from add-task.js\n   - `detectPurposeCategories(task)` - Category classification logic\n   - `findRelatedTasks(taskId)` - Identify dependencies and relationships\n   - `aggregateMultiQueryContext(queries)` - Support for multiple search terms\n\n3. Add configurable context depth levels:\n   - Minimal: Just task title and description\n   - Standard: Include details and immediate relationships\n   - Comprehensive: Full context with all dependencies and related tasks\n\n4. Implement context formatters:\n   - `formatForSystemPrompt(context)` - Structured for AI system instructions\n   - `formatForChatContext(context)` - Conversational format for chat\n   - `formatForResearchQuery(context, query)` - Optimized for research commands\n\n5. Add caching layer for performance optimization:\n   - Implement LRU cache for expensive fuzzy search results\n   - Cache invalidation on task updates\n\n6. Ensure backward compatibility with existing context extraction requirements\n\nThis approach leverages our existing sophisticated search logic rather than rebuilding from scratch, while making it more flexible and reusable across the application.\n</info added on 2025-05-23T21:11:44.560Z>",
          "status": "pending",
          "parentTaskId": 51
        },
        {
          "id": 3,
          "title": "Build Research Command CLI Interface",
          "description": "Implement the Commander.js command structure for the 'research' command with all required options and parameters.",
          "dependencies": [
            1,
            2
          ],
          "details": "Implementation details:\n1. Create a new command file `commands/research.js`\n2. Set up the Commander.js command structure with the following options:\n   - Required search query parameter\n   - `--task` or `-t` option for task/subtask ID\n   - `--prompt` or `-p` option for custom research prompt\n   - `--save` or `-s` option to save results to a file\n   - `--copy` or `-c` option to copy results to clipboard\n   - `--summary` or `-m` option to generate a summary\n   - `--detail` or `-d` option to set research depth (default: medium)\n3. Implement command validation logic\n4. Connect the command to the Perplexity service created in subtask 1\n5. Integrate the context extraction logic from subtask 2\n6. Register the command in the main CLI application\n7. Add help text and examples\n\nTesting approach:\n- Test command registration and option parsing\n- Verify command validation logic works correctly\n- Test with various combinations of options\n- Ensure proper error messages for invalid inputs\n<info added on 2025-05-23T21:09:08.478Z>\nImplementation details:\n1. Create a new module `repl/research-chat.js` for the interactive research experience\n2. Implement REPL-style chat interface using inquirer with:\n   - Persistent conversation history management\n   - Context-aware prompting system\n   - Command parsing for special instructions\n3. Implement REPL commands:\n   - `/save` - Save conversation to file\n   - `/task` - Associate with or load context from a task\n   - `/help` - Show available commands and usage\n   - `/exit` - End the research session\n   - `/copy` - Copy last response to clipboard\n   - `/summary` - Generate summary of conversation\n   - `/detail` - Adjust research depth level\n4. Create context initialization system:\n   - Task/subtask context loading\n   - File content integration\n   - System prompt configuration\n5. Integrate with ai-services-unified.js research mode\n6. Implement conversation state management:\n   - Track message history\n   - Maintain context window\n   - Handle context pruning for long conversations\n7. Design consistent UI patterns using ui.js library\n8. Add entry point in main CLI application\n\nTesting approach:\n- Test REPL command parsing and execution\n- Verify context initialization with various inputs\n- Test conversation state management\n- Ensure proper error handling and recovery\n- Validate UI consistency across different terminal environments\n</info added on 2025-05-23T21:09:08.478Z>",
          "status": "pending",
          "parentTaskId": 51
        },
        {
          "id": 4,
          "title": "Implement Results Processing and Output Formatting",
          "description": "Create functionality to process, format, and display research results in the terminal with options for saving, copying, and summarizing.",
          "dependencies": [
            1,
            3
          ],
          "details": "Implementation details:\n1. Create a new module `utils/researchFormatter.js`\n2. Implement terminal output formatting with:\n   - Color-coded sections for better readability\n   - Proper text wrapping for terminal width\n   - Highlighting of key points\n3. Add functionality to save results to a file:\n   - Create a `research-results` directory if it doesn't exist\n   - Save results with timestamp and query in filename\n   - Support multiple formats (text, markdown, JSON)\n4. Implement clipboard copying using a library like `clipboardy`\n5. Create a summarization function that extracts key points from research results\n6. Add progress indicators during API calls\n7. Implement pagination for long results\n\nTesting approach:\n- Test output formatting with various result lengths and content types\n- Verify file saving functionality creates proper files with correct content\n- Test clipboard functionality\n- Verify summarization produces useful results\n<info added on 2025-05-23T21:10:00.181Z>\nImplementation details:\n1. Create a new module `utils/chatFormatter.js` for REPL interface formatting\n2. Implement terminal output formatting for conversational display:\n   - Color-coded messages distinguishing user inputs and AI responses\n   - Proper text wrapping and indentation for readability\n   - Support for markdown rendering in terminal\n   - Visual indicators for system messages and status updates\n3. Implement streaming/progressive display of AI responses:\n   - Character-by-character or chunk-by-chunk display\n   - Cursor animations during response generation\n   - Ability to interrupt long responses\n4. Design chat history visualization:\n   - Scrollable history with clear message boundaries\n   - Timestamp display options\n   - Session identification\n5. Create specialized formatters for different content types:\n   - Code blocks with syntax highlighting\n   - Bulleted and numbered lists\n   - Tables and structured data\n   - Citations and references\n6. Implement export functionality:\n   - Save conversations to markdown or text files\n   - Export individual responses\n   - Copy responses to clipboard\n7. Adapt existing ui.js patterns for conversational context:\n   - Maintain consistent styling while supporting chat flow\n   - Handle multi-turn context appropriately\n\nTesting approach:\n- Test streaming display with various response lengths and speeds\n- Verify markdown rendering accuracy for complex formatting\n- Test history navigation and scrolling functionality\n- Verify export features create properly formatted files\n- Test display on various terminal sizes and configurations\n- Verify handling of special characters and unicode\n</info added on 2025-05-23T21:10:00.181Z>",
          "status": "pending",
          "parentTaskId": 51
        },
        {
          "id": 5,
          "title": "Implement Caching and Results Management System",
          "description": "Create a persistent caching system for research results and implement functionality to manage, retrieve, and reference previous research.",
          "dependencies": [
            1,
            4
          ],
          "details": "Implementation details:\n1. Create a research results database using a simple JSON file or SQLite:\n   - Store queries, timestamps, and results\n   - Index by query and related task IDs\n2. Implement cache retrieval and validation:\n   - Check for cached results before making API calls\n   - Validate cache freshness with configurable TTL\n3. Add commands to manage research history:\n   - List recent research queries\n   - Retrieve past research by ID or search term\n   - Clear cache or delete specific entries\n4. Create functionality to associate research results with tasks:\n   - Add metadata linking research to specific tasks\n   - Implement command to show all research related to a task\n5. Add configuration options for cache behavior in user settings\n6. Implement export/import functionality for research data\n\nTesting approach:\n- Test cache storage and retrieval with various queries\n- Verify cache invalidation works correctly\n- Test history management commands\n- Verify task association functionality\n- Test with large cache sizes to ensure performance\n<info added on 2025-05-23T21:10:28.544Z>\nImplementation details:\n1. Create a session management system for the REPL experience:\n   - Generate and track unique session IDs\n   - Store conversation history with timestamps\n   - Maintain context and state between interactions\n2. Implement session persistence:\n   - Save sessions to disk automatically\n   - Load previous sessions on startup\n   - Handle graceful recovery from crashes\n3. Build session browser and selector:\n   - List available sessions with preview\n   - Filter sessions by date, topic, or content\n   - Enable quick switching between sessions\n4. Implement conversation state serialization:\n   - Capture full conversation context\n   - Preserve user preferences per session\n   - Handle state migration during updates\n5. Add session sharing capabilities:\n   - Export sessions to portable formats\n   - Import sessions from files\n   - Generate shareable links (if applicable)\n6. Create session management commands:\n   - Create new sessions\n   - Clone existing sessions\n   - Archive or delete old sessions\n\nTesting approach:\n- Verify session persistence across application restarts\n- Test session recovery from simulated crashes\n- Validate state serialization with complex conversations\n- Ensure session switching maintains proper context\n- Test session import/export functionality\n- Verify performance with large conversation histories\n</info added on 2025-05-23T21:10:28.544Z>",
          "status": "cancelled",
          "parentTaskId": 51
        },
        {
          "id": 6,
          "title": "Implement Project Context Generation",
          "description": "Create functionality to generate and include project-level context such as file trees, repository structure, and codebase insights for more informed research.",
          "dependencies": [
            2
          ],
          "details": "Implementation details:\n1. Create a new module `utils/projectContextGenerator.js` for project-level context extraction\n2. Implement file tree generation functionality:\n   - Scan project directory structure recursively\n   - Filter out irrelevant files (node_modules, .git, etc.)\n   - Format file tree for AI consumption\n   - Include file counts and structure statistics\n3. Add code analysis capabilities:\n   - Extract key imports and dependencies\n   - Identify main modules and their relationships\n   - Generate high-level architecture overview\n4. Implement context summarization:\n   - Create concise project overview\n   - Identify key technologies and patterns\n   - Summarize project purpose and structure\n5. Add caching for expensive operations:\n   - Cache file tree with invalidation on changes\n   - Store analysis results with TTL\n6. Create integration with research REPL:\n   - Add project context to system prompts\n   - Support `/project` command to refresh context\n   - Allow selective inclusion of project components\n\nTesting approach:\n- Test file tree generation with various project structures\n- Verify filtering logic works correctly\n- Test context summarization quality\n- Measure performance impact of context generation\n- Verify caching mechanism effectiveness",
          "status": "pending",
          "parentTaskId": 51
        },
        {
          "id": 7,
          "title": "Create REPL Command System",
          "description": "Implement a flexible command system for the research REPL that allows users to control the conversation flow, manage sessions, and access additional functionality.",
          "dependencies": [
            3
          ],
          "details": "Implementation details:\n1. Create a new module `repl/commands.js` for REPL command handling\n2. Implement a command parser that:\n   - Detects commands starting with `/`\n   - Parses arguments and options\n   - Handles quoted strings and special characters\n3. Create a command registry system:\n   - Register command handlers with descriptions\n   - Support command aliases\n   - Enable command discovery and help\n4. Implement core commands:\n   - `/save [filename]` - Save conversation\n   - `/task <taskId>` - Load task context\n   - `/file <path>` - Include file content\n   - `/help [command]` - Show help\n   - `/exit` - End session\n   - `/copy [n]` - Copy nth response\n   - `/summary` - Generate conversation summary\n   - `/detail <level>` - Set detail level\n   - `/clear` - Clear conversation\n   - `/project` - Refresh project context\n   - `/session <id|new>` - Switch/create session\n5. Add command completion and suggestions\n6. Implement error handling for invalid commands\n7. Create a help system with examples\n\nTesting approach:\n- Test command parsing with various inputs\n- Verify command execution and error handling\n- Test command completion functionality\n- Verify help system provides useful information\n- Test with complex command sequences",
          "status": "pending",
          "parentTaskId": 51
        },
        {
          "id": 8,
          "title": "Integrate with AI Services Unified",
          "description": "Integrate the research REPL with the existing ai-services-unified.js to leverage the unified AI service architecture with research mode.",
          "dependencies": [
            3,
            4
          ],
          "details": "Implementation details:\n1. Update `repl/research-chat.js` to integrate with ai-services-unified.js\n2. Configure research mode in AI service:\n   - Set appropriate system prompts\n   - Configure temperature and other parameters\n   - Enable streaming responses\n3. Implement context management:\n   - Format conversation history for AI context\n   - Include task and project context\n   - Handle context window limitations\n4. Add support for different research styles:\n   - Exploratory research with broader context\n   - Focused research with specific questions\n   - Comparative analysis between concepts\n5. Implement response handling:\n   - Process streaming chunks\n   - Format and display responses\n   - Handle errors and retries\n6. Add configuration options for AI service selection\n7. Implement fallback mechanisms for service unavailability\n\nTesting approach:\n- Test integration with mocked AI services\n- Verify context formatting and management\n- Test streaming response handling\n- Verify error handling and recovery\n- Test with various research styles and queries",
          "status": "pending",
          "parentTaskId": 51
        }
      ]
    },
    {
      "id": 52,
      "title": "Implement Task Suggestion Command for CLI",
      "description": "Create a new CLI command 'suggest-task' that generates contextually relevant task suggestions based on existing tasks and allows users to accept, decline, or regenerate suggestions.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Implement a new command 'suggest-task' that can be invoked from the CLI to generate intelligent task suggestions. The command should:\n\n1. Collect a snapshot of all existing tasks including their titles, descriptions, statuses, and dependencies\n2. Extract parent task subtask titles (not full objects) to provide context\n3. Use this information to generate a contextually appropriate new task suggestion\n4. Present the suggestion to the user in a clear format\n5. Provide an interactive interface with options to:\n   - Accept the suggestion (creating a new task with the suggested details)\n   - Decline the suggestion (exiting without creating a task)\n   - Regenerate a new suggestion (requesting an alternative)\n\nThe implementation should follow a similar pattern to the 'generate-subtask' command but operate at the task level rather than subtask level. The command should use the project's existing AI integration to analyze the current task structure and generate relevant suggestions. Ensure proper error handling for API failures and implement a timeout mechanism for suggestion generation.\n\nThe command should accept optional flags to customize the suggestion process, such as:\n- `--parent=<task-id>` to suggest a task related to a specific parent task\n- `--type=<task-type>` to suggest a specific type of task (feature, bugfix, refactor, etc.)\n- `--context=<additional-context>` to provide additional information for the suggestion",
      "testStrategy": "Testing should verify both the functionality and user experience of the suggest-task command:\n\n1. Unit tests:\n   - Test the task collection mechanism to ensure it correctly gathers existing task data\n   - Test the context extraction logic to verify it properly isolates relevant subtask titles\n   - Test the suggestion generation with mocked AI responses\n   - Test the command's parsing of various flag combinations\n\n2. Integration tests:\n   - Test the end-to-end flow with a mock project structure\n   - Verify the command correctly interacts with the AI service\n   - Test the task creation process when a suggestion is accepted\n\n3. User interaction tests:\n   - Test the accept/decline/regenerate interface works correctly\n   - Verify appropriate feedback is displayed to the user\n   - Test handling of unexpected user inputs\n\n4. Edge cases:\n   - Test behavior when run in an empty project with no existing tasks\n   - Test with malformed task data\n   - Test with API timeouts or failures\n   - Test with extremely large numbers of existing tasks\n\nManually verify the command produces contextually appropriate suggestions that align with the project's current state and needs.",
      "subtasks": [
        {
          "id": 1,
          "title": "Design data collection mechanism for existing tasks",
          "description": "Create a module to collect and format existing task data from the system for AI processing",
          "dependencies": [],
          "details": "Implement a function that retrieves all existing tasks from storage, formats them appropriately for AI context, and handles edge cases like empty task lists or corrupted data. Include metadata like task status, dependencies, and creation dates to provide rich context for suggestions.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement AI integration for task suggestions",
          "description": "Develop the core functionality to generate task suggestions using AI based on existing tasks",
          "dependencies": [
            1
          ],
          "details": "Create an AI prompt template that effectively communicates the existing task context and request for suggestions. Implement error handling for API failures, rate limiting, and malformed responses. Include parameters for controlling suggestion quantity and specificity.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Build interactive CLI interface for suggestions",
          "description": "Create the command-line interface for requesting and displaying task suggestions",
          "dependencies": [
            2
          ],
          "details": "Design a user-friendly CLI command structure with appropriate flags for customization. Implement progress indicators during AI processing and format the output of suggestions in a clear, readable format. Include help text and examples in the command documentation.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Implement suggestion selection and task creation",
          "description": "Allow users to interactively select suggestions to convert into actual tasks",
          "dependencies": [
            3
          ],
          "details": "Create an interactive selection interface where users can review suggestions, select which ones to create as tasks, and optionally modify them before creation. Implement batch creation capabilities and validation to ensure new tasks meet system requirements.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Add configuration options and flag handling",
          "description": "Implement various configuration options and command flags for customizing suggestion behavior",
          "dependencies": [
            3,
            4
          ],
          "details": "Create a comprehensive set of command flags for controlling suggestion quantity, specificity, format, and other parameters. Implement persistent configuration options that users can set as defaults. Document all available options and provide examples of common usage patterns.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 53,
      "title": "Implement Subtask Suggestion Feature for Parent Tasks",
      "description": "Create a new CLI command that suggests contextually relevant subtasks for existing parent tasks, allowing users to accept, decline, or regenerate suggestions before adding them to the system.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "Develop a new command `suggest-subtask <task-id>` that generates intelligent subtask suggestions for a specified parent task. The implementation should:\n\n1. Accept a parent task ID as input and validate it exists\n2. Gather a snapshot of all existing tasks in the system (titles only, with their statuses and dependencies)\n3. Retrieve the full details of the specified parent task\n4. Use this context to generate a relevant subtask suggestion that would logically help complete the parent task\n5. Present the suggestion to the user in the CLI with options to:\n   - Accept (a): Add the subtask to the system under the parent task\n   - Decline (d): Reject the suggestion without adding anything\n   - Regenerate (r): Generate a new alternative subtask suggestion\n   - Edit (e): Accept but allow editing the title/description before adding\n\nThe suggestion algorithm should consider:\n- The parent task's description and requirements\n- Current progress (% complete) of the parent task\n- Existing subtasks already created for this parent\n- Similar patterns from other tasks in the system\n- Logical next steps based on software development best practices\n\nWhen a subtask is accepted, it should be properly linked to the parent task and assigned appropriate default values for priority and status.",
      "testStrategy": "Testing should verify both the functionality and the quality of suggestions:\n\n1. Unit tests:\n   - Test command parsing and validation of task IDs\n   - Test snapshot creation of existing tasks\n   - Test the suggestion generation with mocked data\n   - Test the user interaction flow with simulated inputs\n\n2. Integration tests:\n   - Create a test parent task and verify subtask suggestions are contextually relevant\n   - Test the accept/decline/regenerate workflow end-to-end\n   - Verify proper linking of accepted subtasks to parent tasks\n   - Test with various types of parent tasks (frontend, backend, documentation, etc.)\n\n3. Quality assessment:\n   - Create a benchmark set of 10 diverse parent tasks\n   - Generate 3 subtask suggestions for each and have team members rate relevance on 1-5 scale\n   - Ensure average relevance score exceeds 3.5/5\n   - Verify suggestions don't duplicate existing subtasks\n\n4. Edge cases:\n   - Test with a parent task that has no description\n   - Test with a parent task that already has many subtasks\n   - Test with a newly created system with minimal task history",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement parent task validation",
          "description": "Create validation logic to ensure subtasks are being added to valid parent tasks",
          "dependencies": [],
          "details": "Develop functions to verify that the parent task exists in the system before allowing subtask creation. Handle error cases gracefully with informative messages. Include validation for task ID format and existence in the database.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Build context gathering mechanism",
          "description": "Develop a system to collect relevant context from parent task and existing subtasks",
          "dependencies": [
            1
          ],
          "details": "Create functions to extract information from the parent task including title, description, and metadata. Also gather information about any existing subtasks to provide context for AI suggestions. Format this data appropriately for the AI prompt.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Develop AI suggestion logic for subtasks",
          "description": "Create the core AI integration to generate relevant subtask suggestions",
          "dependencies": [
            2
          ],
          "details": "Implement the AI prompt engineering and response handling for subtask generation. Ensure the AI provides structured output with appropriate fields for subtasks. Include error handling for API failures and malformed responses.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Create interactive CLI interface",
          "description": "Build a user-friendly command-line interface for the subtask suggestion feature",
          "dependencies": [
            3
          ],
          "details": "Develop CLI commands and options for requesting subtask suggestions. Include interactive elements for selecting, modifying, or rejecting suggested subtasks. Ensure clear user feedback throughout the process.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Implement subtask linking functionality",
          "description": "Create system to properly link suggested subtasks to their parent task",
          "dependencies": [
            4
          ],
          "details": "Develop the database operations to save accepted subtasks and link them to the parent task. Include functionality for setting dependencies between subtasks. Ensure proper transaction handling to maintain data integrity.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Perform comprehensive testing",
          "description": "Test the subtask suggestion feature across various scenarios",
          "dependencies": [
            5
          ],
          "details": "Create unit tests for each component. Develop integration tests for the full feature workflow. Test edge cases including invalid inputs, API failures, and unusual task structures. Document test results and fix any identified issues.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 54,
      "title": "Add Research Flag to Add-Task Command",
      "description": "Enhance the add-task command with a --research flag that allows users to perform quick research on the task topic before finalizing task creation.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "Modify the existing add-task command to accept a new optional flag '--research'. When this flag is provided, the system should pause the task creation process and invoke the Perplexity research functionality (similar to Task #51) to help users gather information about the task topic before finalizing the task details. The implementation should:\n\n1. Update the command parser to recognize the new --research flag\n2. When the flag is present, extract the task title/description as the research topic\n3. Call the Perplexity research functionality with this topic\n4. Display research results to the user\n5. Allow the user to refine their task based on the research (modify title, description, etc.)\n6. Continue with normal task creation flow after research is complete\n7. Ensure the research results can be optionally attached to the task as reference material\n8. Add appropriate help text explaining this feature in the command help\n\nThe implementation should leverage the existing Perplexity research command from Task #51, ensuring code reuse where possible.",
      "testStrategy": "Testing should verify both the functionality and usability of the new feature:\n\n1. Unit tests:\n   - Verify the command parser correctly recognizes the --research flag\n   - Test that the research functionality is properly invoked with the correct topic\n   - Ensure task creation proceeds correctly after research is complete\n\n2. Integration tests:\n   - Test the complete flow from command invocation to task creation with research\n   - Verify research results are properly attached to the task when requested\n   - Test error handling when research API is unavailable\n\n3. Manual testing:\n   - Run the command with --research flag and verify the user experience\n   - Test with various task topics to ensure research is relevant\n   - Verify the help documentation correctly explains the feature\n   - Test the command without the flag to ensure backward compatibility\n\n4. Edge cases:\n   - Test with very short/vague task descriptions\n   - Test with complex technical topics\n   - Test cancellation of task creation during the research phase"
    },
    {
      "id": 55,
      "title": "Implement Positional Arguments Support for CLI Commands",
      "description": "Upgrade CLI commands to support positional arguments alongside the existing flag-based syntax, allowing for more intuitive command usage.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves modifying the command parsing logic in commands.js to support positional arguments as an alternative to the current flag-based approach. The implementation should:\n\n1. Update the argument parsing logic to detect when arguments are provided without flag prefixes (--)\n2. Map positional arguments to their corresponding parameters based on their order\n3. For each command in commands.js, define a consistent positional argument order (e.g., for set-status: first arg = id, second arg = status)\n4. Maintain backward compatibility with the existing flag-based syntax\n5. Handle edge cases such as:\n   - Commands with optional parameters\n   - Commands with multiple parameters\n   - Commands that accept arrays or complex data types\n6. Update the help text for each command to show both usage patterns\n7. Modify the cursor rules to work with both input styles\n8. Ensure error messages are clear when positional arguments are provided incorrectly\n\nExample implementations:\n- `task-master set-status 25 done` should be equivalent to `task-master set-status --id=25 --status=done`\n- `task-master add-task \"New task name\" \"Task description\"` should be equivalent to `task-master add-task --name=\"New task name\" --description=\"Task description\"`\n\nThe code should prioritize maintaining the existing functionality while adding this new capability.",
      "testStrategy": "Testing should verify both the new positional argument functionality and continued support for flag-based syntax:\n\n1. Unit tests:\n   - Create tests for each command that verify it works with both positional and flag-based arguments\n   - Test edge cases like missing arguments, extra arguments, and mixed usage (some positional, some flags)\n   - Verify help text correctly displays both usage patterns\n\n2. Integration tests:\n   - Test the full CLI with various commands using both syntax styles\n   - Verify that output is identical regardless of which syntax is used\n   - Test commands with different numbers of arguments\n\n3. Manual testing:\n   - Run through a comprehensive set of real-world usage scenarios with both syntax styles\n   - Verify cursor behavior works correctly with both input methods\n   - Check that error messages are helpful when incorrect positional arguments are provided\n\n4. Documentation verification:\n   - Ensure README and help text accurately reflect the new dual syntax support\n   - Verify examples in documentation show both styles where appropriate\n\nAll tests should pass with 100% of commands supporting both argument styles without any regression in existing functionality.",
      "subtasks": [
        {
          "id": 1,
          "title": "Analyze current CLI argument parsing structure",
          "description": "Review the existing CLI argument parsing code to understand how arguments are currently processed and identify integration points for positional arguments.",
          "dependencies": [],
          "details": "Document the current argument parsing flow, identify key classes and methods responsible for argument handling, and determine how named arguments are currently processed. Create a technical design document outlining the current architecture and proposed changes.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Design positional argument specification format",
          "description": "Create a specification for how positional arguments will be defined in command definitions, including their order, required/optional status, and type validation.",
          "dependencies": [
            1
          ],
          "details": "Define a clear syntax for specifying positional arguments in command definitions. Consider how to handle mixed positional and named arguments, default values, and type constraints. Document the specification with examples for different command types.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Implement core positional argument parsing logic",
          "description": "Modify the argument parser to recognize and process positional arguments according to the specification, while maintaining compatibility with existing named arguments.",
          "dependencies": [
            1,
            2
          ],
          "details": "Update the parser to identify arguments without flags as positional, map them to the correct parameter based on order, and apply appropriate validation. Ensure the implementation handles missing required positional arguments and provides helpful error messages.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Handle edge cases and error conditions",
          "description": "Implement robust handling for edge cases such as too many/few arguments, type mismatches, and ambiguous situations between positional and named arguments.",
          "dependencies": [
            3
          ],
          "details": "Create comprehensive error handling for scenarios like: providing both positional and named version of the same argument, incorrect argument types, missing required positional arguments, and excess positional arguments. Ensure error messages are clear and actionable for users.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Update documentation and create usage examples",
          "description": "Update CLI documentation to explain positional argument support and provide clear examples showing how to use positional arguments with different commands.",
          "dependencies": [
            2,
            3,
            4
          ],
          "details": "Revise user documentation to include positional argument syntax, update command reference with positional argument information, and create example command snippets showing both positional and named argument usage. Include a migration guide for users transitioning from named-only to positional arguments.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 56,
      "title": "Refactor Task-Master Files into Node Module Structure",
      "description": "Restructure the task-master files by moving them from the project root into a proper node module structure to improve organization and maintainability.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves a significant refactoring of the task-master system to follow better Node.js module practices. Currently, task-master files are located in the project root, which creates clutter and doesn't follow best practices for Node.js applications. The refactoring should:\n\n1. Create a dedicated directory structure within node_modules or as a local package\n2. Update all import/require paths throughout the codebase to reference the new module location\n3. Reorganize the files into a logical structure (lib/, utils/, commands/, etc.)\n4. Ensure the module has a proper package.json with dependencies and exports\n5. Update any build processes, scripts, or configuration files to reflect the new structure\n6. Maintain backward compatibility where possible to minimize disruption\n7. Document the new structure and any changes to usage patterns\n\nThis is a high-risk refactoring as it touches many parts of the system, so it should be approached methodically with frequent testing. Consider using a feature branch and implementing the changes incrementally rather than all at once.",
      "testStrategy": "Testing for this refactoring should be comprehensive to ensure nothing breaks during the restructuring:\n\n1. Create a complete inventory of existing functionality through automated tests before starting\n2. Implement unit tests for each module to verify they function correctly in the new structure\n3. Create integration tests that verify the interactions between modules work as expected\n4. Test all CLI commands to ensure they continue to function with the new module structure\n5. Verify that all import/require statements resolve correctly\n6. Test on different environments (development, staging) to ensure compatibility\n7. Perform regression testing on all features that depend on task-master functionality\n8. Create a rollback plan and test it to ensure we can revert changes if critical issues arise\n9. Conduct performance testing to ensure the refactoring doesn't introduce overhead\n10. Have multiple developers test the changes on their local environments before merging"
    },
    {
      "id": 57,
      "title": "Enhance Task-Master CLI User Experience and Interface",
      "description": "Improve the Task-Master CLI's user experience by refining the interface, reducing verbose logging, and adding visual polish to create a more professional and intuitive tool.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "The current Task-Master CLI interface is functional but lacks polish and produces excessive log output. This task involves several key improvements:\n\n1. Log Management:\n   - Implement log levels (ERROR, WARN, INFO, DEBUG, TRACE)\n   - Only show INFO and above by default\n   - Add a --verbose flag to show all logs\n   - Create a dedicated log file for detailed logs\n\n2. Visual Enhancements:\n   - Add a clean, branded header when the tool starts\n   - Implement color-coding for different types of messages (success in green, errors in red, etc.)\n   - Use spinners or progress indicators for operations that take time\n   - Add clear visual separation between command input and output\n\n3. Interactive Elements:\n   - Add loading animations for longer operations\n   - Implement interactive prompts for complex inputs instead of requiring all parameters upfront\n   - Add confirmation dialogs for destructive operations\n\n4. Output Formatting:\n   - Format task listings in tables with consistent spacing\n   - Implement a compact mode and a detailed mode for viewing tasks\n   - Add visual indicators for task status (icons or colors)\n\n5. Help and Documentation:\n   - Enhance help text with examples and clearer descriptions\n   - Add contextual hints for common next steps after commands\n\nUse libraries like chalk, ora, inquirer, and boxen to implement these improvements. Ensure the interface remains functional in CI/CD environments where interactive elements might not be supported.",
      "testStrategy": "Testing should verify both functionality and user experience improvements:\n\n1. Automated Tests:\n   - Create unit tests for log level filtering functionality\n   - Test that all commands still function correctly with the new UI\n   - Verify that non-interactive mode works in CI environments\n   - Test that verbose and quiet modes function as expected\n\n2. User Experience Testing:\n   - Create a test script that runs through common user flows\n   - Capture before/after screenshots for visual comparison\n   - Measure and compare the number of lines output for common operations\n\n3. Usability Testing:\n   - Have 3-5 team members perform specific tasks using the new interface\n   - Collect feedback on clarity, ease of use, and visual appeal\n   - Identify any confusion points or areas for improvement\n\n4. Edge Case Testing:\n   - Test in terminals with different color schemes and sizes\n   - Verify functionality in environments without color support\n   - Test with very large task lists to ensure formatting remains clean\n\nAcceptance Criteria:\n- Log output is reduced by at least 50% in normal operation\n- All commands provide clear visual feedback about their progress and completion\n- Help text is comprehensive and includes examples\n- Interface is visually consistent across all commands\n- Tool remains fully functional in non-interactive environments",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Configurable Log Levels",
          "description": "Create a logging system with different verbosity levels that users can configure",
          "dependencies": [],
          "details": "Design and implement a logging system with at least 4 levels (ERROR, WARNING, INFO, DEBUG). Add command-line options to set the verbosity level. Ensure logs are color-coded by severity and can be redirected to files. Include timestamp formatting options.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Design Terminal Color Scheme and Visual Elements",
          "description": "Create a consistent and accessible color scheme for the CLI interface",
          "dependencies": [],
          "details": "Define a color palette that works across different terminal environments. Implement color-coding for different task states, priorities, and command categories. Add support for terminals without color capabilities. Design visual separators, headers, and footers for different output sections.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Implement Progress Indicators and Loading Animations",
          "description": "Add visual feedback for long-running operations",
          "dependencies": [
            2
          ],
          "details": "Create spinner animations for operations that take time to complete. Implement progress bars for operations with known completion percentages. Ensure animations degrade gracefully in terminals with limited capabilities. Add estimated time remaining calculations where possible.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Develop Interactive Selection Menus",
          "description": "Create interactive menus for task selection and configuration",
          "dependencies": [
            2
          ],
          "details": "Implement arrow-key navigation for selecting tasks from a list. Add checkbox and radio button interfaces for multi-select and single-select options. Include search/filter functionality for large task lists. Ensure keyboard shortcuts are consistent and documented.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Design Tabular and Structured Output Formats",
          "description": "Improve the formatting of task lists and detailed information",
          "dependencies": [
            2
          ],
          "details": "Create table layouts with proper column alignment for task lists. Implement tree views for displaying task hierarchies and dependencies. Add support for different output formats (plain text, JSON, CSV). Ensure outputs are properly paginated for large datasets.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Create Help System and Interactive Documentation",
          "description": "Develop an in-CLI help system with examples and contextual assistance",
          "dependencies": [
            2,
            4,
            5
          ],
          "details": "Implement a comprehensive help command with examples for each feature. Add contextual help that suggests relevant commands based on user actions. Create interactive tutorials for new users. Include command auto-completion suggestions and syntax highlighting for command examples.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 58,
      "title": "Implement Elegant Package Update Mechanism for Task-Master",
      "description": "Create a robust update mechanism that handles package updates gracefully, ensuring all necessary files are updated when the global package is upgraded.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "Develop a comprehensive update system with these components:\n\n1. **Update Detection**: When task-master runs, check if the current version matches the installed version. If not, notify the user an update is available.\n\n2. **Update Command**: Implement a dedicated `task-master update` command that:\n   - Updates the global package (`npm -g task-master-ai@latest`)\n   - Automatically runs necessary initialization steps\n   - Preserves user configurations while updating system files\n\n3. **Smart File Management**:\n   - Create a manifest of core files with checksums\n   - During updates, compare existing files with the manifest\n   - Only overwrite files that have changed in the update\n   - Preserve user-modified files with an option to merge changes\n\n4. **Configuration Versioning**:\n   - Add version tracking to configuration files\n   - Implement migration paths for configuration changes between versions\n   - Provide backward compatibility for older configurations\n\n5. **Update Notifications**:\n   - Add a non-intrusive notification when updates are available\n   - Include a changelog summary of what's new\n\nThis system should work seamlessly with the existing `task-master init` command but provide a more automated and user-friendly update experience.",
      "testStrategy": "Test the update mechanism with these specific scenarios:\n\n1. **Version Detection Test**:\n   - Install an older version, then verify the system correctly detects when a newer version is available\n   - Test with minor and major version changes\n\n2. **Update Command Test**:\n   - Verify `task-master update` successfully updates the global package\n   - Confirm all necessary files are updated correctly\n   - Test with and without user-modified files present\n\n3. **File Preservation Test**:\n   - Modify configuration files, then update\n   - Verify user changes are preserved while system files are updated\n   - Test with conflicts between user changes and system updates\n\n4. **Rollback Test**:\n   - Implement and test a rollback mechanism if updates fail\n   - Verify system returns to previous working state\n\n5. **Integration Test**:\n   - Create a test project with the current version\n   - Run through the update process\n   - Verify all functionality continues to work after update\n\n6. **Edge Case Tests**:\n   - Test updating with insufficient permissions\n   - Test updating with network interruptions\n   - Test updating from very old versions to latest"
    },
    {
      "id": 59,
      "title": "Remove Manual Package.json Modifications and Implement Automatic Dependency Management",
      "description": "Eliminate code that manually modifies users' package.json files and implement proper npm dependency management that automatically handles package requirements when users install task-master-ai.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "Currently, the application is attempting to manually modify users' package.json files, which is not the recommended approach for npm packages. Instead:\n\n1. Review all code that directly manipulates package.json files in users' projects\n2. Remove these manual modifications\n3. Properly define all dependencies in the package.json of task-master-ai itself\n4. Ensure all peer dependencies are correctly specified\n5. For any scripts that need to be available to users, use proper npm bin linking or npx commands\n6. Update the installation process to leverage npm's built-in dependency management\n7. If configuration is needed in users' projects, implement a proper initialization command that creates config files rather than modifying package.json\n8. Document the new approach in the README and any other relevant documentation\n\nThis change will make the package more reliable, follow npm best practices, and prevent potential conflicts or errors when modifying users' project files.",
      "testStrategy": "1. Create a fresh test project directory\n2. Install the updated task-master-ai package using npm install task-master-ai\n3. Verify that no code attempts to modify the test project's package.json\n4. Confirm all dependencies are properly installed in node_modules\n5. Test all commands to ensure they work without the previous manual package.json modifications\n6. Try installing in projects with various existing configurations to ensure no conflicts occur\n7. Test the uninstall process to verify it cleanly removes the package without leaving unwanted modifications\n8. Verify the package works in different npm environments (npm 6, 7, 8) and with different Node.js versions\n9. Create an integration test that simulates a real user workflow from installation through usage",
      "subtasks": [
        {
          "id": 1,
          "title": "Conduct Code Audit for Dependency Management",
          "description": "Review the current codebase to identify all areas where dependencies are manually managed, modified, or referenced outside of npm best practices.",
          "dependencies": [],
          "details": "Focus on scripts, configuration files, and any custom logic related to dependency installation or versioning.",
          "status": "done"
        },
        {
          "id": 2,
          "title": "Remove Manual Dependency Modifications",
          "description": "Eliminate any custom scripts or manual steps that alter dependencies outside of npm's standard workflow.",
          "dependencies": [
            1
          ],
          "details": "Refactor or delete code that manually installs, updates, or modifies dependencies, ensuring all dependency management is handled via npm.",
          "status": "done"
        },
        {
          "id": 3,
          "title": "Update npm Dependencies",
          "description": "Update all project dependencies using npm, ensuring versions are current and compatible, and resolve any conflicts.",
          "dependencies": [
            2
          ],
          "details": "Run npm update, audit for vulnerabilities, and adjust package.json and package-lock.json as needed.",
          "status": "done"
        },
        {
          "id": 4,
          "title": "Update Initialization and Installation Commands",
          "description": "Revise project setup scripts and documentation to reflect the new npm-based dependency management approach.",
          "dependencies": [
            3
          ],
          "details": "Ensure that all initialization commands (e.g., npm install) are up-to-date and remove references to deprecated manual steps.",
          "status": "done"
        },
        {
          "id": 5,
          "title": "Update Documentation",
          "description": "Revise project documentation to describe the new dependency management process and provide clear setup instructions.",
          "dependencies": [
            4
          ],
          "details": "Update README, onboarding guides, and any developer documentation to align with npm best practices.",
          "status": "done"
        },
        {
          "id": 6,
          "title": "Perform Regression Testing",
          "description": "Run comprehensive tests to ensure that the refactor has not introduced any regressions or broken existing functionality.",
          "dependencies": [
            5
          ],
          "details": "Execute automated and manual tests, focusing on areas affected by dependency management changes.",
          "status": "done"
        }
      ]
    },
    {
      "id": 60,
      "title": "Implement Mentor System with Round-Table Discussion Feature",
      "description": "Create a mentor system that allows users to add simulated mentors to their projects and facilitate round-table discussions between these mentors to gain diverse perspectives and insights on tasks.",
      "details": "Implement a comprehensive mentor system with the following features:\n\n1. **Mentor Management**:\n   - Create a `mentors.json` file to store mentor data including name, personality, expertise, and other relevant attributes\n   - Implement `add-mentor` command that accepts a name and prompt describing the mentor's characteristics\n   - Implement `remove-mentor` command to delete mentors from the system\n   - Implement `list-mentors` command to display all configured mentors and their details\n   - Set a recommended maximum of 5 mentors with appropriate warnings\n\n2. **Round-Table Discussion**:\n   - Create a `round-table` command with the following parameters:\n     - `--prompt`: Optional text prompt to guide the discussion\n     - `--id`: Optional task/subtask ID(s) to provide context (support comma-separated values)\n     - `--turns`: Number of discussion rounds (each mentor speaks once per turn)\n     - `--output`: Optional flag to export results to a file\n   - Implement an interactive CLI experience using inquirer for the round-table\n   - Generate a simulated discussion where each mentor speaks in turn based on their personality\n   - After all turns complete, generate insights, recommendations, and a summary\n   - Display results in the CLI\n   - When `--output` is specified, create a `round-table.txt` file containing:\n     - Initial prompt\n     - Target task ID(s)\n     - Full round-table discussion transcript\n     - Recommendations and insights section\n\n3. **Integration with Task System**:\n   - Enhance `update`, `update-task`, and `update-subtask` commands to accept a round-table.txt file\n   - Use the round-table output as input for updating tasks or subtasks\n   - Allow appending round-table insights to subtasks\n\n4. **LLM Integration**:\n   - Configure the system to effectively simulate different personalities using LLM\n   - Ensure mentors maintain consistent personalities across different round-tables\n   - Implement proper context handling to ensure relevant task information is included\n\nEnsure all commands have proper help text and error handling for cases like no mentors configured, invalid task IDs, etc.",
      "testStrategy": "1. **Unit Tests**:\n   - Test mentor data structure creation and validation\n   - Test mentor addition with various input formats\n   - Test mentor removal functionality\n   - Test listing of mentors with different configurations\n   - Test round-table parameter parsing and validation\n\n2. **Integration Tests**:\n   - Test the complete flow of adding mentors and running a round-table\n   - Test round-table with different numbers of turns\n   - Test round-table with task context vs. custom prompt\n   - Test output file generation and format\n   - Test using round-table output to update tasks and subtasks\n\n3. **Edge Cases**:\n   - Test behavior when no mentors are configured but round-table is called\n   - Test with invalid task IDs in the --id parameter\n   - Test with extremely long discussions (many turns)\n   - Test with mentors that have similar personalities\n   - Test removing a mentor that doesn't exist\n   - Test adding more than the recommended 5 mentors\n\n4. **Manual Testing Scenarios**:\n   - Create mentors with distinct personalities (e.g., Vitalik Buterin, Steve Jobs, etc.)\n   - Run a round-table on a complex task and verify the insights are helpful\n   - Verify the personality simulation is consistent and believable\n   - Test the round-table output file readability and usefulness\n   - Verify that using round-table output to update tasks produces meaningful improvements",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Design Mentor System Architecture",
          "description": "Create a comprehensive architecture for the mentor system, defining data models, relationships, and interaction patterns.",
          "dependencies": [],
          "details": "Define mentor profiles structure, expertise categorization, availability tracking, and relationship to user accounts. Design the database schema for storing mentor information and interactions. Create flowcharts for mentor-mentee matching algorithms and interaction workflows.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement Mentor Profile Management",
          "description": "Develop the functionality for creating, editing, and managing mentor profiles in the system.",
          "dependencies": [
            1
          ],
          "details": "Build UI components for mentor profile creation and editing. Implement backend APIs for profile CRUD operations. Create expertise tagging system and availability calendar. Add profile verification and approval workflows for quality control.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Develop Round-Table Discussion Framework",
          "description": "Create the core framework for hosting and managing round-table discussions between mentors and users.",
          "dependencies": [
            1
          ],
          "details": "Design the discussion room data model and state management. Implement discussion scheduling and participant management. Create discussion topic and agenda setting functionality. Develop discussion moderation tools and rules enforcement mechanisms.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Implement LLM Integration for AI Mentors",
          "description": "Integrate LLM capabilities to simulate AI mentors that can participate in round-table discussions.",
          "dependencies": [
            3
          ],
          "details": "Select appropriate LLM models for mentor simulation. Develop prompt engineering templates for different mentor personas and expertise areas. Implement context management to maintain conversation coherence. Create fallback mechanisms for handling edge cases in discussions.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Build Discussion Output Formatter",
          "description": "Create a system to format and present round-table discussion outputs in a structured, readable format.",
          "dependencies": [
            3,
            4
          ],
          "details": "Design templates for discussion summaries and transcripts. Implement real-time formatting of ongoing discussions. Create exportable formats for discussion outcomes (PDF, markdown, etc.). Develop highlighting and annotation features for key insights.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Integrate Mentor System with Task Management",
          "description": "Connect the mentor system with the existing task management functionality to enable task-specific mentoring.",
          "dependencies": [
            2,
            3
          ],
          "details": "Create APIs to link tasks with relevant mentors based on expertise. Implement functionality to initiate discussions around specific tasks. Develop mechanisms for mentors to provide feedback and guidance on tasks. Build notification system for task-related mentor interactions.",
          "status": "pending"
        },
        {
          "id": 7,
          "title": "Test and Optimize Round-Table Discussions",
          "description": "Conduct comprehensive testing of the round-table discussion feature and optimize for performance and user experience.",
          "dependencies": [
            4,
            5,
            6
          ],
          "details": "Perform load testing with multiple concurrent discussions. Test AI mentor responses for quality and relevance. Optimize LLM usage for cost efficiency. Conduct user testing sessions and gather feedback. Implement performance monitoring and analytics for ongoing optimization.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 61,
      "title": "Implement Flexible AI Model Management",
      "description": "Currently, Task Master only supports Claude for main operations and Perplexity for research. Users are limited in flexibility when managing AI models. Adding comprehensive support for multiple popular AI models (OpenAI, Ollama, Gemini, OpenRouter, Grok) and providing intuitive CLI commands for model management will significantly enhance usability, transparency, and adaptability to user preferences and project-specific needs. This task will now leverage Vercel's AI SDK to streamline integration and management of these models.",
      "details": "### Proposed Solution\nImplement an intuitive CLI command for AI model management, leveraging Vercel's AI SDK for seamless integration:\n\n- `task-master models`: Lists currently configured models for main operations and research.\n- `task-master models --set-main=\"<model_name>\" --set-research=\"<model_name>\"`: Sets the desired models for main operations and research tasks respectively.\n\nSupported AI Models:\n- **Main Operations:** Claude (current default), OpenAI, Ollama, Gemini, OpenRouter\n- **Research Operations:** Perplexity (current default), OpenAI, Ollama, Grok\n\nIf a user specifies an invalid model, the CLI lists available models clearly.\n\n### Example CLI Usage\n\nList current models:\n```shell\ntask-master models\n```\nOutput example:\n```\nCurrent AI Model Configuration:\n- Main Operations: Claude\n- Research Operations: Perplexity\n```\n\nSet new models:\n```shell\ntask-master models --set-main=\"gemini\" --set-research=\"grok\"\n```\n\nAttempt invalid model:\n```shell\ntask-master models --set-main=\"invalidModel\"\n```\nOutput example:\n```\nError: \"invalidModel\" is not a valid model.\n\nAvailable models for Main Operations:\n- claude\n- openai\n- ollama\n- gemini\n- openrouter\n```\n\n### High-Level Workflow\n1. Update CLI parsing logic to handle new `models` command and associated flags.\n2. Consolidate all AI calls into `ai-services.js` for centralized management.\n3. Utilize Vercel's AI SDK to implement robust wrapper functions for each AI API:\n   - Claude (existing)\n   - Perplexity (existing)\n   - OpenAI\n   - Ollama\n   - Gemini\n   - OpenRouter\n   - Grok\n4. Update environment variables and provide clear documentation in `.env_example`:\n```env\n# MAIN_MODEL options: claude, openai, ollama, gemini, openrouter\nMAIN_MODEL=claude\n\n# RESEARCH_MODEL options: perplexity, openai, ollama, grok\nRESEARCH_MODEL=perplexity\n```\n5. Ensure dynamic model switching via environment variables or configuration management.\n6. Provide clear CLI feedback and validation of model names.\n\n### Vercel AI SDK Integration\n- Use Vercel's AI SDK to abstract API calls for supported models, ensuring consistent error handling and response formatting.\n- Implement a configuration layer to map model names to their respective Vercel SDK integrations.\n- Example pattern for integration:\n```javascript\nimport { createClient } from '@vercel/ai';\n\nconst clients = {\n  claude: createClient({ provider: 'anthropic', apiKey: process.env.ANTHROPIC_API_KEY }),\n  openai: createClient({ provider: 'openai', apiKey: process.env.OPENAI_API_KEY }),\n  ollama: createClient({ provider: 'ollama', apiKey: process.env.OLLAMA_API_KEY }),\n  gemini: createClient({ provider: 'gemini', apiKey: process.env.GEMINI_API_KEY }),\n  openrouter: createClient({ provider: 'openrouter', apiKey: process.env.OPENROUTER_API_KEY }),\n  perplexity: createClient({ provider: 'perplexity', apiKey: process.env.PERPLEXITY_API_KEY }),\n  grok: createClient({ provider: 'xai', apiKey: process.env.XAI_API_KEY })\n};\n\nexport function getClient(model) {\n  if (!clients[model]) {\n    throw new Error(`Invalid model: ${model}`);\n  }\n  return clients[model];\n}\n```\n- Leverage `generateText` and `streamText` functions from the SDK for text generation and streaming capabilities.\n- Ensure compatibility with serverless and edge deployments using Vercel's infrastructure.\n\n### Key Elements\n- Enhanced model visibility and intuitive management commands.\n- Centralized and robust handling of AI API integrations via Vercel AI SDK.\n- Clear CLI responses with detailed validation feedback.\n- Flexible, easy-to-understand environment configuration.\n\n### Implementation Considerations\n- Centralize all AI interactions through a single, maintainable module (`ai-services.js`).\n- Ensure comprehensive error handling for invalid model selections.\n- Clearly document environment variable options and their purposes.\n- Validate model names rigorously to prevent runtime errors.\n\n### Out of Scope (Future Considerations)\n- Automatic benchmarking or model performance comparison.\n- Dynamic runtime switching of models based on task type or complexity.",
      "testStrategy": "### Test Strategy\n1. **Unit Tests**:\n   - Test CLI commands for listing, setting, and validating models.\n   - Mock Vercel AI SDK calls to ensure proper integration and error handling.\n\n2. **Integration Tests**:\n   - Validate end-to-end functionality of model management commands.\n   - Test dynamic switching of models via environment variables.\n\n3. **Error Handling Tests**:\n   - Simulate invalid model names and verify error messages.\n   - Test API failures for each model provider and ensure graceful degradation.\n\n4. **Documentation Validation**:\n   - Verify that `.env_example` and CLI usage examples are accurate and comprehensive.\n\n5. **Performance Tests**:\n   - Measure response times for API calls through Vercel AI SDK.\n   - Ensure no significant latency is introduced by model switching.\n\n6. **SDK-Specific Tests**:\n   - Validate the behavior of `generateText` and `streamText` functions for supported models.\n   - Test compatibility with serverless and edge deployments.",
      "status": "done",
      "dependencies": [],
      "priority": "high",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Configuration Management Module",
          "description": "Develop a centralized configuration module to manage AI model settings and preferences, leveraging the Strategy pattern for model selection.",
          "dependencies": [],
          "details": "1. Create a new `config-manager.js` module to handle model configuration\n2. Implement functions to read/write model preferences to a local config file\n3. Define model validation logic with clear error messages\n4. Create mapping of valid models for main and research operations\n5. Implement getters and setters for model configuration\n6. Add utility functions to validate model names against available options\n7. Include default fallback models\n8. Testing approach: Write unit tests to verify config reading/writing and model validation logic\n\n<info added on 2025-04-14T21:54:28.887Z>\nHere's the additional information to add:\n\n```\nThe configuration management module should:\n\n1. Use a `.taskmasterconfig` JSON file in the project root directory to store model settings\n2. Structure the config file with two main keys: `main` and `research` for respective model selections\n3. Implement functions to locate the project root directory (using package.json as reference)\n4. Define constants for valid models:\n   ```javascript\n   const VALID_MAIN_MODELS = ['gpt-4', 'gpt-3.5-turbo', 'gpt-4-turbo'];\n   const VALID_RESEARCH_MODELS = ['gpt-4', 'gpt-4-turbo', 'claude-2'];\n   const DEFAULT_MAIN_MODEL = 'gpt-3.5-turbo';\n   const DEFAULT_RESEARCH_MODEL = 'gpt-4';\n   ```\n5. Implement model getters with priority order:\n   - First check `.taskmasterconfig` file\n   - Fall back to environment variables if config file missing/invalid\n   - Use defaults as last resort\n6. Implement model setters that validate input against valid model lists before updating config\n7. Keep API key management in `ai-services.js` using environment variables (don't store keys in config file)\n8. Add helper functions for config file operations:\n   ```javascript\n   function getConfigPath() { /* locate .taskmasterconfig */ }\n   function readConfig() { /* read and parse config file */ }\n   function writeConfig(config) { /* stringify and write config */ }\n   ```\n9. Include error handling for file operations and invalid configurations\n```\n</info added on 2025-04-14T21:54:28.887Z>\n\n<info added on 2025-04-14T22:52:29.551Z>\n```\nThe configuration management module should be updated to:\n\n1. Separate model configuration into provider and modelId components:\n   ```javascript\n   // Example config structure\n   {\n     \"models\": {\n       \"main\": {\n         \"provider\": \"openai\",\n         \"modelId\": \"gpt-3.5-turbo\"\n       },\n       \"research\": {\n         \"provider\": \"openai\",\n         \"modelId\": \"gpt-4\"\n       }\n     }\n   }\n   ```\n\n2. Define provider constants:\n   ```javascript\n   const VALID_MAIN_PROVIDERS = ['openai', 'anthropic', 'local'];\n   const VALID_RESEARCH_PROVIDERS = ['openai', 'anthropic', 'cohere'];\n   const DEFAULT_MAIN_PROVIDER = 'openai';\n   const DEFAULT_RESEARCH_PROVIDER = 'openai';\n   ```\n\n3. Implement optional MODEL_MAP for validation:\n   ```javascript\n   const MODEL_MAP = {\n     'openai': ['gpt-3.5-turbo', 'gpt-4', 'gpt-4-turbo'],\n     'anthropic': ['claude-2', 'claude-instant'],\n     'cohere': ['command', 'command-light'],\n     'local': ['llama2', 'mistral']\n   };\n   ```\n\n4. Update getter functions to handle provider/modelId separation:\n   ```javascript\n   function getMainProvider() { /* return provider with fallbacks */ }\n   function getMainModelId() { /* return modelId with fallbacks */ }\n   function getResearchProvider() { /* return provider with fallbacks */ }\n   function getResearchModelId() { /* return modelId with fallbacks */ }\n   ```\n\n5. Update setter functions to validate both provider and modelId:\n   ```javascript\n   function setMainModel(provider, modelId) {\n     // Validate provider is in VALID_MAIN_PROVIDERS\n     // Optionally validate modelId is valid for provider using MODEL_MAP\n     // Update config file with new values\n   }\n   ```\n\n6. Add utility functions for provider-specific validation:\n   ```javascript\n   function isValidProviderModelCombination(provider, modelId) {\n     return MODEL_MAP[provider]?.includes(modelId) || false;\n   }\n   ```\n\n7. Extend unit tests to cover provider/modelId separation, including:\n   - Testing provider validation\n   - Testing provider-modelId combination validation\n   - Verifying getters return correct provider and modelId values\n   - Confirming setters properly validate and store both components\n```\n</info added on 2025-04-14T22:52:29.551Z>",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 2,
          "title": "Implement CLI Command Parser for Model Management",
          "description": "Extend the CLI command parser to handle the new 'models' command and associated flags for model management.",
          "dependencies": [
            1
          ],
          "details": "1. Update the CLI command parser to recognize the 'models' command\n2. Add support for '--set-main' and '--set-research' flags\n3. Implement validation for command arguments\n4. Create help text and usage examples for the models command\n5. Add error handling for invalid command usage\n6. Connect CLI parser to the configuration manager\n7. Implement command output formatting for model listings\n8. Testing approach: Create integration tests that verify CLI commands correctly interact with the configuration manager",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 3,
          "title": "Integrate Vercel AI SDK and Create Client Factory",
          "description": "Set up Vercel AI SDK integration and implement a client factory pattern to create and manage AI model clients.",
          "dependencies": [
            1
          ],
          "details": "1. Install Vercel AI SDK: `npm install @vercel/ai`\n2. Create an `ai-client-factory.js` module that implements the Factory pattern\n3. Define client creation functions for each supported model (Claude, OpenAI, Ollama, Gemini, OpenRouter, Perplexity, Grok)\n4. Implement error handling for missing API keys or configuration issues\n5. Add caching mechanism to reuse existing clients\n6. Create a unified interface for all clients regardless of the underlying model\n7. Implement client validation to ensure proper initialization\n8. Testing approach: Mock API responses to test client creation and error handling\n\n<info added on 2025-04-14T23:02:30.519Z>\nHere's additional information for the client factory implementation:\n\nFor the client factory implementation:\n\n1. Structure the factory with a modular approach:\n```javascript\n// ai-client-factory.js\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createAnthropic } from '@ai-sdk/anthropic';\nimport { createGoogle } from '@ai-sdk/google';\nimport { createPerplexity } from '@ai-sdk/perplexity';\n\nconst clientCache = new Map();\n\nexport function createClientInstance(providerName, options = {}) {\n  // Implementation details below\n}\n```\n\n2. For OpenAI-compatible providers (Ollama), implement specific configuration:\n```javascript\ncase 'ollama':\n  const ollamaBaseUrl = process.env.OLLAMA_BASE_URL || 'http://localhost:11434';\n  return createOpenAI({\n    baseURL: ollamaBaseUrl,\n    apiKey: 'ollama', // Ollama doesn't require a real API key\n    ...options\n  });\n```\n\n3. Add provider-specific model mapping:\n```javascript\n// Model mapping helper\nconst getModelForProvider = (provider, requestedModel) => {\n  const modelMappings = {\n    openai: {\n      default: 'gpt-3.5-turbo',\n      // Add other mappings\n    },\n    anthropic: {\n      default: 'claude-3-opus-20240229',\n      // Add other mappings\n    },\n    // Add mappings for other providers\n  };\n  \n  return (modelMappings[provider] && modelMappings[provider][requestedModel]) \n    || modelMappings[provider]?.default \n    || requestedModel;\n};\n```\n\n4. Implement caching with provider+model as key:\n```javascript\nexport function getClient(providerName, model) {\n  const cacheKey = `${providerName}:${model || 'default'}`;\n  \n  if (clientCache.has(cacheKey)) {\n    return clientCache.get(cacheKey);\n  }\n  \n  const modelName = getModelForProvider(providerName, model);\n  const client = createClientInstance(providerName, { model: modelName });\n  clientCache.set(cacheKey, client);\n  \n  return client;\n}\n```\n\n5. Add detailed environment variable validation:\n```javascript\nfunction validateEnvironment(provider) {\n  const requirements = {\n    openai: ['OPENAI_API_KEY'],\n    anthropic: ['ANTHROPIC_API_KEY'],\n    google: ['GOOGLE_API_KEY'],\n    perplexity: ['PERPLEXITY_API_KEY'],\n    openrouter: ['OPENROUTER_API_KEY'],\n    ollama: ['OLLAMA_BASE_URL'],\n    xai: ['XAI_API_KEY']\n  };\n  \n  const missing = requirements[provider]?.filter(env => !process.env[env]) || [];\n  \n  if (missing.length > 0) {\n    throw new Error(`Missing environment variables for ${provider}: ${missing.join(', ')}`);\n  }\n}\n```\n\n6. Add Jest test examples:\n```javascript\n// ai-client-factory.test.js\ndescribe('AI Client Factory', () => {\n  beforeEach(() => {\n    // Mock environment variables\n    process.env.OPENAI_API_KEY = 'test-openai-key';\n    process.env.ANTHROPIC_API_KEY = 'test-anthropic-key';\n    // Add other mocks\n  });\n  \n  test('creates OpenAI client with correct configuration', () => {\n    const client = getClient('openai');\n    expect(client).toBeDefined();\n    // Add assertions for client configuration\n  });\n  \n  test('throws error when environment variables are missing', () => {\n    delete process.env.OPENAI_API_KEY;\n    expect(() => getClient('openai')).toThrow(/Missing environment variables/);\n  });\n  \n  // Add tests for other providers\n});\n```\n</info added on 2025-04-14T23:02:30.519Z>",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 4,
          "title": "Develop Centralized AI Services Module",
          "description": "Create a centralized AI services module that abstracts all AI interactions through a unified interface, using the Decorator pattern for adding functionality like logging and retries.",
          "dependencies": [
            3
          ],
          "details": "1. Create `ai-services.js` module to consolidate all AI model interactions\n2. Implement wrapper functions for text generation and streaming\n3. Add retry mechanisms for handling API rate limits and transient errors\n4. Implement logging for all AI interactions for observability\n5. Create model-specific adapters to normalize responses across different providers\n6. Add caching layer for frequently used responses to optimize performance\n7. Implement graceful fallback mechanisms when primary models fail\n8. Testing approach: Create unit tests with mocked responses to verify service behavior\n\n<info added on 2025-04-19T23:51:22.219Z>\nBased on the exploration findings, here's additional information for the AI services module refactoring:\n\nThe existing `ai-services.js` should be refactored to:\n\n1. Leverage the `ai-client-factory.js` for model instantiation while providing a higher-level service abstraction\n2. Implement a layered architecture:\n   - Base service layer handling common functionality (retries, logging, caching)\n   - Model-specific service implementations extending the base\n   - Facade pattern to provide a unified API for all consumers\n\n3. Integration points:\n   - Replace direct OpenAI client usage with factory-provided clients\n   - Maintain backward compatibility with existing service consumers\n   - Add service registration mechanism for new AI providers\n\n4. Performance considerations:\n   - Implement request batching for high-volume operations\n   - Add request priority queuing for critical vs non-critical operations\n   - Implement circuit breaker pattern to prevent cascading failures\n\n5. Monitoring enhancements:\n   - Add detailed telemetry for response times, token usage, and costs\n   - Implement standardized error classification for better diagnostics\n\n6. Implementation sequence:\n   - Start with abstract base service class\n   - Refactor existing OpenAI implementations\n   - Add adapter layer for new providers\n   - Implement the unified facade\n</info added on 2025-04-19T23:51:22.219Z>",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 5,
          "title": "Implement Environment Variable Management",
          "description": "Update environment variable handling to support multiple AI models and create documentation for configuration options.",
          "dependencies": [
            1,
            3
          ],
          "details": "1. Update `.env.example` with all required API keys for supported models\n2. Implement environment variable validation on startup\n3. Create clear error messages for missing or invalid environment variables\n4. Add support for model-specific configuration options\n5. Document all environment variables and their purposes\n6. Implement a check to ensure required API keys are present for selected models\n7. Add support for optional configuration parameters for each model\n8. Testing approach: Create tests that verify environment variable validation logic",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 6,
          "title": "Implement Model Listing Command",
          "description": "Implement the 'task-master models' command to display currently configured models and available options.",
          "dependencies": [
            1,
            2,
            4
          ],
          "details": "1. Create handler for the models command without flags\n2. Implement formatted output showing current model configuration\n3. Add color-coding for better readability using a library like chalk\n4. Include version information for each configured model\n5. Show API status indicators (connected/disconnected)\n6. Display usage examples for changing models\n7. Add support for verbose output with additional details\n8. Testing approach: Create integration tests that verify correct output formatting and content",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 7,
          "title": "Implement Model Setting Commands",
          "description": "Implement the commands to set main and research models with proper validation and feedback.",
          "dependencies": [
            1,
            2,
            4,
            6
          ],
          "details": "1. Create handlers for '--set-main' and '--set-research' flags\n2. Implement validation logic for model names\n3. Add clear error messages for invalid model selections\n4. Implement confirmation messages for successful model changes\n5. Add support for setting both models in a single command\n6. Implement dry-run option to validate without making changes\n7. Add verbose output option for debugging\n8. Testing approach: Create integration tests that verify model setting functionality with various inputs",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 8,
          "title": "Update Main Task Processing Logic",
          "description": "Refactor the main task processing logic to use the new AI services module and support dynamic model selection.",
          "dependencies": [
            4,
            5,
            "61.18"
          ],
          "details": "1. Update task processing functions to use the centralized AI services\n2. Implement dynamic model selection based on configuration\n3. Add error handling for model-specific failures\n4. Implement graceful degradation when preferred models are unavailable\n5. Update prompts to be model-agnostic where possible\n6. Add telemetry for model performance monitoring\n7. Implement response validation to ensure quality across different models\n8. Testing approach: Create integration tests that verify task processing with different model configurations\n\n<info added on 2025-04-20T03:55:56.310Z>\nWhen updating the main task processing logic, implement the following changes to align with the new configuration system:\n\n1. Replace direct environment variable access with calls to the configuration manager:\n   ```javascript\n   // Before\n   const apiKey = process.env.OPENAI_API_KEY;\n   const modelId = process.env.MAIN_MODEL || \"gpt-4\";\n   \n   // After\n   import { getMainProvider, getMainModelId, getMainMaxTokens, getMainTemperature } from './config-manager.js';\n   \n   const provider = getMainProvider();\n   const modelId = getMainModelId();\n   const maxTokens = getMainMaxTokens();\n   const temperature = getMainTemperature();\n   ```\n\n2. Implement model fallback logic using the configuration hierarchy:\n   ```javascript\n   async function processTaskWithFallback(task) {\n     try {\n       return await processWithModel(task, getMainModelId());\n     } catch (error) {\n       logger.warn(`Primary model failed: ${error.message}`);\n       const fallbackModel = getMainFallbackModelId();\n       if (fallbackModel) {\n         return await processWithModel(task, fallbackModel);\n       }\n       throw error;\n     }\n   }\n   ```\n\n3. Add configuration-aware telemetry points to track model usage and performance:\n   ```javascript\n   function trackModelPerformance(modelId, startTime, success) {\n     const duration = Date.now() - startTime;\n     telemetry.trackEvent('model_usage', {\n       modelId,\n       provider: getMainProvider(),\n       duration,\n       success,\n       configVersion: getConfigVersion()\n     });\n   }\n   ```\n\n4. Ensure all prompt templates are loaded through the configuration system rather than hardcoded:\n   ```javascript\n   const promptTemplate = getPromptTemplate('task_processing');\n   const prompt = formatPrompt(promptTemplate, { task: taskData });\n   ```\n</info added on 2025-04-20T03:55:56.310Z>",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 9,
          "title": "Update Research Processing Logic",
          "description": "Refactor the research processing logic to use the new AI services module and support dynamic model selection for research operations.",
          "dependencies": [
            4,
            5,
            8,
            "61.18"
          ],
          "details": "1. Update research functions to use the centralized AI services\n2. Implement dynamic model selection for research operations\n3. Add specialized error handling for research-specific issues\n4. Optimize prompts for research-focused models\n5. Implement result caching for research operations\n6. Add support for model-specific research parameters\n7. Create fallback mechanisms for research operations\n8. Testing approach: Create integration tests that verify research functionality with different model configurations\n\n<info added on 2025-04-20T03:55:39.633Z>\nWhen implementing the refactored research processing logic, ensure the following:\n\n1. Replace direct environment variable access with the new configuration system:\n   ```javascript\n   // Old approach\n   const apiKey = process.env.OPENAI_API_KEY;\n   const model = \"gpt-4\";\n   \n   // New approach\n   import { getResearchProvider, getResearchModelId, getResearchMaxTokens, \n            getResearchTemperature } from './config-manager.js';\n   \n   const provider = getResearchProvider();\n   const modelId = getResearchModelId();\n   const maxTokens = getResearchMaxTokens();\n   const temperature = getResearchTemperature();\n   ```\n\n2. Implement model fallback chains using the configuration system:\n   ```javascript\n   async function performResearch(query) {\n     try {\n       return await callAIService({\n         provider: getResearchProvider(),\n         modelId: getResearchModelId(),\n         maxTokens: getResearchMaxTokens(),\n         temperature: getResearchTemperature()\n       });\n     } catch (error) {\n       logger.warn(`Primary research model failed: ${error.message}`);\n       return await callAIService({\n         provider: getResearchProvider('fallback'),\n         modelId: getResearchModelId('fallback'),\n         maxTokens: getResearchMaxTokens('fallback'),\n         temperature: getResearchTemperature('fallback')\n       });\n     }\n   }\n   ```\n\n3. Add support for dynamic parameter adjustment based on research type:\n   ```javascript\n   function getResearchParameters(researchType) {\n     // Get base parameters\n     const baseParams = {\n       provider: getResearchProvider(),\n       modelId: getResearchModelId(),\n       maxTokens: getResearchMaxTokens(),\n       temperature: getResearchTemperature()\n     };\n     \n     // Adjust based on research type\n     switch(researchType) {\n       case 'deep':\n         return {...baseParams, maxTokens: baseParams.maxTokens * 1.5};\n       case 'creative':\n         return {...baseParams, temperature: Math.min(baseParams.temperature + 0.2, 1.0)};\n       case 'factual':\n         return {...baseParams, temperature: Math.max(baseParams.temperature - 0.2, 0)};\n       default:\n         return baseParams;\n     }\n   }\n   ```\n\n4. Ensure the caching mechanism uses configuration-based TTL settings:\n   ```javascript\n   const researchCache = new Cache({\n     ttl: getResearchCacheTTL(),\n     maxSize: getResearchCacheMaxSize()\n   });\n   ```\n</info added on 2025-04-20T03:55:39.633Z>",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 10,
          "title": "Create Comprehensive Documentation and Examples",
          "description": "Develop comprehensive documentation for the new model management features, including examples, troubleshooting guides, and best practices.",
          "dependencies": [
            6,
            7,
            8,
            9
          ],
          "details": "1. Update README.md with new model management commands\n2. Create usage examples for all supported models\n3. Document environment variable requirements for each model\n4. Create troubleshooting guide for common issues\n5. Add performance considerations and best practices\n6. Document API key acquisition process for each supported service\n7. Create comparison chart of model capabilities and limitations\n8. Testing approach: Conduct user testing with the documentation to ensure clarity and completeness\n\n<info added on 2025-04-20T03:55:20.433Z>\n## Documentation Update for Configuration System Refactoring\n\n### Configuration System Architecture\n- Document the separation between environment variables and configuration file:\n  - API keys: Sourced exclusively from environment variables (process.env or session.env)\n  - All other settings: Centralized in `.taskmasterconfig` JSON file\n\n### `.taskmasterconfig` Structure\n```json\n{\n  \"models\": {\n    \"completion\": \"gpt-3.5-turbo\",\n    \"chat\": \"gpt-4\",\n    \"embedding\": \"text-embedding-ada-002\"\n  },\n  \"parameters\": {\n    \"temperature\": 0.7,\n    \"maxTokens\": 2000,\n    \"topP\": 1\n  },\n  \"logging\": {\n    \"enabled\": true,\n    \"level\": \"info\"\n  },\n  \"defaults\": {\n    \"outputFormat\": \"markdown\"\n  }\n}\n```\n\n### Configuration Access Patterns\n- Document the getter functions in `config-manager.js`:\n  - `getModelForRole(role)`: Returns configured model for a specific role\n  - `getParameter(name)`: Retrieves model parameters\n  - `getLoggingConfig()`: Access logging settings\n  - Example usage: `const completionModel = getModelForRole('completion')`\n\n### Environment Variable Resolution\n- Explain the `resolveEnvVariable(key)` function:\n  - Checks both process.env and session.env\n  - Prioritizes session variables over process variables\n  - Returns null if variable not found\n\n### Configuration Precedence\n- Document the order of precedence:\n  1. Command-line arguments (highest priority)\n  2. Session environment variables\n  3. Process environment variables\n  4. `.taskmasterconfig` settings\n  5. Hardcoded defaults (lowest priority)\n\n### Migration Guide\n- Steps for users to migrate from previous configuration approach\n- How to verify configuration is correctly loaded\n</info added on 2025-04-20T03:55:20.433Z>",
          "status": "done",
          "parentTaskId": 61
        },
        {
          "id": 11,
          "title": "Refactor PRD Parsing to use generateObjectService",
          "description": "Update PRD processing logic (callClaude, processClaudeResponse, handleStreamingRequest in ai-services.js) to use the new `generateObjectService` from `ai-services-unified.js` with an appropriate Zod schema.",
          "details": "\n\n<info added on 2025-04-20T03:55:01.707Z>\nThe PRD parsing refactoring should align with the new configuration system architecture. When implementing this change:\n\n1. Replace direct environment variable access with `resolveEnvVariable` calls for API keys.\n\n2. Remove any hardcoded model names or parameters in the PRD processing functions. Instead, use the config-manager.js getters:\n   - `getModelForRole('prd')` to determine the appropriate model\n   - `getModelParameters('prd')` to retrieve temperature, maxTokens, etc.\n\n3. When constructing the generateObjectService call, ensure parameters are sourced from config:\n```javascript\nconst modelConfig = getModelParameters('prd');\nconst model = getModelForRole('prd');\n\nconst result = await generateObjectService({\n  model,\n  temperature: modelConfig.temperature,\n  maxTokens: modelConfig.maxTokens,\n  // other parameters as needed\n  schema: prdSchema,\n  // existing prompt/context parameters\n});\n```\n\n4. Update any logging to respect the logging configuration from config-manager (e.g., `isLoggingEnabled('ai')`)\n\n5. Ensure any default values previously hardcoded are now retrieved from the configuration system.\n</info added on 2025-04-20T03:55:01.707Z>",
          "status": "done",
          "dependencies": [
            "61.23"
          ],
          "parentTaskId": 61
        },
        {
          "id": 12,
          "title": "Refactor Basic Subtask Generation to use generateObjectService",
          "description": "Update the `generateSubtasks` function in `ai-services.js` to use the new `generateObjectService` from `ai-services-unified.js` with a Zod schema for the subtask array.",
          "details": "\n\n<info added on 2025-04-20T03:54:45.542Z>\nThe refactoring should leverage the new configuration system:\n\n1. Replace direct model references with calls to config-manager.js getters:\n   ```javascript\n   const { getModelForRole, getModelParams } = require('./config-manager');\n   \n   // Instead of hardcoded models/parameters:\n   const model = getModelForRole('subtask-generator');\n   const modelParams = getModelParams('subtask-generator');\n   ```\n\n2. Update API key handling to use the resolveEnvVariable pattern:\n   ```javascript\n   const { resolveEnvVariable } = require('./utils');\n   const apiKey = resolveEnvVariable('OPENAI_API_KEY');\n   ```\n\n3. When calling generateObjectService, pass the configuration parameters:\n   ```javascript\n   const result = await generateObjectService({\n     schema: subtasksArraySchema,\n     prompt: subtaskPrompt,\n     model: model,\n     temperature: modelParams.temperature,\n     maxTokens: modelParams.maxTokens,\n     // Other parameters from config\n   });\n   ```\n\n4. Add error handling that respects logging configuration:\n   ```javascript\n   const { isLoggingEnabled } = require('./config-manager');\n   \n   try {\n     // Generation code\n   } catch (error) {\n     if (isLoggingEnabled('errors')) {\n       console.error('Subtask generation error:', error);\n     }\n     throw error;\n   }\n   ```\n</info added on 2025-04-20T03:54:45.542Z>",
          "status": "done",
          "dependencies": [
            "61.23"
          ],
          "parentTaskId": 61
        },
        {
          "id": 13,
          "title": "Refactor Research Subtask Generation to use generateObjectService",
          "description": "Update the `generateSubtasksWithPerplexity` function in `ai-services.js` to first perform research (potentially keeping the Perplexity call separate or adapting it) and then use `generateObjectService` from `ai-services-unified.js` with research results included in the prompt.",
          "details": "\n\n<info added on 2025-04-20T03:54:26.882Z>\nThe refactoring should align with the new configuration system by:\n\n1. Replace direct environment variable access with `resolveEnvVariable` for API keys\n2. Use the config-manager.js getters to retrieve model parameters:\n   - Replace hardcoded model names with `getModelForRole('research')`\n   - Use `getParametersForRole('research')` to get temperature, maxTokens, etc.\n3. Implement proper error handling that respects the `getLoggingConfig()` settings\n4. Example implementation pattern:\n```javascript\nconst { getModelForRole, getParametersForRole, getLoggingConfig } = require('./config-manager');\nconst { resolveEnvVariable } = require('./environment-utils');\n\n// In the refactored function:\nconst researchModel = getModelForRole('research');\nconst { temperature, maxTokens } = getParametersForRole('research');\nconst apiKey = resolveEnvVariable('PERPLEXITY_API_KEY');\nconst { verbose } = getLoggingConfig();\n\n// Then use these variables in the API call configuration\n```\n5. Ensure the transition to generateObjectService maintains all existing functionality while leveraging the new configuration system\n</info added on 2025-04-20T03:54:26.882Z>",
          "status": "done",
          "dependencies": [
            "61.23"
          ],
          "parentTaskId": 61
        },
        {
          "id": 14,
          "title": "Refactor Research Task Description Generation to use generateObjectService",
          "description": "Update the `generateTaskDescriptionWithPerplexity` function in `ai-services.js` to first perform research and then use `generateObjectService` from `ai-services-unified.js` to generate the structured task description.",
          "details": "\n\n<info added on 2025-04-20T03:54:04.420Z>\nThe refactoring should incorporate the new configuration management system:\n\n1. Update imports to include the config-manager:\n```javascript\nconst { getModelForRole, getParametersForRole } = require('./config-manager');\n```\n\n2. Replace any hardcoded model selections or parameters with config-manager calls:\n```javascript\n// Replace direct model references like:\n// const model = \"perplexity-model-7b-online\" \n// With:\nconst model = getModelForRole('research');\nconst parameters = getParametersForRole('research');\n```\n\n3. For API key handling, use the resolveEnvVariable pattern:\n```javascript\nconst apiKey = resolveEnvVariable('PERPLEXITY_API_KEY');\n```\n\n4. When calling generateObjectService, pass the configuration-derived parameters:\n```javascript\nreturn generateObjectService({\n  prompt: researchResults,\n  schema: taskDescriptionSchema,\n  role: 'taskDescription',\n  // Config-driven parameters will be applied within generateObjectService\n});\n```\n\n5. Remove any hardcoded configuration values, ensuring all settings are retrieved from the centralized configuration system.\n</info added on 2025-04-20T03:54:04.420Z>",
          "status": "done",
          "dependencies": [
            "61.23"
          ],
          "parentTaskId": 61
        },
        {
          "id": 15,
          "title": "Refactor Complexity Analysis AI Call to use generateObjectService",
          "description": "Update the logic that calls the AI after using `generateComplexityAnalysisPrompt` in `ai-services.js` to use the new `generateObjectService` from `ai-services-unified.js` with a Zod schema for the complexity report.",
          "details": "\n\n<info added on 2025-04-20T03:53:46.120Z>\nThe complexity analysis AI call should be updated to align with the new configuration system architecture. When refactoring to use `generateObjectService`, implement the following changes:\n\n1. Replace direct model references with calls to the appropriate config getter:\n   ```javascript\n   const modelName = getComplexityAnalysisModel(); // Use the specific getter from config-manager.js\n   ```\n\n2. Retrieve AI parameters from the config system:\n   ```javascript\n   const temperature = getAITemperature('complexityAnalysis');\n   const maxTokens = getAIMaxTokens('complexityAnalysis');\n   ```\n\n3. When constructing the call to `generateObjectService`, pass these configuration values:\n   ```javascript\n   const result = await generateObjectService({\n     prompt,\n     schema: complexityReportSchema,\n     modelName,\n     temperature,\n     maxTokens,\n     sessionEnv: session?.env\n   });\n   ```\n\n4. Ensure API key resolution uses the `resolveEnvVariable` helper:\n   ```javascript\n   // Don't hardcode API keys or directly access process.env\n   // The generateObjectService should handle this internally with resolveEnvVariable\n   ```\n\n5. Add logging configuration based on settings:\n   ```javascript\n   const enableLogging = getAILoggingEnabled('complexityAnalysis');\n   if (enableLogging) {\n     // Use the logging mechanism defined in the configuration\n   }\n   ```\n</info added on 2025-04-20T03:53:46.120Z>",
          "status": "done",
          "dependencies": [
            "61.23"
          ],
          "parentTaskId": 61
        },
        {
          "id": 16,
          "title": "Refactor Task Addition AI Call to use generateObjectService",
          "description": "Update the logic that calls the AI after using `_buildAddTaskPrompt` in `ai-services.js` to use the new `generateObjectService` from `ai-services-unified.js` with a Zod schema for the single task object.",
          "details": "\n\n<info added on 2025-04-20T03:53:27.455Z>\nTo implement this refactoring, you'll need to:\n\n1. Replace direct AI calls with the new `generateObjectService` approach:\n   ```javascript\n   // OLD approach\n   const aiResponse = await callLLM(prompt, modelName, temperature, maxTokens);\n   const task = parseAIResponseToTask(aiResponse);\n   \n   // NEW approach using generateObjectService with config-manager\n   import { generateObjectService } from '../services/ai-services-unified.js';\n   import { getAIModelForRole, getAITemperature, getAIMaxTokens } from '../config/config-manager.js';\n   import { taskSchema } from '../schemas/task-schema.js'; // Create this Zod schema for a single task\n   \n   const modelName = getAIModelForRole('taskCreation');\n   const temperature = getAITemperature('taskCreation');\n   const maxTokens = getAIMaxTokens('taskCreation');\n   \n   const task = await generateObjectService({\n     prompt: _buildAddTaskPrompt(...),\n     schema: taskSchema,\n     modelName,\n     temperature,\n     maxTokens\n   });\n   ```\n\n2. Create a Zod schema for the task object in a new file `schemas/task-schema.js` that defines the expected structure.\n\n3. Ensure API key resolution uses the new pattern:\n   ```javascript\n   // This happens inside generateObjectService, but verify it uses:\n   import { resolveEnvVariable } from '../config/config-manager.js';\n   // Instead of direct process.env access\n   ```\n\n4. Update any error handling to match the new service's error patterns.\n</info added on 2025-04-20T03:53:27.455Z>",
          "status": "done",
          "dependencies": [
            "61.23"
          ],
          "parentTaskId": 61
        },
        {
          "id": 17,
          "title": "Refactor General Chat/Update AI Calls",
          "description": "Refactor functions like `sendChatWithContext` (and potentially related task update functions in `task-manager.js` if they make direct AI calls) to use `streamTextService` or `generateTextService` from `ai-services-unified.js`.",
          "details": "\n\n<info added on 2025-04-20T03:53:03.709Z>\nWhen refactoring `sendChatWithContext` and related functions, ensure they align with the new configuration system:\n\n1. Replace direct model references with config getter calls:\n   ```javascript\n   // Before\n   const model = \"gpt-4\";\n   \n   // After\n   import { getModelForRole } from './config-manager.js';\n   const model = getModelForRole('chat'); // or appropriate role\n   ```\n\n2. Extract AI parameters from config rather than hardcoding:\n   ```javascript\n   import { getAIParameters } from './config-manager.js';\n   const { temperature, maxTokens } = getAIParameters('chat');\n   ```\n\n3. When calling `streamTextService` or `generateTextService`, pass parameters from config:\n   ```javascript\n   await streamTextService({\n     messages,\n     model: getModelForRole('chat'),\n     temperature: getAIParameters('chat').temperature,\n     // other parameters as needed\n   });\n   ```\n\n4. For logging control, check config settings:\n   ```javascript\n   import { isLoggingEnabled } from './config-manager.js';\n   \n   if (isLoggingEnabled('aiCalls')) {\n     console.log('AI request:', messages);\n   }\n   ```\n\n5. Ensure any default behaviors respect configuration defaults rather than hardcoded values.\n</info added on 2025-04-20T03:53:03.709Z>",
          "status": "done",
          "dependencies": [
            "61.23"
          ],
          "parentTaskId": 61
        },
        {
          "id": 18,
          "title": "Refactor Callers of AI Parsing Utilities",
          "description": "Update the code that calls `parseSubtasksFromText`, `parseTaskJsonResponse`, and `parseTasksFromCompletion` to instead directly handle the structured JSON output provided by `generateObjectService` (as the refactored AI calls will now use it).",
          "details": "\n\n<info added on 2025-04-20T03:52:45.518Z>\nThe refactoring of callers to AI parsing utilities should align with the new configuration system. When updating these callers:\n\n1. Replace direct API key references with calls to the configuration system using `resolveEnvVariable` for sensitive credentials.\n\n2. Update model selection logic to use the centralized configuration from `.taskmasterconfig` via the getter functions in `config-manager.js`. For example:\n   ```javascript\n   // Old approach\n   const model = \"gpt-4\";\n   \n   // New approach\n   import { getModelForRole } from './config-manager';\n   const model = getModelForRole('parsing'); // or appropriate role\n   ```\n\n3. Similarly, replace hardcoded parameters with configuration-based values:\n   ```javascript\n   // Old approach\n   const maxTokens = 2000;\n   const temperature = 0.2;\n   \n   // New approach\n   import { getAIParameterValue } from './config-manager';\n   const maxTokens = getAIParameterValue('maxTokens', 'parsing');\n   const temperature = getAIParameterValue('temperature', 'parsing');\n   ```\n\n4. Ensure logging behavior respects the centralized logging configuration settings.\n\n5. When calling `generateObjectService`, pass the appropriate configuration context to ensure it uses the correct settings from the centralized configuration system.\n</info added on 2025-04-20T03:52:45.518Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 19,
          "title": "Refactor `updateSubtaskById` AI Call",
          "description": "Refactor the AI call within `updateSubtaskById` in `task-manager.js` (which generates additional information based on a prompt) to use the appropriate unified service function (e.g., `generateTextService`) from `ai-services-unified.js`.",
          "details": "\n\n<info added on 2025-04-20T03:52:28.196Z>\nThe `updateSubtaskById` function currently makes direct AI calls with hardcoded parameters. When refactoring to use the unified service:\n\n1. Replace direct OpenAI calls with `generateTextService` from `ai-services-unified.js`\n2. Use configuration parameters from `config-manager.js`:\n   - Replace hardcoded model with `getMainModel()`\n   - Use `getMainMaxTokens()` for token limits\n   - Apply `getMainTemperature()` for response randomness\n3. Ensure prompt construction remains consistent but passes these dynamic parameters\n4. Handle API key resolution through the unified service (which uses `resolveEnvVariable`)\n5. Update error handling to work with the unified service response format\n6. If the function uses any logging, ensure it respects `getLoggingEnabled()` setting\n\nExample refactoring pattern:\n```javascript\n// Before\nconst completion = await openai.chat.completions.create({\n  model: \"gpt-4\",\n  temperature: 0.7,\n  max_tokens: 1000,\n  messages: [/* prompt messages */]\n});\n\n// After\nconst completion = await generateTextService({\n  model: getMainModel(),\n  temperature: getMainTemperature(),\n  max_tokens: getMainMaxTokens(),\n  messages: [/* prompt messages */]\n});\n```\n</info added on 2025-04-20T03:52:28.196Z>\n\n<info added on 2025-04-22T06:05:42.437Z>\n- When testing the non-streaming `generateTextService` call within `updateSubtaskById`, ensure that the function awaits the full response before proceeding with subtask updates. This allows you to validate that the unified service returns the expected structure (e.g., `completion.choices.message.content`) and that error handling logic correctly interprets any error objects or status codes returned by the service.\n\n- Mock or stub the `generateTextService` in unit tests to simulate both successful and failed completions. For example, verify that when the service returns a valid completion, the subtask is updated with the generated content, and when an error is returned, the error handling path is triggered and logged appropriately.\n\n- Confirm that the non-streaming mode does not emit partial results or require event-based handling; the function should only process the final, complete response.\n\n- Example test assertion:\n  ```javascript\n  // Mocked response from generateTextService\n  const mockCompletion = {\n    choices: [{ message: { content: \"Generated subtask details.\" } }]\n  };\n  generateTextService.mockResolvedValue(mockCompletion);\n\n  // Call updateSubtaskById and assert the subtask is updated\n  await updateSubtaskById(...);\n  expect(subtask.details).toBe(\"Generated subtask details.\");\n  ```\n\n- If the unified service supports both streaming and non-streaming modes, explicitly set or verify the `stream` parameter is `false` (or omitted) to ensure non-streaming behavior during these tests.\n</info added on 2025-04-22T06:05:42.437Z>\n\n<info added on 2025-04-22T06:20:19.747Z>\nWhen testing the non-streaming `generateTextService` call in `updateSubtaskById`, implement these verification steps:\n\n1. Add unit tests that verify proper parameter transformation between the old and new implementation:\n   ```javascript\n   test('should correctly transform parameters when calling generateTextService', async () => {\n     // Setup mocks for config values\n     jest.spyOn(configManager, 'getMainModel').mockReturnValue('gpt-4');\n     jest.spyOn(configManager, 'getMainTemperature').mockReturnValue(0.7);\n     jest.spyOn(configManager, 'getMainMaxTokens').mockReturnValue(1000);\n     \n     const generateTextServiceSpy = jest.spyOn(aiServices, 'generateTextService')\n       .mockResolvedValue({ choices: [{ message: { content: 'test content' } }] });\n     \n     await updateSubtaskById(/* params */);\n     \n     // Verify the service was called with correct transformed parameters\n     expect(generateTextServiceSpy).toHaveBeenCalledWith({\n       model: 'gpt-4',\n       temperature: 0.7,\n       max_tokens: 1000,\n       messages: expect.any(Array)\n     });\n   });\n   ```\n\n2. Implement response validation to ensure the subtask content is properly extracted:\n   ```javascript\n   // In updateSubtaskById function\n   try {\n     const completion = await generateTextService({\n       // parameters\n     });\n     \n     // Validate response structure before using\n     if (!completion?.choices?.[0]?.message?.content) {\n       throw new Error('Invalid response structure from AI service');\n     }\n     \n     // Continue with updating subtask\n   } catch (error) {\n     // Enhanced error handling\n   }\n   ```\n\n3. Add integration tests that verify the end-to-end flow with actual configuration values.\n</info added on 2025-04-22T06:20:19.747Z>\n\n<info added on 2025-04-22T06:23:23.247Z>\n<info added on 2025-04-22T06:35:14.892Z>\nWhen testing the non-streaming `generateTextService` call in `updateSubtaskById`, implement these specific verification steps:\n\n1. Create a dedicated test fixture that isolates the AI service interaction:\n   ```javascript\n   describe('updateSubtaskById AI integration', () => {\n     beforeEach(() => {\n       // Reset all mocks and spies\n       jest.clearAllMocks();\n       // Setup environment with controlled config values\n       process.env.OPENAI_API_KEY = 'test-key';\n     });\n     \n     // Test cases follow...\n   });\n   ```\n\n2. Test error propagation from the unified service:\n   ```javascript\n   test('should properly handle AI service errors', async () => {\n     const mockError = new Error('Service unavailable');\n     mockError.status = 503;\n     jest.spyOn(aiServices, 'generateTextService').mockRejectedValue(mockError);\n     \n     // Capture console errors if needed\n     const consoleSpy = jest.spyOn(console, 'error').mockImplementation();\n     \n     // Execute with error expectation\n     await expect(updateSubtaskById(1, { prompt: 'test' })).rejects.toThrow();\n     \n     // Verify error was logged with appropriate context\n     expect(consoleSpy).toHaveBeenCalledWith(\n       expect.stringContaining('AI service error'),\n       expect.objectContaining({ status: 503 })\n     );\n   });\n   ```\n\n3. Verify that the function correctly preserves existing subtask content when appending new AI-generated information:\n   ```javascript\n   test('should preserve existing content when appending AI-generated details', async () => {\n     // Setup mock subtask with existing content\n     const mockSubtask = {\n       id: 1,\n       details: 'Existing details.\\n\\n'\n     };\n     \n     // Mock database retrieval\n     getSubtaskById.mockResolvedValue(mockSubtask);\n     \n     // Mock AI response\n     generateTextService.mockResolvedValue({\n       choices: [{ message: { content: 'New AI content.' } }]\n     });\n     \n     await updateSubtaskById(1, { prompt: 'Enhance this subtask' });\n     \n     // Verify the update preserves existing content\n     expect(updateSubtaskInDb).toHaveBeenCalledWith(\n       1,\n       expect.objectContaining({\n         details: expect.stringContaining('Existing details.\\n\\n<info added on')\n       })\n     );\n     \n     // Verify the new content was added\n     expect(updateSubtaskInDb).toHaveBeenCalledWith(\n       1,\n       expect.objectContaining({\n         details: expect.stringContaining('New AI content.')\n       })\n     );\n   });\n   ```\n\n4. Test that the function correctly formats the timestamp and wraps the AI-generated content:\n   ```javascript\n   test('should format timestamp and wrap content correctly', async () => {\n     // Mock date for consistent testing\n     const mockDate = new Date('2025-04-22T10:00:00Z');\n     jest.spyOn(global, 'Date').mockImplementation(() => mockDate);\n     \n     // Setup and execute test\n     // ...\n     \n     // Verify correct formatting\n     expect(updateSubtaskInDb).toHaveBeenCalledWith(\n       expect.any(Number),\n       expect.objectContaining({\n         details: expect.stringMatching(\n           /<info added on 2025-04-22T10:00:00\\.000Z>\\n.*\\n<\\/info added on 2025-04-22T10:00:00\\.000Z>/s\n         )\n       })\n     );\n   });\n   ```\n\n5. Verify that the function correctly handles the case when no existing details are present:\n   ```javascript\n   test('should handle subtasks with no existing details', async () => {\n     // Setup mock subtask with no details\n     const mockSubtask = { id: 1 };\n     getSubtaskById.mockResolvedValue(mockSubtask);\n     \n     // Execute test\n     // ...\n     \n     // Verify details were initialized properly\n     expect(updateSubtaskInDb).toHaveBeenCalledWith(\n       1,\n       expect.objectContaining({\n         details: expect.stringMatching(/^<info added on/)\n       })\n     );\n   });\n   ```\n</info added on 2025-04-22T06:35:14.892Z>\n</info added on 2025-04-22T06:23:23.247Z>",
          "status": "done",
          "dependencies": [
            "61.23"
          ],
          "parentTaskId": 61
        },
        {
          "id": 20,
          "title": "Implement `anthropic.js` Provider Module using Vercel AI SDK",
          "description": "Create and implement the `anthropic.js` module within `src/ai-providers/`. This module should contain functions to interact with the Anthropic API (streaming and non-streaming) using the **Vercel AI SDK**, adhering to the standardized input/output format defined for `ai-services-unified.js`.",
          "details": "\n\n<info added on 2025-04-24T02:54:40.326Z>\n- Use the `@ai-sdk/anthropic` package to implement the provider module. You can import the default provider instance with `import { anthropic } from '@ai-sdk/anthropic'`, or create a custom instance using `createAnthropic` if you need to specify custom headers, API key, or base URL (such as for beta features or proxying)[1][4].\n\n- To address persistent 'Not Found' errors, ensure the model name matches the latest Anthropic model IDs (e.g., `claude-3-haiku-20240307`, `claude-3-5-sonnet-20241022`). Model naming is case-sensitive and must match Anthropic's published versions[4][5].\n\n- If you require custom headers (such as for beta features), use the `createAnthropic` function and pass a `headers` object. For example:\n  ```js\n  import { createAnthropic } from '@ai-sdk/anthropic';\n  const anthropic = createAnthropic({\n    apiKey: process.env.ANTHROPIC_API_KEY,\n    headers: { 'anthropic-beta': 'tools-2024-04-04' }\n  });\n  ```\n\n- For streaming and non-streaming support, the Vercel AI SDK provides both `generateText` (non-streaming) and `streamText` (streaming) functions. Use these with the Anthropic provider instance as the `model` parameter[5].\n\n- Example usage for non-streaming:\n  ```js\n  import { generateText } from 'ai';\n  import { anthropic } from '@ai-sdk/anthropic';\n\n  const result = await generateText({\n    model: anthropic('claude-3-haiku-20240307'),\n    messages: [{ role: 'user', content: [{ type: 'text', text: 'Hello!' }] }]\n  });\n  ```\n\n- Example usage for streaming:\n  ```js\n  import { streamText } from 'ai';\n  import { anthropic } from '@ai-sdk/anthropic';\n\n  const stream = await streamText({\n    model: anthropic('claude-3-haiku-20240307'),\n    messages: [{ role: 'user', content: [{ type: 'text', text: 'Hello!' }] }]\n  });\n  ```\n\n- Ensure that your implementation adheres to the standardized input/output format defined for `ai-services-unified.js`, mapping the SDK's response structure to your unified format.\n\n- If you continue to encounter 'Not Found' errors, verify:\n  - The API key is valid and has access to the requested models.\n  - The model name is correct and available to your Anthropic account.\n  - Any required beta headers are included if using beta features or models[1].\n\n- Prefer direct provider instantiation with explicit headers and API key configuration for maximum compatibility and to avoid SDK-level abstraction issues[1].\n</info added on 2025-04-24T02:54:40.326Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 21,
          "title": "Implement `perplexity.js` Provider Module using Vercel AI SDK",
          "description": "Create and implement the `perplexity.js` module within `src/ai-providers/`. This module should contain functions to interact with the Perplexity API (likely using their OpenAI-compatible endpoint) via the **Vercel AI SDK**, adhering to the standardized input/output format defined for `ai-services-unified.js`.",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 22,
          "title": "Implement `openai.js` Provider Module using Vercel AI SDK",
          "description": "Create and implement the `openai.js` module within `src/ai-providers/`. This module should contain functions to interact with the OpenAI API (streaming and non-streaming) using the **Vercel AI SDK**, adhering to the standardized input/output format defined for `ai-services-unified.js`. (Optional, implement if OpenAI models are needed).",
          "details": "\n\n<info added on 2025-04-27T05:33:49.977Z>\n```javascript\n// Implementation details for openai.js provider module\n\nimport { createOpenAI } from 'ai';\n\n/**\n * Generates text using OpenAI models via Vercel AI SDK\n * \n * @param {Object} params - Configuration parameters\n * @param {string} params.apiKey - OpenAI API key\n * @param {string} params.modelId - Model ID (e.g., 'gpt-4', 'gpt-3.5-turbo')\n * @param {Array} params.messages - Array of message objects with role and content\n * @param {number} [params.maxTokens] - Maximum tokens to generate\n * @param {number} [params.temperature=0.7] - Sampling temperature (0-1)\n * @returns {Promise<string>} The generated text response\n */\nexport async function generateOpenAIText(params) {\n  try {\n    const { apiKey, modelId, messages, maxTokens, temperature = 0.7 } = params;\n    \n    if (!apiKey) throw new Error('OpenAI API key is required');\n    if (!modelId) throw new Error('Model ID is required');\n    if (!messages || !Array.isArray(messages)) throw new Error('Messages array is required');\n    \n    const openai = createOpenAI({ apiKey });\n    \n    const response = await openai.chat.completions.create({\n      model: modelId,\n      messages,\n      max_tokens: maxTokens,\n      temperature,\n    });\n    \n    return response.choices[0].message.content;\n  } catch (error) {\n    console.error('OpenAI text generation error:', error);\n    throw new Error(`OpenAI API error: ${error.message}`);\n  }\n}\n\n/**\n * Streams text using OpenAI models via Vercel AI SDK\n * \n * @param {Object} params - Configuration parameters (same as generateOpenAIText)\n * @returns {ReadableStream} A stream of text chunks\n */\nexport async function streamOpenAIText(params) {\n  try {\n    const { apiKey, modelId, messages, maxTokens, temperature = 0.7 } = params;\n    \n    if (!apiKey) throw new Error('OpenAI API key is required');\n    if (!modelId) throw new Error('Model ID is required');\n    if (!messages || !Array.isArray(messages)) throw new Error('Messages array is required');\n    \n    const openai = createOpenAI({ apiKey });\n    \n    const stream = await openai.chat.completions.create({\n      model: modelId,\n      messages,\n      max_tokens: maxTokens,\n      temperature,\n      stream: true,\n    });\n    \n    return stream;\n  } catch (error) {\n    console.error('OpenAI streaming error:', error);\n    throw new Error(`OpenAI streaming error: ${error.message}`);\n  }\n}\n\n/**\n * Generates a structured object using OpenAI models via Vercel AI SDK\n * \n * @param {Object} params - Configuration parameters\n * @param {string} params.apiKey - OpenAI API key\n * @param {string} params.modelId - Model ID (e.g., 'gpt-4', 'gpt-3.5-turbo')\n * @param {Array} params.messages - Array of message objects\n * @param {Object} params.schema - JSON schema for the response object\n * @param {string} params.objectName - Name of the object to generate\n * @returns {Promise<Object>} The generated structured object\n */\nexport async function generateOpenAIObject(params) {\n  try {\n    const { apiKey, modelId, messages, schema, objectName } = params;\n    \n    if (!apiKey) throw new Error('OpenAI API key is required');\n    if (!modelId) throw new Error('Model ID is required');\n    if (!messages || !Array.isArray(messages)) throw new Error('Messages array is required');\n    if (!schema) throw new Error('Schema is required');\n    if (!objectName) throw new Error('Object name is required');\n    \n    const openai = createOpenAI({ apiKey });\n    \n    // Using the Vercel AI SDK's function calling capabilities\n    const response = await openai.chat.completions.create({\n      model: modelId,\n      messages,\n      functions: [\n        {\n          name: objectName,\n          description: `Generate a ${objectName} object`,\n          parameters: schema,\n        },\n      ],\n      function_call: { name: objectName },\n    });\n    \n    const functionCall = response.choices[0].message.function_call;\n    return JSON.parse(functionCall.arguments);\n  } catch (error) {\n    console.error('OpenAI object generation error:', error);\n    throw new Error(`OpenAI object generation error: ${error.message}`);\n  }\n}\n```\n</info added on 2025-04-27T05:33:49.977Z>\n\n<info added on 2025-04-27T05:35:03.679Z>\n<info added on 2025-04-28T10:15:22.123Z>\n```javascript\n// Additional implementation notes for openai.js\n\n/**\n * Export a provider info object for OpenAI\n */\nexport const providerInfo = {\n  id: 'openai',\n  name: 'OpenAI',\n  description: 'OpenAI API integration using Vercel AI SDK',\n  models: {\n    'gpt-4': {\n      id: 'gpt-4',\n      name: 'GPT-4',\n      contextWindow: 8192,\n      supportsFunctions: true,\n    },\n    'gpt-4-turbo': {\n      id: 'gpt-4-turbo',\n      name: 'GPT-4 Turbo',\n      contextWindow: 128000,\n      supportsFunctions: true,\n    },\n    'gpt-3.5-turbo': {\n      id: 'gpt-3.5-turbo',\n      name: 'GPT-3.5 Turbo',\n      contextWindow: 16385,\n      supportsFunctions: true,\n    }\n  }\n};\n\n/**\n * Helper function to format error responses consistently\n * \n * @param {Error} error - The caught error\n * @param {string} operation - The operation being performed\n * @returns {Error} A formatted error\n */\nfunction formatError(error, operation) {\n  // Extract OpenAI specific error details if available\n  const statusCode = error.status || error.statusCode;\n  const errorType = error.type || error.code || 'unknown_error';\n  \n  // Create a more detailed error message\n  const message = `OpenAI ${operation} error (${errorType}): ${error.message}`;\n  \n  // Create a new error with the formatted message\n  const formattedError = new Error(message);\n  \n  // Add additional properties for debugging\n  formattedError.originalError = error;\n  formattedError.provider = 'openai';\n  formattedError.statusCode = statusCode;\n  formattedError.errorType = errorType;\n  \n  return formattedError;\n}\n\n/**\n * Example usage with the unified AI services interface:\n * \n * // In ai-services-unified.js\n * import * as openaiProvider from './ai-providers/openai.js';\n * \n * export async function generateText(params) {\n *   switch(params.provider) {\n *     case 'openai':\n *       return openaiProvider.generateOpenAIText(params);\n *     // other providers...\n *   }\n * }\n */\n\n// Note: For proper error handling with the Vercel AI SDK, you may need to:\n// 1. Check for rate limiting errors (429)\n// 2. Handle token context window exceeded errors\n// 3. Implement exponential backoff for retries on 5xx errors\n// 4. Parse streaming errors properly from the ReadableStream\n```\n</info added on 2025-04-28T10:15:22.123Z>\n</info added on 2025-04-27T05:35:03.679Z>\n\n<info added on 2025-04-27T05:39:31.942Z>\n```javascript\n// Correction for openai.js provider module\n\n// IMPORTANT: Use the correct import from Vercel AI SDK\nimport { createOpenAI, openai } from '@ai-sdk/openai';\n\n// Note: Before using this module, install the required dependency:\n// npm install @ai-sdk/openai\n\n// The rest of the implementation remains the same, but uses the correct imports.\n// When implementing this module, ensure your package.json includes this dependency.\n\n// For streaming implementations with the Vercel AI SDK, you can also use the \n// streamText and experimental streamUI methods:\n\n/**\n * Example of using streamText for simpler streaming implementation\n */\nexport async function streamOpenAITextSimplified(params) {\n  try {\n    const { apiKey, modelId, messages, maxTokens, temperature = 0.7 } = params;\n    \n    if (!apiKey) throw new Error('OpenAI API key is required');\n    \n    const openaiClient = createOpenAI({ apiKey });\n    \n    return openaiClient.streamText({\n      model: modelId,\n      messages,\n      temperature,\n      maxTokens,\n    });\n  } catch (error) {\n    console.error('OpenAI streaming error:', error);\n    throw new Error(`OpenAI streaming error: ${error.message}`);\n  }\n}\n```\n</info added on 2025-04-27T05:39:31.942Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 23,
          "title": "Implement Conditional Provider Logic in `ai-services-unified.js`",
          "description": "Implement logic within the functions of `ai-services-unified.js` (e.g., `generateTextService`, `generateObjectService`, `streamChatService`) to dynamically select and call the appropriate provider module (`anthropic.js`, `perplexity.js`, etc.) based on configuration (e.g., environment variables like `AI_PROVIDER` and `AI_MODEL` from `process.env` or `session.env`).",
          "details": "\n\n<info added on 2025-04-20T03:52:13.065Z>\nThe unified service should now use the configuration manager for provider selection rather than directly accessing environment variables. Here's the implementation approach:\n\n1. Import the config-manager functions:\n```javascript\nconst { \n  getMainProvider, \n  getResearchProvider, \n  getFallbackProvider,\n  getModelForRole,\n  getProviderParameters\n} = require('./config-manager');\n```\n\n2. Implement provider selection based on context/role:\n```javascript\nfunction selectProvider(role = 'default', context = {}) {\n  // Try to get provider based on role or context\n  let provider;\n  \n  if (role === 'research') {\n    provider = getResearchProvider();\n  } else if (context.fallback) {\n    provider = getFallbackProvider();\n  } else {\n    provider = getMainProvider();\n  }\n  \n  // Dynamically import the provider module\n  return require(`./${provider}.js`);\n}\n```\n\n3. Update service functions to use this selection logic:\n```javascript\nasync function generateTextService(prompt, options = {}) {\n  const { role = 'default', ...otherOptions } = options;\n  const provider = selectProvider(role, options);\n  const model = getModelForRole(role);\n  const parameters = getProviderParameters(provider.name);\n  \n  return provider.generateText(prompt, { \n    model, \n    ...parameters,\n    ...otherOptions \n  });\n}\n```\n\n4. Implement fallback logic for service resilience:\n```javascript\nasync function executeWithFallback(serviceFunction, ...args) {\n  try {\n    return await serviceFunction(...args);\n  } catch (error) {\n    console.error(`Primary provider failed: ${error.message}`);\n    const fallbackProvider = require(`./${getFallbackProvider()}.js`);\n    return fallbackProvider[serviceFunction.name](...args);\n  }\n}\n```\n\n5. Add provider capability checking to prevent calling unsupported features:\n```javascript\nfunction checkProviderCapability(provider, capability) {\n  const capabilities = {\n    'anthropic': ['text', 'chat', 'stream'],\n    'perplexity': ['text', 'chat', 'stream', 'research'],\n    'openai': ['text', 'chat', 'stream', 'embedding', 'vision']\n    // Add other providers as needed\n  };\n  \n  return capabilities[provider]?.includes(capability) || false;\n}\n```\n</info added on 2025-04-20T03:52:13.065Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 24,
          "title": "Implement `google.js` Provider Module using Vercel AI SDK",
          "description": "Create and implement the `google.js` module within `src/ai-providers/`. This module should contain functions to interact with Google AI models (e.g., Gemini) using the **Vercel AI SDK (`@ai-sdk/google`)**, adhering to the standardized input/output format defined for `ai-services-unified.js`.",
          "details": "\n\n<info added on 2025-04-27T00:00:46.675Z>\n```javascript\n// Implementation details for google.js provider module\n\n// 1. Required imports\nimport { GoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { streamText, generateText, generateObject } from \"@ai-sdk/core\";\n\n// 2. Model configuration\nconst DEFAULT_MODEL = \"gemini-1.5-pro\"; // Default model, can be overridden\nconst TEMPERATURE_DEFAULT = 0.7;\n\n// 3. Function implementations\nexport async function generateGoogleText({ \n  prompt, \n  model = DEFAULT_MODEL, \n  temperature = TEMPERATURE_DEFAULT,\n  apiKey \n}) {\n  if (!apiKey) throw new Error(\"Google API key is required\");\n  \n  const googleAI = new GoogleGenerativeAI(apiKey);\n  const googleModel = googleAI.getGenerativeModel({ model });\n  \n  const result = await generateText({\n    model: googleModel,\n    prompt,\n    temperature\n  });\n  \n  return result;\n}\n\nexport async function streamGoogleText({ \n  prompt, \n  model = DEFAULT_MODEL, \n  temperature = TEMPERATURE_DEFAULT,\n  apiKey \n}) {\n  if (!apiKey) throw new Error(\"Google API key is required\");\n  \n  const googleAI = new GoogleGenerativeAI(apiKey);\n  const googleModel = googleAI.getGenerativeModel({ model });\n  \n  const stream = await streamText({\n    model: googleModel,\n    prompt,\n    temperature\n  });\n  \n  return stream;\n}\n\nexport async function generateGoogleObject({ \n  prompt, \n  schema,\n  model = DEFAULT_MODEL, \n  temperature = TEMPERATURE_DEFAULT,\n  apiKey \n}) {\n  if (!apiKey) throw new Error(\"Google API key is required\");\n  \n  const googleAI = new GoogleGenerativeAI(apiKey);\n  const googleModel = googleAI.getGenerativeModel({ model });\n  \n  const result = await generateObject({\n    model: googleModel,\n    prompt,\n    schema,\n    temperature\n  });\n  \n  return result;\n}\n\n// 4. Environment variable setup in .env.local\n// GOOGLE_API_KEY=your_google_api_key_here\n\n// 5. Error handling considerations\n// - Implement proper error handling for API rate limits\n// - Add retries for transient failures\n// - Consider adding logging for debugging purposes\n```\n</info added on 2025-04-27T00:00:46.675Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 25,
          "title": "Implement `ollama.js` Provider Module",
          "description": "Create and implement the `ollama.js` module within `src/ai-providers/`. This module should contain functions to interact with local Ollama models using the **`ollama-ai-provider` library**, adhering to the standardized input/output format defined for `ai-services-unified.js`. Note the specific library used.",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 26,
          "title": "Implement `mistral.js` Provider Module using Vercel AI SDK",
          "description": "Create and implement the `mistral.js` module within `src/ai-providers/`. This module should contain functions to interact with Mistral AI models using the **Vercel AI SDK (`@ai-sdk/mistral`)**, adhering to the standardized input/output format defined for `ai-services-unified.js`.",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 27,
          "title": "Implement `azure.js` Provider Module using Vercel AI SDK",
          "description": "Create and implement the `azure.js` module within `src/ai-providers/`. This module should contain functions to interact with Azure OpenAI models using the **Vercel AI SDK (`@ai-sdk/azure`)**, adhering to the standardized input/output format defined for `ai-services-unified.js`.",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 28,
          "title": "Implement `openrouter.js` Provider Module",
          "description": "Create and implement the `openrouter.js` module within `src/ai-providers/`. This module should contain functions to interact with various models via OpenRouter using the **`@openrouter/ai-sdk-provider` library**, adhering to the standardized input/output format defined for `ai-services-unified.js`. Note the specific library used.",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 29,
          "title": "Implement `xai.js` Provider Module using Vercel AI SDK",
          "description": "Create and implement the `xai.js` module within `src/ai-providers/`. This module should contain functions to interact with xAI models (e.g., Grok) using the **Vercel AI SDK (`@ai-sdk/xai`)**, adhering to the standardized input/output format defined for `ai-services-unified.js`.",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 30,
          "title": "Update Configuration Management for AI Providers",
          "description": "Update `config-manager.js` and related configuration logic/documentation to support the new provider/model selection mechanism for `ai-services-unified.js` (e.g., using `AI_PROVIDER`, `AI_MODEL` env vars from `process.env` or `session.env`), ensuring compatibility with existing role-based selection if needed.",
          "details": "\n\n<info added on 2025-04-20T00:42:35.876Z>\n```javascript\n// Implementation details for config-manager.js updates\n\n/**\n * Unified configuration resolution function that checks multiple sources in priority order:\n * 1. process.env\n * 2. session.env (if available)\n * 3. Default values from .taskmasterconfig\n * \n * @param {string} key - Configuration key to resolve\n * @param {object} session - Optional session object that may contain env values\n * @param {*} defaultValue - Default value if not found in any source\n * @returns {*} Resolved configuration value\n */\nfunction resolveConfig(key, session = null, defaultValue = null) {\n  return process.env[key] ?? session?.env?.[key] ?? defaultValue;\n}\n\n// AI provider/model resolution with fallback to role-based selection\nfunction resolveAIConfig(session = null, role = 'default') {\n  const provider = resolveConfig('AI_PROVIDER', session);\n  const model = resolveConfig('AI_MODEL', session);\n  \n  // If explicit provider/model specified, use those\n  if (provider && model) {\n    return { provider, model };\n  }\n  \n  // Otherwise fall back to role-based configuration\n  const roleConfig = getRoleBasedAIConfig(role);\n  return {\n    provider: provider || roleConfig.provider,\n    model: model || roleConfig.model\n  };\n}\n\n// Example usage in ai-services-unified.js:\n// const { provider, model } = resolveAIConfig(session, role);\n// const client = getProviderClient(provider, resolveConfig(`${provider.toUpperCase()}_API_KEY`, session));\n\n/**\n * Configuration Resolution Documentation:\n * \n * 1. Environment Variables:\n *    - AI_PROVIDER: Explicitly sets the AI provider (e.g., 'openai', 'anthropic')\n *    - AI_MODEL: Explicitly sets the model to use (e.g., 'gpt-4', 'claude-2')\n *    - OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.: Provider-specific API keys\n * \n * 2. Resolution Strategy:\n *    - Values are first checked in process.env\n *    - If not found, session.env is checked (when available)\n *    - If still not found, defaults from .taskmasterconfig are used\n *    - For AI provider/model, explicit settings override role-based configuration\n * \n * 3. Backward Compatibility:\n *    - Role-based selection continues to work when AI_PROVIDER/AI_MODEL are not set\n *    - Existing code using getRoleBasedAIConfig() will continue to function\n */\n```\n</info added on 2025-04-20T00:42:35.876Z>\n\n<info added on 2025-04-20T03:51:51.967Z>\n<info added on 2025-04-20T14:30:12.456Z>\n```javascript\n/**\n * Refactored configuration management implementation\n */\n\n// Core configuration getters - replace direct CONFIG access\nconst getMainProvider = () => resolveConfig('AI_PROVIDER', null, CONFIG.ai?.mainProvider || 'openai');\nconst getMainModel = () => resolveConfig('AI_MODEL', null, CONFIG.ai?.mainModel || 'gpt-4');\nconst getLogLevel = () => resolveConfig('LOG_LEVEL', null, CONFIG.logging?.level || 'info');\nconst getMaxTokens = (role = 'default') => {\n  const explicitMaxTokens = parseInt(resolveConfig('MAX_TOKENS', null, 0), 10);\n  if (explicitMaxTokens > 0) return explicitMaxTokens;\n  \n  // Fall back to role-based configuration\n  return CONFIG.ai?.roles?.[role]?.maxTokens || CONFIG.ai?.defaultMaxTokens || 4096;\n};\n\n// API key resolution - separate from general configuration\nfunction resolveEnvVariable(key, session = null) {\n  return process.env[key] ?? session?.env?.[key] ?? null;\n}\n\nfunction isApiKeySet(provider, session = null) {\n  const keyName = `${provider.toUpperCase()}_API_KEY`;\n  return Boolean(resolveEnvVariable(keyName, session));\n}\n\n/**\n * Migration guide for application components:\n * \n * 1. Replace direct CONFIG access:\n *    - Before: `const provider = CONFIG.ai.mainProvider;`\n *    - After: `const provider = getMainProvider();`\n * \n * 2. Replace direct process.env access for API keys:\n *    - Before: `const apiKey = process.env.OPENAI_API_KEY;`\n *    - After: `const apiKey = resolveEnvVariable('OPENAI_API_KEY', session);`\n * \n * 3. Check API key availability:\n *    - Before: `if (process.env.OPENAI_API_KEY) {...}`\n *    - After: `if (isApiKeySet('openai', session)) {...}`\n * \n * 4. Update provider/model selection in ai-services:\n *    - Before: \n *      ```\n *      const provider = role ? CONFIG.ai.roles[role]?.provider : CONFIG.ai.mainProvider;\n *      const model = role ? CONFIG.ai.roles[role]?.model : CONFIG.ai.mainModel;\n *      ```\n *    - After:\n *      ```\n *      const { provider, model } = resolveAIConfig(session, role);\n *      ```\n */\n\n// Update .taskmasterconfig schema documentation\nconst configSchema = {\n  \"ai\": {\n    \"mainProvider\": \"Default AI provider (overridden by AI_PROVIDER env var)\",\n    \"mainModel\": \"Default AI model (overridden by AI_MODEL env var)\",\n    \"defaultMaxTokens\": \"Default max tokens (overridden by MAX_TOKENS env var)\",\n    \"roles\": {\n      \"role_name\": {\n        \"provider\": \"Provider for this role (fallback if AI_PROVIDER not set)\",\n        \"model\": \"Model for this role (fallback if AI_MODEL not set)\",\n        \"maxTokens\": \"Max tokens for this role (fallback if MAX_TOKENS not set)\"\n      }\n    }\n  },\n  \"logging\": {\n    \"level\": \"Logging level (overridden by LOG_LEVEL env var)\"\n  }\n};\n```\n\nImplementation notes:\n1. All configuration getters should provide environment variable override capability first, then fall back to .taskmasterconfig values\n2. API key resolution should be kept separate from general configuration to maintain security boundaries\n3. Update all application components to use these new getters rather than accessing CONFIG or process.env directly\n4. Document the priority order (env vars > session.env > .taskmasterconfig) in JSDoc comments\n5. Ensure backward compatibility by maintaining support for role-based configuration when explicit env vars aren't set\n</info added on 2025-04-20T14:30:12.456Z>\n</info added on 2025-04-20T03:51:51.967Z>\n\n<info added on 2025-04-22T02:41:51.174Z>\n**Implementation Update (Deviation from Original Plan):**\n\n- The configuration management system has been refactored to **eliminate environment variable overrides** (such as `AI_PROVIDER`, `AI_MODEL`, `MAX_TOKENS`, etc.) for all settings except API keys and select endpoints. All configuration values for providers, models, parameters, and logging are now sourced *exclusively* from the loaded `.taskmasterconfig` file (merged with defaults), ensuring a single source of truth.\n\n- The `resolveConfig` and `resolveAIConfig` helpers, which previously checked `process.env` and `session.env`, have been **removed**. All configuration getters now directly access the loaded configuration object.\n\n- A new `MissingConfigError` is thrown if the `.taskmasterconfig` file is not found at startup. This error is caught in the application entrypoint (`ai-services-unified.js`), which then instructs the user to initialize the configuration file before proceeding.\n\n- API key and endpoint resolution remains an exception: environment variable overrides are still supported for secrets like `OPENAI_API_KEY` or provider-specific endpoints, maintaining security best practices.\n\n- Documentation (`README.md`, inline JSDoc, and `.taskmasterconfig` schema) has been updated to clarify that **environment variables are no longer used for general configuration** (other than secrets), and that all settings must be defined in `.taskmasterconfig`.\n\n- All application components have been updated to use the new configuration getters, and any direct access to `CONFIG`, `process.env`, or the previous helpers has been removed.\n\n- This stricter approach enforces configuration-as-code principles, ensures reproducibility, and prevents configuration drift, aligning with modern best practices for immutable infrastructure and automated configuration management[2][4].\n</info added on 2025-04-22T02:41:51.174Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 31,
          "title": "Implement Integration Tests for Unified AI Service",
          "description": "Implement integration tests for `ai-services-unified.js`. These tests should verify the correct routing to different provider modules based on configuration and ensure the unified service functions (`generateTextService`, `generateObjectService`, etc.) work correctly when called from modules like `task-manager.js`. [Updated: 5/2/2025] [Updated: 5/2/2025] [Updated: 5/2/2025] [Updated: 5/2/2025]",
          "status": "done",
          "dependencies": [
            "61.18"
          ],
          "details": "\n\n<info added on 2025-04-20T03:51:23.368Z>\nFor the integration tests of the Unified AI Service, consider the following implementation details:\n\n1. Setup test fixtures:\n   - Create a mock `.taskmasterconfig` file with different provider configurations\n   - Define test cases with various model selections and parameter settings\n   - Use environment variable mocks only for API keys (e.g., `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`)\n\n2. Test configuration resolution:\n   - Verify that `ai-services-unified.js` correctly retrieves settings from `config-manager.js`\n   - Test that model selection follows the hierarchy defined in `.taskmasterconfig`\n   - Ensure fallback mechanisms work when primary providers are unavailable\n\n3. Mock the provider modules:\n   ```javascript\n   jest.mock('../services/openai-service.js');\n   jest.mock('../services/anthropic-service.js');\n   ```\n\n4. Test specific scenarios:\n   - Provider selection based on configured preferences\n   - Parameter inheritance from config (temperature, maxTokens)\n   - Error handling when API keys are missing\n   - Proper routing when specific models are requested\n\n5. Verify integration with task-manager:\n   ```javascript\n   test('task-manager correctly uses unified AI service with config-based settings', async () => {\n     // Setup mock config with specific settings\n     mockConfigManager.getAIProviderPreference.mockReturnValue(['openai', 'anthropic']);\n     mockConfigManager.getModelForRole.mockReturnValue('gpt-4');\n     mockConfigManager.getParametersForModel.mockReturnValue({ temperature: 0.7, maxTokens: 2000 });\n     \n     // Verify task-manager uses these settings when calling the unified service\n     // ...\n   });\n   ```\n\n6. Include tests for configuration changes at runtime and their effect on service behavior.\n</info added on 2025-04-20T03:51:23.368Z>\n\n<info added on 2025-05-02T18:41:13.374Z>\n]\n{\n  \"id\": 31,\n  \"title\": \"Implement Integration Test for Unified AI Service\",\n  \"description\": \"Implement integration tests for `ai-services-unified.js`. These tests should verify the correct routing to different provider module based on configuration and ensure the unified service function (`generateTextService`, `generateObjectService`, etc.) work correctly when called from module like `task-manager.js`.\",\n  \"details\": \"\\n\\n<info added on 2025-04-20T03:51:23.368Z>\\nFor the integration test of the Unified AI Service, consider the following implementation details:\\n\\n1. Setup test fixture:\\n   - Create a mock `.taskmasterconfig` file with different provider configuration\\n   - Define test case with various model selection and parameter setting\\n   - Use environment variable mock only for API key (e.g., `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`)\\n\\n2. Test configuration resolution:\\n   - Verify that `ai-services-unified.js` correctly retrieve setting from `config-manager.js`\\n   - Test that model selection follow the hierarchy defined in `.taskmasterconfig`\\n   - Ensure fallback mechanism work when primary provider are unavailable\\n\\n3. Mock the provider module:\\n   ```javascript\\n   jest.mock('../service/openai-service.js');\\n   jest.mock('../service/anthropic-service.js');\\n   ```\\n\\n4. Test specific scenario:\\n   - Provider selection based on configured preference\\n   - Parameter inheritance from config (temperature, maxToken)\\n   - Error handling when API key are missing\\n   - Proper routing when specific model are requested\\n\\n5. Verify integration with task-manager:\\n   ```javascript\\n   test('task-manager correctly use unified AI service with config-based setting', async () => {\\n     // Setup mock config with specific setting\\n     mockConfigManager.getAIProviderPreference.mockReturnValue(['openai', 'anthropic']);\\n     mockConfigManager.getModelForRole.mockReturnValue('gpt-4');\\n     mockConfigManager.getParameterForModel.mockReturnValue({ temperature: 0.7, maxToken: 2000 });\\n     \\n     // Verify task-manager use these setting when calling the unified service\\n     // ...\\n   });\\n   ```\\n\\n6. Include test for configuration change at runtime and their effect on service behavior.\\n</info added on 2025-04-20T03:51:23.368Z>\\n[2024-01-15 10:30:45] A custom e2e script was created to test all the CLI command but that we'll need one to test the MCP too and that task 76 are dedicated to that\",\n  \"status\": \"pending\",\n  \"dependency\": [\n    \"61.18\"\n  ],\n  \"parentTaskId\": 61\n}\n</info added on 2025-05-02T18:41:13.374Z>\n[2023-11-24 20:05:45] It's my birthday today\n[2023-11-24 20:05:46] add more low level details\n[2023-11-24 20:06:45] Additional low-level details for integration tests:\n\n- Ensure that each test case logs detailed output for each step, including configuration retrieval, provider selection, and API call results.\n- Implement a utility function to reset mocks and configurations between tests to avoid state leakage.\n- Use a combination of spies and mocks to verify that internal methods are called with expected arguments, especially for critical functions like `generateTextService`.\n- Consider edge cases such as empty configurations, invalid API keys, and network failures to ensure robustness.\n- Document each test case with expected outcomes and any assumptions made during the test design.\n- Leverage parallel test execution where possible to reduce test suite runtime, ensuring that tests are independent and do not interfere with each other.\n<info added on 2025-05-02T20:42:14.388Z>\n<info added on 2025-04-20T03:51:23.368Z>\nFor the integration tests of the Unified AI Service, consider the following implementation details:\n\n1. Setup test fixtures:\n   - Create a mock `.taskmasterconfig` file with different provider configurations\n   - Define test cases with various model selections and parameter settings\n   - Use environment variable mocks only for API keys (e.g., `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`)\n\n2. Test configuration resolution:\n   - Verify that `ai-services-unified.js` correctly retrieves settings from `config-manager.js`\n   - Test that model selection follows the hierarchy defined in `.taskmasterconfig`\n   - Ensure fallback mechanisms work when primary providers are unavailable\n\n3. Mock the provider modules:\n   ```javascript\n   jest.mock('../services/openai-service.js');\n   jest.mock('../services/anthropic-service.js');\n   ```\n\n4. Test specific scenarios:\n   - Provider selection based on configured preferences\n   - Parameter inheritance from config (temperature, maxTokens)\n   - Error handling when API keys are missing\n   - Proper routing when specific models are requested\n\n5. Verify integration with task-manager:\n   ```javascript\n   test('task-manager correctly uses unified AI service with config-based settings', async () => {\n     // Setup mock config with specific settings\n     mockConfigManager.getAIProviderPreference.mockReturnValue(['openai', 'anthropic']);\n     mockConfigManager.getModelForRole.mockReturnValue('gpt-4');\n     mockConfigManager.getParametersForModel.mockReturnValue({ temperature: 0.7, maxTokens: 2000 });\n     \n     // Verify task-manager uses these settings when calling the unified service\n     // ...\n   });\n   ```\n\n6. Include tests for configuration changes at runtime and their effect on service behavior.\n</info added on 2025-04-20T03:51:23.368Z>\n\n<info added on 2025-05-02T18:41:13.374Z>\n]\n{\n  \"id\": 31,\n  \"title\": \"Implement Integration Test for Unified AI Service\",\n  \"description\": \"Implement integration tests for `ai-services-unified.js`. These tests should verify the correct routing to different provider module based on configuration and ensure the unified service function (`generateTextService`, `generateObjectService`, etc.) work correctly when called from module like `task-manager.js`.\",\n  \"details\": \"\\n\\n<info added on 2025-04-20T03:51:23.368Z>\\nFor the integration test of the Unified AI Service, consider the following implementation details:\\n\\n1. Setup test fixture:\\n   - Create a mock `.taskmasterconfig` file with different provider configuration\\n   - Define test case with various model selection and parameter setting\\n   - Use environment variable mock only for API key (e.g., `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`)\\n\\n2. Test configuration resolution:\\n   - Verify that `ai-services-unified.js` correctly retrieve setting from `config-manager.js`\\n   - Test that model selection follow the hierarchy defined in `.taskmasterconfig`\\n   - Ensure fallback mechanism work when primary provider are unavailable\\n\\n3. Mock the provider module:\\n   ```javascript\\n   jest.mock('../service/openai-service.js');\\n   jest.mock('../service/anthropic-service.js');\\n   ```\\n\\n4. Test specific scenario:\\n   - Provider selection based on configured preference\\n   - Parameter inheritance from config (temperature, maxToken)\\n   - Error handling when API key are missing\\n   - Proper routing when specific model are requested\\n\\n5. Verify integration with task-manager:\\n   ```javascript\\n   test('task-manager correctly use unified AI service with config-based setting', async () => {\\n     // Setup mock config with specific setting\\n     mockConfigManager.getAIProviderPreference.mockReturnValue(['openai', 'anthropic']);\\n     mockConfigManager.getModelForRole.mockReturnValue('gpt-4');\\n     mockConfigManager.getParameterForModel.mockReturnValue({ temperature: 0.7, maxToken: 2000 });\\n     \\n     // Verify task-manager use these setting when calling the unified service\\n     // ...\\n   });\\n   ```\\n\\n6. Include test for configuration change at runtime and their effect on service behavior.\\n</info added on 2025-04-20T03:51:23.368Z>\\n[2024-01-15 10:30:45] A custom e2e script was created to test all the CLI command but that we'll need one to test the MCP too and that task 76 are dedicated to that\",\n  \"status\": \"pending\",\n  \"dependency\": [\n    \"61.18\"\n  ],\n  \"parentTaskId\": 61\n}\n</info added on 2025-05-02T18:41:13.374Z>\n[2023-11-24 20:05:45] It's my birthday today\n[2023-11-24 20:05:46] add more low level details\n[2023-11-24 20:06:45] Additional low-level details for integration tests:\n\n- Ensure that each test case logs detailed output for each step, including configuration retrieval, provider selection, and API call results.\n- Implement a utility function to reset mocks and configurations between tests to avoid state leakage.\n- Use a combination of spies and mocks to verify that internal methods are called with expected arguments, especially for critical functions like `generateTextService`.\n- Consider edge cases such as empty configurations, invalid API keys, and network failures to ensure robustness.\n- Document each test case with expected outcomes and any assumptions made during the test design.\n- Leverage parallel test execution where possible to reduce test suite runtime, ensuring that tests are independent and do not interfere with each other.\n\n<info added on 2023-11-24T20:10:00.000Z>\n- Implement detailed logging for each API call, capturing request and response data to facilitate debugging.\n- Create a comprehensive test matrix to cover all possible combinations of provider configurations and model selections.\n- Use snapshot testing to verify that the output of `generateTextService` and `generateObjectService` remains consistent across code changes.\n- Develop a set of utility functions to simulate network latency and failures, ensuring the service handles such scenarios gracefully.\n- Regularly review and update test cases to reflect changes in the configuration management or provider APIs.\n- Ensure that all test data is anonymized and does not contain sensitive information.\n</info added on 2023-11-24T20:10:00.000Z>\n</info added on 2025-05-02T20:42:14.388Z>"
        },
        {
          "id": 32,
          "title": "Update Documentation for New AI Architecture",
          "description": "Update relevant documentation files (e.g., `architecture.mdc`, `taskmaster.mdc`, environment variable guides, README) to accurately reflect the new AI service architecture using `ai-services-unified.js`, provider modules, the Vercel AI SDK, and the updated configuration approach.",
          "details": "\n\n<info added on 2025-04-20T03:51:04.461Z>\nThe new AI architecture introduces a clear separation between sensitive credentials and configuration settings:\n\n## Environment Variables vs Configuration File\n\n- **Environment Variables (.env)**: \n  - Store only sensitive API keys and credentials\n  - Accessed via `resolveEnvVariable()` which checks both process.env and session.env\n  - Example: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY`\n  - No model names, parameters, or non-sensitive settings should be here\n\n- **.taskmasterconfig File**:\n  - Central location for all non-sensitive configuration\n  - Structured JSON with clear sections for different aspects of the system\n  - Contains:\n    - Model mappings by role (e.g., `systemModels`, `userModels`)\n    - Default parameters (temperature, maxTokens, etc.)\n    - Logging preferences\n    - Provider-specific settings\n  - Accessed via getter functions from `config-manager.js` like:\n    ```javascript\n    import { getModelForRole, getDefaultTemperature } from './config-manager.js';\n    \n    // Usage examples\n    const model = getModelForRole('system');\n    const temp = getDefaultTemperature();\n    ```\n\n## Implementation Notes\n- Document the structure of `.taskmasterconfig` with examples\n- Explain the migration path for users with existing setups\n- Include a troubleshooting section for common configuration issues\n- Add a configuration validation section explaining how the system verifies settings\n</info added on 2025-04-20T03:51:04.461Z>",
          "status": "done",
          "dependencies": [
            "61.31"
          ],
          "parentTaskId": 61
        },
        {
          "id": 33,
          "title": "Cleanup Old AI Service Files",
          "description": "After all other migration subtasks (refactoring, provider implementation, testing, documentation) are complete and verified, remove the old `ai-services.js` and `ai-client-factory.js` files from the `scripts/modules/` directory. Ensure no code still references them.",
          "details": "\n\n<info added on 2025-04-22T06:51:02.444Z>\nI'll provide additional technical information to enhance the \"Cleanup Old AI Service Files\" subtask:\n\n## Implementation Details\n\n**Pre-Cleanup Verification Steps:**\n- Run a comprehensive codebase search for any remaining imports or references to `ai-services.js` and `ai-client-factory.js` using grep or your IDE's search functionality[1][4]\n- Check for any dynamic imports that might not be caught by static analysis tools\n- Verify that all dependent modules have been properly migrated to the new AI service architecture\n\n**Cleanup Process:**\n- Create a backup of the files before deletion in case rollback is needed\n- Document the file removal in the migration changelog with timestamps and specific file paths[5]\n- Update any build configuration files that might reference these files (webpack configs, etc.)\n- Run a full test suite after removal to ensure no runtime errors occur[2]\n\n**Post-Cleanup Validation:**\n- Implement automated tests to verify the application functions correctly without the removed files\n- Monitor application logs and error reporting systems for 48-72 hours after deployment to catch any missed dependencies[3]\n- Perform a final code review to ensure clean architecture principles are maintained in the new implementation\n\n**Technical Considerations:**\n- Check for any circular dependencies that might have been created during the migration process\n- Ensure proper garbage collection by removing any cached instances of the old services\n- Verify that performance metrics remain stable after the removal of legacy code\n</info added on 2025-04-22T06:51:02.444Z>",
          "status": "done",
          "dependencies": [
            "61.31",
            "61.32"
          ],
          "parentTaskId": 61
        },
        {
          "id": 34,
          "title": "Audit and Standardize Env Variable Access",
          "description": "Audit the entire codebase (core modules, provider modules, utilities) to ensure all accesses to environment variables (API keys, configuration flags) consistently use a standardized resolution function (like `resolveEnvVariable` or a new utility) that checks `process.env` first and then `session.env` if available. Refactor any direct `process.env` access where `session.env` should also be considered.",
          "details": "\n\n<info added on 2025-04-20T03:50:25.632Z>\nThis audit should distinguish between two types of configuration:\n\n1. **Sensitive credentials (API keys)**: These should exclusively use the `resolveEnvVariable` pattern to check both `process.env` and `session.env`. Verify that no API keys are hardcoded or accessed through direct `process.env` references.\n\n2. **Application configuration**: All non-credential settings should be migrated to use the centralized `.taskmasterconfig` system via the `config-manager.js` getters. This includes:\n   - Model selections and role assignments\n   - Parameter settings (temperature, maxTokens, etc.)\n   - Logging configuration\n   - Default behaviors and fallbacks\n\nImplementation notes:\n- Create a comprehensive inventory of all environment variable accesses\n- Categorize each as either credential or application configuration\n- For credentials: standardize on `resolveEnvVariable` pattern\n- For app config: migrate to appropriate `config-manager.js` getter methods\n- Document any exceptions that require special handling\n- Add validation to prevent regression (e.g., ESLint rules against direct `process.env` access)\n\nThis separation ensures security best practices for credentials while centralizing application configuration for better maintainability.\n</info added on 2025-04-20T03:50:25.632Z>\n\n<info added on 2025-04-20T06:58:36.731Z>\n**Plan & Analysis (Added on 2023-05-15T14:32:18.421Z)**:\n\n**Goal:**\n1.  **Standardize API Key Access**: Ensure all accesses to sensitive API keys (Anthropic, Perplexity, etc.) consistently use a standard function (like `resolveEnvVariable(key, session)`) that checks both `process.env` and `session.env`. Replace direct `process.env.API_KEY` access.\n2.  **Centralize App Configuration**: Ensure all non-sensitive configuration values (model names, temperature, logging levels, max tokens, etc.) are accessed *only* through `scripts/modules/config-manager.js` getters. Eliminate direct `process.env` access for these.\n\n**Strategy: Inventory -> Analyze -> Target -> Refine**\n\n1.  **Inventory (`process.env` Usage):** Performed grep search (`rg \"process\\.env\"`). Results indicate widespread usage across multiple files.\n2.  **Analysis (Categorization of Usage):**\n    *   **API Keys (Credentials):** ANTHROPIC_API_KEY, PERPLEXITY_API_KEY, OPENAI_API_KEY, etc. found in `task-manager.js`, `ai-services.js`, `commands.js`, `dependency-manager.js`, `ai-client-utils.js`, test files. Needs replacement with `resolveEnvVariable(key, session)`.\n    *   **App Configuration:** PERPLEXITY_MODEL, TEMPERATURE, MAX_TOKENS, MODEL, DEBUG, LOG_LEVEL, DEFAULT_*, PROJECT_*, TASK_MASTER_PROJECT_ROOT found in `task-manager.js`, `ai-services.js`, `scripts/init.js`, `mcp-server/src/logger.js`, `mcp-server/src/tools/utils.js`, test files. Needs replacement with `config-manager.js` getters.\n    *   **System/Environment Info:** HOME, USERPROFILE, SHELL in `scripts/init.js`. Needs review (e.g., `os.homedir()` preference).\n    *   **Test Code/Setup:** Extensive usage in test files. Acceptable for mocking, but code under test must use standard methods. May require test adjustments.\n    *   **Helper Functions/Comments:** Definitions/comments about `resolveEnvVariable`. No action needed.\n3.  **Target (High-Impact Areas & Initial Focus):**\n    *   High Impact: `task-manager.js` (~5800 lines), `ai-services.js` (~1500 lines).\n    *   Medium Impact: `commands.js`, Test Files.\n    *   Foundational: `ai-client-utils.js`, `config-manager.js`, `utils.js`.\n    *   **Initial Target Command:** `task-master analyze-complexity` for a focused, end-to-end refactoring exercise.\n\n4.  **Refine (Plan for `analyze-complexity`):**\n    a.  **Trace Code Path:** Identify functions involved in `analyze-complexity`.\n    b.  **Refactor API Key Access:** Replace direct `process.env.PERPLEXITY_API_KEY` with `resolveEnvVariable(key, session)`.\n    c.  **Refactor App Config Access:** Replace direct `process.env` for model name, temp, tokens with `config-manager.js` getters.\n    d.  **Verify `resolveEnvVariable`:** Ensure robustness, especially handling potentially undefined `session`.\n    e.  **Test:** Verify command works locally and via MCP context (if possible). Update tests.\n\nThis piecemeal approach aims to establish the refactoring pattern before tackling the entire codebase.\n</info added on 2025-04-20T06:58:36.731Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 35,
          "title": "Refactor add-task.js for Unified AI Service & Config",
          "description": "Replace direct AI calls (old `ai-services.js` helpers) with `generateObjectService` or `generateTextService` from `ai-services-unified.js`. Pass `role` and `session`. Remove direct config getter usage (from `config-manager.js`) for AI parameters; use unified service instead. Keep `getDefaultPriority` usage.",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 36,
          "title": "Refactor analyze-task-complexity.js for Unified AI Service & Config",
          "description": "Replace direct AI calls with `generateObjectService` from `ai-services-unified.js`. Pass `role` and `session`. Remove direct config getter usage (from `config-manager.js`) for AI parameters; use unified service instead. Keep config getters needed for report metadata (`getProjectName`, `getDefaultSubtasks`).",
          "details": "\n\n<info added on 2025-04-24T17:45:51.956Z>\n## Additional Implementation Notes for Refactoring\n\n**General Guidance**\n\n- Ensure all AI-related logic in `analyze-task-complexity.js` is abstracted behind the `generateObjectService` interface. The function should only specify *what* to generate (schema, prompt, and parameters), not *how* the AI call is made or which model/config is used.\n- Remove any code that directly fetches AI model parameters or credentials from configuration files. All such details must be handled by the unified service layer.\n\n**1. Core Logic Function (analyze-task-complexity.js)**\n\n- Refactor the function signature to accept a `session` object and a `role` parameter, in addition to the existing arguments.\n- When preparing the service call, construct a payload object containing:\n  - The Zod schema for expected output.\n  - The prompt or input for the AI.\n  - The `role` (e.g., \"researcher\" or \"default\") based on the `useResearch` flag.\n  - The `session` context for downstream configuration and authentication.\n- Example service call:\n  ```js\n  const result = await generateObjectService({\n    schema: complexitySchema,\n    prompt: buildPrompt(task, options),\n    role,\n    session,\n  });\n  ```\n- Remove all references to direct AI client instantiation or configuration fetching.\n\n**2. CLI Command Action Handler (commands.js)**\n\n- Ensure the CLI handler for `analyze-complexity`:\n  - Accepts and parses the `--use-research` flag (or equivalent).\n  - Passes the `useResearch` flag and the current session context to the core function.\n  - Handles errors from the unified service gracefully, providing user-friendly feedback.\n\n**3. MCP Tool Definition (mcp-server/src/tools/analyze.js)**\n\n- Align the Zod schema for CLI options with the parameters expected by the core function, including `useResearch` and any new required fields.\n- Use `getMCPProjectRoot` to resolve the project path before invoking the core function.\n- Add status logging before and after the analysis, e.g., \"Analyzing task complexity...\" and \"Analysis complete.\"\n- Ensure the tool calls the core function with all required parameters, including session and resolved paths.\n\n**4. MCP Direct Function Wrapper (mcp-server/src/core/direct-functions/analyze-complexity-direct.js)**\n\n- Remove any direct AI client or config usage.\n- Implement a logger wrapper that standardizes log output for this function (e.g., `logger.info`, `logger.error`).\n- Pass the session context through to the core function to ensure all environment/config access is centralized.\n- Return a standardized response object, e.g.:\n  ```js\n  return {\n    success: true,\n    data: analysisResult,\n    message: \"Task complexity analysis completed.\",\n  };\n  ```\n\n**Testing and Validation**\n\n- After refactoring, add or update tests to ensure:\n  - The function does not break if AI service configuration changes.\n  - The correct role and session are always passed to the unified service.\n  - Errors from the unified service are handled and surfaced appropriately.\n\n**Best Practices**\n\n- Keep the core logic function pure and focused on orchestration, not implementation details.\n- Use dependency injection for session/context to facilitate testing and future extensibility.\n- Document the expected structure of the session and role parameters for maintainability.\n\nThese enhancements will ensure the refactored code is modular, maintainable, and fully decoupled from AI implementation details, aligning with modern refactoring best practices[1][3][5].\n</info added on 2025-04-24T17:45:51.956Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 37,
          "title": "Refactor expand-task.js for Unified AI Service & Config",
          "description": "Replace direct AI calls (old `ai-services.js` helpers like `generateSubtasksWithPerplexity`) with `generateObjectService` from `ai-services-unified.js`. Pass `role` and `session`. Remove direct config getter usage (from `config-manager.js`) for AI parameters; use unified service instead. Keep `getDefaultSubtasks` usage.",
          "details": "\n\n<info added on 2025-04-24T17:46:51.286Z>\n- In expand-task.js, ensure that all AI parameter configuration (such as model, temperature, max tokens) is passed via the unified generateObjectService interface, not fetched directly from config files or environment variables. This centralizes AI config management and supports future service changes without further refactoring.\n\n- When preparing the service call, construct the payload to include both the prompt and any schema or validation requirements expected by generateObjectService. For example, if subtasks must conform to a Zod schema, pass the schema definition or reference as part of the call.\n\n- For the CLI handler, ensure that the --research flag is mapped to the useResearch boolean and that this is explicitly passed to the core expand-task logic. Also, propagate any session or user context from CLI options to the core function for downstream auditing or personalization.\n\n- In the MCP tool definition, validate that all CLI-exposed parameters are reflected in the Zod schema, including optional ones like prompt overrides or force regeneration. This ensures strict input validation and prevents runtime errors.\n\n- In the direct function wrapper, implement a try/catch block around the core expandTask invocation. On error, log the error with context (task id, session id) and return a standardized error response object with error code and message fields.\n\n- Add unit tests or integration tests to verify that expand-task.js no longer imports or uses any direct AI client or config getter, and that all AI calls are routed through ai-services-unified.js.\n\n- Document the expected shape of the session object and any required fields for downstream service calls, so future maintainers know what context must be provided.\n</info added on 2025-04-24T17:46:51.286Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 38,
          "title": "Refactor expand-all-tasks.js for Unified AI Helpers & Config",
          "description": "Ensure this file correctly calls the refactored `getSubtasksFromAI` helper. Update config usage to only use `getDefaultSubtasks` from `config-manager.js` directly. AI interaction itself is handled by the helper.",
          "details": "\n\n<info added on 2025-04-24T17:48:09.354Z>\n## Additional Implementation Notes for Refactoring expand-all-tasks.js\n\n- Replace any direct imports of AI clients (e.g., OpenAI, Anthropic) and configuration getters with a single import of `expandTask` from `expand-task.js`, which now encapsulates all AI and config logic.\n- Ensure that the orchestration logic in `expand-all-tasks.js`:\n  - Iterates over all pending tasks, checking for existing subtasks before invoking expansion.\n  - For each task, calls `expandTask` and passes both the `useResearch` flag and the current `session` object as received from upstream callers.\n  - Does not contain any logic for AI prompt construction, API calls, or config file reading—these are now delegated to the unified helpers.\n- Maintain progress reporting by emitting status updates (e.g., via events or logging) before and after each task expansion, and ensure that errors from `expandTask` are caught and reported with sufficient context (task ID, error message).\n- Example code snippet for calling the refactored helper:\n\n```js\n// Pseudocode for orchestration loop\nfor (const task of pendingTasks) {\n  try {\n    reportProgress(`Expanding task ${task.id}...`);\n    await expandTask({\n      task,\n      useResearch,\n      session,\n    });\n    reportProgress(`Task ${task.id} expanded.`);\n  } catch (err) {\n    reportError(`Failed to expand task ${task.id}: ${err.message}`);\n  }\n}\n```\n\n- Remove any fallback or legacy code paths that previously handled AI or config logic directly within this file.\n- Ensure that all configuration defaults are accessed exclusively via `getDefaultSubtasks` from `config-manager.js` and only within the unified helper, not in `expand-all-tasks.js`.\n- Add or update JSDoc comments to clarify that this module is now a pure orchestrator and does not perform AI or config operations directly.\n</info added on 2025-04-24T17:48:09.354Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 39,
          "title": "Refactor get-subtasks-from-ai.js for Unified AI Service & Config",
          "description": "Replace direct AI calls (old `ai-services.js` helpers) with `generateObjectService` or `generateTextService` from `ai-services-unified.js`. Pass `role` and `session`. Remove direct config getter usage (from `config-manager.js`) for AI parameters; use unified service instead.",
          "details": "\n\n<info added on 2025-04-24T17:48:35.005Z>\n**Additional Implementation Notes for Refactoring get-subtasks-from-ai.js**\n\n- **Zod Schema Definition**:  \n  Define a Zod schema that precisely matches the expected subtask object structure. For example, if a subtask should have an id (string), title (string), and status (string), use:\n  ```js\n  import { z } from 'zod';\n\n  const SubtaskSchema = z.object({\n    id: z.string(),\n    title: z.string(),\n    status: z.string(),\n    // Add other fields as needed\n  });\n\n  const SubtasksArraySchema = z.array(SubtaskSchema);\n  ```\n  This ensures robust runtime validation and clear error reporting if the AI response does not match expectations[5][1][3].\n\n- **Unified Service Invocation**:  \n  Replace all direct AI client and config usage with:\n  ```js\n  import { generateObjectService } from './ai-services-unified';\n\n  // Example usage:\n  const subtasks = await generateObjectService({\n    schema: SubtasksArraySchema,\n    prompt,\n    role,\n    session,\n  });\n  ```\n  This centralizes AI invocation and parameter management, ensuring consistency and easier maintenance.\n\n- **Role Determination**:  \n  Use the `useResearch` flag to select the AI role:\n  ```js\n  const role = useResearch ? 'researcher' : 'default';\n  ```\n\n- **Error Handling**:  \n  Implement structured error handling:\n  ```js\n  try {\n    // AI service call\n  } catch (err) {\n    if (err.name === 'ServiceUnavailableError') {\n      // Handle AI service unavailability\n    } else if (err.name === 'ZodError') {\n      // Handle schema validation errors\n      // err.errors contains detailed validation issues\n    } else if (err.name === 'PromptConstructionError') {\n      // Handle prompt construction issues\n    } else {\n      // Handle unexpected errors\n    }\n    throw err; // or wrap and rethrow as needed\n  }\n  ```\n  This pattern ensures that consumers can distinguish between different failure modes and respond appropriately.\n\n- **Consumer Contract**:  \n  Update the function signature to require both `useResearch` and `session` parameters, and document this in JSDoc/type annotations for clarity.\n\n- **Prompt Construction**:  \n  Move all prompt construction logic outside the core function if possible, or encapsulate it so that errors can be caught and reported as `PromptConstructionError`.\n\n- **No AI Implementation Details**:  \n  The refactored function should not expose or depend on any AI implementation specifics—only the unified service interface and schema validation.\n\n- **Testing**:  \n  Add or update tests to cover:\n  - Successful subtask generation\n  - Schema validation failures (invalid AI output)\n  - Service unavailability scenarios\n  - Prompt construction errors\n\nThese enhancements ensure the refactored file is robust, maintainable, and aligned with the unified AI service architecture, leveraging Zod for strict runtime validation and clear error boundaries[5][1][3].\n</info added on 2025-04-24T17:48:35.005Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 40,
          "title": "Refactor update-task-by-id.js for Unified AI Service & Config",
          "description": "Replace direct AI calls (old `ai-services.js` helpers) with `generateObjectService` or `generateTextService` from `ai-services-unified.js`. Pass `role` and `session`. Remove direct config getter usage (from `config-manager.js`) for AI parameters and fallback logic; use unified service instead. Keep `getDebugFlag`.",
          "details": "\n\n<info added on 2025-04-24T17:48:58.133Z>\n- When defining the Zod schema for task update validation, consider using Zod's function schemas to validate both the input parameters and the expected output of the update function. This approach helps separate validation logic from business logic and ensures type safety throughout the update process[1][2].\n\n- For the core logic, use Zod's `.implement()` method to wrap the update function, so that all inputs (such as task ID, prompt, and options) are validated before execution, and outputs are type-checked. This reduces runtime errors and enforces contract compliance between layers[1][2].\n\n- In the MCP tool definition, ensure that the Zod schema explicitly validates all required parameters (e.g., `id` as a string, `prompt` as a string, `research` as a boolean or optional flag). This guarantees that only well-formed requests reach the core logic, improving reliability and error reporting[3][5].\n\n- When preparing the unified AI service call, pass the validated and sanitized data from the Zod schema directly to `generateObjectService`, ensuring that no unvalidated data is sent to the AI layer.\n\n- For output formatting, leverage Zod's ability to define and enforce the shape of the returned object, ensuring that the response structure (including success/failure status and updated task data) is always consistent and predictable[1][2][3].\n\n- If you need to validate or transform nested objects (such as task metadata or options), use Zod's object and nested schema capabilities to define these structures precisely, catching errors early and simplifying downstream logic[3][5].\n</info added on 2025-04-24T17:48:58.133Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 41,
          "title": "Refactor update-tasks.js for Unified AI Service & Config",
          "description": "Replace direct AI calls (old `ai-services.js` helpers) with `generateObjectService` or `generateTextService` from `ai-services-unified.js`. Pass `role` and `session`. Remove direct config getter usage (from `config-manager.js`) for AI parameters and fallback logic; use unified service instead. Keep `getDebugFlag`.",
          "details": "\n\n<info added on 2025-04-24T17:49:25.126Z>\n## Additional Implementation Notes for Refactoring update-tasks.js\n\n- **Zod Schema for Batch Updates**:  \n  Define a Zod schema to validate the structure of the batch update payload. For example, if updating tasks requires an array of task objects with specific fields, use:\n  ```typescript\n  import { z } from \"zod\";\n\n  const TaskUpdateSchema = z.object({\n    id: z.number(),\n    status: z.string(),\n    // add other fields as needed\n  });\n\n  const BatchUpdateSchema = z.object({\n    tasks: z.array(TaskUpdateSchema),\n    from: z.number(),\n    prompt: z.string().optional(),\n    useResearch: z.boolean().optional(),\n  });\n  ```\n  This ensures all incoming data for batch updates is validated at runtime, catching malformed input early and providing clear error messages[4][5].\n\n- **Function Schema Validation**:  \n  If exposing the update logic as a callable function (e.g., for CLI or API), consider using Zod's function schema to validate both input and output:\n  ```typescript\n  const updateTasksFunction = z\n    .function()\n    .args(BatchUpdateSchema, z.object({ session: z.any() }))\n    .returns(z.promise(z.object({ success: z.boolean(), updated: z.number() })))\n    .implement(async (input, { session }) => {\n      // implementation here\n    });\n  ```\n  This pattern enforces correct usage and output shape, improving reliability[1].\n\n- **Error Handling and Reporting**:  \n  Use Zod's `.safeParse()` or `.parse()` methods to validate input. On validation failure, return or throw a formatted error to the caller (CLI, API, etc.), ensuring actionable feedback for users[5].\n\n- **Consistent JSON Output**:  \n  When invoking the core update function from wrappers (CLI, MCP), ensure the output is always serialized as JSON. This is critical for downstream consumers and for automated tooling.\n\n- **Logger Wrapper Example**:  \n  Implement a logger utility that can be toggled for silent mode:\n  ```typescript\n  function createLogger(silent: boolean) {\n    return {\n      log: (...args: any[]) => { if (!silent) console.log(...args); },\n      error: (...args: any[]) => { if (!silent) console.error(...args); }\n    };\n  }\n  ```\n  Pass this logger to the core logic for consistent, suppressible output.\n\n- **Session Context Usage**:  \n  Ensure all AI service calls and config access are routed through the provided session context, not global config getters. This supports multi-user and multi-session environments.\n\n- **Task Filtering Logic**:  \n  Before invoking the AI service, filter the tasks array to only include those with `id >= from` and `status === \"pending\"`. This preserves the intended batch update semantics.\n\n- **Preserve File Regeneration**:  \n  After updating tasks, ensure any logic that regenerates or writes task files is retained and invoked as before.\n\n- **CLI and API Parameter Validation**:  \n  Use the same Zod schemas to validate CLI arguments and API payloads, ensuring consistency across all entry points[5].\n\n- **Example: Validating CLI Arguments**\n  ```typescript\n  const cliArgsSchema = z.object({\n    from: z.string().regex(/^\\d+$/).transform(Number),\n    research: z.boolean().optional(),\n    session: z.any(),\n  });\n\n  const parsedArgs = cliArgsSchema.parse(cliArgs);\n  ```\n\nThese enhancements ensure robust validation, unified service usage, and maintainable, predictable batch update behavior.\n</info added on 2025-04-24T17:49:25.126Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 42,
          "title": "Remove all unused imports",
          "description": "",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 43,
          "title": "Remove all unnecessary console logs",
          "description": "",
          "details": "<info added on 2025-05-02T20:47:07.566Z>\n1. Identify all files within the project directory that contain console log statements.\n2. Use a code editor or IDE with search functionality to locate all instances of console.log().\n3. Review each console log statement to determine if it is necessary for debugging or logging purposes.\n4. For each unnecessary console log, remove the statement from the code.\n5. Ensure that the removal of console logs does not affect the functionality of the application.\n6. Test the application thoroughly to confirm that no errors are introduced by the removal of these logs.\n7. Commit the changes to the version control system with a message indicating the cleanup of console logs.\n</info added on 2025-05-02T20:47:07.566Z>\n<info added on 2025-05-02T20:47:56.080Z>\nHere are more detailed steps for removing unnecessary console logs:\n\n1. Identify all files within the project directory that contain console log statements:\n   - Use grep or similar tools: `grep -r \"console.log\" --include=\"*.js\" --include=\"*.jsx\" --include=\"*.ts\" --include=\"*.tsx\" ./src`\n   - Alternatively, use your IDE's project-wide search functionality with regex pattern `console\\.(log|debug|info|warn|error)`\n\n2. Categorize console logs:\n   - Essential logs: Error reporting, critical application state changes\n   - Debugging logs: Temporary logs used during development\n   - Informational logs: Non-critical information that might be useful\n   - Redundant logs: Duplicated information or trivial data\n\n3. Create a spreadsheet or document to track:\n   - File path\n   - Line number\n   - Console log content\n   - Category (essential/debugging/informational/redundant)\n   - Decision (keep/remove)\n\n4. Apply these specific removal criteria:\n   - Remove all logs with comments like \"TODO\", \"TEMP\", \"DEBUG\"\n   - Remove logs that only show function entry/exit without meaningful data\n   - Remove logs that duplicate information already available in the UI\n   - Keep logs related to error handling or critical user actions\n   - Consider replacing some logs with proper error handling\n\n5. For logs you decide to keep:\n   - Add clear comments explaining why they're necessary\n   - Consider moving them to a centralized logging service\n   - Implement log levels (debug, info, warn, error) if not already present\n\n6. Use search and replace with regex to batch remove similar patterns:\n   - Example: `console\\.log\\(\\s*['\"]Processing.*?['\"]\\s*\\);`\n\n7. After removal, implement these testing steps:\n   - Run all unit tests\n   - Check browser console for any remaining logs during manual testing\n   - Verify error handling still works properly\n   - Test edge cases where logs might have been masking issues\n\n8. Consider implementing a linting rule to prevent unnecessary console logs in future code:\n   - Add ESLint rule \"no-console\" with appropriate exceptions\n   - Configure CI/CD pipeline to fail if new console logs are added\n\n9. Document any logging standards for the team to follow going forward.\n\n10. After committing changes, monitor the application in staging environment to ensure no critical information is lost.\n</info added on 2025-05-02T20:47:56.080Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 44,
          "title": "Add setters for temperature, max tokens on per role basis.",
          "description": "NOT per model/provider basis though we could probably just define those in the .taskmasterconfig file but then they would be hard-coded. if we let users define them on a per role basis, they will define incorrect values. maybe a good middle ground is to do both - we enforce maximum using known max tokens for input and output at the .taskmasterconfig level but then we also give setters to adjust temp/input tokens/output tokens for each of the 3 roles.",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        },
        {
          "id": 45,
          "title": "Add support for Bedrock provider with ai sdk and unified service",
          "description": "",
          "details": "\n\n<info added on 2025-04-25T19:03:42.584Z>\n- Install the Bedrock provider for the AI SDK using your package manager (e.g., npm i @ai-sdk/amazon-bedrock) and ensure the core AI SDK is present[3][4].\n\n- To integrate with your existing config manager, externalize all Bedrock-specific configuration (such as region, model name, and credential provider) into your config management system. For example, store values like region (\"us-east-1\") and model identifier (\"meta.llama3-8b-instruct-v1:0\") in your config files or environment variables, and load them at runtime.\n\n- For credentials, leverage the AWS SDK credential provider chain to avoid hardcoding secrets. Use the @aws-sdk/credential-providers package and pass a credentialProvider (e.g., fromNodeProviderChain()) to the Bedrock provider. This allows your config manager to control credential sourcing via environment, profiles, or IAM roles, consistent with other AWS integrations[1].\n\n- Example integration with config manager:\n  ```js\n  import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';\n  import { fromNodeProviderChain } from '@aws-sdk/credential-providers';\n\n  // Assume configManager.get returns your config values\n  const region = configManager.get('bedrock.region');\n  const model = configManager.get('bedrock.model');\n\n  const bedrock = createAmazonBedrock({\n    region,\n    credentialProvider: fromNodeProviderChain(),\n  });\n\n  // Use with AI SDK methods\n  const { text } = await generateText({\n    model: bedrock(model),\n    prompt: 'Your prompt here',\n  });\n  ```\n\n- If your config manager supports dynamic provider selection, you can abstract the provider initialization so switching between Bedrock and other providers (like OpenAI or Anthropic) is seamless.\n\n- Be aware that Bedrock exposes multiple models from different vendors, each with potentially different API behaviors. Your config should allow specifying the exact model string, and your integration should handle any model-specific options or response formats[5].\n\n- For unified service integration, ensure your service layer can route requests to Bedrock using the configured provider instance, and normalize responses if you support multiple AI backends.\n</info added on 2025-04-25T19:03:42.584Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 61
        }
      ]
    },
    {
      "id": 62,
      "title": "Add --simple Flag to Update Commands for Direct Text Input",
      "description": "Implement a --simple flag for update-task and update-subtask commands that allows users to add timestamped notes without AI processing, directly using the text from the prompt.",
      "details": "This task involves modifying the update-task and update-subtask commands to accept a new --simple flag option. When this flag is present, the system should bypass the AI processing pipeline and directly use the text provided by the user as the update content. The implementation should:\n\n1. Update the command parsers for both update-task and update-subtask to recognize the --simple flag\n2. Modify the update logic to check for this flag and conditionally skip AI processing\n3. When the flag is present, format the user's input text with a timestamp in the same format as AI-processed updates\n4. Ensure the update is properly saved to the task or subtask's history\n5. Update the help documentation to include information about this new flag\n6. The timestamp format should match the existing format used for AI-generated updates\n7. The simple update should be visually distinguishable from AI updates in the display (consider adding a 'manual update' indicator)\n8. Maintain all existing functionality when the flag is not used",
      "testStrategy": "Testing should verify both the functionality and user experience of the new feature:\n\n1. Unit tests:\n   - Test that the command parser correctly recognizes the --simple flag\n   - Verify that AI processing is bypassed when the flag is present\n   - Ensure timestamps are correctly formatted and added\n\n2. Integration tests:\n   - Update a task with --simple flag and verify the exact text is saved\n   - Update a subtask with --simple flag and verify the exact text is saved\n   - Compare the output format with AI-processed updates to ensure consistency\n\n3. User experience tests:\n   - Verify help documentation correctly explains the new flag\n   - Test with various input lengths to ensure proper formatting\n   - Ensure the update appears correctly when viewing task history\n\n4. Edge cases:\n   - Test with empty input text\n   - Test with very long input text\n   - Test with special characters and formatting in the input",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Update command parsers to recognize --simple flag",
          "description": "Modify the command parsers for both update-task and update-subtask commands to recognize and process the new --simple flag option.",
          "dependencies": [],
          "details": "Add the --simple flag option to the command parser configurations in the CLI module. This should be implemented as a boolean flag that doesn't require any additional arguments. Update both the update-task and update-subtask command definitions to include this new option.",
          "status": "pending",
          "testStrategy": "Test that both commands correctly recognize the --simple flag when provided and that the flag's presence is properly captured in the command arguments object."
        },
        {
          "id": 2,
          "title": "Implement conditional logic to bypass AI processing",
          "description": "Modify the update logic to check for the --simple flag and conditionally skip the AI processing pipeline when the flag is present.",
          "dependencies": [
            1
          ],
          "details": "In the update handlers for both commands, add a condition to check if the --simple flag is set. If it is, create a path that bypasses the normal AI processing flow. This will require modifying the update functions to accept the flag parameter and branch the execution flow accordingly.",
          "status": "pending",
          "testStrategy": "Test that when the --simple flag is provided, the AI processing functions are not called, and when the flag is not provided, the normal AI processing flow is maintained."
        },
        {
          "id": 3,
          "title": "Format user input with timestamp for simple updates",
          "description": "Implement functionality to format the user's direct text input with a timestamp in the same format as AI-processed updates when the --simple flag is used.",
          "dependencies": [
            2
          ],
          "details": "Create a utility function that takes the user's raw input text and prepends a timestamp in the same format used for AI-generated updates. This function should be called when the --simple flag is active. Ensure the timestamp format is consistent with the existing format used throughout the application.",
          "status": "pending",
          "testStrategy": "Verify that the timestamp format matches the AI-generated updates and that the user's text is preserved exactly as entered."
        },
        {
          "id": 4,
          "title": "Add visual indicator for manual updates",
          "description": "Make simple updates visually distinguishable from AI-processed updates by adding a 'manual update' indicator or other visual differentiation.",
          "dependencies": [
            3
          ],
          "details": "Modify the update formatting to include a visual indicator (such as '[Manual Update]' prefix or different styling) when displaying updates that were created using the --simple flag. This will help users distinguish between AI-processed and manually entered updates.",
          "status": "pending",
          "testStrategy": "Check that updates made with the --simple flag are visually distinct from AI-processed updates when displayed in the task or subtask history."
        },
        {
          "id": 5,
          "title": "Implement storage of simple updates in history",
          "description": "Ensure that updates made with the --simple flag are properly saved to the task or subtask's history in the same way as AI-processed updates.",
          "dependencies": [
            3,
            4
          ],
          "details": "Modify the storage logic to save the formatted simple updates to the task or subtask history. The storage format should be consistent with AI-processed updates, but include the manual indicator. Ensure that the update is properly associated with the correct task or subtask.",
          "status": "pending",
          "testStrategy": "Test that updates made with the --simple flag are correctly saved to the history and persist between application restarts."
        },
        {
          "id": 6,
          "title": "Update help documentation for the new flag",
          "description": "Update the help documentation for both update-task and update-subtask commands to include information about the new --simple flag.",
          "dependencies": [
            1
          ],
          "details": "Add clear descriptions of the --simple flag to the help text for both commands. The documentation should explain that the flag allows users to add timestamped notes without AI processing, directly using the text from the prompt. Include examples of how to use the flag.",
          "status": "pending",
          "testStrategy": "Verify that the help command correctly displays information about the --simple flag for both update commands."
        },
        {
          "id": 7,
          "title": "Implement integration tests for the simple update feature",
          "description": "Create comprehensive integration tests to verify that the --simple flag works correctly in both commands and integrates properly with the rest of the system.",
          "dependencies": [
            1,
            2,
            3,
            4,
            5
          ],
          "details": "Develop integration tests that verify the entire flow of using the --simple flag with both update commands. Tests should confirm that updates are correctly formatted, stored, and displayed. Include edge cases such as empty input, very long input, and special characters.",
          "status": "pending",
          "testStrategy": "Run integration tests that simulate user input with and without the --simple flag and verify the correct behavior in each case."
        },
        {
          "id": 8,
          "title": "Perform final validation and documentation",
          "description": "Conduct final validation of the feature across all use cases and update the user documentation to include the new functionality.",
          "dependencies": [
            1,
            2,
            3,
            4,
            5,
            6,
            7
          ],
          "details": "Perform end-to-end testing of the feature to ensure it works correctly in all scenarios. Update the user documentation with detailed information about the new --simple flag, including its purpose, how to use it, and examples. Ensure that the documentation clearly explains the difference between AI-processed updates and simple updates.",
          "status": "pending",
          "testStrategy": "Manually test all use cases and review documentation for completeness and clarity."
        }
      ]
    },
    {
      "id": 63,
      "title": "Add pnpm Support for the Taskmaster Package",
      "description": "Implement full support for pnpm as an alternative package manager in the Taskmaster application, ensuring users have the exact same experience as with npm when installing and managing the package. The installation process, including any CLI prompts or web interfaces, must serve the exact same content and user experience regardless of whether npm or pnpm is used. The project uses 'module' as the package type, defines binaries 'task-master' and 'task-master-mcp', and its core logic resides in 'scripts/modules/'. The 'init' command (via scripts/init.js) creates the directory structure (.cursor/rules, scripts, tasks), copies templates (.env.example, .gitignore, rule files, dev.js), manages package.json merging, and sets up MCP config (.cursor/mcp.json). All dependencies are standard npm dependencies listed in package.json, and manual modifications are being removed.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves:\n\n1. Update the installation documentation to include pnpm installation commands (e.g., `pnpm add taskmaster`).\n\n2. Ensure all package scripts are compatible with pnpm's execution model:\n   - Review and modify package.json scripts if necessary\n   - Test script execution with pnpm syntax (`pnpm run <script>`)\n   - Address any pnpm-specific path or execution differences\n   - Confirm that scripts responsible for showing a website or prompt during install behave identically with pnpm and npm\n\n3. Create a pnpm-lock.yaml file by installing dependencies with pnpm.\n\n4. Test the application's installation and operation when installed via pnpm:\n   - Global installation (`pnpm add -g taskmaster`)\n   - Local project installation\n   - Verify CLI commands work correctly when installed with pnpm\n   - Verify binaries `task-master` and `task-master-mcp` are properly linked\n   - Ensure the `init` command (scripts/init.js) correctly creates directory structure and copies templates as described\n\n5. Update CI/CD pipelines to include testing with pnpm:\n   - Add a pnpm test matrix to GitHub Actions workflows\n   - Ensure tests pass when dependencies are installed with pnpm\n\n6. Handle any pnpm-specific dependency resolution issues:\n   - Address potential hoisting differences between npm and pnpm\n   - Test with pnpm's strict mode to ensure compatibility\n   - Verify proper handling of 'module' package type\n\n7. Document any pnpm-specific considerations or commands in the README and documentation.\n\n8. Verify that the `scripts/init.js` file works correctly with pnpm:\n   - Ensure it properly creates `.cursor/rules`, `scripts`, and `tasks` directories\n   - Verify template copying (`.env.example`, `.gitignore`, rule files, `dev.js`)\n   - Confirm `package.json` merging works correctly\n   - Test MCP config setup (`.cursor/mcp.json`)\n\n9. Ensure core logic in `scripts/modules/` works correctly when installed via pnpm.\n\nThis implementation should maintain full feature parity and identical user experience regardless of which package manager is used to install Taskmaster.",
      "testStrategy": "1. Manual Testing:\n   - Install Taskmaster globally using pnpm: `pnpm add -g taskmaster`\n   - Install Taskmaster locally in a test project: `pnpm add taskmaster`\n   - Verify all CLI commands function correctly with both installation methods\n   - Test all major features to ensure they work identically to npm installations\n   - Verify binaries `task-master` and `task-master-mcp` are properly linked and executable\n   - Test the `init` command to ensure it correctly sets up the directory structure and files as defined in scripts/init.js\n\n2. Automated Testing:\n   - Create a dedicated test workflow in GitHub Actions that uses pnpm\n   - Run the full test suite using pnpm to install dependencies\n   - Verify all tests pass with the same results as npm\n\n3. Documentation Testing:\n   - Review all documentation to ensure pnpm commands are correctly documented\n   - Verify installation instructions work as written\n   - Test any pnpm-specific instructions or notes\n\n4. Compatibility Testing:\n   - Test on different operating systems (Windows, macOS, Linux)\n   - Verify compatibility with different pnpm versions (latest stable and LTS)\n   - Test in environments with multiple package managers installed\n   - Verify proper handling of 'module' package type\n\n5. Edge Case Testing:\n   - Test installation in a project that uses pnpm workspaces\n   - Verify behavior when upgrading from an npm installation to pnpm\n   - Test with pnpm's various flags and modes (--frozen-lockfile, --strict-peer-dependencies)\n\n6. Performance Comparison:\n   - Measure and document any performance differences between package managers\n   - Compare installation times and disk space usage\n\n7. Structure Testing:\n   - Verify that the core logic in `scripts/modules/` is accessible and functions correctly\n   - Confirm that the `init` command properly creates all required directories and files as per scripts/init.js\n   - Test package.json merging functionality\n   - Verify MCP config setup\n\nSuccess criteria: Taskmaster should install and function identically regardless of whether it was installed via npm or pnpm, with no degradation in functionality, performance, or user experience. All binaries should be properly linked, and the directory structure should be correctly created.",
      "subtasks": [
        {
          "id": 1,
          "title": "Update Documentation for pnpm Support",
          "description": "Revise installation and usage documentation to include pnpm commands and instructions for installing and managing Taskmaster with pnpm. Clearly state that the installation process, including any website or UI shown, is identical to npm. Ensure documentation reflects the use of 'module' package type, binaries, and the init process as defined in scripts/init.js.",
          "dependencies": [],
          "details": "Add pnpm installation commands (e.g., `pnpm add taskmaster`) and update all relevant sections in the README and official docs to reflect pnpm as a supported package manager. Document that any installation website or prompt is the same as with npm. Include notes on the 'module' package type, binaries, and the directory/template setup performed by scripts/init.js.",
          "status": "done",
          "testStrategy": "Verify that documentation changes are clear, accurate, and render correctly in all documentation formats. Confirm that documentation explicitly states the identical experience for npm and pnpm, including any website or UI shown during install, and describes the init process and binaries."
        },
        {
          "id": 2,
          "title": "Ensure Package Scripts Compatibility with pnpm",
          "description": "Review and update package.json scripts to ensure they work seamlessly with pnpm's execution model. Confirm that any scripts responsible for showing a website or prompt during install behave identically with pnpm and npm. Ensure compatibility with 'module' package type and correct binary definitions.",
          "dependencies": [
            1
          ],
          "details": "Test all scripts using `pnpm run <script>`, address any pnpm-specific path or execution differences, and modify scripts as needed for compatibility. Pay special attention to any scripts that trigger a website or prompt during installation, ensuring they serve the same content as npm. Validate that scripts/init.js and binaries are referenced correctly for ESM ('module') projects.",
          "status": "done",
          "testStrategy": "Run all package scripts using pnpm and confirm expected behavior matches npm, especially for any website or UI shown during install. Validate correct execution of scripts/init.js and binary linking."
        },
        {
          "id": 3,
          "title": "Generate and Validate pnpm Lockfile",
          "description": "Install dependencies using pnpm to create a pnpm-lock.yaml file and ensure it accurately reflects the project's dependency tree, considering the 'module' package type.",
          "dependencies": [
            2
          ],
          "details": "Run `pnpm install` to generate the lockfile, check it into version control, and verify that dependency resolution is correct and consistent. Ensure that all dependencies listed in package.json are resolved as expected for an ESM project.",
          "status": "done",
          "testStrategy": "Compare dependency trees between npm and pnpm; ensure no missing or extraneous dependencies. Validate that the lockfile works for both CLI and init.js flows."
        },
        {
          "id": 4,
          "title": "Test Taskmaster Installation and Operation with pnpm",
          "description": "Thoroughly test Taskmaster's installation and CLI operation when installed via pnpm, both globally and locally. Confirm that any website or UI shown during installation is identical to npm. Validate that binaries and the init process (scripts/init.js) work as expected.",
          "dependencies": [
            3
          ],
          "details": "Perform global (`pnpm add -g taskmaster`) and local installations, verify CLI commands, and check for any pnpm-specific issues or incompatibilities. Ensure any installation UIs or websites appear identical to npm installations, including any website or prompt shown during install. Test that binaries 'task-master' and 'task-master-mcp' are linked and that scripts/init.js creates the correct structure and templates.",
          "status": "done",
          "testStrategy": "Document and resolve any errors encountered during installation or usage with pnpm. Compare the installation experience side-by-side with npm, including any website or UI shown during install. Validate directory and template setup as per scripts/init.js."
        },
        {
          "id": 5,
          "title": "Integrate pnpm into CI/CD Pipeline",
          "description": "Update CI/CD workflows to include pnpm in the test matrix, ensuring all tests pass when dependencies are installed with pnpm. Confirm that tests cover the 'module' package type, binaries, and init process.",
          "dependencies": [
            4
          ],
          "details": "Modify GitHub Actions or other CI configurations to use pnpm/action-setup, run tests with pnpm, and cache pnpm dependencies for efficiency. Ensure that CI covers CLI commands, binary linking, and the directory/template setup performed by scripts/init.js.",
          "status": "done",
          "testStrategy": "Confirm that CI passes for all supported package managers, including pnpm, and that pnpm-specific jobs are green. Validate that tests cover ESM usage, binaries, and init.js flows."
        },
        {
          "id": 6,
          "title": "Verify Installation UI/Website Consistency",
          "description": "Ensure any installation UIs, websites, or interactive prompts—including any website or prompt shown during install—appear and function identically when installing with pnpm compared to npm. Confirm that the experience is consistent for the 'module' package type and the init process.",
          "dependencies": [
            4
          ],
          "details": "Identify all user-facing elements during the installation process, including any website or prompt shown during install, and verify they are consistent across package managers. If a website is shown during installation, ensure it appears the same regardless of package manager used. Validate that any prompts or UIs triggered by scripts/init.js are identical.",
          "status": "done",
          "testStrategy": "Perform side-by-side installations with npm and pnpm, capturing screenshots of any UIs or websites for comparison. Test all interactive elements to ensure identical behavior, including any website or prompt shown during install and those from scripts/init.js."
        },
        {
          "id": 7,
          "title": "Test init.js Script with pnpm",
          "description": "Verify that the scripts/init.js file works correctly when Taskmaster is installed via pnpm, creating the proper directory structure and copying all required templates as defined in the project structure.",
          "dependencies": [
            4
          ],
          "details": "Test the init command to ensure it properly creates .cursor/rules, scripts, and tasks directories, copies templates (.env.example, .gitignore, rule files, dev.js), handles package.json merging, and sets up MCP config (.cursor/mcp.json) as per scripts/init.js.",
          "status": "done",
          "testStrategy": "Run the init command after installing with pnpm and verify all directories and files are created correctly. Compare the results with an npm installation to ensure identical behavior and structure."
        },
        {
          "id": 8,
          "title": "Verify Binary Links with pnpm",
          "description": "Ensure that the task-master and task-master-mcp binaries are properly defined in package.json, linked, and executable when installed via pnpm, in both global and local installations.",
          "dependencies": [
            4
          ],
          "details": "Check that the binaries defined in package.json are correctly linked in node_modules/.bin when installed with pnpm, and that they can be executed without errors. Validate that binaries work for ESM ('module') projects and are accessible after both global and local installs.",
          "status": "done",
          "testStrategy": "Install Taskmaster with pnpm and verify that the binaries are accessible and executable. Test both global and local installations, ensuring correct behavior for ESM projects."
        }
      ]
    },
    {
      "id": 64,
      "title": "Add Yarn Support for Taskmaster Installation",
      "description": "Implement full support for installing and managing Taskmaster using Yarn package manager, ensuring users have the exact same experience as with npm or pnpm. The installation process, including any CLI prompts or web interfaces, must serve the exact same content and user experience regardless of whether npm, pnpm, or Yarn is used. The project uses 'module' as the package type, defines binaries 'task-master' and 'task-master-mcp', and its core logic resides in 'scripts/modules/'. The 'init' command (via scripts/init.js) creates the directory structure (.cursor/rules, scripts, tasks), copies templates (.env.example, .gitignore, rule files, dev.js), manages package.json merging, and sets up MCP config (.cursor/mcp.json). All dependencies are standard npm dependencies listed in package.json, and manual modifications are being removed. \n\nIf the installation process includes a website component (such as for account setup or registration), ensure that any required website actions (e.g., creating an account, logging in, or configuring user settings) are clearly documented and tested for parity between Yarn and other package managers. If no website or account setup is required, confirm and document this explicitly.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves adding comprehensive Yarn support to the Taskmaster package to ensure it can be properly installed and managed using Yarn. Implementation should include:\n\n1. Update package.json to ensure compatibility with Yarn installation methods, considering the 'module' package type and binary definitions\n2. Verify all scripts and dependencies work correctly with Yarn\n3. Add Yarn-specific configuration files (e.g., .yarnrc.yml if needed)\n4. Update installation documentation to include Yarn installation instructions\n5. Ensure all post-install scripts work correctly with Yarn\n6. Verify that all CLI commands function properly when installed via Yarn\n7. Ensure binaries `task-master` and `task-master-mcp` are properly linked\n8. Test the `scripts/init.js` file with Yarn to verify it correctly:\n   - Creates directory structure (`.cursor/rules`, `scripts`, `tasks`)\n   - Copies templates (`.env.example`, `.gitignore`, rule files, `dev.js`)\n   - Manages `package.json` merging\n   - Sets up MCP config (`.cursor/mcp.json`)\n9. Handle any Yarn-specific package resolution or hoisting issues\n10. Test compatibility with different Yarn versions (classic and berry/v2+)\n11. Ensure proper lockfile generation and management\n12. Update any package manager detection logic in the codebase to recognize Yarn installations\n13. Verify that core logic in `scripts/modules/` works correctly when installed via Yarn\n14. If the installation process includes a website component, verify that any account setup or user registration flows work identically with Yarn as they do with npm or pnpm. If website actions are required, document the steps and ensure they are tested for parity. If not, confirm and document that no website or account setup is needed.\n\nThe implementation should maintain feature parity and identical user experience regardless of which package manager (npm, pnpm, or Yarn) is used to install Taskmaster.",
      "testStrategy": "Testing should verify complete Yarn support through the following steps:\n\n1. Fresh installation tests:\n   - Install Taskmaster using `yarn add taskmaster` (global and local installations)\n   - Verify installation completes without errors\n   - Check that binaries `task-master` and `task-master-mcp` are properly linked\n   - Test the `init` command to ensure it correctly sets up the directory structure and files as defined in scripts/init.js\n\n2. Functionality tests:\n   - Run all Taskmaster commands on a Yarn-installed version\n   - Verify all features work identically to npm installations\n   - Test with both Yarn v1 (classic) and Yarn v2+ (berry)\n   - Verify proper handling of 'module' package type\n\n3. Update/uninstall tests:\n   - Test updating the package using Yarn commands\n   - Verify clean uninstallation using Yarn\n\n4. CI integration:\n   - Add Yarn installation tests to CI pipeline\n   - Test on different operating systems (Windows, macOS, Linux)\n\n5. Documentation verification:\n   - Ensure all documentation accurately reflects Yarn installation methods\n   - Verify any Yarn-specific commands or configurations are properly documented\n\n6. Edge cases:\n   - Test installation in monorepo setups using Yarn workspaces\n   - Verify compatibility with other Yarn-specific features (plug'n'play, zero-installs)\n\n7. Structure Testing:\n   - Verify that the core logic in `scripts/modules/` is accessible and functions correctly\n   - Confirm that the `init` command properly creates all required directories and files as per scripts/init.js\n   - Test package.json merging functionality\n   - Verify MCP config setup\n\n8. Website/Account Setup Testing:\n   - If the installation process includes a website component, test the complete user flow including account setup, registration, or configuration steps. Ensure these work identically with Yarn as with npm. If no website or account setup is required, confirm and document this in the test results.\n   - Document any website-specific steps that users need to complete during installation.\n\nAll tests should pass with the same results as when using npm, with identical user experience throughout the installation and usage process.",
      "subtasks": [
        {
          "id": 1,
          "title": "Update package.json for Yarn Compatibility",
          "description": "Modify the package.json file to ensure all dependencies, scripts, and configurations are compatible with Yarn's installation and resolution methods. Confirm that any scripts responsible for showing a website or prompt during install behave identically with Yarn and npm. Ensure compatibility with 'module' package type and correct binary definitions.",
          "dependencies": [],
          "details": "Review and update dependency declarations, script syntax, and any package manager-specific fields to avoid conflicts or unsupported features when using Yarn. Pay special attention to any scripts that trigger a website or prompt during installation, ensuring they serve the same content as npm. Validate that scripts/init.js and binaries are referenced correctly for ESM ('module') projects.",
          "status": "done",
          "testStrategy": "Run 'yarn install' and 'yarn run <script>' for all scripts to confirm successful execution and dependency resolution, especially for any website or UI shown during install. Validate correct execution of scripts/init.js and binary linking."
        },
        {
          "id": 2,
          "title": "Add Yarn-Specific Configuration Files",
          "description": "Introduce Yarn-specific configuration files such as .yarnrc.yml if needed to optimize Yarn behavior and ensure consistent installs for 'module' package type and binary definitions.",
          "dependencies": [
            1
          ],
          "details": "Determine if Yarn v2+ (Berry) or classic requires additional configuration for the project, and add or update .yarnrc.yml or .yarnrc files accordingly. Ensure configuration supports ESM and binary linking.",
          "status": "done",
          "testStrategy": "Verify that Yarn respects the configuration by running installs and checking for expected behaviors (e.g., plug'n'play, nodeLinker settings, ESM support, binary linking)."
        },
        {
          "id": 3,
          "title": "Test and Fix Yarn Compatibility for Scripts and CLI",
          "description": "Ensure all scripts, post-install hooks, and CLI commands function correctly when Taskmaster is installed and managed via Yarn. Confirm that any website or UI shown during installation is identical to npm. Validate that binaries and the init process (scripts/init.js) work as expected.",
          "dependencies": [
            2
          ],
          "details": "Test all lifecycle scripts, post-install actions, and CLI commands using Yarn. Address any issues related to environment variables, script execution, or dependency hoisting. Ensure any website or prompt shown during install is the same as with npm. Validate that binaries 'task-master' and 'task-master-mcp' are linked and that scripts/init.js creates the correct structure and templates.",
          "status": "done",
          "testStrategy": "Install Taskmaster using Yarn and run all documented scripts and CLI commands, comparing results to npm installations, especially for any website or UI shown during install. Validate directory and template setup as per scripts/init.js."
        },
        {
          "id": 4,
          "title": "Update Documentation for Yarn Installation and Usage",
          "description": "Revise installation and usage documentation to include clear instructions for installing and managing Taskmaster with Yarn. Clearly state that the installation process, including any website or UI shown, is identical to npm. Ensure documentation reflects the use of 'module' package type, binaries, and the init process as defined in scripts/init.js. If the installation process includes a website component or requires account setup, document the steps users must follow. If not, explicitly state that no website or account setup is required.",
          "dependencies": [
            3
          ],
          "details": "Add Yarn-specific installation commands, troubleshooting tips, and notes on version compatibility to the README and any relevant docs. Document that any installation website or prompt is the same as with npm. Include notes on the 'module' package type, binaries, and the directory/template setup performed by scripts/init.js. If website or account setup is required during installation, provide clear instructions; otherwise, confirm and document that no such steps are needed.",
          "status": "done",
          "testStrategy": "Review documentation for accuracy and clarity; have a user follow the Yarn instructions to verify successful installation and usage. Confirm that documentation explicitly states the identical experience for npm and Yarn, including any website or UI shown during install, and describes the init process and binaries. If website/account setup is required, verify that instructions are complete and accurate; if not, confirm this is documented."
        },
        {
          "id": 5,
          "title": "Implement and Test Package Manager Detection Logic",
          "description": "Update or add logic in the codebase to detect Yarn installations and handle Yarn-specific behaviors, ensuring feature parity across package managers. Ensure detection logic works for 'module' package type and binary definitions.",
          "dependencies": [
            4
          ],
          "details": "Modify detection logic to recognize Yarn (classic and berry), handle lockfile generation, and resolve any Yarn-specific package resolution or hoisting issues. Ensure detection logic supports ESM and binary linking.",
          "status": "done",
          "testStrategy": "Install Taskmaster using npm, pnpm, and Yarn (classic and berry), verifying that the application detects the package manager correctly and behaves consistently for ESM projects and binaries."
        },
        {
          "id": 6,
          "title": "Verify Installation UI/Website Consistency",
          "description": "Ensure any installation UIs, websites, or interactive prompts—including any website or prompt shown during install—appear and function identically when installing with Yarn compared to npm. Confirm that the experience is consistent for the 'module' package type and the init process. If the installation process includes a website or account setup, verify that all required website actions (e.g., account creation, login) are consistent and documented. If not, confirm and document that no website or account setup is needed.",
          "dependencies": [
            3
          ],
          "details": "Identify all user-facing elements during the installation process, including any website or prompt shown during install, and verify they are consistent across package managers. If a website is shown during installation or account setup is required, ensure it appears and functions the same regardless of package manager used, and document the steps. If not, confirm and document that no website or account setup is needed. Validate that any prompts or UIs triggered by scripts/init.js are identical.",
          "status": "done",
          "testStrategy": "Perform side-by-side installations with npm and Yarn, capturing screenshots of any UIs or websites for comparison. Test all interactive elements to ensure identical behavior, including any website or prompt shown during install and those from scripts/init.js. If website/account setup is required, verify and document the steps; if not, confirm this is documented."
        },
        {
          "id": 7,
          "title": "Test init.js Script with Yarn",
          "description": "Verify that the scripts/init.js file works correctly when Taskmaster is installed via Yarn, creating the proper directory structure and copying all required templates as defined in the project structure.",
          "dependencies": [
            3
          ],
          "details": "Test the init command to ensure it properly creates .cursor/rules, scripts, and tasks directories, copies templates (.env.example, .gitignore, rule files, dev.js), handles package.json merging, and sets up MCP config (.cursor/mcp.json) as per scripts/init.js.",
          "status": "done",
          "testStrategy": "Run the init command after installing with Yarn and verify all directories and files are created correctly. Compare the results with an npm installation to ensure identical behavior and structure."
        },
        {
          "id": 8,
          "title": "Verify Binary Links with Yarn",
          "description": "Ensure that the task-master and task-master-mcp binaries are properly defined in package.json, linked, and executable when installed via Yarn, in both global and local installations.",
          "dependencies": [
            3
          ],
          "details": "Check that the binaries defined in package.json are correctly linked in node_modules/.bin when installed with Yarn, and that they can be executed without errors. Validate that binaries work for ESM ('module') projects and are accessible after both global and local installs.",
          "status": "done",
          "testStrategy": "Install Taskmaster with Yarn and verify that the binaries are accessible and executable. Test both global and local installations, ensuring correct behavior for ESM projects."
        },
        {
          "id": 9,
          "title": "Test Website Account Setup with Yarn",
          "description": "If the installation process includes a website component, verify that account setup, registration, or any other user-specific configurations work correctly when Taskmaster is installed via Yarn. If no website or account setup is required, confirm and document this explicitly.",
          "dependencies": [
            6
          ],
          "details": "Test the complete user flow for any website component that appears during installation, including account creation, login, and configuration steps. Ensure that all website interactions work identically with Yarn as they do with npm or pnpm. Document any website-specific steps that users need to complete during the installation process. If no website or account setup is required, confirm and document this.\n\n<info added on 2025-04-25T08:45:48.709Z>\nSince the request is vague, I'll provide helpful implementation details for testing website account setup with Yarn:\n\nFor thorough testing, create a test matrix covering different browsers (Chrome, Firefox, Safari) and operating systems (Windows, macOS, Linux). Document specific Yarn-related environment variables that might affect website connectivity. Use tools like Playwright or Cypress to automate the account setup flow testing, capturing screenshots at each step for documentation. Implement network throttling tests to verify behavior under poor connectivity. Create a checklist of all UI elements that should be verified during the account setup process, including form validation, error messages, and success states. If no website component exists, explicitly document this in the project README and installation guides to prevent user confusion.\n</info added on 2025-04-25T08:45:48.709Z>\n\n<info added on 2025-04-25T08:46:08.651Z>\n- For environments where the website component requires integration with external authentication providers (such as OAuth, SSO, or LDAP), ensure that these flows are tested specifically when Taskmaster is installed via Yarn. Validate that redirect URIs, token exchanges, and session persistence behave as expected across all supported browsers.\n\n- If the website setup involves configuring application pools or web server settings (e.g., with IIS), document any Yarn-specific considerations, such as environment variable propagation or file permission differences, that could affect the web service's availability or configuration[2].\n\n- When automating tests, include validation for accessibility compliance (e.g., using axe-core or Lighthouse) during the account setup process to ensure the UI is usable for all users.\n\n- Capture and log all HTTP requests and responses during the account setup flow to help diagnose any discrepancies between Yarn and other package managers. This can be achieved by enabling network logging in Playwright or Cypress test runs.\n\n- If the website component supports batch operations or automated uploads (such as uploading user data or configuration files), verify that these automation features function identically after installation with Yarn[3].\n\n- For documentation, provide annotated screenshots or screen recordings of the account setup process, highlighting any Yarn-specific prompts, warnings, or differences encountered.\n\n- If the website component is not required, add a badge or prominent note in the README and installation guides stating \"No website or account setup required,\" and reference the test results confirming this.\n</info added on 2025-04-25T08:46:08.651Z>\n\n<info added on 2025-04-25T17:04:12.550Z>\nFor clarity, this task does not involve setting up a Yarn account. Yarn itself is just a package manager that doesn't require any account creation. The task is about testing whether any website component that is part of Taskmaster (if one exists) works correctly when Taskmaster is installed using Yarn as the package manager.\n\nTo be specific:\n- You don't need to create a Yarn account\n- Yarn is simply the tool used to install Taskmaster (`yarn add taskmaster` instead of `npm install taskmaster`)\n- The testing focuses on whether any web interfaces or account setup processes that are part of Taskmaster itself function correctly when the installation was done via Yarn\n- If Taskmaster includes a web dashboard or requires users to create accounts within the Taskmaster system, those features should be tested\n\nIf you're uncertain whether Taskmaster includes a website component at all, the first step would be to check the project documentation or perform an initial installation to determine if any web interface exists.\n</info added on 2025-04-25T17:04:12.550Z>\n\n<info added on 2025-04-25T17:19:03.256Z>\nWhen testing website account setup with Yarn after the codebase refactor, pay special attention to:\n\n- Verify that any environment-specific configuration files (like `.env` or config JSON files) are properly loaded when the application is installed via Yarn\n- Test the session management implementation to ensure user sessions persist correctly across page refreshes and browser restarts\n- Check that any database migrations or schema updates required for account setup execute properly when installed via Yarn\n- Validate that client-side form validation logic works consistently with server-side validation\n- Ensure that any WebSocket connections for real-time features initialize correctly after the refactor\n- Test account deletion and data export functionality to verify GDPR compliance remains intact\n- Document any changes to the authentication flow that resulted from the refactor and confirm they work identically with Yarn installation\n</info added on 2025-04-25T17:19:03.256Z>\n\n<info added on 2025-04-25T17:22:05.951Z>\nWhen testing website account setup with Yarn after the logging fix, implement these additional verification steps:\n\n1. Verify that all account-related actions are properly logged with the correct log levels (debug, info, warn, error) according to the updated logging framework\n2. Test the error handling paths specifically - force authentication failures and verify the logs contain sufficient diagnostic information\n3. Check that sensitive user information is properly redacted in logs according to privacy requirements\n4. Confirm that log rotation and persistence work correctly when high volumes of authentication attempts occur\n5. Validate that any custom logging middleware correctly captures HTTP request/response data for account operations\n6. Test that log aggregation tools (if used) can properly parse and display the account setup logs in their expected format\n7. Verify that performance metrics for account setup flows are correctly captured in logs for monitoring purposes\n8. Document any Yarn-specific environment variables that affect the logging configuration for the website component\n</info added on 2025-04-25T17:22:05.951Z>\n\n<info added on 2025-04-25T17:22:46.293Z>\nWhen testing website account setup with Yarn, consider implementing a positive user experience validation:\n\n1. Measure and document time-to-completion for the account setup process to ensure it meets usability standards\n2. Create a satisfaction survey for test users to rate the account setup experience on a 1-5 scale\n3. Implement A/B testing for different account setup flows to identify the most user-friendly approach\n4. Add delightful micro-interactions or success animations that make the setup process feel rewarding\n5. Test the \"welcome\" or \"onboarding\" experience that follows successful account creation\n6. Ensure helpful tooltips and contextual help are displayed at appropriate moments during setup\n7. Verify that error messages are friendly, clear, and provide actionable guidance rather than technical jargon\n8. Test the account recovery flow to ensure users have a smooth experience if they forget credentials\n</info added on 2025-04-25T17:22:46.293Z>",
          "status": "done",
          "testStrategy": "Perform a complete installation with Yarn and follow through any website account setup process. Compare the experience with npm installation to ensure identical behavior. Test edge cases such as account creation failures, login issues, and configuration changes. If no website or account setup is required, confirm and document this in the test results."
        }
      ]
    },
    {
      "id": 65,
      "title": "Add Bun Support for Taskmaster Installation",
      "description": "Implement full support for installing and managing Taskmaster using the Bun package manager, ensuring the installation process and user experience are identical to npm, pnpm, and Yarn.",
      "details": "Update the Taskmaster installation scripts and documentation to support Bun as a first-class package manager. Ensure that users can install Taskmaster and run all CLI commands (including 'init' via scripts/init.js) using Bun, with the same directory structure, template copying, package.json merging, and MCP config setup as with npm, pnpm, and Yarn. Verify that all dependencies are compatible with Bun and that any Bun-specific configuration (such as lockfile handling or binary linking) is handled correctly. If the installation process includes a website or account setup, document and test these flows for parity; if not, explicitly confirm and document that no such steps are required. Update all relevant documentation and installation guides to include Bun instructions for macOS, Linux, and Windows (including WSL and PowerShell). Address any known Bun-specific issues (e.g., sporadic install hangs) with clear troubleshooting guidance.",
      "testStrategy": "1. Install Taskmaster using Bun on macOS, Linux, and Windows (including WSL and PowerShell), following the updated documentation. 2. Run the full installation and initialization process, verifying that the directory structure, templates, and MCP config are set up identically to npm, pnpm, and Yarn. 3. Execute all CLI commands (including 'init') and confirm functional parity. 4. If a website or account setup is required, test these flows for consistency; if not, confirm and document this. 5. Check for Bun-specific issues (e.g., install hangs) and verify that troubleshooting steps are effective. 6. Ensure the documentation is clear, accurate, and up to date for all supported platforms.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Research Bun compatibility requirements",
          "description": "Investigate Bun's JavaScript runtime environment and identify key differences from Node.js that may affect Taskmaster's installation and operation.",
          "dependencies": [],
          "details": "Research Bun's package management, module resolution, and API compatibility with Node.js. Document any potential issues or limitations that might affect Taskmaster. Identify required changes to make Taskmaster compatible with Bun's execution model.",
          "status": "done"
        },
        {
          "id": 2,
          "title": "Update installation scripts for Bun compatibility",
          "description": "Modify the existing installation scripts to detect and support Bun as a runtime environment.",
          "dependencies": [
            1
          ],
          "details": "Add Bun detection logic to installation scripts. Update package management commands to use Bun equivalents where needed. Ensure all dependencies are compatible with Bun. Modify any Node.js-specific code to work with Bun's runtime.",
          "status": "done"
        },
        {
          "id": 3,
          "title": "Create Bun-specific installation path",
          "description": "Implement a dedicated installation flow for Bun users that optimizes for Bun's capabilities.",
          "dependencies": [
            2
          ],
          "details": "Create a Bun-specific installation script that leverages Bun's performance advantages. Update any environment detection logic to properly identify Bun environments. Ensure proper path resolution and environment variable handling for Bun.",
          "status": "done"
        },
        {
          "id": 4,
          "title": "Test Taskmaster installation with Bun",
          "description": "Perform comprehensive testing of the installation process using Bun across different operating systems.",
          "dependencies": [
            3
          ],
          "details": "Test installation on Windows, macOS, and Linux using Bun. Verify that all Taskmaster features work correctly when installed via Bun. Document any issues encountered and implement fixes as needed.",
          "status": "done"
        },
        {
          "id": 5,
          "title": "Test Taskmaster operation with Bun",
          "description": "Ensure all Taskmaster functionality works correctly when running under Bun.",
          "dependencies": [
            4
          ],
          "details": "Test all Taskmaster commands and features when running with Bun. Compare performance metrics between Node.js and Bun. Identify and fix any runtime issues specific to Bun. Ensure all plugins and extensions are compatible.",
          "status": "done"
        },
        {
          "id": 6,
          "title": "Update documentation for Bun support",
          "description": "Update all relevant documentation to include information about installing and running Taskmaster with Bun.",
          "dependencies": [
            4,
            5
          ],
          "details": "Add Bun installation instructions to README and documentation. Document any Bun-specific considerations or limitations. Update troubleshooting guides to include Bun-specific issues. Create examples showing Bun usage with Taskmaster.",
          "status": "done"
        }
      ]
    },
    {
      "id": 66,
      "title": "Support Status Filtering in Show Command for Subtasks",
      "description": "Enhance the 'show' command to accept a status parameter that filters subtasks by their current status, allowing users to view only subtasks matching a specific status.",
      "details": "This task involves modifying the existing 'show' command functionality to support status-based filtering of subtasks. Implementation details include:\n\n1. Update the command parser to accept a new '--status' or '-s' flag followed by a status value (e.g., 'task-master show --status=in-progress' or 'task-master show -s completed').\n\n2. Modify the show command handler in the appropriate module (likely in scripts/modules/) to:\n   - Parse and validate the status parameter\n   - Filter the subtasks collection based on the provided status before displaying results\n   - Handle invalid status values gracefully with appropriate error messages\n   - Support standard status values (e.g., 'not-started', 'in-progress', 'completed', 'blocked')\n   - Consider supporting multiple status values (comma-separated or multiple flags)\n\n3. Update the help documentation to include information about the new status filtering option.\n\n4. Ensure backward compatibility - the show command should function as before when no status parameter is provided.\n\n5. Consider adding a '--status-list' option to display all available status values for reference.\n\n6. Update any relevant unit tests to cover the new functionality.\n\n7. If the application uses a database or persistent storage, ensure the filtering happens at the query level for performance when possible.\n\n8. Maintain consistent formatting and styling of output regardless of filtering.",
      "testStrategy": "Testing for this feature should include:\n\n1. Unit tests:\n   - Test parsing of the status parameter in various formats (--status=value, -s value)\n   - Test filtering logic with different status values\n   - Test error handling for invalid status values\n   - Test backward compatibility (no status parameter)\n   - Test edge cases (empty status, case sensitivity, etc.)\n\n2. Integration tests:\n   - Verify that the command correctly filters subtasks when a valid status is provided\n   - Verify that all subtasks are shown when no status filter is applied\n   - Test with a project containing subtasks of various statuses\n\n3. Manual testing:\n   - Create a test project with multiple subtasks having different statuses\n   - Run the show command with different status filters and verify results\n   - Test with both long-form (--status) and short-form (-s) parameters\n   - Verify help documentation correctly explains the new parameter\n\n4. Edge case testing:\n   - Test with non-existent status values\n   - Test with empty project (no subtasks)\n   - Test with a project where all subtasks have the same status\n\n5. Documentation verification:\n   - Ensure the README or help documentation is updated to include the new parameter\n   - Verify examples in documentation work as expected\n\nAll tests should pass before considering this task complete.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "subtasks": []
    },
    {
      "id": 67,
      "title": "Add CLI JSON output and Cursor keybindings integration",
      "description": "Enhance Taskmaster CLI with JSON output option and add a new command to install pre-configured Cursor keybindings",
      "status": "pending",
      "dependencies": [],
      "priority": "high",
      "details": "This task has two main components:\\n\\n1. Add `--json` flag to all relevant CLI commands:\\n   - Modify the CLI command handlers to check for a `--json` flag\\n   - When the flag is present, output the raw data from the MCP tools in JSON format instead of formatting for human readability\\n   - Ensure consistent JSON schema across all commands\\n   - Add documentation for this feature in the help text for each command\\n   - Test with common scenarios like `task-master next --json` and `task-master show <id> --json`\\n\\n2. Create a new `install-keybindings` command:\\n   - Create a new CLI command that installs pre-configured Taskmaster keybindings to Cursor\\n   - Detect the user's OS to determine the correct path to Cursor's keybindings.json\\n   - Check if the file exists; create it if it doesn't\\n   - Add useful Taskmaster keybindings like:\\n     - Quick access to next task with output to clipboard\\n     - Task status updates\\n     - Opening new agent chat with context from the current task\\n   - Implement safeguards to prevent duplicate keybindings\\n   - Add undo functionality or backup of previous keybindings\\n   - Support custom key combinations via command flags",
      "testStrategy": "1. JSON output testing:\\n   - Unit tests for each command with the --json flag\\n   - Verify JSON schema consistency across commands\\n   - Validate that all necessary task data is included in the JSON output\\n   - Test piping output to other commands like jq\\n\\n2. Keybindings command testing:\\n   - Test on different OSes (macOS, Windows, Linux)\\n   - Verify correct path detection for Cursor's keybindings.json\\n   - Test behavior when file doesn't exist\\n   - Test behavior when existing keybindings conflict\\n   - Validate the installed keybindings work as expected\\n   - Test uninstall/restore functionality",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement Core JSON Output Logic for `next` and `show` Commands",
          "description": "Modify the command handlers for `task-master next` and `task-master show <id>` to recognize and handle a `--json` flag. When the flag is present, output the raw data received from MCP tools directly as JSON.",
          "dependencies": [],
          "details": "1. Update the CLI argument parser to add the `--json` boolean flag to both commands\n2. Create a `formatAsJson` utility function in `src/utils/output.js` that takes a data object and returns a properly formatted JSON string\n3. In the command handler functions (`src/commands/next.js` and `src/commands/show.js`), add a conditional check for the `--json` flag\n4. If the flag is set, call the `formatAsJson` function with the raw data object and print the result\n5. If the flag is not set, continue with the existing human-readable formatting logic\n6. Ensure proper error handling for JSON serialization failures\n7. Update the command help text in both files to document the new flag",
          "status": "pending",
          "testStrategy": "1. Create unit tests in `tests/commands/next.test.js` and `tests/commands/show.test.js`\n2. Mock the MCP data response and verify the JSON output matches expected format\n3. Test with both valid and invalid task IDs for the `show` command\n4. Verify the JSON output can be parsed back into a valid object\n5. Run manual tests with `task-master next --json` and `task-master show 123 --json` to confirm functionality"
        },
        {
          "id": 2,
          "title": "Extend JSON Output to All Relevant Commands and Ensure Schema Consistency",
          "description": "Apply the JSON output pattern established in subtask 1 to all other relevant Taskmaster CLI commands that display data (e.g., `list`, `status`, etc.). Ensure the JSON structure is consistent where applicable (e.g., task objects should have the same fields). Add help text mentioning the `--json` flag for each modified command.",
          "dependencies": [
            1
          ],
          "details": "1. Create a JSON schema definition file at `src/schemas/task.json` to define the standard structure for task objects\n2. Modify the following command files to support the `--json` flag:\n   - `src/commands/list.js`\n   - `src/commands/status.js`\n   - `src/commands/search.js`\n   - `src/commands/summary.js`\n3. Refactor the `formatAsJson` utility to handle different data types (single task, task array, status object, etc.)\n4. Add a `validateJsonSchema` function in `src/utils/validation.js` to ensure output conforms to defined schemas\n5. Update each command's help text documentation to include the `--json` flag description\n6. Implement consistent error handling for JSON output (using a standard error object format)\n7. For list-type commands, ensure array outputs are properly formatted as JSON arrays",
          "status": "pending",
          "testStrategy": "1. Create unit tests for each modified command in their respective test files\n2. Test each command with the `--json` flag and validate output against the defined schemas\n3. Create specific test cases for edge conditions (empty lists, error states, etc.)\n4. Verify help text includes `--json` documentation for each command\n5. Test piping JSON output to tools like `jq` to confirm proper formatting\n6. Create integration tests that verify schema consistency across different commands"
        },
        {
          "id": 3,
          "title": "Create `install-keybindings` Command Structure and OS Detection",
          "description": "Set up the basic structure for the new `task-master install-keybindings` command. Implement logic to detect the user's operating system (Linux, macOS, Windows) and determine the default path to Cursor's `keybindings.json` file.",
          "dependencies": [],
          "details": "1. Create a new command file at `src/commands/install-keybindings.js`\n2. Register the command in the main CLI entry point (`src/index.js`)\n3. Implement OS detection using `os.platform()` in Node.js\n4. Define the following path constants in `src/config/paths.js`:\n   - Windows: `%APPDATA%\\Cursor\\User\\keybindings.json`\n   - macOS: `~/Library/Application Support/Cursor/User/keybindings.json`\n   - Linux: `~/.config/Cursor/User/keybindings.json`\n5. Create a `getCursorKeybindingsPath()` function that returns the appropriate path based on detected OS\n6. Add path override capability via a `--path` command line option\n7. Implement proper error handling for unsupported operating systems\n8. Add detailed help text explaining the command's purpose and options",
          "status": "pending",
          "testStrategy": "1. Create unit tests in `tests/commands/install-keybindings.test.js`\n2. Mock the OS detection to test path resolution for each supported platform\n3. Test the path override functionality with the `--path` option\n4. Verify error handling for unsupported OS scenarios\n5. Test the command's help output to ensure it's comprehensive\n6. Run manual tests on different operating systems if possible"
        },
        {
          "id": 4,
          "title": "Implement Keybinding File Handling and Backup Logic",
          "description": "Implement the core logic within the `install-keybindings` command to read the target `keybindings.json` file. If it exists, create a backup. If it doesn't exist, create a new file with an empty JSON array `[]`. Prepare the structure to add new keybindings.",
          "dependencies": [
            3
          ],
          "details": "1. Create a `KeybindingsManager` class in `src/utils/keybindings.js` with the following methods:\n   - `checkFileExists(path)`: Verify if the keybindings file exists\n   - `createBackup(path)`: Copy existing file to `keybindings.json.bak`\n   - `readKeybindings(path)`: Read and parse the JSON file\n   - `writeKeybindings(path, data)`: Serialize and write data to the file\n   - `createEmptyFile(path)`: Create a new file with `[]` content\n2. In the command handler, use these methods to:\n   - Check if the target file exists\n   - Create a backup if it does (with timestamp in filename)\n   - Read existing keybindings or create an empty file\n   - Parse the JSON content with proper error handling\n3. Add a `--no-backup` flag to skip backup creation\n4. Implement verbose logging with a `--verbose` flag\n5. Handle all potential file system errors (permissions, disk space, etc.)\n6. Add a `--dry-run` option that shows what would be done without making changes",
          "status": "pending",
          "testStrategy": "1. Create unit tests for the `KeybindingsManager` class\n2. Test all file handling scenarios with mocked file system:\n   - File exists with valid JSON\n   - File exists with invalid JSON\n   - File doesn't exist\n   - File exists but is not writable\n   - Backup creation succeeds/fails\n3. Test the `--no-backup` and `--dry-run` flags\n4. Verify error messages are clear and actionable\n5. Test with various mock file contents to ensure proper parsing"
        },
        {
          "id": 5,
          "title": "Add Taskmaster Keybindings, Prevent Duplicates, and Support Customization",
          "description": "Define the specific Taskmaster keybindings (e.g., next task to clipboard, status update, open agent chat) and implement the logic to merge them into the user's `keybindings.json` data. Prevent adding duplicate keybindings (based on command ID or key combination). Add support for custom key combinations via command flags.",
          "dependencies": [
            4
          ],
          "details": "1. Define default Taskmaster keybindings in `src/config/default-keybindings.js` as an array of objects with:\n   - `key`: Default key combination (e.g., `\"ctrl+alt+n\"`)\n   - `command`: Cursor command ID (e.g., `\"taskmaster.nextTask\"`)\n   - `when`: Context when keybinding is active (e.g., `\"editorTextFocus\"`)\n   - `args`: Any command arguments as an object\n   - `description`: Human-readable description of what the keybinding does\n2. Implement the following keybindings:\n   - Next task to clipboard: `ctrl+alt+n`\n   - Update task status: `ctrl+alt+u`\n   - Open agent chat with task context: `ctrl+alt+a`\n   - Show task details: `ctrl+alt+d`\n3. Add command-line options to customize each keybinding:\n   - `--next-key=\"ctrl+alt+n\"`\n   - `--update-key=\"ctrl+alt+u\"`\n   - `--agent-key=\"ctrl+alt+a\"`\n   - `--details-key=\"ctrl+alt+d\"`\n4. Implement a `mergeKeybindings(existing, new)` function that:\n   - Checks for duplicates based on command ID\n   - Checks for key combination conflicts\n   - Warns about conflicts but allows override with `--force` flag\n   - Preserves existing non-Taskmaster keybindings\n5. Add a `--reset` flag to remove all existing Taskmaster keybindings before adding new ones\n6. Add a `--list` option to display currently installed Taskmaster keybindings\n7. Implement an `--uninstall` option to remove all Taskmaster keybindings",
          "status": "pending",
          "testStrategy": "1. Create unit tests for the keybinding merging logic\n2. Test duplicate detection and conflict resolution\n3. Test each customization flag to verify it properly overrides defaults\n4. Test the `--reset`, `--list`, and `--uninstall` options\n5. Create integration tests with various starting keybindings.json states\n6. Manually verify the installed keybindings work in Cursor\n7. Test edge cases like:\n   - All keybindings customized\n   - Conflicting key combinations with `--force` and without\n   - Empty initial keybindings file\n   - File with existing Taskmaster keybindings"
        }
      ]
    },
    {
      "id": 68,
      "title": "Ability to create tasks without parsing PRD",
      "description": "Which just means that when we create a task, if there's no tasks.json, we should create it calling the same function that is done by parse-prd. this lets taskmaster be used without a prd as a starding point.",
      "details": "",
      "testStrategy": "",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Design task creation form without PRD",
          "description": "Create a user interface form that allows users to manually input task details without requiring a PRD document",
          "dependencies": [],
          "details": "Design a form with fields for task title, description, priority, assignee, due date, and other relevant task attributes. Include validation to ensure required fields are completed. The form should be intuitive and provide clear guidance on how to create a task manually.",
          "status": "done"
        },
        {
          "id": 2,
          "title": "Implement task saving functionality",
          "description": "Develop the backend functionality to save manually created tasks to the database",
          "dependencies": [
            1
          ],
          "details": "Create API endpoints to handle task creation requests from the frontend. Implement data validation, error handling, and confirmation messages. Ensure the saved tasks appear in the task list view and can be edited or deleted like PRD-parsed tasks.",
          "status": "done"
        }
      ]
    },
    {
      "id": 69,
      "title": "Enhance Analyze Complexity for Specific Task IDs",
      "description": "Modify the analyze-complexity feature (CLI and MCP) to allow analyzing only specified task IDs or ranges, and append/update results in the report.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "\nImplementation Plan:\n\n1. **Core Logic (`scripts/modules/task-manager/analyze-task-complexity.js`)**\n    * Modify function signature to accept optional parameters: `options.ids` (string, comma-separated IDs) and range parameters `options.from` and `options.to`.\n    * If `options.ids` is present:\n        * Parse the `ids` string into an array of target IDs.\n        * Filter `tasksData.tasks` to include only tasks matching the target IDs.\n        * Handle cases where provided IDs don't exist in `tasks.json`.\n    * If range parameters (`options.from` and `options.to`) are present:\n        * Parse these values into integers.\n        * Filter tasks within the specified ID range (inclusive).\n    * If neither `options.ids` nor range parameters are present: Continue with existing logic (filtering by active status).\n    * Maintain existing logic for skipping completed tasks.\n    * **Report Handling:**\n        * Before generating analysis, check if the `outputPath` report file exists.\n        * If it exists:\n            * Read the existing `complexityAnalysis` array.\n            * Generate new analysis only for target tasks (filtered by ID or range).\n            * Merge results: Remove entries from the existing array that match IDs analyzed in the current run, then append new analysis results to the array.\n            * Update the `meta` section (`generatedAt`, `tasksAnalyzed`).\n            * Write merged `complexityAnalysis` and updated `meta` back to report file.\n        * If the report file doesn't exist: Create it as usual.\n    * **Prompt Generation:** Ensure `generateInternalComplexityAnalysisPrompt` receives correctly filtered list of tasks.\n\n2. **CLI (`scripts/modules/commands.js`)**\n    * Add new options to the `analyze-complexity` command:\n        * `--id/-i <ids>`: \"Comma-separated list of specific task IDs to analyze\"\n        * `--from/-f <startId>`: \"Start ID for range analysis (inclusive)\"\n        * `--to/-t <endId>`: \"End ID for range analysis (inclusive)\"\n    * In the `.action` handler:\n        * Check if `options.id`, `options.from`, or `options.to` are provided.\n        * If yes, pass appropriate values to the `analyzeTaskComplexity` core function via the `options` object.\n        * Update user feedback messages to indicate specific task analysis.\n\n3. **MCP Tool (`mcp-server/src/tools/analyze.js`)**\n    * Add new optional parameters to Zod schema for `analyze_project_complexity` tool:\n        * `ids: z.string().optional().describe(\"Comma-separated list of task IDs to analyze specifically\")`\n        * `from: z.number().optional().describe(\"Start ID for range analysis (inclusive)\")`\n        * `to: z.number().optional().describe(\"End ID for range analysis (inclusive)\")`\n    * In the `execute` method, pass `args.ids`, `args.from`, and `args.to` to the `analyzeTaskComplexityDirect` function within its `args` object.\n\n4. **Direct Function (`mcp-server/src/core/direct-functions/analyze-task-complexity.js`)**\n    * Update function to receive `ids`, `from`, and `to` values within the `args` object.\n    * Pass these values along to the core `analyzeTaskComplexity` function within its `options` object.\n\n5. **Documentation:** Update relevant rule files (`commands.mdc`, `taskmaster.mdc`) to reflect new `--id/-i`, `--from/-f`, and `--to/-t` options/parameters.",
      "testStrategy": "\n1. **CLI:**\n    * Run `task-master analyze-complexity -i=<id1>` (where report doesn't exist). Verify report created with only task id1.\n    * Run `task-master analyze-complexity -i=<id2>` (where report exists). Verify report updated, containing analysis for both id1 and id2 (id2 replaces any previous id2 analysis).\n    * Run `task-master analyze-complexity -i=<id1>,<id3>`. Verify report updated, containing id1, id2, id3.\n    * Run `task-master analyze-complexity -f=50 -t=60`. Verify report created/updated with tasks in the range 50-60.\n    * Run `task-master analyze-complexity` (no flags). Verify it analyzes all active tasks and updates the report accordingly, merging with previous specific analyses.\n    * Test with invalid/non-existent IDs or ranges.\n    * Verify that completed tasks are still skipped in all scenarios, maintaining existing behavior.\n2. **MCP:**\n    * Call `analyze_project_complexity` tool with `ids: \"<id1>\"`. Verify report creation/update.\n    * Call `analyze_project_complexity` tool with `ids: \"<id1>,<id2>,<id3>\"`. Verify report created/updated with multiple specific tasks.\n    * Call `analyze_project_complexity` tool with `from: 50, to: 60`. Verify report created/updated for tasks in range.\n    * Call `analyze_project_complexity` tool without parameters. Verify full analysis and merging.\n3. Verify report `meta` section is updated correctly on each run.",
      "subtasks": [
        {
          "id": 1,
          "title": "Modify core complexity analysis logic",
          "description": "Update the core complexity analysis function to accept specific task IDs or ranges as input parameters",
          "dependencies": [],
          "details": "Refactor the existing complexity analysis module to allow filtering by task IDs or ranges. This involves modifying the data processing pipeline to filter tasks before analysis, ensuring the complexity metrics are calculated only for the specified tasks while maintaining context awareness.",
          "status": "done"
        },
        {
          "id": 2,
          "title": "Update CLI interface for task-specific complexity analysis",
          "description": "Extend the CLI to accept task IDs or ranges as parameters for the complexity analysis command",
          "dependencies": [
            1
          ],
          "details": "Add new flags `--id/-i`, `--from/-f`, and `--to/-t` to the CLI that allow users to specify task IDs or ranges for targeted complexity analysis. Update the command parser, help documentation, and ensure proper validation of the provided values.",
          "status": "done"
        },
        {
          "id": 3,
          "title": "Integrate task-specific analysis with MCP tool",
          "description": "Update the MCP tool interface to support analyzing complexity for specific tasks or ranges",
          "dependencies": [
            1
          ],
          "details": "Modify the MCP tool's API endpoints and UI components to allow users to select specific tasks or ranges for complexity analysis. Ensure the UI provides clear feedback about which tasks are being analyzed and update the visualization components to properly display partial analysis results.",
          "status": "done"
        },
        {
          "id": 4,
          "title": "Create comprehensive tests for task-specific complexity analysis",
          "description": "Develop test cases to verify the correct functioning of task-specific complexity analysis",
          "dependencies": [
            1,
            2,
            3
          ],
          "details": "Create unit and integration tests that verify the task-specific complexity analysis works correctly across both CLI and MCP interfaces. Include tests for edge cases such as invalid task IDs, tasks with dependencies outside the selected set, and performance tests for large task sets.",
          "status": "done"
        }
      ]
    },
    {
      "id": 70,
      "title": "Implement 'diagram' command for Mermaid diagram generation",
      "description": "Develop a CLI command named 'diagram' that generates Mermaid diagrams to visualize task dependencies and workflows, with options to target specific tasks or generate comprehensive diagrams for all tasks.",
      "details": "The task involves implementing a new command that accepts an optional '--id' parameter: if provided, the command generates a diagram illustrating the chosen task and its dependencies; if omitted, it produces a diagram that includes all tasks. The diagrams should use color coding to reflect task status and arrows to denote dependencies. In addition to CLI rendering, the command should offer an option to save the output as a Markdown (.md) file. Consider integrating with the existing task management system to pull task details and status. Pay attention to formatting consistency and error handling for invalid or missing task IDs. Comments should be added to the code to improve maintainability, and unit tests should cover edge cases such as cyclic dependencies, missing tasks, and invalid input formats.",
      "testStrategy": "Verify the command functionality by testing with both specific task IDs and general invocation: 1) Run the command with a valid '--id' and ensure the resulting diagram accurately depicts the specified task's dependencies with correct color codings for statuses. 2) Execute the command without '--id' to ensure a complete workflow diagram is generated for all tasks. 3) Check that arrows correctly represent dependency relationships. 4) Validate the Markdown (.md) file export option by confirming the file format and content after saving. 5) Test error responses for non-existent task IDs and malformed inputs.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Design the 'diagram' command interface",
          "description": "Define the command structure, arguments, and options for the Mermaid diagram generation feature",
          "dependencies": [],
          "details": "Create a command specification that includes: input parameters for diagram source (file, stdin, or string), output options (file, stdout, clipboard), format options (SVG, PNG, PDF), styling parameters, and help documentation. Consider compatibility with existing command patterns in the application.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement Mermaid diagram generation core functionality",
          "description": "Create the core logic to parse Mermaid syntax and generate diagram output",
          "dependencies": [
            1
          ],
          "details": "Integrate with the Mermaid library to parse diagram syntax. Implement error handling for invalid syntax. Create the rendering pipeline to generate the diagram in memory before output. Support all standard Mermaid diagram types (flowchart, sequence, class, etc.). Include proper logging for the generation process.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Develop output handling mechanisms",
          "description": "Implement different output options for the generated diagrams",
          "dependencies": [
            2
          ],
          "details": "Create handlers for different output formats (SVG, PNG, PDF). Implement file output with appropriate naming conventions and directory handling. Add clipboard support for direct pasting. Implement stdout output for piping to other commands. Include progress indicators for longer rendering operations.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Create documentation and examples",
          "description": "Provide comprehensive documentation and examples for the 'diagram' command",
          "dependencies": [
            3
          ],
          "details": "Write detailed command documentation with all options explained. Create example diagrams covering different diagram types. Include troubleshooting section for common errors. Add documentation on extending the command with custom themes or templates. Create integration examples showing how to use the command in workflows with other tools.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 71,
      "title": "Add Model-Specific maxTokens Override Configuration",
      "description": "Implement functionality to allow specifying a maximum token limit for individual AI models within .taskmasterconfig, overriding the role-based maxTokens if the model-specific limit is lower.",
      "details": "1. **Modify `.taskmasterconfig` Structure:** Add a new top-level section `modelOverrides` (e.g., `\"modelOverrides\": { \"o3-mini\": { \"maxTokens\": 100000 } }`).\n2. **Update `config-manager.js`:**\n   - Modify config loading to read the new `modelOverrides` section.\n   - Update `getParametersForRole(role)` logic: Fetch role defaults (roleMaxTokens, temperature). Get the modelId for the role. Look up `modelOverrides[modelId].maxTokens` (modelSpecificMaxTokens). Calculate `effectiveMaxTokens = Math.min(roleMaxTokens, modelSpecificMaxTokens ?? Infinity)`. Return `{ maxTokens: effectiveMaxTokens, temperature }`.\n3. **Update Documentation:** Add an example of `modelOverrides` to `.taskmasterconfig.example` or relevant documentation.",
      "testStrategy": "1. **Unit Tests (`config-manager.js`):**\n   - Verify `getParametersForRole` returns role defaults when no override exists.\n   - Verify `getParametersForRole` returns the lower model-specific limit when an override exists and is lower.\n   - Verify `getParametersForRole` returns the role limit when an override exists but is higher.\n   - Verify handling of missing `modelOverrides` section.\n2. **Integration Tests (`ai-services-unified.js`):**\n   - Call an AI service (e.g., `generateTextService`) with a config having a model override.\n   - Mock the underlying provider function.\n   - Assert that the `maxTokens` value passed to the mocked provider function matches the expected (potentially overridden) minimum value.",
      "status": "done",
      "dependencies": [],
      "priority": "high",
      "subtasks": []
    },
    {
      "id": 72,
      "title": "Implement PDF Generation for Project Progress and Dependency Overview",
      "description": "Develop a feature to generate a PDF report summarizing the current project progress and visualizing the dependency chain of tasks.",
      "details": "This task involves creating a new CLI command named 'progress-pdf' within the existing project framework to generate a PDF document. The PDF should include: 1) A summary of project progress, detailing completed, in-progress, and pending tasks with their respective statuses and completion percentages if applicable. 2) A visual representation of the task dependency chain, leveraging the output format from the 'diagram' command (Task 70) to include Mermaid diagrams or similar visualizations converted to image format for PDF embedding. Use a suitable PDF generation library (e.g., jsPDF for JavaScript environments or ReportLab for Python) compatible with the project’s tech stack. Ensure the command accepts optional parameters to filter tasks by status or ID for customized reports. Handle large dependency chains by implementing pagination or zoomable image sections in the PDF. Provide error handling for cases where diagram generation or PDF creation fails, logging detailed error messages for debugging. Consider accessibility by ensuring text in the PDF is selectable and images have alt text descriptions. Integrate this feature with the existing CLI structure, ensuring it aligns with the project’s configuration settings (e.g., output directory for generated files). Document the command usage and parameters in the project’s help or README file.",
      "testStrategy": "Verify the completion of this task through a multi-step testing approach: 1) Unit Tests: Create tests for the PDF generation logic to ensure data (task statuses and dependencies) is correctly fetched and formatted. Mock the PDF library to test edge cases like empty task lists or broken dependency links. 2) Integration Tests: Run the 'progress-pdf' command via CLI to confirm it generates a PDF file without errors under normal conditions, with filtered task IDs, and with various status filters. Validate that the output file exists in the specified directory and can be opened. 3) Content Validation: Manually or via automated script, check the generated PDF content to ensure it accurately reflects the current project state (compare task counts and statuses against a known project state) and includes dependency diagrams as images. 4) Error Handling Tests: Simulate failures in diagram generation or PDF creation (e.g., invalid output path, library errors) and verify that appropriate error messages are logged and the command exits gracefully. 5) Accessibility Checks: Use a PDF accessibility tool or manual inspection to confirm that text is selectable and images have alt text. Run these tests across different project sizes (small with few tasks, large with complex dependencies) to ensure scalability. Document test results and include a sample PDF output in the project repository for reference.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Research and select PDF generation library",
          "description": "Evaluate available PDF generation libraries for Node.js that can handle diagrams and formatted text",
          "dependencies": [],
          "details": "Compare libraries like PDFKit, jsPDF, and Puppeteer based on features, performance, and ease of integration. Consider compatibility with diagram visualization tools. Document findings and make a recommendation with justification.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Design PDF template and layout",
          "description": "Create a template design for the project progress PDF including sections for summary, metrics, and dependency visualization",
          "dependencies": [
            1
          ],
          "details": "Design should include header/footer, progress summary section, key metrics visualization, dependency diagram placement, and styling guidelines. Create a mockup of the final PDF output for approval.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Implement project progress data collection module",
          "description": "Develop functionality to gather and process project data for the PDF report",
          "dependencies": [
            1
          ],
          "details": "Create functions to extract task completion percentages, milestone status, timeline adherence, and other relevant metrics from the project database. Include data transformation logic to prepare for PDF rendering.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Integrate with dependency visualization system",
          "description": "Connect to the existing diagram command to generate visual representation of task dependencies",
          "dependencies": [
            1,
            3
          ],
          "details": "Implement adapter for the diagram command output to be compatible with the PDF generation library. Handle different scales of dependency chains and ensure proper rendering of complex relationships.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Build PDF generation core functionality",
          "description": "Develop the main module that combines data and visualizations into a formatted PDF document",
          "dependencies": [
            2,
            3,
            4
          ],
          "details": "Implement the core PDF generation logic using the selected library. Include functions for adding text sections, embedding visualizations, formatting tables, and applying the template design. Add pagination and document metadata.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Create export options and command interface",
          "description": "Implement user-facing commands and options for generating and saving PDF reports",
          "dependencies": [
            5
          ],
          "details": "Develop CLI commands for PDF generation with parameters for customization (time period, detail level, etc.). Include options for automatic saving to specified locations, email distribution, and integration with existing project workflows.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 73,
      "title": "Implement Custom Model ID Support for Ollama/OpenRouter",
      "description": "Allow users to specify custom model IDs for Ollama and OpenRouter providers via CLI flag and interactive setup, with appropriate validation and warnings.",
      "details": "**CLI (`task-master models --set-<role> <id> --custom`):**\n- Modify `scripts/modules/task-manager/models.js`: `setModel` function.\n- Check internal `available_models.json` first.\n- If not found and `--custom` is provided:\n    - Fetch `https://openrouter.ai/api/v1/models`. (Need to add `https` import).\n    - If ID found in OpenRouter list: Set `provider: 'openrouter'`, `modelId: <id>`. Warn user about lack of official validation.\n    - If ID not found in OpenRouter: Assume Ollama. Set `provider: 'ollama'`, `modelId: <id>`. Warn user strongly (model must be pulled, compatibility not guaranteed).\n- If not found and `--custom` is *not* provided: Fail with error message guiding user to use `--custom`.\n\n**Interactive Setup (`task-master models --setup`):**\n- Modify `scripts/modules/commands.js`: `runInteractiveSetup` function.\n- Add options to `inquirer` choices for each role: `OpenRouter (Enter Custom ID)` and `Ollama (Enter Custom ID)`.\n- If `__CUSTOM_OPENROUTER__` selected:\n    - Prompt for custom ID.\n    - Fetch OpenRouter list and validate ID exists. Fail setup for that role if not found.\n    - Update config and show warning if found.\n- If `__CUSTOM_OLLAMA__` selected:\n    - Prompt for custom ID.\n    - Update config directly (no live validation).\n    - Show strong Ollama warning.",
      "testStrategy": "**Unit Tests:**\n- Test `setModel` logic for internal models, custom OpenRouter (valid/invalid), custom Ollama, missing `--custom` flag.\n- Test `runInteractiveSetup` for new custom options flow, including OpenRouter validation success/failure.\n\n**Integration Tests:**\n- Test the `task-master models` command with `--custom` flag variations.\n- Test the `task-master models --setup` interactive flow for custom options.\n\n**Manual Testing:**\n- Run `task-master models --setup` and select custom options.\n- Run `task-master models --set-main <valid_openrouter_id> --custom`. Verify config and warning.\n- Run `task-master models --set-main <invalid_openrouter_id> --custom`. Verify error.\n- Run `task-master models --set-main <ollama_model_id> --custom`. Verify config and warning.\n- Run `task-master models --set-main <custom_id>` (without `--custom`). Verify error.\n- Check `getModelConfiguration` output reflects custom models correctly.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "subtasks": []
    },
    {
      "id": 74,
      "title": "PR Review: better-model-management",
      "description": "will add subtasks",
      "details": "",
      "testStrategy": "",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "pull out logWrapper into utils",
          "description": "its being used a lot across direct functions and repeated right now",
          "details": "",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 74
        }
      ]
    },
    {
      "id": 75,
      "title": "Integrate Google Search Grounding for Research Role",
      "description": "Update the AI service layer to enable Google Search Grounding specifically when a Google model is used in the 'research' role.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "**Goal:** Conditionally enable Google Search Grounding based on the AI role.\\n\\n**Implementation Plan:**\\n\\n1.  **Modify `ai-services-unified.js`:** Update `generateTextService`, `streamTextService`, and `generateObjectService`.\\n2.  **Conditional Logic:** Inside these functions, check if `providerName === 'google'` AND `role === 'research'`.\\n3.  **Construct `providerOptions`:** If the condition is met, create an options object:\\n    ```javascript\\n    let providerSpecificOptions = {};\\n    if (providerName === 'google' && role === 'research') {\\n        log('info', 'Enabling Google Search Grounding for research role.');\\n        providerSpecificOptions = {\\n            google: {\\n                useSearchGrounding: true,\\n                // Optional: Add dynamic retrieval for compatible models\\n                // dynamicRetrievalConfig: { mode: 'MODE_DYNAMIC' } \\n            }\\n        };\\n    }\\n    ```\\n4.  **Pass Options to SDK:** Pass `providerSpecificOptions` to the Vercel AI SDK functions (`generateText`, `streamText`, `generateObject`) via the `providerOptions` parameter:\\n    ```javascript\\n    const { text, ... } = await generateText({\\n        // ... other params\\n        providerOptions: providerSpecificOptions \\n    });\\n    ```\\n5.  **Update `supported-models.json`:** Ensure Google models intended for research (e.g., `gemini-1.5-pro-latest`, `gemini-1.5-flash-latest`) include `'research'` in their `allowed_roles` array.\\n\\n**Rationale:** This approach maintains the clear separation between 'main' and 'research' roles, ensuring grounding is only activated when explicitly requested via the `--research` flag or when the research model is invoked.\\n\\n**Clarification:** The Search Grounding feature is specifically designed to provide up-to-date information from the web when using Google models. This implementation ensures that grounding is only activated in research contexts where current information is needed, while preserving normal operation for standard tasks. The `useSearchGrounding: true` flag instructs the Google API to augment the model's knowledge with recent web search results relevant to the query.",
      "testStrategy": "1. Configure a Google model (e.g., gemini-1.5-flash-latest) as the 'research' model in `.taskmasterconfig`.\\n2. Run a command with the `--research` flag (e.g., `task-master add-task --prompt='Latest news on AI SDK 4.2' --research`).\\n3. Verify logs show 'Enabling Google Search Grounding'.\\n4. Check if the task output incorporates recent information.\\n5. Configure the same Google model as the 'main' model.\\n6. Run a command *without* the `--research` flag.\\n7. Verify logs *do not* show grounding being enabled.\\n8. Add unit tests to `ai-services-unified.test.js` to verify the conditional logic for adding `providerOptions`. Ensure mocks correctly simulate different roles and providers.",
      "subtasks": [
        {
          "id": 1,
          "title": "Modify AI service layer to support Google Search Grounding",
          "description": "Update the AI service layer to include the capability to integrate with Google Search Grounding API for research-related queries.",
          "dependencies": [],
          "details": "Extend the existing AI service layer by adding new methods and interfaces to handle Google Search Grounding API calls. This includes creating authentication mechanisms, request formatters, and response parsers specific to the Google Search API. Ensure proper error handling and retry logic for API failures.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement conditional logic for research role detection",
          "description": "Create logic to detect when a conversation is in 'research mode' and should trigger the Google Search Grounding functionality.",
          "dependencies": [
            1
          ],
          "details": "Develop heuristics or machine learning-based detection to identify when a user's query requires research capabilities. Implement a decision tree that determines when to activate Google Search Grounding based on conversation context, explicit user requests for research, or specific keywords. Include configuration options to adjust sensitivity of the detection mechanism.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Update supported models configuration",
          "description": "Modify the model configuration to specify which AI models can utilize the Google Search Grounding capability.",
          "dependencies": [
            1
          ],
          "details": "Update the model configuration files to include flags for Google Search Grounding compatibility. Create a registry of supported models with their specific parameters for optimal integration with the search API. Implement version checking to ensure compatibility between model versions and the Google Search Grounding API version.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Create end-to-end testing suite for research functionality",
          "description": "Develop comprehensive tests to verify the correct operation of the Google Search Grounding integration in research contexts.",
          "dependencies": [
            1,
            2,
            3
          ],
          "details": "Build automated test cases that cover various research scenarios, including edge cases. Create mock responses for the Google Search API to enable testing without actual API calls. Implement integration tests that verify the entire flow from user query to research-enhanced response. Include performance benchmarks to ensure the integration doesn't significantly impact response times.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 76,
      "title": "Develop E2E Test Framework for Taskmaster MCP Server (FastMCP over stdio)",
      "description": "Design and implement an end-to-end (E2E) test framework for the Taskmaster MCP server, enabling programmatic interaction with the FastMCP server over stdio by sending and receiving JSON tool request/response messages.",
      "status": "pending",
      "dependencies": [],
      "priority": "high",
      "details": "Research existing E2E testing approaches for MCP servers, referencing examples such as the MCP Server E2E Testing Example. Architect a test harness (preferably in Python or Node.js) that can launch the FastMCP server as a subprocess, establish stdio communication, and send well-formed JSON tool request messages. \n\nImplementation details:\n1. Use `subprocess.Popen` (Python) or `child_process.spawn` (Node.js) to launch the FastMCP server with appropriate stdin/stdout pipes\n2. Implement a message protocol handler that formats JSON requests with proper line endings and message boundaries\n3. Create a buffered reader for stdout that correctly handles chunked responses and reconstructs complete JSON objects\n4. Develop a request/response correlation mechanism using unique IDs for each request\n5. Implement timeout handling for requests that don't receive responses\n\nImplement robust parsing of JSON responses, including error handling for malformed or unexpected output. The framework should support defining test cases as scripts or data files, allowing for easy addition of new scenarios. \n\nTest case structure should include:\n- Setup phase for environment preparation\n- Sequence of tool requests with expected responses\n- Validation functions for response verification\n- Teardown phase for cleanup\n\nEnsure the framework can assert on both the structure and content of responses, and provide clear logging for debugging. Document setup, usage, and extension instructions. Consider cross-platform compatibility and CI integration.\n\n**Clarification:** The E2E test framework should focus on testing the FastMCP server's ability to correctly process tool requests and return appropriate responses. This includes verifying that the server properly handles different types of tool calls (e.g., file operations, web requests, task management), validates input parameters, and returns well-structured responses. The framework should be designed to be extensible, allowing new test cases to be added as the server's capabilities evolve. Tests should cover both happy paths and error conditions to ensure robust server behavior under various scenarios.",
      "testStrategy": "Verify the framework by implementing a suite of representative E2E tests that cover typical tool requests and edge cases. Specific test cases should include:\n\n1. Basic tool request/response validation\n   - Send a simple file_read request and verify response structure\n   - Test with valid and invalid file paths\n   - Verify error handling for non-existent files\n\n2. Concurrent request handling\n   - Send multiple requests in rapid succession\n   - Verify all responses are received and correlated correctly\n\n3. Large payload testing\n   - Test with large file contents (>1MB)\n   - Verify correct handling of chunked responses\n\n4. Error condition testing\n   - Malformed JSON requests\n   - Invalid tool names\n   - Missing required parameters\n   - Server crash recovery\n\nConfirm that tests can start and stop the FastMCP server, send requests, and accurately parse and validate responses. Implement specific assertions for response timing, structure validation using JSON schema, and content verification. Intentionally introduce malformed requests and simulate server errors to ensure robust error handling. \n\nImplement detailed logging with different verbosity levels:\n- ERROR: Failed tests and critical issues\n- WARNING: Unexpected but non-fatal conditions\n- INFO: Test progress and results\n- DEBUG: Raw request/response data\n\nRun the test suite in a clean environment and confirm all expected assertions and logs are produced. Validate that new test cases can be added with minimal effort and that the framework integrates with CI pipelines. Create a CI configuration that runs tests on each commit.",
      "subtasks": [
        {
          "id": 1,
          "title": "Design E2E Test Framework Architecture",
          "description": "Create a high-level design document for the E2E test framework that outlines components, interactions, and test flow",
          "dependencies": [],
          "details": "Define the overall architecture of the test framework, including test runner, FastMCP server launcher, message protocol handler, and assertion components. Document how these components will interact and the data flow between them. Include error handling strategies and logging requirements.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Implement FastMCP Server Launcher",
          "description": "Create a component that can programmatically launch and manage the FastMCP server process over stdio",
          "dependencies": [
            1
          ],
          "details": "Develop a module that can spawn the FastMCP server as a child process, establish stdio communication channels, handle process lifecycle events, and implement proper cleanup procedures. Include error handling for process failures and timeout mechanisms.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Develop Message Protocol Handler",
          "description": "Implement a handler that can serialize/deserialize messages according to the FastMCP protocol specification",
          "dependencies": [
            1
          ],
          "details": "Create a protocol handler that formats outgoing messages and parses incoming messages according to the FastMCP protocol. Implement validation for message format compliance and error handling for malformed messages. Support all required message types defined in the protocol.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Create Request/Response Correlation Mechanism",
          "description": "Implement a system to track and correlate requests with their corresponding responses",
          "dependencies": [
            3
          ],
          "details": "Develop a correlation mechanism using unique identifiers to match requests with their responses. Implement timeout handling for unresponded requests and proper error propagation. Design the API to support both synchronous and asynchronous request patterns.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Build Test Assertion Framework",
          "description": "Create a set of assertion utilities specific to FastMCP server testing",
          "dependencies": [
            3,
            4
          ],
          "details": "Develop assertion utilities that can validate server responses against expected values, verify timing constraints, and check for proper error handling. Include support for complex response validation patterns and detailed failure reporting.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Implement Test Cases",
          "description": "Develop a comprehensive set of test cases covering all FastMCP server functionality",
          "dependencies": [
            2,
            4,
            5
          ],
          "details": "Create test cases for basic server operations, error conditions, edge cases, and performance scenarios. Organize tests into logical groups and ensure proper isolation between test cases. Include documentation for each test explaining its purpose and expected outcomes.",
          "status": "pending"
        },
        {
          "id": 7,
          "title": "Create CI Integration and Documentation",
          "description": "Set up continuous integration for the test framework and create comprehensive documentation",
          "dependencies": [
            6
          ],
          "details": "Configure the test framework to run in CI environments, generate reports, and fail builds appropriately. Create documentation covering framework architecture, usage instructions, test case development guidelines, and troubleshooting procedures. Include examples of extending the framework for new test scenarios.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 77,
      "title": "Implement AI Usage Telemetry for Taskmaster (with external analytics endpoint)",
      "description": "Capture detailed AI usage data (tokens, costs, models, commands) within Taskmaster and send this telemetry to an external, closed-source analytics backend for usage analysis, profitability measurement, and pricing optimization.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "details": "*   Add a telemetry utility (`logAiUsage`) within `ai-services.js` to track AI usage.\n*   Collected telemetry data fields must include:\n    *   `timestamp`: Current date/time in ISO 8601.\n    *   `userId`: Unique user identifier generated at setup (stored in `.taskmasterconfig`).\n    *   `commandName`: Taskmaster command invoked (`expand`, `parse-prd`, `research`, etc.).\n    *   `modelUsed`: Name/ID of the AI model invoked.\n    *   `inputTokens`: Count of input tokens used.\n    *   `outputTokens`: Count of output tokens generated.\n    *   `totalTokens`: Sum of input and output tokens.\n    *   `totalCost`: Monetary cost calculated using pricing from `supported_models.json`.\n*   Send telemetry payload securely via HTTPS POST request from user's Taskmaster installation directly to the closed-source analytics API (Express/Supabase backend).\n*   Introduce a privacy notice and explicit user consent prompt upon initial installation/setup to enable telemetry.\n*   Provide a graceful fallback if telemetry request fails (e.g., no internet connectivity).\n*   Optionally display a usage summary directly in Taskmaster CLI output for user transparency.",
      "testStrategy": "",
      "subtasks": [
        {
          "id": 1,
          "title": "Implement telemetry utility and data collection",
          "description": "Create the logAiUsage utility in ai-services.js that captures all required telemetry data fields",
          "dependencies": [],
          "details": "Develop the logAiUsage function that collects timestamp, userId, commandName, modelUsed, inputTokens, outputTokens, totalTokens, and totalCost. Implement token counting logic and cost calculation using pricing from supported_models.json. Ensure proper error handling and data validation.\n<info added on 2025-05-05T21:08:51.413Z>\nDevelop the logAiUsage function that collects timestamp, userId, commandName, modelUsed, inputTokens, outputTokens, totalTokens, and totalCost. Implement token counting logic and cost calculation using pricing from supported_models.json. Ensure proper error handling and data validation.\n\nImplementation Plan:\n1. Define `logAiUsage` function in `ai-services-unified.js` that accepts parameters: userId, commandName, providerName, modelId, inputTokens, and outputTokens.\n\n2. Implement data collection and calculation logic:\n   - Generate timestamp using `new Date().toISOString()`\n   - Calculate totalTokens by adding inputTokens and outputTokens\n   - Create a helper function `_getCostForModel(providerName, modelId)` that:\n     - Loads pricing data from supported-models.json\n     - Finds the appropriate provider/model entry\n     - Returns inputCost and outputCost rates or defaults if not found\n   - Calculate totalCost using the formula: ((inputTokens/1,000,000) * inputCost) + ((outputTokens/1,000,000) * outputCost)\n   - Assemble complete telemetryData object with all required fields\n\n3. Add initial logging functionality:\n   - Use existing log utility to record telemetry data at 'info' level\n   - Implement proper error handling with try/catch blocks\n\n4. Integrate with `_unifiedServiceRunner`:\n   - Modify to accept commandName and userId parameters\n   - After successful API calls, extract usage data from results\n   - Call logAiUsage with the appropriate parameters\n\n5. Update provider functions in src/ai-providers/*.js:\n   - Ensure all provider functions return both the primary result and usage statistics\n   - Standardize the return format to include a usage object with inputTokens and outputTokens\n</info added on 2025-05-05T21:08:51.413Z>\n<info added on 2025-05-07T17:28:57.361Z>\nTo implement the AI usage telemetry effectively, we need to update each command across our different stacks. Let's create a structured approach for this implementation:\n\nCommand Integration Plan:\n1. Core Function Commands:\n   - Identify all AI-utilizing commands in the core function library\n   - For each command, modify to pass commandName and userId to _unifiedServiceRunner\n   - Update return handling to process and forward usage statistics\n\n2. Direct Function Commands:\n   - Map all direct function commands that leverage AI capabilities\n   - Implement telemetry collection at the appropriate execution points\n   - Ensure consistent error handling and telemetry reporting\n\n3. MCP Tool Stack Commands:\n   - Inventory all MCP commands with AI dependencies\n   - Standardize the telemetry collection approach across the tool stack\n   - Add telemetry hooks that maintain backward compatibility\n\nFor each command category, we'll need to:\n- Document current implementation details\n- Define specific code changes required\n- Create tests to verify telemetry is being properly collected\n- Establish validation procedures to ensure data accuracy\n</info added on 2025-05-07T17:28:57.361Z>",
          "status": "done",
          "testStrategy": "Unit test the utility with mock AI usage data to verify all fields are correctly captured and calculated"
        },
        {
          "id": 2,
          "title": "Implement secure telemetry transmission",
          "description": "Create a secure mechanism to transmit telemetry data to the external analytics endpoint",
          "dependencies": [
            1
          ],
          "details": "Implement HTTPS POST request functionality to securely send the telemetry payload to the closed-source analytics API. Include proper encryption in transit using TLS. Implement retry logic and graceful fallback mechanisms for handling transmission failures due to connectivity issues.\n<info added on 2025-05-14T17:52:40.647Z>\nTo securely send structured JSON telemetry payloads from a Node.js CLI tool to an external analytics backend, follow these steps:\n\n1. Use the Axios library for HTTPS POST requests. Install it with: npm install axios.\n2. Store sensitive configuration such as the analytics endpoint URL and any secret keys in environment variables (e.g., process.env.ANALYTICS_URL, process.env.ANALYTICS_KEY). Use dotenv or a similar library to load these securely.\n3. Construct the telemetry payload as a JSON object with the required fields: userId, commandName, modelUsed, inputTokens, outputTokens, totalTokens, totalCost, and timestamp (ISO 8601).\n4. Implement robust retry logic using the axios-retry package (npm install axios-retry). Configure exponential backoff with a recommended maximum of 3 retries and a base delay (e.g., 500ms).\n5. Ensure all requests use HTTPS to guarantee TLS encryption in transit. Axios automatically uses HTTPS when the endpoint URL starts with https://.\n6. Handle errors gracefully: catch all transmission errors, log them for diagnostics, and ensure failures do not interrupt or degrade the CLI user experience. Optionally, queue failed payloads for later retry if persistent connectivity issues occur.\n7. Example code snippet:\n\nrequire('dotenv').config();\nconst axios = require('axios');\nconst axiosRetry = require('axios-retry');\n\naxiosRetry(axios, {\n  retries: 3,\n  retryDelay: axiosRetry.exponentialDelay,\n  retryCondition: (error) => axiosRetry.isNetworkOrIdempotentRequestError(error),\n});\n\nasync function sendTelemetry(payload) {\n  try {\n    await axios.post(process.env.ANALYTICS_URL, payload, {\n      headers: {\n        'Content-Type': 'application/json',\n        'Authorization': `Bearer ${process.env.ANALYTICS_KEY}`,\n      },\n      timeout: 5000,\n    });\n  } catch (error) {\n    // Log error, do not throw to avoid impacting CLI UX\n    console.error('Telemetry transmission failed:', error.message);\n    // Optionally, queue payload for later retry\n  }\n}\n\nconst telemetryPayload = {\n  userId: 'user-123',\n  commandName: 'expand',\n  modelUsed: 'gpt-4',\n  inputTokens: 100,\n  outputTokens: 200,\n  totalTokens: 300,\n  totalCost: 0.0123,\n  timestamp: new Date().toISOString(),\n};\n\nsendTelemetry(telemetryPayload);\n\n8. Best practices:\n- Never hardcode secrets or endpoint URLs in source code.\n- Use environment variables and restrict access permissions.\n- Validate all payload fields before transmission.\n- Ensure the CLI continues to function even if telemetry transmission fails.\n\nReferences: [1][2][3][5]\n</info added on 2025-05-14T17:52:40.647Z>\n<info added on 2025-05-14T17:57:18.218Z>\nUser ID Retrieval and Generation:\n\nThe telemetry system must securely retrieve the user ID from the .taskmasterconfig globals, where it should have been generated during the initialization phase. Implementation should:\n\n1. Check for an existing user ID in the .taskmasterconfig file before sending any telemetry data.\n2. If no user ID exists (for users who run AI commands without prior initialization or during upgrades), automatically generate a new UUID v4 and persist it to the .taskmasterconfig file.\n3. Implement a getOrCreateUserId() function that:\n   - Reads from the global configuration file\n   - Returns the existing ID if present\n   - Generates a cryptographically secure UUID v4 if not present\n   - Saves the newly generated ID to the configuration file\n   - Handles file access errors gracefully\n\n4. Example implementation:\n```javascript\nconst fs = require('fs');\nconst path = require('path');\nconst { v4: uuidv4 } = require('uuid');\n\nfunction getOrCreateUserId() {\n  const configPath = path.join(os.homedir(), '.taskmasterconfig');\n  \n  try {\n    // Try to read existing config\n    const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));\n    \n    if (config.userId) {\n      return config.userId;\n    }\n    \n    // No user ID found, generate and save\n    config.userId = uuidv4();\n    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));\n    return config.userId;\n  } catch (error) {\n    // Handle case where config doesn't exist or is invalid\n    const userId = uuidv4();\n    const newConfig = { userId };\n    \n    try {\n      fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));\n    } catch (writeError) {\n      console.error('Failed to save user ID to config:', writeError.message);\n    }\n    \n    return userId;\n  }\n}\n```\n\n5. Ensure this function is called before constructing any telemetry payload to guarantee a consistent user ID across all telemetry events.\n</info added on 2025-05-14T17:57:18.218Z>\n<info added on 2025-05-15T18:45:32.123Z>\n**Invocation Point for Sending Telemetry:**\n* The primary invocation for sending the telemetry payload should occur in `scripts/modules/ai-services-unified.js`.\n* This should happen *after* the `telemetryData` object is fully constructed and *after* user consent (from subtask 77.3) has been confirmed.\n\n**Dedicated Module for Transmission Logic:**\n* The actual HTTPS POST request mechanism, including TLS encryption, retry logic, and graceful fallbacks, should be implemented in a new, separate module (e.g., `scripts/modules/telemetry-sender.js` or `scripts/utils/telemetry-client.js`).\n* This module will be imported and utilized by `scripts/modules/ai-services-unified.js`.\n\n**Key Considerations:**\n* Robust error handling must be in place for the telemetry transmission process; failures should be logged locally and must not disrupt core application functionality.\n* The entire telemetry sending process is contingent upon explicit user consent as outlined in subtask 77.3.\n\n**Implementation Plan:**\n1. Create a new module `scripts/utils/telemetry-client.js` with the following functions:\n   - `sendTelemetryData(telemetryPayload)`: Main function that handles the HTTPS POST request\n   - `isUserConsentGiven()`: Helper function to check if user has consented to telemetry\n   - `logTelemetryError(error)`: Helper function for consistent error logging\n\n2. In `ai-services-unified.js`, after constructing the telemetryData object:\n   ```javascript\n   const telemetryClient = require('../utils/telemetry-client');\n   \n   // After telemetryData is constructed\n   if (telemetryClient.isUserConsentGiven()) {\n     // Non-blocking telemetry submission\n     telemetryClient.sendTelemetryData(telemetryData)\n       .catch(error => telemetryClient.logTelemetryError(error));\n   }\n   ```\n\n3. Ensure the telemetry-client module implements:\n   - Axios with retry logic for robust HTTP requests\n   - Proper TLS encryption via HTTPS\n   - Comprehensive error handling\n   - Configuration loading from environment variables\n   - Validation of payload data before transmission\n</info added on 2025-05-15T18:45:32.123Z>",
          "status": "deferred",
          "testStrategy": "Test with mock endpoints to verify secure transmission and proper handling of various response scenarios"
        },
        {
          "id": 3,
          "title": "Develop user consent and privacy notice system",
          "description": "Create a privacy notice and explicit consent mechanism during Taskmaster setup",
          "dependencies": [],
          "details": "Design and implement a clear privacy notice explaining what data is collected and how it's used. Create a user consent prompt during initial installation/setup that requires explicit opt-in. Store the consent status in the .taskmasterconfig file and respect this setting throughout the application.",
          "status": "deferred",
          "testStrategy": "Test the consent flow to ensure users can opt in/out and that their preference is properly stored and respected"
        },
        {
          "id": 4,
          "title": "Integrate telemetry into Taskmaster commands",
          "description": "Integrate the telemetry utility across all relevant Taskmaster commands",
          "dependencies": [
            1,
            3
          ],
          "details": "Modify each Taskmaster command (expand, parse-prd, research, etc.) to call the logAiUsage utility after AI interactions. Ensure telemetry is only sent if user has provided consent. Implement the integration in a way that doesn't impact command performance or user experience.\n<info added on 2025-05-06T17:57:13.980Z>\nModify each Taskmaster command (expand, parse-prd, research, etc.) to call the logAiUsage utility after AI interactions. Ensure telemetry is only sent if user has provided consent. Implement the integration in a way that doesn't impact command performance or user experience.\n\nSuccessfully integrated telemetry calls into `addTask` (core) and `addTaskDirect` (MCP) functions by passing `commandName` and `outputType` parameters to the telemetry system. The `ai-services-unified.js` module now logs basic telemetry data, including calculated cost information, whenever the `add-task` command or tool is invoked. This integration respects user consent settings and maintains performance standards.\n</info added on 2025-05-06T17:57:13.980Z>",
          "status": "done",
          "testStrategy": "Integration tests to verify telemetry is correctly triggered across different commands with proper data"
        },
        {
          "id": 5,
          "title": "Implement usage summary display",
          "description": "Create an optional feature to display AI usage summary in the CLI output",
          "dependencies": [
            1,
            4
          ],
          "details": "Develop functionality to display a concise summary of AI usage (tokens used, estimated cost) directly in the CLI output after command execution. Make this feature configurable through Taskmaster settings. Ensure the display is formatted clearly and doesn't clutter the main command output.",
          "status": "done",
          "testStrategy": "User acceptance testing to verify the summary display is clear, accurate, and properly configurable"
        },
        {
          "id": 6,
          "title": "Telemetry Integration for parse-prd",
          "description": "Integrate AI usage telemetry capture and propagation for the parse-prd functionality.",
          "details": "\\\nApply telemetry pattern from telemetry.mdc:\n\n1.  **Core (`scripts/modules/task-manager/parse-prd.js`):**\n    *   Modify AI service call to include `commandName: \\'parse-prd\\'` and `outputType`.\n    *   Receive `{ mainResult, telemetryData }`.\n    *   Return object including `telemetryData`.\n    *   Handle CLI display via `displayAiUsageSummary` if applicable.\n\n2.  **Direct (`mcp-server/src/core/direct-functions/parse-prd.js`):**\n    *   Pass `commandName`, `outputType: \\'mcp\\'` to core.\n    *   Pass `outputFormat: \\'json\\'` if applicable.\n    *   Receive `{ ..., telemetryData }` from core.\n    *   Return `{ success: true, data: { ..., telemetryData } }`.\n\n3.  **Tool (`mcp-server/src/tools/parse-prd.js`):**\n    *   Verify `handleApiResult` correctly passes `data.telemetryData` through.\n",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 7,
          "title": "Telemetry Integration for expand-task",
          "description": "Integrate AI usage telemetry capture and propagation for the expand-task functionality.",
          "details": "\\\nApply telemetry pattern from telemetry.mdc:\n\n1.  **Core (`scripts/modules/task-manager/expand-task.js`):**\n    *   Modify AI service call to include `commandName: \\'expand-task\\'` and `outputType`.\n    *   Receive `{ mainResult, telemetryData }`.\n    *   Return object including `telemetryData`.\n    *   Handle CLI display via `displayAiUsageSummary` if applicable.\n\n2.  **Direct (`mcp-server/src/core/direct-functions/expand-task.js`):**\n    *   Pass `commandName`, `outputType: \\'mcp\\'` to core.\n    *   Pass `outputFormat: \\'json\\'` if applicable.\n    *   Receive `{ ..., telemetryData }` from core.\n    *   Return `{ success: true, data: { ..., telemetryData } }`.\n\n3.  **Tool (`mcp-server/src/tools/expand-task.js`):**\n    *   Verify `handleApiResult` correctly passes `data.telemetryData` through.\n",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 8,
          "title": "Telemetry Integration for expand-all-tasks",
          "description": "Integrate AI usage telemetry capture and propagation for the expand-all-tasks functionality.",
          "details": "\\\nApply telemetry pattern from telemetry.mdc:\n\n1.  **Core (`scripts/modules/task-manager/expand-all-tasks.js`):**\n    *   Modify AI service call (likely within a loop or called by a helper) to include `commandName: \\'expand-all-tasks\\'` and `outputType`.\n    *   Receive `{ mainResult, telemetryData }`.\n    *   Aggregate or handle `telemetryData` appropriately if multiple AI calls are made.\n    *   Return object including aggregated/relevant `telemetryData`.\n    *   Handle CLI display via `displayAiUsageSummary` if applicable.\n\n2.  **Direct (`mcp-server/src/core/direct-functions/expand-all-tasks.js`):**\n    *   Pass `commandName`, `outputType: \\'mcp\\'` to core.\n    *   Pass `outputFormat: \\'json\\'` if applicable.\n    *   Receive `{ ..., telemetryData }` from core.\n    *   Return `{ success: true, data: { ..., telemetryData } }`.\n\n3.  **Tool (`mcp-server/src/tools/expand-all.js`):**\n    *   Verify `handleApiResult` correctly passes `data.telemetryData` through.\n",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 9,
          "title": "Telemetry Integration for update-tasks",
          "description": "Integrate AI usage telemetry capture and propagation for the update-tasks (bulk update) functionality.",
          "details": "\\\nApply telemetry pattern from telemetry.mdc:\n\n1.  **Core (`scripts/modules/task-manager/update-tasks.js`):**\n    *   Modify AI service call (likely within a loop) to include `commandName: \\'update-tasks\\'` and `outputType`.\n    *   Receive `{ mainResult, telemetryData }` for each AI call.\n    *   Aggregate or handle `telemetryData` appropriately for multiple calls.\n    *   Return object including aggregated/relevant `telemetryData`.\n    *   Handle CLI display via `displayAiUsageSummary` if applicable.\n\n2.  **Direct (`mcp-server/src/core/direct-functions/update-tasks.js`):**\n    *   Pass `commandName`, `outputType: \\'mcp\\'` to core.\n    *   Pass `outputFormat: \\'json\\'` if applicable.\n    *   Receive `{ ..., telemetryData }` from core.\n    *   Return `{ success: true, data: { ..., telemetryData } }`.\n\n3.  **Tool (`mcp-server/src/tools/update.js`):**\n    *   Verify `handleApiResult` correctly passes `data.telemetryData` through.\n",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 10,
          "title": "Telemetry Integration for update-task-by-id",
          "description": "Integrate AI usage telemetry capture and propagation for the update-task-by-id functionality.",
          "details": "\\\nApply telemetry pattern from telemetry.mdc:\n\n1.  **Core (`scripts/modules/task-manager/update-task-by-id.js`):**\n    *   Modify AI service call to include `commandName: \\'update-task\\'` and `outputType`.\n    *   Receive `{ mainResult, telemetryData }`.\n    *   Return object including `telemetryData`.\n    *   Handle CLI display via `displayAiUsageSummary` if applicable.\n\n2.  **Direct (`mcp-server/src/core/direct-functions/update-task-by-id.js`):**\n    *   Pass `commandName`, `outputType: \\'mcp\\'` to core.\n    *   Pass `outputFormat: \\'json\\'` if applicable.\n    *   Receive `{ ..., telemetryData }` from core.\n    *   Return `{ success: true, data: { ..., telemetryData } }`.\n\n3.  **Tool (`mcp-server/src/tools/update-task.js`):**\n    *   Verify `handleApiResult` correctly passes `data.telemetryData` through.\n",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 11,
          "title": "Telemetry Integration for update-subtask-by-id",
          "description": "Integrate AI usage telemetry capture and propagation for the update-subtask-by-id functionality.",
          "details": "\\\nApply telemetry pattern from telemetry.mdc:\n\n1.  **Core (`scripts/modules/task-manager/update-subtask-by-id.js`):**\n    *   Verify if this function *actually* calls an AI service. If it only appends text, telemetry integration might not apply directly here, but ensure its callers handle telemetry if they use AI.\n    *   *If it calls AI:* Modify AI service call to include `commandName: \\'update-subtask\\'` and `outputType`.\n    *   *If it calls AI:* Receive `{ mainResult, telemetryData }`.\n    *   *If it calls AI:* Return object including `telemetryData`.\n    *   *If it calls AI:* Handle CLI display via `displayAiUsageSummary` if applicable.\n\n2.  **Direct (`mcp-server/src/core/direct-functions/update-subtask-by-id.js`):**\n    *   *If core calls AI:* Pass `commandName`, `outputType: \\'mcp\\'` to core.\n    *   *If core calls AI:* Pass `outputFormat: \\'json\\'` if applicable.\n    *   *If core calls AI:* Receive `{ ..., telemetryData }` from core.\n    *   *If core calls AI:* Return `{ success: true, data: { ..., telemetryData } }`.\n\n3.  **Tool (`mcp-server/src/tools/update-subtask.js`):**\n    *   Verify `handleApiResult` correctly passes `data.telemetryData` through (if present).\n",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77,
          "parentTask": {
            "id": 77,
            "title": "Implement AI Usage Telemetry for Taskmaster (with external analytics endpoint)",
            "status": "in-progress"
          },
          "isSubtask": true
        },
        {
          "id": 12,
          "title": "Telemetry Integration for analyze-task-complexity",
          "description": "Integrate AI usage telemetry capture and propagation for the analyze-task-complexity functionality. [Updated: 5/9/2025]",
          "details": "\\\nApply telemetry pattern from telemetry.mdc:\n\n1.  **Core (`scripts/modules/task-manager/analyze-task-complexity.js`):**\n    *   Modify AI service call to include `commandName: \\'analyze-complexity\\'` and `outputType`.\n    *   Receive `{ mainResult, telemetryData }`.\n    *   Return object including `telemetryData` (perhaps alongside the complexity report data).\n    *   Handle CLI display via `displayAiUsageSummary` if applicable.\n\n2.  **Direct (`mcp-server/src/core/direct-functions/analyze-task-complexity.js`):**\n    *   Pass `commandName`, `outputType: \\'mcp\\'` to core.\n    *   Pass `outputFormat: \\'json\\'` if applicable.\n    *   Receive `{ ..., telemetryData }` from core.\n    *   Return `{ success: true, data: { ..., telemetryData } }`.\n\n3.  **Tool (`mcp-server/src/tools/analyze.js`):**\n    *   Verify `handleApiResult` correctly passes `data.telemetryData` through.\n\n<info added on 2025-05-09T04:02:44.847Z>\n## Implementation Details for Telemetry Integration\n\n### Best Practices for Implementation\n\n1. **Use Structured Telemetry Objects:**\n   - Create a standardized `TelemetryEvent` object with fields:\n     ```javascript\n     {\n       commandName: string,       // e.g., 'analyze-complexity'\n       timestamp: ISO8601 string,\n       duration: number,          // in milliseconds\n       inputTokens: number,\n       outputTokens: number,\n       model: string,             // e.g., 'gpt-4'\n       success: boolean,\n       errorType?: string,        // if applicable\n       metadata: object           // command-specific context\n     }\n     ```\n\n2. **Asynchronous Telemetry Processing:**\n   - Use non-blocking telemetry submission to avoid impacting performance\n   - Implement queue-based processing for reliability during network issues\n\n3. **Error Handling:**\n   - Implement robust try/catch blocks around telemetry operations\n   - Ensure telemetry failures don't affect core functionality\n   - Log telemetry failures locally for debugging\n\n4. **Privacy Considerations:**\n   - Never include PII or sensitive data in telemetry\n   - Implement data minimization principles\n   - Add sanitization functions for metadata fields\n\n5. **Testing Strategy:**\n   - Create mock telemetry endpoints for testing\n   - Add unit tests verifying correct telemetry data structure\n   - Implement integration tests for end-to-end telemetry flow\n\n### Code Implementation Examples\n\n```javascript\n// Example telemetry submission function\nasync function submitTelemetry(telemetryData, endpoint) {\n  try {\n    // Non-blocking submission\n    fetch(endpoint, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify(telemetryData)\n    }).catch(err => console.error('Telemetry submission failed:', err));\n  } catch (error) {\n    // Log locally but don't disrupt main flow\n    console.error('Telemetry error:', error);\n  }\n}\n\n// Example integration in AI service call\nasync function callAiService(params) {\n  const startTime = Date.now();\n  try {\n    const result = await aiService.call({\n      ...params,\n      commandName: 'analyze-complexity',\n      outputType: 'mcp'\n    });\n    \n    // Construct telemetry object\n    const telemetryData = {\n      commandName: 'analyze-complexity',\n      timestamp: new Date().toISOString(),\n      duration: Date.now() - startTime,\n      inputTokens: result.usage?.prompt_tokens || 0,\n      outputTokens: result.usage?.completion_tokens || 0,\n      model: result.model || 'unknown',\n      success: true,\n      metadata: {\n        taskId: params.taskId,\n        // Add other relevant non-sensitive metadata\n      }\n    };\n    \n    return { mainResult: result.data, telemetryData };\n  } catch (error) {\n    // Error telemetry\n    const telemetryData = {\n      commandName: 'analyze-complexity',\n      timestamp: new Date().toISOString(),\n      duration: Date.now() - startTime,\n      success: false,\n      errorType: error.name,\n      metadata: {\n        taskId: params.taskId,\n        errorMessage: sanitizeErrorMessage(error.message)\n      }\n    };\n    \n    // Re-throw the original error after capturing telemetry\n    throw error;\n  }\n}\n```\n</info added on 2025-05-09T04:02:44.847Z>",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 13,
          "title": "Update google.js for Telemetry Compatibility",
          "description": "Modify src/ai-providers/google.js functions to return usage data.",
          "details": "Update the provider functions in `src/ai-providers/google.js` to ensure they return telemetry-compatible results:\\n\\n1.  **`generateGoogleText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\\n2.  **`generateGoogleObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\\n3.  **`streamGoogleText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\\n\\nReference `anthropic.js` for the pattern.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 14,
          "title": "Update openai.js for Telemetry Compatibility",
          "description": "Modify src/ai-providers/openai.js functions to return usage data.",
          "details": "Update the provider functions in `src/ai-providers/openai.js` to ensure they return telemetry-compatible results:\\n\\n1.  **`generateOpenAIText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\\n2.  **`generateOpenAIObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\\n3.  **`streamOpenAIText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\\n\\nReference `anthropic.js` for the pattern.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 15,
          "title": "Update openrouter.js for Telemetry Compatibility",
          "description": "Modify src/ai-providers/openrouter.js functions to return usage data.",
          "details": "Update the provider functions in `src/ai-providers/openrouter.js` to ensure they return telemetry-compatible results:\\n\\n1.  **`generateOpenRouterText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\\n2.  **`generateOpenRouterObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\\n3.  **`streamOpenRouterText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\\n\\nReference `anthropic.js` for the pattern.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 16,
          "title": "Update perplexity.js for Telemetry Compatibility",
          "description": "Modify src/ai-providers/perplexity.js functions to return usage data.",
          "details": "Update the provider functions in `src/ai-providers/perplexity.js` to ensure they return telemetry-compatible results:\\n\\n1.  **`generatePerplexityText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\\n2.  **`generatePerplexityObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\\n3.  **`streamPerplexityText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\\n\\nReference `anthropic.js` for the pattern.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 17,
          "title": "Update xai.js for Telemetry Compatibility",
          "description": "Modify src/ai-providers/xai.js functions to return usage data.",
          "details": "Update the provider functions in `src/ai-providers/xai.js` to ensure they return telemetry-compatible results:\\n\\n1.  **`generateXaiText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\\n2.  **`generateXaiObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\\n3.  **`streamXaiText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\\n\\nReference `anthropic.js` for the pattern.",
          "status": "done",
          "dependencies": [],
          "parentTaskId": 77
        },
        {
          "id": 18,
          "title": "Create dedicated telemetry transmission module",
          "description": "Implement a separate module for handling telemetry transmission logic",
          "details": "Create a new module (e.g., `scripts/utils/telemetry-client.js`) that encapsulates all telemetry transmission functionality:\n\n1. Implement core functions:\n   - `sendTelemetryData(telemetryPayload)`: Main function to handle HTTPS POST requests\n   - `isUserConsentGiven()`: Helper to check if user has consented to telemetry\n   - `logTelemetryError(error)`: Helper for consistent error logging\n\n2. Use Axios with retry logic:\n   - Configure with exponential backoff (max 3 retries, 500ms base delay)\n   - Implement proper TLS encryption via HTTPS\n   - Set appropriate timeouts (5000ms recommended)\n\n3. Implement robust error handling:\n   - Catch all transmission errors\n   - Log failures locally without disrupting application flow\n   - Ensure failures are transparent to users\n\n4. Configure securely:\n   - Load endpoint URL and authentication from environment variables\n   - Never hardcode secrets in source code\n   - Validate payload data before transmission\n\n5. Integration with ai-services-unified.js:\n   - Import the telemetry-client module\n   - Call after telemetryData object is constructed\n   - Only send if user consent is confirmed\n   - Use non-blocking approach to avoid performance impact",
          "status": "done",
          "dependencies": [
            1,
            3
          ],
          "parentTaskId": 77,
          "testStrategy": "Unit test with mock endpoints to verify proper transmission, error handling, and respect for user consent settings"
        }
      ]
    },
    {
      "id": 80,
      "title": "Implement Unique User ID Generation and Storage During Installation",
      "description": "Generate a unique user identifier during npm installation and store it in the .taskmasterconfig globals to enable anonymous usage tracking and telemetry without requiring user registration.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "This task involves implementing a mechanism to generate and store a unique user identifier during the npm installation process of Taskmaster. The implementation should:\n\n1. Create a post-install script that runs automatically after npm install completes\n2. Generate a cryptographically secure random UUID v4 as the unique user identifier\n3. Check if a user ID already exists in the .taskmasterconfig file before generating a new one\n4. Add the generated user ID to the globals section of the .taskmasterconfig file\n5. Ensure the user ID persists across updates but is regenerated on fresh installations\n6. Handle edge cases such as failed installations, manual deletions of the config file, or permission issues\n7. Add appropriate logging to notify users that an anonymous ID is being generated (with clear privacy messaging)\n8. Document the purpose of this ID in the codebase and user documentation\n9. Ensure the ID generation is compatible with all supported operating systems\n10. Make the ID accessible to the telemetry system implemented in Task #77\n\nThe implementation should respect user privacy by:\n- Not collecting any personally identifiable information\n- Making it clear in documentation how users can opt out of telemetry\n- Ensuring the ID cannot be traced back to specific users or installations\n\nThis user ID will serve as the foundation for anonymous usage tracking, helping to understand how Taskmaster is used without compromising user privacy. Note that while we're implementing the ID generation now, the actual server-side collection is not yet available, so this data will initially only be stored locally.",
      "testStrategy": "Testing for this feature should include:\n\n1. **Unit Tests**:\n   - Verify the UUID generation produces valid UUIDs\n   - Test the config file reading and writing functionality\n   - Ensure proper error handling for file system operations\n   - Verify the ID remains consistent across multiple reads\n\n2. **Integration Tests**:\n   - Run a complete npm installation in a clean environment and verify a new ID is generated\n   - Simulate an update installation and verify the existing ID is preserved\n   - Test the interaction between the ID generation and the telemetry system\n   - Verify the ID is correctly stored in the expected location in .taskmasterconfig\n\n3. **Manual Testing**:\n   - Perform fresh installations on different operating systems (Windows, macOS, Linux)\n   - Verify the installation process completes without errors\n   - Check that the .taskmasterconfig file contains the generated ID\n   - Test scenarios where the config file is manually deleted or corrupted\n\n4. **Edge Case Testing**:\n   - Test behavior when the installation is run without sufficient permissions\n   - Verify handling of network disconnections during installation\n   - Test with various npm versions to ensure compatibility\n   - Verify behavior when .taskmasterconfig already exists but doesn't contain a user ID section\n\n5. **Validation**:\n   - Create a simple script to extract and analyze generated IDs to ensure uniqueness\n   - Verify the ID format meets UUID v4 specifications\n   - Confirm the ID is accessible to the telemetry system from Task #77\n\nThe test plan should include documentation of all test cases, expected results, and actual outcomes. A successful implementation will generate unique IDs for each installation while maintaining that ID across updates.",
      "subtasks": [
        {
          "id": 1,
          "title": "Create post-install script structure",
          "description": "Set up the post-install script that will run automatically after npm installation to handle user ID generation.",
          "dependencies": [],
          "details": "Create a new file called 'postinstall.js' in the project root. Configure package.json to run this script after installation by adding it to the 'scripts' section with the key 'postinstall'. The script should import necessary dependencies (fs, path, crypto) and set up the basic structure to access and modify the .taskmasterconfig file. Include proper error handling and logging to capture any issues during execution.",
          "status": "pending",
          "testStrategy": "Create a mock installation environment to verify the script executes properly after npm install. Test with various permission scenarios to ensure robust error handling."
        },
        {
          "id": 2,
          "title": "Implement UUID generation functionality",
          "description": "Create a function to generate cryptographically secure UUIDs v4 for unique user identification.",
          "dependencies": [
            1
          ],
          "details": "Implement a function called 'generateUniqueUserId()' that uses the crypto module to create a UUID v4. The function should follow RFC 4122 for UUID generation to ensure uniqueness and security. Include validation to verify the generated ID matches the expected UUID v4 format. Document the function with JSDoc comments explaining its purpose for anonymous telemetry.",
          "status": "pending",
          "testStrategy": "Write unit tests to verify UUID format compliance, uniqueness across multiple generations, and cryptographic randomness properties."
        },
        {
          "id": 3,
          "title": "Develop config file handling logic",
          "description": "Create functions to read, parse, modify, and write to the .taskmasterconfig file for storing the user ID.",
          "dependencies": [
            1
          ],
          "details": "Implement functions to: 1) Check if .taskmasterconfig exists and create it if not, 2) Read and parse the existing config file, 3) Check if a user ID already exists in the globals section, 4) Add or update the user ID in the globals section, and 5) Write the updated config back to disk. Handle edge cases like malformed config files, permission issues, and concurrent access. Use atomic write operations to prevent config corruption.",
          "status": "pending",
          "testStrategy": "Test with various initial config states: non-existent config, config without globals section, config with existing user ID. Verify file integrity after operations and proper error handling."
        },
        {
          "id": 4,
          "title": "Integrate user ID generation with config storage",
          "description": "Connect the UUID generation with the config file handling to create and store user IDs during installation.",
          "dependencies": [
            2,
            3
          ],
          "details": "Combine the UUID generation and config handling functions to: 1) Check if a user ID already exists in config, 2) Generate a new ID only if needed, 3) Store the ID in the config file, and 4) Handle installation scenarios (fresh install vs. update). Add appropriate logging to inform users about the anonymous ID generation with privacy-focused messaging. Ensure the process is idempotent so running it multiple times won't create multiple IDs.",
          "status": "pending",
          "testStrategy": "Create integration tests simulating fresh installations and updates. Verify ID persistence across simulated updates and regeneration on fresh installs."
        },
        {
          "id": 5,
          "title": "Add documentation and telemetry system access",
          "description": "Document the user ID system and create an API for the telemetry system to access the user ID.",
          "dependencies": [
            4
          ],
          "details": "Create comprehensive documentation explaining: 1) The purpose of the anonymous ID, 2) How user privacy is protected, 3) How to opt out of telemetry, and 4) Technical details of the implementation. Implement a simple API function 'getUserId()' that reads the ID from config for use by the telemetry system. Update the README and user documentation to include information about anonymous usage tracking. Ensure cross-platform compatibility by testing on all supported operating systems. Make it clear in the documentation that while we're collecting this ID, the server-side collection is not yet implemented, so data remains local for now.",
          "status": "pending",
          "testStrategy": "Verify documentation accuracy and completeness. Test the getUserId() function across platforms to ensure consistent behavior. Create a mock telemetry system to verify proper ID access."
        }
      ]
    },
    {
      "id": 82,
      "title": "Update supported-models.json with token limit fields",
      "description": "Modify the supported-models.json file to include contextWindowTokens and maxOutputTokens fields for each model, replacing the ambiguous max_tokens field.",
      "details": "For each model entry in supported-models.json:\n1. Add `contextWindowTokens` field representing the total context window (input + output tokens)\n2. Add `maxOutputTokens` field representing the maximum tokens the model can generate\n3. Remove or deprecate the ambiguous `max_tokens` field if present\n\nResearch and populate accurate values for each model from official documentation:\n- For OpenAI models (e.g., gpt-4o): contextWindowTokens=128000, maxOutputTokens=16384\n- For Anthropic models (e.g., Claude 3.7): contextWindowTokens=200000, maxOutputTokens=8192\n- For other providers, find official documentation or use reasonable defaults\n\nExample entry:\n```json\n{\n  \"id\": \"claude-3-7-sonnet-20250219\",\n  \"swe_score\": 0.623,\n  \"cost_per_1m_tokens\": { \"input\": 3.0, \"output\": 15.0 },\n  \"allowed_roles\": [\"main\", \"fallback\"],\n  \"contextWindowTokens\": 200000,\n  \"maxOutputTokens\": 8192\n}\n```",
      "testStrategy": "1. Validate JSON syntax after changes\n2. Verify all models have the new fields with reasonable values\n3. Check that the values align with official documentation from each provider\n4. Ensure backward compatibility by maintaining any fields other systems might depend on",
      "priority": "high",
      "dependencies": [],
      "status": "pending",
      "subtasks": []
    },
    {
      "id": 83,
      "title": "Update config-manager.js defaults and getters",
      "description": "Modify the config-manager.js module to replace maxTokens with maxInputTokens and maxOutputTokens in the DEFAULTS object and update related getter functions.",
      "details": "1. Update the `DEFAULTS` object in config-manager.js:\n```javascript\nconst DEFAULTS = {\n  // ... existing defaults\n  main: {\n    // Replace maxTokens with these two fields\n    maxInputTokens: 16000, // Example default\n    maxOutputTokens: 4000, // Example default\n    temperature: 0.7\n    // ... other fields\n  },\n  research: {\n    maxInputTokens: 16000,\n    maxOutputTokens: 4000,\n    temperature: 0.7\n    // ... other fields\n  },\n  fallback: {\n    maxInputTokens: 8000,\n    maxOutputTokens: 2000,\n    temperature: 0.7\n    // ... other fields\n  }\n  // ... rest of DEFAULTS\n};\n```\n\n2. Update `getParametersForRole` function to return the new fields:\n```javascript\nfunction getParametersForRole(role, explicitRoot = null) {\n  const config = _getConfig(explicitRoot);\n  return {\n    maxInputTokens: config[role]?.maxInputTokens,\n    maxOutputTokens: config[role]?.maxOutputTokens,\n    temperature: config[role]?.temperature\n    // ... any other parameters\n  };\n}\n```\n\n3. Add a new function to get model capabilities:\n```javascript\nfunction getModelCapabilities(providerName, modelId) {\n  const models = MODEL_MAP[providerName?.toLowerCase()];\n  const model = models?.find(m => m.id === modelId);\n  return {\n    contextWindowTokens: model?.contextWindowTokens,\n    maxOutputTokens: model?.maxOutputTokens\n  };\n}\n```\n\n4. Deprecate or update the role-specific maxTokens getters:\n```javascript\n// Either remove these or update them to return maxInputTokens\nfunction getMainMaxTokens(explicitRoot = null) {\n  console.warn('getMainMaxTokens is deprecated. Use getParametersForRole(\"main\") instead.');\n  return getParametersForRole(\"main\", explicitRoot).maxInputTokens;\n}\n// Same for getResearchMaxTokens and getFallbackMaxTokens\n```\n\n5. Export the new functions:\n```javascript\nmodule.exports = {\n  // ... existing exports\n  getParametersForRole,\n  getModelCapabilities\n};\n```",
      "testStrategy": "1. Unit test the updated getParametersForRole function with various configurations\n2. Verify the new getModelCapabilities function returns correct values\n3. Test with both default and custom configurations\n4. Ensure backward compatibility by checking that existing code using the old getters still works (with warnings)",
      "priority": "high",
      "dependencies": [
        82
      ],
      "status": "pending",
      "subtasks": [
        {
          "id": 1,
          "title": "Update config-manager.js with specific token limit fields",
          "description": "Modify the DEFAULTS object in config-manager.js to replace maxTokens with more specific token limit fields (maxInputTokens, maxOutputTokens, maxTotalTokens) and update related getter functions while maintaining backward compatibility.",
          "dependencies": [],
          "details": "1. Replace maxTokens in the DEFAULTS object with maxInputTokens, maxOutputTokens, and maxTotalTokens\n2. Update any getter functions that reference maxTokens to handle both old and new configurations\n3. Ensure backward compatibility so existing code using maxTokens continues to work\n4. Update any related documentation or comments to reflect the new token limit fields\n5. Test the changes to verify both new specific token limits and legacy maxTokens usage work correctly",
          "status": "pending"
        }
      ]
    },
    {
      "id": 84,
      "title": "Implement token counting utility",
      "description": "Create a utility function to count tokens for prompts based on the model being used, primarily using tiktoken for OpenAI and Anthropic models with character-based fallbacks for other providers.",
      "details": "1. Install the tiktoken package:\n```bash\nnpm install tiktoken\n```\n\n2. Create a new file `scripts/modules/token-counter.js`:\n```javascript\nconst tiktoken = require('tiktoken');\n\n/**\n * Count tokens for a given text and model\n * @param {string} text - The text to count tokens for\n * @param {string} provider - The AI provider (e.g., 'openai', 'anthropic')\n * @param {string} modelId - The model ID\n * @returns {number} - Estimated token count\n */\nfunction countTokens(text, provider, modelId) {\n  if (!text) return 0;\n  \n  // Convert to lowercase for case-insensitive matching\n  const providerLower = provider?.toLowerCase();\n  \n  try {\n    // OpenAI models\n    if (providerLower === 'openai') {\n      // Most OpenAI chat models use cl100k_base encoding\n      const encoding = tiktoken.encoding_for_model(modelId) || tiktoken.get_encoding('cl100k_base');\n      return encoding.encode(text).length;\n    }\n    \n    // Anthropic models - can use cl100k_base as an approximation\n    // or follow Anthropic's guidance\n    if (providerLower === 'anthropic') {\n      try {\n        // Try to use cl100k_base as a reasonable approximation\n        const encoding = tiktoken.get_encoding('cl100k_base');\n        return encoding.encode(text).length;\n      } catch (e) {\n        // Fallback to Anthropic's character-based estimation\n        return Math.ceil(text.length / 3.5); // ~3.5 chars per token for English\n      }\n    }\n    \n    // For other providers, use character-based estimation as fallback\n    // Different providers may have different tokenization schemes\n    return Math.ceil(text.length / 4); // General fallback estimate\n  } catch (error) {\n    console.warn(`Token counting error: ${error.message}. Using character-based estimate.`);\n    return Math.ceil(text.length / 4); // Fallback if tiktoken fails\n  }\n}\n\nmodule.exports = { countTokens };\n```\n\n3. Add tests for the token counter in `tests/token-counter.test.js`:\n```javascript\nconst { countTokens } = require('../scripts/modules/token-counter');\n\ndescribe('Token Counter', () => {\n  test('counts tokens for OpenAI models', () => {\n    const text = 'Hello, world! This is a test.';\n    const count = countTokens(text, 'openai', 'gpt-4');\n    expect(count).toBeGreaterThan(0);\n    expect(typeof count).toBe('number');\n  });\n  \n  test('counts tokens for Anthropic models', () => {\n    const text = 'Hello, world! This is a test.';\n    const count = countTokens(text, 'anthropic', 'claude-3-7-sonnet-20250219');\n    expect(count).toBeGreaterThan(0);\n    expect(typeof count).toBe('number');\n  });\n  \n  test('handles empty text', () => {\n    expect(countTokens('', 'openai', 'gpt-4')).toBe(0);\n    expect(countTokens(null, 'openai', 'gpt-4')).toBe(0);\n  });\n});\n```",
      "testStrategy": "1. Unit test the countTokens function with various inputs and models\n2. Compare token counts with known examples from OpenAI and Anthropic documentation\n3. Test edge cases: empty strings, very long texts, non-English texts\n4. Test fallback behavior when tiktoken fails or is not applicable",
      "priority": "high",
      "dependencies": [
        82
      ],
      "status": "pending",
      "subtasks": []
    },
    {
      "id": 85,
      "title": "Update ai-services-unified.js for dynamic token limits",
      "description": "Modify the _unifiedServiceRunner function in ai-services-unified.js to use the new token counting utility and dynamically adjust output token limits based on input length.",
      "details": "1. Import the token counter in `ai-services-unified.js`:\n```javascript\nconst { countTokens } = require('./token-counter');\nconst { getParametersForRole, getModelCapabilities } = require('./config-manager');\n```\n\n2. Update the `_unifiedServiceRunner` function to implement dynamic token limit adjustment:\n```javascript\nasync function _unifiedServiceRunner({\n  serviceType,\n  provider,\n  modelId,\n  systemPrompt,\n  prompt,\n  temperature,\n  currentRole,\n  effectiveProjectRoot,\n  // ... other parameters\n}) {\n  // Get role parameters with new token limits\n  const roleParams = getParametersForRole(currentRole, effectiveProjectRoot);\n  \n  // Get model capabilities\n  const modelCapabilities = getModelCapabilities(provider, modelId);\n  \n  // Count tokens in the prompts\n  const systemPromptTokens = countTokens(systemPrompt, provider, modelId);\n  const userPromptTokens = countTokens(prompt, provider, modelId);\n  const totalPromptTokens = systemPromptTokens + userPromptTokens;\n  \n  // Validate against input token limits\n  if (totalPromptTokens > roleParams.maxInputTokens) {\n    throw new Error(\n      `Prompt (${totalPromptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`\n    );\n  }\n  \n  // Validate against model's absolute context window\n  if (modelCapabilities.contextWindowTokens && totalPromptTokens > modelCapabilities.contextWindowTokens) {\n    throw new Error(\n      `Prompt (${totalPromptTokens} tokens) exceeds model's context window (${modelCapabilities.contextWindowTokens}) for ${modelId}.`\n    );\n  }\n  \n  // Calculate available output tokens\n  // If model has a combined context window, we need to subtract input tokens\n  let availableOutputTokens = roleParams.maxOutputTokens;\n  \n  // If model has a context window constraint, ensure we don't exceed it\n  if (modelCapabilities.contextWindowTokens) {\n    const remainingContextTokens = modelCapabilities.contextWindowTokens - totalPromptTokens;\n    availableOutputTokens = Math.min(availableOutputTokens, remainingContextTokens);\n  }\n  \n  // Also respect the model's absolute max output limit\n  if (modelCapabilities.maxOutputTokens) {\n    availableOutputTokens = Math.min(availableOutputTokens, modelCapabilities.maxOutputTokens);\n  }\n  \n  // Prepare API call parameters\n  const callParams = {\n    apiKey,\n    modelId,\n    maxTokens: availableOutputTokens, // Use dynamically calculated output limit\n    temperature: roleParams.temperature,\n    messages,\n    baseUrl,\n    ...(serviceType === 'generateObject' && { schema, objectName }),\n    ...restApiParams\n  };\n  \n  // Log token usage information\n  console.debug(`Token usage: ${totalPromptTokens} input tokens, ${availableOutputTokens} max output tokens`);\n  \n  // Rest of the function remains the same...\n}\n```\n\n3. Update the error handling to provide clear messages about token limits:\n```javascript\ntry {\n  // Existing code...\n} catch (error) {\n  if (error.message.includes('tokens')) {\n    // Token-related errors should be clearly identified\n    console.error(`Token limit error: ${error.message}`);\n  }\n  throw error;\n}\n```",
      "testStrategy": "1. Test with prompts of various lengths to verify dynamic adjustment\n2. Test with different models to ensure model-specific limits are respected\n3. Verify error messages are clear when limits are exceeded\n4. Test edge cases: very short prompts, prompts near the limit\n5. Integration test with actual API calls to verify the calculated limits work in practice",
      "priority": "medium",
      "dependencies": [
        83,
        84
      ],
      "status": "pending",
      "subtasks": []
    },
    {
      "id": 86,
      "title": "Update .taskmasterconfig schema and user guide",
      "description": "Create a migration guide for users to update their .taskmasterconfig files and document the new token limit configuration options.",
      "details": "1. Create a migration script or guide for users to update their existing `.taskmasterconfig` files:\n\n```javascript\n// Example migration snippet for .taskmasterconfig\n{\n  \"main\": {\n    // Before:\n    // \"maxTokens\": 16000,\n    \n    // After:\n    \"maxInputTokens\": 16000,\n    \"maxOutputTokens\": 4000,\n    \"temperature\": 0.7\n  },\n  \"research\": {\n    \"maxInputTokens\": 16000,\n    \"maxOutputTokens\": 4000,\n    \"temperature\": 0.7\n  },\n  \"fallback\": {\n    \"maxInputTokens\": 8000,\n    \"maxOutputTokens\": 2000,\n    \"temperature\": 0.7\n  }\n}\n```\n\n2. Update the user documentation to explain the new token limit fields:\n\n```markdown\n# Token Limit Configuration\n\nTask Master now provides more granular control over token limits with separate settings for input and output tokens:\n\n- `maxInputTokens`: Maximum number of tokens allowed in the input prompt (system prompt + user prompt)\n- `maxOutputTokens`: Maximum number of tokens the model should generate in its response\n\n## Benefits\n\n- More precise control over token usage\n- Better cost management\n- Reduced likelihood of hitting model context limits\n- Dynamic adjustment to maximize output space based on input length\n\n## Migration from Previous Versions\n\nIf you're upgrading from a previous version, you'll need to update your `.taskmasterconfig` file:\n\n1. Replace the single `maxTokens` field with separate `maxInputTokens` and `maxOutputTokens` fields\n2. Recommended starting values:\n   - Set `maxInputTokens` to your previous `maxTokens` value\n   - Set `maxOutputTokens` to approximately 1/4 of your model's context window\n\n## Example Configuration\n\n```json\n{\n  \"main\": {\n    \"maxInputTokens\": 16000,\n    \"maxOutputTokens\": 4000,\n    \"temperature\": 0.7\n  }\n}\n```\n```\n\n3. Update the schema validation in `config-manager.js` to validate the new fields:\n\n```javascript\nfunction _validateConfig(config) {\n  // ... existing validation\n  \n  // Validate token limits for each role\n  ['main', 'research', 'fallback'].forEach(role => {\n    if (config[role]) {\n      // Check if old maxTokens is present and warn about migration\n      if (config[role].maxTokens !== undefined) {\n        console.warn(`Warning: 'maxTokens' in ${role} role is deprecated. Please use 'maxInputTokens' and 'maxOutputTokens' instead.`);\n      }\n      \n      // Validate new token limit fields\n      if (config[role].maxInputTokens !== undefined && (!Number.isInteger(config[role].maxInputTokens) || config[role].maxInputTokens <= 0)) {\n        throw new Error(`Invalid maxInputTokens for ${role} role: must be a positive integer`);\n      }\n      \n      if (config[role].maxOutputTokens !== undefined && (!Number.isInteger(config[role].maxOutputTokens) || config[role].maxOutputTokens <= 0)) {\n        throw new Error(`Invalid maxOutputTokens for ${role} role: must be a positive integer`);\n      }\n    }\n  });\n  \n  return config;\n}\n```",
      "testStrategy": "1. Verify documentation is clear and provides migration steps\n2. Test the validation logic with various config formats\n3. Test backward compatibility with old config format\n4. Ensure error messages are helpful when validation fails",
      "priority": "medium",
      "dependencies": [
        83
      ],
      "status": "pending",
      "subtasks": []
    },
    {
      "id": 87,
      "title": "Implement validation and error handling",
      "description": "Add comprehensive validation and error handling for token limits throughout the system, including helpful error messages and graceful fallbacks.",
      "details": "1. Add validation when loading models in `config-manager.js`:\n```javascript\nfunction _validateModelMap(modelMap) {\n  // Validate each provider's models\n  Object.entries(modelMap).forEach(([provider, models]) => {\n    models.forEach(model => {\n      // Check for required token limit fields\n      if (!model.contextWindowTokens) {\n        console.warn(`Warning: Model ${model.id} from ${provider} is missing contextWindowTokens field`);\n      }\n      if (!model.maxOutputTokens) {\n        console.warn(`Warning: Model ${model.id} from ${provider} is missing maxOutputTokens field`);\n      }\n    });\n  });\n  return modelMap;\n}\n```\n\n2. Add validation when setting up a model in the CLI:\n```javascript\nfunction validateModelConfig(modelConfig, modelCapabilities) {\n  const issues = [];\n  \n  // Check if input tokens exceed model's context window\n  if (modelConfig.maxInputTokens > modelCapabilities.contextWindowTokens) {\n    issues.push(`maxInputTokens (${modelConfig.maxInputTokens}) exceeds model's context window (${modelCapabilities.contextWindowTokens})`);\n  }\n  \n  // Check if output tokens exceed model's maximum\n  if (modelConfig.maxOutputTokens > modelCapabilities.maxOutputTokens) {\n    issues.push(`maxOutputTokens (${modelConfig.maxOutputTokens}) exceeds model's maximum output tokens (${modelCapabilities.maxOutputTokens})`);\n  }\n  \n  // Check if combined tokens exceed context window\n  if (modelConfig.maxInputTokens + modelConfig.maxOutputTokens > modelCapabilities.contextWindowTokens) {\n    issues.push(`Combined maxInputTokens and maxOutputTokens (${modelConfig.maxInputTokens + modelConfig.maxOutputTokens}) exceeds model's context window (${modelCapabilities.contextWindowTokens})`);\n  }\n  \n  return issues;\n}\n```\n\n3. Add graceful fallbacks in `ai-services-unified.js`:\n```javascript\n// Fallback for missing token limits\nif (!roleParams.maxInputTokens) {\n  console.warn(`Warning: maxInputTokens not specified for role '${currentRole}'. Using default value.`);\n  roleParams.maxInputTokens = 8000; // Reasonable default\n}\n\nif (!roleParams.maxOutputTokens) {\n  console.warn(`Warning: maxOutputTokens not specified for role '${currentRole}'. Using default value.`);\n  roleParams.maxOutputTokens = 2000; // Reasonable default\n}\n\n// Fallback for missing model capabilities\nif (!modelCapabilities.contextWindowTokens) {\n  console.warn(`Warning: contextWindowTokens not specified for model ${modelId}. Using conservative estimate.`);\n  modelCapabilities.contextWindowTokens = roleParams.maxInputTokens + roleParams.maxOutputTokens;\n}\n\nif (!modelCapabilities.maxOutputTokens) {\n  console.warn(`Warning: maxOutputTokens not specified for model ${modelId}. Using role configuration.`);\n  modelCapabilities.maxOutputTokens = roleParams.maxOutputTokens;\n}\n```\n\n4. Add detailed logging for token usage:\n```javascript\nfunction logTokenUsage(provider, modelId, inputTokens, outputTokens, role) {\n  const inputCost = calculateTokenCost(provider, modelId, 'input', inputTokens);\n  const outputCost = calculateTokenCost(provider, modelId, 'output', outputTokens);\n  \n  console.info(`Token usage for ${role} role with ${provider}/${modelId}:`);\n  console.info(`- Input: ${inputTokens.toLocaleString()} tokens ($${inputCost.toFixed(6)})`);\n  console.info(`- Output: ${outputTokens.toLocaleString()} tokens ($${outputCost.toFixed(6)})`);\n  console.info(`- Total cost: $${(inputCost + outputCost).toFixed(6)}`);\n  console.info(`- Available output tokens: ${availableOutputTokens.toLocaleString()}`);\n}\n```\n\n5. Add a helper function to suggest configuration improvements:\n```javascript\nfunction suggestTokenConfigImprovements(roleParams, modelCapabilities, promptTokens) {\n  const suggestions = [];\n  \n  // If prompt is using less than 50% of allowed input\n  if (promptTokens < roleParams.maxInputTokens * 0.5) {\n    suggestions.push(`Consider reducing maxInputTokens from ${roleParams.maxInputTokens} to save on potential costs`);\n  }\n  \n  // If output tokens are very limited due to large input\n  const availableOutput = Math.min(\n    roleParams.maxOutputTokens,\n    modelCapabilities.contextWindowTokens - promptTokens\n  );\n  \n  if (availableOutput < roleParams.maxOutputTokens * 0.5) {\n    suggestions.push(`Available output tokens (${availableOutput}) are significantly less than configured maxOutputTokens (${roleParams.maxOutputTokens}) due to large input`);\n  }\n  \n  return suggestions;\n}\n```",
      "testStrategy": "1. Test validation functions with valid and invalid configurations\n2. Verify fallback behavior works correctly when configuration is missing\n3. Test error messages are clear and actionable\n4. Test logging functions provide useful information\n5. Verify suggestion logic provides helpful recommendations",
      "priority": "low",
      "dependencies": [
        85
      ],
      "status": "pending",
      "subtasks": []
    },
    {
      "id": 88,
      "title": "Enhance Add-Task Functionality to Consider All Task Dependencies",
      "description": "Improve the add-task feature to accurately account for all dependencies among tasks, ensuring proper task ordering and execution.",
      "details": "1. Review current implementation of add-task functionality.\n2. Identify existing mechanisms for handling task dependencies.\n3. Modify add-task to recursively analyze and incorporate all dependencies.\n4. Ensure that dependencies are resolved in the correct order during task execution.\n5. Update documentation to reflect changes in dependency handling.\n6. Consider edge cases such as circular dependencies and handle them appropriately.\n7. Optimize performance to ensure efficient dependency resolution, especially for projects with a large number of tasks.\n8. Integrate with existing validation and error handling mechanisms (from Task 87) to provide clear feedback if dependencies cannot be resolved.\n9. Test thoroughly with various dependency scenarios to ensure robustness.",
      "testStrategy": "1. Create test cases with simple linear dependencies to verify correct ordering.\n2. Develop test cases with complex, nested dependencies to ensure recursive resolution works correctly.\n3. Include tests for edge cases such as circular dependencies, verifying appropriate error messages are displayed.\n4. Measure performance with large sets of tasks and dependencies to ensure efficiency.\n5. Conduct integration testing with other components that rely on task dependencies.\n6. Perform manual code reviews to validate implementation against requirements.\n7. Execute automated tests to verify no regressions in existing functionality.",
      "status": "done",
      "dependencies": [],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Review Current Add-Task Implementation and Identify Dependency Mechanisms",
          "description": "Examine the existing add-task functionality to understand how task dependencies are currently handled.",
          "dependencies": [],
          "details": "Conduct a code review of the add-task feature. Document any existing mechanisms for handling task dependencies.",
          "status": "done",
          "testStrategy": "Verify that all current dependency handling features work as expected."
        },
        {
          "id": 2,
          "title": "Modify Add-Task to Recursively Analyze Dependencies",
          "description": "Update the add-task functionality to recursively analyze and incorporate all task dependencies.",
          "dependencies": [
            1
          ],
          "details": "Implement a recursive algorithm that identifies and incorporates all dependencies for a given task. Ensure it handles nested dependencies correctly.",
          "status": "done",
          "testStrategy": "Test with various dependency scenarios, including nested dependencies."
        },
        {
          "id": 3,
          "title": "Ensure Correct Order of Dependency Resolution",
          "description": "Modify the add-task functionality to ensure that dependencies are resolved in the correct order during task execution.",
          "dependencies": [
            2
          ],
          "details": "Implement logic to sort and execute tasks based on their dependency order. Handle cases where multiple tasks depend on each other.",
          "status": "done",
          "testStrategy": "Test with complex dependency chains to verify correct ordering."
        },
        {
          "id": 4,
          "title": "Integrate with Existing Validation and Error Handling",
          "description": "Update the add-task functionality to integrate with existing validation and error handling mechanisms (from Task 87).",
          "dependencies": [
            3
          ],
          "details": "Modify the code to provide clear feedback if dependencies cannot be resolved. Ensure that circular dependencies are detected and handled appropriately.",
          "status": "done",
          "testStrategy": "Test with invalid dependency scenarios to verify proper error handling."
        },
        {
          "id": 5,
          "title": "Optimize Performance for Large Projects",
          "description": "Optimize the add-task functionality to ensure efficient dependency resolution, especially for projects with a large number of tasks.",
          "dependencies": [
            4
          ],
          "details": "Profile and optimize the recursive dependency analysis algorithm. Implement caching or other performance improvements as needed.",
          "status": "done",
          "testStrategy": "Test with large sets of tasks to verify performance improvements."
        }
      ]
    },
    {
      "id": 89,
      "title": "Introduce Prioritize Command with Enhanced Priority Levels",
      "description": "Implement a prioritize command with --up/--down/--priority/--id flags and shorthand equivalents (-u/-d/-p/-i). Add 'lowest' and 'highest' priority levels, updating CLI output accordingly.",
      "status": "pending",
      "dependencies": [],
      "priority": "medium",
      "details": "The new prioritize command should allow users to adjust task priorities using the specified flags. The --up and --down flags will modify the priority relative to the current level, while --priority sets an absolute priority. The --id flag specifies which task to prioritize. Shorthand equivalents (-u/-d/-p/-i) should be supported for user convenience.\n\nThe priority levels should now include 'lowest', 'low', 'medium', 'high', and 'highest'. The CLI output should be updated to reflect these new priority levels accurately.\n\nConsiderations:\n- Ensure backward compatibility with existing commands and configurations.\n- Update the help documentation to include the new command and its usage.\n- Implement proper error handling for invalid priority levels or missing flags.",
      "testStrategy": "To verify task completion, perform the following tests:\n1. Test each flag (--up, --down, --priority, --id) individually and in combination to ensure they function as expected.\n2. Verify that shorthand equivalents (-u, -d, -p, -i) work correctly.\n3. Check that the new priority levels ('lowest' and 'highest') are recognized and displayed properly in CLI output.\n4. Test error handling for invalid inputs (e.g., non-existent task IDs, invalid priority levels).\n5. Ensure that the help command displays accurate information about the new prioritize command.",
      "subtasks": []
    },
    {
      "id": 90,
      "title": "Implement Subtask Progress Analyzer and Reporting System",
      "description": "Develop a subtask analyzer that monitors the progress of all subtasks, validates their status, and generates comprehensive reports for users to track project advancement.",
      "details": "The subtask analyzer should be implemented with the following components and considerations:\n\n1. Progress Tracking Mechanism:\n   - Create a function to scan the task data structure and identify all tasks with subtasks\n   - Implement logic to determine the completion status of each subtask\n   - Calculate overall progress percentages for tasks with multiple subtasks\n\n2. Status Validation:\n   - Develop validation rules to check if subtasks are progressing according to expected timelines\n   - Implement detection for stalled or blocked subtasks\n   - Create alerts for subtasks that are behind schedule or have dependency issues\n\n3. Reporting System:\n   - Design a structured report format that clearly presents:\n     - Overall project progress\n     - Task-by-task breakdown with subtask status\n     - Highlighted issues or blockers\n   - Support multiple output formats (console, JSON, exportable text)\n   - Include visual indicators for progress (e.g., progress bars in CLI)\n\n4. Integration Points:\n   - Hook into the existing task management system\n   - Ensure the analyzer can be triggered via CLI commands\n   - Make the reporting feature accessible through the main command interface\n\n5. Performance Considerations:\n   - Optimize for large task lists with many subtasks\n   - Implement caching if necessary to avoid redundant calculations\n   - Ensure reports generate quickly even for complex project structures\n\nThe implementation should follow the existing code style and patterns, leveraging the task data structure already in place. The analyzer should be non-intrusive to existing functionality while providing valuable insights to users.",
      "testStrategy": "Testing for the subtask analyzer should include:\n\n1. Unit Tests:\n   - Test the progress calculation logic with various task/subtask configurations\n   - Verify status validation correctly identifies issues in different scenarios\n   - Ensure report generation produces consistent and accurate output\n   - Test edge cases (empty subtasks, all complete, all incomplete, mixed states)\n\n2. Integration Tests:\n   - Verify the analyzer correctly integrates with the existing task data structure\n   - Test CLI command integration and parameter handling\n   - Ensure reports reflect actual changes to task/subtask status\n\n3. Performance Tests:\n   - Benchmark report generation with large task sets (100+ tasks with multiple subtasks)\n   - Verify memory usage remains reasonable during analysis\n\n4. User Acceptance Testing:\n   - Create sample projects with various subtask configurations\n   - Generate reports and verify they provide clear, actionable information\n   - Confirm visual indicators accurately represent progress\n\n5. Regression Testing:\n   - Verify that the analyzer doesn't interfere with existing task management functionality\n   - Ensure backward compatibility with existing task data structures\n\nDocumentation should be updated to include examples of how to use the new analyzer and interpret the reports. Success criteria include accurate progress tracking, clear reporting, and performance that scales with project size.",
      "status": "pending",
      "dependencies": [
        1,
        3
      ],
      "priority": "medium",
      "subtasks": []
    },
    {
      "id": 91,
      "title": "Implement Move Command for Tasks and Subtasks",
      "description": "Introduce a 'move' command to enable moving tasks or subtasks to a different id, facilitating conflict resolution by allowing teams to assign new ids as needed.",
      "status": "done",
      "dependencies": [
        1,
        3
      ],
      "priority": "medium",
      "details": "The move command will consist of three core components: 1) Core Logic Function in scripts/modules/task-manager/move-task.js, 2) Direct Function Wrapper in mcp-server/src/core/direct-functions/move-task.js, and 3) MCP Tool in mcp-server/src/tools/move-task.js. The command will accept source and destination IDs, handling various scenarios including moving tasks to become subtasks, subtasks to become tasks, and subtasks between different parents. The implementation will handle edge cases such as invalid ids, non-existent parents, circular dependencies, and will properly update all dependencies.",
      "testStrategy": "Testing will follow a three-tier approach: 1) Unit tests for core functionality including moving tasks to subtasks, subtasks to tasks, subtasks between parents, dependency handling, and validation error cases; 2) Integration tests for the direct function with mock MCP environment and task file regeneration; 3) End-to-end tests for the full MCP tool call path. This will verify all scenarios including moving a task to a new id, moving a subtask under a different parent while preserving its hierarchy, and handling errors for invalid operations.",
      "subtasks": [
        {
          "id": 1,
          "title": "Design and implement core move logic",
          "description": "Create the fundamental logic for moving tasks and subtasks within the task management system hierarchy",
          "dependencies": [],
          "details": "Implement the core logic function in scripts/modules/task-manager/move-task.js with the signature that accepts tasksPath, sourceId, destinationId, and generateFiles parameters. Develop functions to handle all movement operations including task-to-subtask, subtask-to-task, and subtask-to-subtask conversions. Implement validation for source and destination IDs, and ensure proper updating of parent-child relationships and dependencies.",
          "status": "done",
          "parentTaskId": 91
        },
        {
          "id": 2,
          "title": "Implement edge case handling",
          "description": "Develop robust error handling for all potential edge cases in the move operation",
          "dependencies": [
            1
          ],
          "details": "Create validation functions to detect invalid task IDs, non-existent parent tasks, and circular dependencies. Handle special cases such as moving a task to become the first/last subtask, reordering within the same parent, preventing moving a task to itself, and preventing moving a parent to its own subtask. Implement proper error messages and status codes for each edge case, and ensure system stability if a move operation fails.",
          "status": "done",
          "parentTaskId": 91
        },
        {
          "id": 3,
          "title": "Update CLI interface for move commands",
          "description": "Extend the command-line interface to support the new move functionality with appropriate flags and options",
          "dependencies": [
            1
          ],
          "details": "Create the Direct Function Wrapper in mcp-server/src/core/direct-functions/move-task.js to adapt the core logic for MCP, handling path resolution and parameter validation. Implement silent mode to prevent console output interfering with JSON responses. Create the MCP Tool in mcp-server/src/tools/move-task.js that exposes the functionality to Cursor, handles project root resolution, and includes proper Zod parameter definitions. Update MCP tool definition in .cursor/mcp.json and register the tool in mcp-server/src/tools/index.js.",
          "status": "done",
          "parentTaskId": 91
        },
        {
          "id": 4,
          "title": "Ensure data integrity during moves",
          "description": "Implement safeguards to maintain data consistency and update all relationships during move operations",
          "dependencies": [
            1,
            2
          ],
          "details": "Implement dependency handling logic to update dependencies when converting between task/subtask, add appropriate parent dependencies when needed, and validate no circular dependencies are created. Create transaction-like operations to ensure atomic moves that either complete fully or roll back. Implement functions to update all affected task relationships after a move, and add verification steps to confirm data integrity post-move.",
          "status": "done",
          "parentTaskId": 91
        },
        {
          "id": 5,
          "title": "Create comprehensive test suite",
          "description": "Develop and execute tests covering all move scenarios and edge cases",
          "dependencies": [
            1,
            2,
            3,
            4
          ],
          "details": "Create unit tests for core functionality including moving tasks to subtasks, subtasks to tasks, subtasks between parents, dependency handling, and validation error cases. Implement integration tests for the direct function with mock MCP environment and task file regeneration. Develop end-to-end tests for the full MCP tool call path. Ensure tests cover all identified edge cases and potential failure points, and verify data integrity after moves.",
          "status": "done",
          "parentTaskId": 91
        },
        {
          "id": 6,
          "title": "Export and integrate the move function",
          "description": "Ensure the move function is properly exported and integrated with existing code",
          "dependencies": [
            1
          ],
          "details": "Export the move function in scripts/modules/task-manager.js. Update task-master-core.js to include the direct function. Reuse validation logic from add-subtask.js and remove-subtask.js where appropriate. Follow silent mode implementation pattern from other direct functions and match parameter naming conventions in MCP tools.",
          "status": "done",
          "parentTaskId": 91
        }
      ]
    },
    {
      "id": 92,
      "title": "Implement Project Root Environment Variable Support in MCP Configuration",
      "description": "Add support for a 'TASK_MASTER_PROJECT_ROOT' environment variable in MCP configuration, allowing it to be set in both mcp.json and .env, with precedence over other methods. This will define the root directory for the MCP server and take precedence over all other project root resolution methods. The implementation should be backward compatible with existing workflows that don't use this variable.",
      "status": "review",
      "dependencies": [
        1,
        3,
        17
      ],
      "priority": "medium",
      "details": "Update the MCP server configuration system to support the TASK_MASTER_PROJECT_ROOT environment variable as the standard way to specify the project root directory. This provides better namespacing and avoids conflicts with other tools that might use a generic PROJECT_ROOT variable. Implement a clear precedence order for project root resolution:\n\n1. TASK_MASTER_PROJECT_ROOT environment variable (from shell or .env file)\n2. 'projectRoot' key in mcp_config.toml or mcp.json configuration files\n3. Existing resolution logic (CLI args, current working directory, etc.)\n\nModify the configuration loading logic to check for these sources in the specified order, ensuring backward compatibility. All MCP tools and components should use this standardized project root resolution logic. The TASK_MASTER_PROJECT_ROOT environment variable will be required because path resolution is delegated to the MCP client implementation, ensuring consistent behavior across different environments.\n\nImplementation steps:\n1. Identify all code locations where project root is determined (initialization, utility functions)\n2. Update configuration loaders to check for TASK_MASTER_PROJECT_ROOT in environment variables\n3. Add support for 'projectRoot' in configuration files as a fallback\n4. Refactor project root resolution logic to follow the new precedence rules\n5. Ensure all MCP tools and functions use the updated resolution logic\n6. Add comprehensive error handling for cases where TASK_MASTER_PROJECT_ROOT is not set or invalid\n7. Implement validation to ensure the specified directory exists and is accessible",
      "testStrategy": "1. Write unit tests to verify that the config loader correctly reads project root from environment variables and configuration files with the expected precedence:\n   - Test TASK_MASTER_PROJECT_ROOT environment variable takes precedence when set\n   - Test 'projectRoot' in configuration files is used when environment variable is absent\n   - Test fallback to existing resolution logic when neither is specified\n\n2. Add integration tests to ensure that the MCP server and all tools use the correct project root:\n   - Test server startup with TASK_MASTER_PROJECT_ROOT set to various valid and invalid paths\n   - Test configuration file loading from the specified project root\n   - Test path resolution for resources relative to the project root\n\n3. Test backward compatibility:\n   - Verify existing workflows function correctly without the new variables\n   - Ensure no regression in projects not using the new configuration options\n\n4. Manual testing:\n   - Set TASK_MASTER_PROJECT_ROOT in shell environment and verify correct behavior\n   - Set TASK_MASTER_PROJECT_ROOT in .env file and verify it's properly loaded\n   - Configure 'projectRoot' in configuration files and test precedence\n   - Test with invalid or non-existent directories to verify error handling",
      "subtasks": [
        {
          "id": 1,
          "title": "Update configuration loader to check for TASK_MASTER_PROJECT_ROOT environment variable",
          "description": "Modify the configuration loading system to check for the TASK_MASTER_PROJECT_ROOT environment variable as the primary source for project root directory. Ensure proper error handling if the variable is set but points to a non-existent or inaccessible directory.",
          "status": "pending"
        },
        {
          "id": 2,
          "title": "Add support for 'projectRoot' in configuration files",
          "description": "Implement support for a 'projectRoot' key in mcp_config.toml and mcp.json configuration files as a fallback when the environment variable is not set. Update the configuration parser to recognize and validate this field.",
          "status": "pending"
        },
        {
          "id": 3,
          "title": "Refactor project root resolution logic with clear precedence rules",
          "description": "Create a unified project root resolution function that follows the precedence order: 1) TASK_MASTER_PROJECT_ROOT environment variable, 2) 'projectRoot' in config files, 3) existing resolution methods. Ensure this function is used consistently throughout the codebase.",
          "status": "pending"
        },
        {
          "id": 4,
          "title": "Update all MCP tools to use the new project root resolution",
          "description": "Identify all MCP tools and components that need to access the project root and update them to use the new resolution logic. Ensure consistent behavior across all parts of the system.",
          "status": "pending"
        },
        {
          "id": 5,
          "title": "Add comprehensive tests for the new project root resolution",
          "description": "Create unit and integration tests to verify the correct behavior of the project root resolution logic under various configurations and edge cases.",
          "status": "pending"
        },
        {
          "id": 6,
          "title": "Update documentation with new configuration options",
          "description": "Update the project documentation to clearly explain the new TASK_MASTER_PROJECT_ROOT environment variable, the 'projectRoot' configuration option, and the precedence rules. Include examples of different configuration scenarios.",
          "status": "pending"
        },
        {
          "id": 7,
          "title": "Implement validation for project root directory",
          "description": "Add validation to ensure the specified project root directory exists and has the necessary permissions. Provide clear error messages when validation fails.",
          "status": "pending"
        },
        {
          "id": 8,
          "title": "Implement support for loading environment variables from .env files",
          "description": "Add functionality to load the TASK_MASTER_PROJECT_ROOT variable from .env files in the workspace, following best practices for environment variable management in MCP servers.",
          "status": "pending"
        }
      ]
    },
    {
      "id": 93,
      "title": "Implement Google Vertex AI Provider Integration",
      "description": "Develop a dedicated Google Vertex AI provider in the codebase, enabling users to leverage Vertex AI models with enterprise-grade configuration and authentication.",
      "details": "1. Create a new provider class in `src/ai-providers/google-vertex.js` that extends the existing BaseAIProvider, following the established structure used by other providers (e.g., google.js, openai.js).\n2. Integrate the Vercel AI SDK's `@ai-sdk/google-vertex` package. Use the default `vertex` provider for standard usage, and allow for custom configuration via `createVertex` for advanced scenarios (e.g., specifying project ID, location, and credentials).\n3. Implement all required interface methods (such as `getClient`, `generateText`, etc.) to ensure compatibility with the provider system. Reference the implementation patterns from other providers for consistency.\n4. Handle Vertex AI-specific configuration, including project ID, location, and Google Cloud authentication. Support both environment-based authentication and explicit service account credentials via `googleAuthOptions`.\n5. Implement robust error handling for Vertex-specific issues, including authentication failures and API errors, leveraging the system-wide error handling patterns.\n6. Update `src/ai-providers/index.js` to export the new provider, and add the 'vertex' entry to the PROVIDERS object in `scripts/modules/ai-services-unified.js`.\n7. Update documentation to provide clear setup instructions for Google Vertex AI, including required environment variables, service account setup, and configuration examples.\n8. Ensure the implementation is modular and maintainable, supporting future expansion for additional Vertex AI features or models.",
      "testStrategy": "- Write unit tests for the new provider class, covering all interface methods and configuration scenarios (default, custom, error cases).\n- Verify that the provider can successfully authenticate using both environment-based and explicit service account credentials.\n- Test integration with the provider system by selecting 'vertex' as the provider and generating text using supported Vertex AI models (e.g., Gemini).\n- Simulate authentication and API errors to confirm robust error handling and user feedback.\n- Confirm that the provider is correctly exported and available in the PROVIDERS object.\n- Review and validate the updated documentation for accuracy and completeness.",
      "status": "pending",
      "dependencies": [
        19,
        94
      ],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Google Vertex AI Provider Class",
          "description": "Develop a new provider class in `src/ai-providers/google-vertex.js` that extends the BaseAIProvider, following the structure of existing providers.",
          "dependencies": [],
          "details": "Ensure the new class is consistent with the architecture of other providers such as google.js and openai.js, and is ready to integrate with the AI SDK.",
          "status": "pending",
          "testStrategy": "Verify the class structure matches other providers and can be instantiated without errors."
        },
        {
          "id": 2,
          "title": "Integrate Vercel AI SDK Google Vertex Package",
          "description": "Integrate the `@ai-sdk/google-vertex` package, supporting both the default provider and custom configuration via `createVertex`.",
          "dependencies": [
            1
          ],
          "details": "Allow for standard usage with the default `vertex` provider and advanced scenarios using `createVertex` for custom project ID, location, and credentials as per SDK documentation.",
          "status": "pending",
          "testStrategy": "Write unit tests to ensure both default and custom provider instances can be created and configured."
        },
        {
          "id": 3,
          "title": "Implement Provider Interface Methods",
          "description": "Implement all required interface methods (e.g., `getClient`, `generateText`) to ensure compatibility with the provider system.",
          "dependencies": [
            2
          ],
          "details": "Reference implementation patterns from other providers to maintain consistency and ensure all required methods are present and functional.",
          "status": "pending",
          "testStrategy": "Run integration tests to confirm the provider responds correctly to all interface method calls."
        },
        {
          "id": 4,
          "title": "Handle Vertex AI Configuration and Authentication",
          "description": "Implement support for Vertex AI-specific configuration, including project ID, location, and authentication via environment variables or explicit service account credentials.",
          "dependencies": [
            3
          ],
          "details": "Support both environment-based authentication and explicit credentials using `googleAuthOptions`, following Google Cloud and Vertex AI setup best practices.",
          "status": "pending",
          "testStrategy": "Test with both environment variable-based and explicit service account authentication to ensure both methods work as expected."
        },
        {
          "id": 5,
          "title": "Update Exports, Documentation, and Error Handling",
          "description": "Export the new provider, update the PROVIDERS object, and document setup instructions, including robust error handling for Vertex-specific issues.",
          "dependencies": [
            4
          ],
          "details": "Update `src/ai-providers/index.js` and `scripts/modules/ai-services-unified.js`, and provide clear documentation for setup, configuration, and error handling patterns.",
          "status": "pending",
          "testStrategy": "Verify the provider is available for import, documentation is accurate, and error handling works by simulating common failure scenarios."
        }
      ]
    },
    {
      "id": 94,
      "title": "Implement Azure OpenAI Provider Integration",
      "description": "Create a comprehensive Azure OpenAI provider implementation that integrates with the existing AI provider system, enabling users to leverage Azure-hosted OpenAI models through proper authentication and configuration.",
      "details": "Implement the Azure OpenAI provider following the established provider pattern:\n\n1. **Create Azure Provider Class** (`src/ai-providers/azure.js`):\n   - Extend BaseAIProvider class following the same pattern as openai.js and google.js\n   - Import and use `createAzureOpenAI` from `@ai-sdk/azure` package\n   - Implement required interface methods: `getClient()`, `validateConfig()`, and any other abstract methods\n   - Handle Azure-specific configuration: endpoint URL, API key, and deployment name\n   - Add proper error handling for missing or invalid Azure configuration\n\n2. **Configuration Management**:\n   - Support environment variables: AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, AZURE_OPENAI_DEPLOYMENT\n   - Validate that both endpoint and API key are provided\n   - Provide clear error messages for configuration issues\n   - Follow the same configuration pattern as other providers\n\n3. **Integration Updates**:\n   - Update `src/ai-providers/index.js` to export the new AzureProvider\n   - Add 'azure' entry to the PROVIDERS object in `scripts/modules/ai-services-unified.js`\n   - Ensure the provider is properly registered and accessible through the unified AI services\n\n4. **Error Handling**:\n   - Implement Azure-specific error handling for authentication failures\n   - Handle endpoint connectivity issues with helpful error messages\n   - Validate deployment name and provide guidance for common configuration mistakes\n   - Follow the established error handling patterns from Task 19\n\n5. **Documentation Updates**:\n   - Update any provider documentation to include Azure OpenAI setup instructions\n   - Add configuration examples for Azure OpenAI environment variables\n   - Include troubleshooting guidance for common Azure-specific issues\n\nThe implementation should maintain consistency with existing provider implementations while handling Azure's unique authentication and endpoint requirements.",
      "testStrategy": "Verify the Azure OpenAI provider implementation through comprehensive testing:\n\n1. **Unit Testing**:\n   - Test provider class instantiation and configuration validation\n   - Verify getClient() method returns properly configured Azure OpenAI client\n   - Test error handling for missing/invalid configuration parameters\n   - Validate that the provider correctly extends BaseAIProvider\n\n2. **Integration Testing**:\n   - Test provider registration in the unified AI services system\n   - Verify the provider appears in the PROVIDERS object and is accessible\n   - Test end-to-end functionality with valid Azure OpenAI credentials\n   - Validate that the provider works with existing AI operation workflows\n\n3. **Configuration Testing**:\n   - Test with various environment variable combinations\n   - Verify proper error messages for missing endpoint or API key\n   - Test with invalid endpoint URLs and ensure graceful error handling\n   - Validate deployment name handling and error reporting\n\n4. **Manual Verification**:\n   - Set up test Azure OpenAI credentials and verify successful connection\n   - Test actual AI operations (like task expansion) using the Azure provider\n   - Verify that the provider selection works correctly in the CLI\n   - Confirm that error messages are helpful and actionable for users\n\n5. **Documentation Verification**:\n   - Ensure all configuration examples work as documented\n   - Verify that setup instructions are complete and accurate\n   - Test troubleshooting guidance with common error scenarios",
      "status": "done",
      "dependencies": [
        19,
        26
      ],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Create Azure Provider Class",
          "description": "Implement the AzureProvider class that extends BaseAIProvider to handle Azure OpenAI integration",
          "dependencies": [],
          "details": "Create the AzureProvider class in src/ai-providers/azure.js that extends BaseAIProvider. Import createAzureOpenAI from @ai-sdk/azure package. Implement required interface methods including getClient() and validateConfig(). Handle Azure-specific configuration parameters: endpoint URL, API key, and deployment name. Follow the established pattern in openai.js and google.js. Ensure proper error handling for missing or invalid configuration.",
          "status": "done",
          "testStrategy": "Create unit tests that verify the AzureProvider class correctly initializes with valid configuration and throws appropriate errors with invalid configuration. Test the getClient() method returns a properly configured client instance.",
          "parentTaskId": 94
        },
        {
          "id": 2,
          "title": "Implement Configuration Management",
          "description": "Add support for Azure OpenAI environment variables and configuration validation",
          "dependencies": [
            1
          ],
          "details": "Implement configuration management for Azure OpenAI provider that supports environment variables: AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, and AZURE_OPENAI_DEPLOYMENT. Add validation logic to ensure both endpoint and API key are provided. Create clear error messages for configuration issues. Follow the same configuration pattern as implemented in other providers. Ensure the validateConfig() method properly checks all required Azure configuration parameters.",
          "status": "done",
          "testStrategy": "Test configuration validation with various combinations of missing or invalid parameters. Verify environment variables are correctly loaded and applied to the provider configuration.",
          "parentTaskId": 94
        },
        {
          "id": 3,
          "title": "Update Provider Integration",
          "description": "Integrate the Azure provider into the existing AI provider system",
          "dependencies": [
            1,
            2
          ],
          "details": "Update src/ai-providers/index.js to export the new AzureProvider class. Add 'azure' entry to the PROVIDERS object in scripts/modules/ai-services-unified.js. Ensure the provider is properly registered and accessible through the unified AI services. Test that the provider can be instantiated and used through the provider selection mechanism. Follow the same integration pattern used for existing providers.",
          "status": "done",
          "testStrategy": "Create integration tests that verify the Azure provider is correctly registered and can be selected through the provider system. Test that the provider is properly initialized when selected.",
          "parentTaskId": 94
        },
        {
          "id": 4,
          "title": "Implement Azure-Specific Error Handling",
          "description": "Add specialized error handling for Azure OpenAI-specific issues",
          "dependencies": [
            1,
            2
          ],
          "details": "Implement Azure-specific error handling for authentication failures, endpoint connectivity issues, and deployment name validation. Provide helpful error messages that guide users to resolve common configuration mistakes. Follow the established error handling patterns from Task 19. Create custom error classes if needed for Azure-specific errors. Ensure errors are properly propagated and formatted for user display.",
          "status": "done",
          "testStrategy": "Test error handling by simulating various failure scenarios including authentication failures, invalid endpoints, and missing deployment names. Verify appropriate error messages are generated.",
          "parentTaskId": 94
        },
        {
          "id": 5,
          "title": "Update Documentation",
          "description": "Create comprehensive documentation for the Azure OpenAI provider integration",
          "dependencies": [
            1,
            2,
            3,
            4
          ],
          "details": "Update provider documentation to include Azure OpenAI setup instructions. Add configuration examples for Azure OpenAI environment variables. Include troubleshooting guidance for common Azure-specific issues. Document the required Azure resource creation process with references to Microsoft's documentation. Provide examples of valid configuration settings and explain each required parameter. Include information about Azure OpenAI model deployment requirements.",
          "status": "done",
          "testStrategy": "Review documentation for completeness, accuracy, and clarity. Ensure all configuration options are documented and examples are provided. Verify troubleshooting guidance addresses common issues identified during implementation.",
          "parentTaskId": 94
        }
      ]
    },
    {
      "id": 95,
      "title": "Implement .taskmaster Directory Structure",
      "description": "Consolidate all Task Master-managed files in user projects into a clean, centralized .taskmaster/ directory structure to improve organization and keep user project directories clean, based on GitHub issue #275.",
      "status": "done",
      "dependencies": [
        1,
        3,
        4,
        17
      ],
      "priority": "high",
      "details": "This task involves restructuring how Task Master organizes files within user projects to improve maintainability and keep project directories clean:\n\n1. Create a new `.taskmaster/` directory structure in user projects:\n   - Move task files from `tasks/` to `.taskmaster/tasks/`\n   - Move PRD files from `scripts/` to `.taskmaster/docs/`\n   - Move analysis reports to `.taskmaster/reports/`\n   - Move configuration from `.taskmasterconfig` to `.taskmaster/config.json`\n   - Create `.taskmaster/templates/` for user templates\n\n2. Update all Task Master code that creates/reads user files:\n   - Modify task file generation to use `.taskmaster/tasks/`\n   - Update PRD file handling to use `.taskmaster/docs/`\n   - Adjust report generation to save to `.taskmaster/reports/`\n   - Update configuration loading to look for `.taskmaster/config.json`\n   - Modify any path resolution logic in Task Master's codebase\n\n3. Ensure backward compatibility during migration:\n   - Implement path fallback logic that checks both old and new locations\n   - Add deprecation warnings when old paths are detected\n   - Create a migration command to help users transition to the new structure\n   - Preserve existing user data during migration\n\n4. Update the project initialization process:\n   - Modify the init command to create the new `.taskmaster/` directory structure\n   - Update default file creation to use new paths\n\n5. Benefits of the new structure:\n   - Keeps user project directories clean and organized\n   - Clearly separates Task Master files from user project files\n   - Makes it easier to add Task Master to .gitignore if desired\n   - Provides logical grouping of different file types\n\n6. Test thoroughly to ensure all functionality works with the new structure:\n   - Verify all Task Master commands work with the new paths\n   - Ensure backward compatibility functions correctly\n   - Test migration process preserves all user data\n\n7. Update documentation:\n   - Update README.md to reflect the new user file structure\n   - Add migration guide for existing users\n   - Document the benefits of the cleaner organization",
      "testStrategy": "1. Unit Testing:\n   - Create unit tests for path resolution that verify both new and old paths work\n   - Test configuration loading with both `.taskmasterconfig` and `.taskmaster/config.json`\n   - Verify the migration command correctly moves files and preserves content\n   - Test file creation in all new subdirectories\n\n2. Integration Testing:\n   - Run all existing integration tests with the new directory structure\n   - Verify that all Task Master commands function correctly with new paths\n   - Test backward compatibility by running commands with old file structure\n\n3. Migration Testing:\n   - Test the migration process on sample projects with existing tasks and files\n   - Verify all tasks, PRDs, reports, and configurations are correctly moved\n   - Ensure no data loss occurs during migration\n   - Test migration with partial existing structures (e.g., only tasks/ exists)\n\n4. User Workflow Testing:\n   - Test complete workflows: init → create tasks → generate reports → update PRDs\n   - Verify all generated files go to correct locations in `.taskmaster/`\n   - Test that user project directories remain clean\n\n5. Manual Testing:\n   - Perform end-to-end testing with the new structure\n   - Create, update, and delete tasks using the new structure\n   - Generate reports and verify they're saved to `.taskmaster/reports/`\n\n6. Documentation Verification:\n   - Review all documentation to ensure it accurately reflects the new user file structure\n   - Verify the migration guide provides clear instructions\n\n7. Regression Testing:\n   - Run the full test suite to ensure no regressions were introduced\n   - Verify existing user projects continue to work during transition period",
      "subtasks": [
        {
          "id": 1,
          "title": "Create .taskmaster directory structure",
          "description": "Create the new .taskmaster directory and move existing files to their new locations",
          "dependencies": [],
          "details": "Create a new .taskmaster/ directory in the project root. Move the tasks/ directory to .taskmaster/tasks/. Move the scripts/ directory to .taskmaster/scripts/. Move the .taskmasterconfig file to .taskmaster/config.json. Ensure proper file permissions are maintained during the move.\n<info added on 2025-05-29T15:03:56.912Z>\nCreate the new .taskmaster/ directory structure in user projects with subdirectories for tasks/, docs/, reports/, and templates/. Move the existing .taskmasterconfig file to .taskmaster/config.json. Since this project is also a Task Master user, move this project's current user files (tasks.json, PRD files, etc.) to the new .taskmaster/ structure to test the implementation. This subtask focuses on user project directory structure, not Task Master source code relocation.\n</info added on 2025-05-29T15:03:56.912Z>",
          "status": "done",
          "testStrategy": "Verify all files have been moved correctly with their content intact. Check directory permissions match the original settings."
        },
        {
          "id": 2,
          "title": "Update Task Master code for new user file paths",
          "description": "Modify all Task Master code that creates or reads user project files to use the new .taskmaster structure",
          "dependencies": [
            1
          ],
          "details": "Update Task Master's file handling code to use the new paths: tasks in .taskmaster/tasks/, PRD files in .taskmaster/docs/, reports in .taskmaster/reports/, and config in .taskmaster/config.json. Modify path resolution logic throughout the Task Master codebase to reference the new user file locations.",
          "status": "done",
          "testStrategy": "Run unit tests to ensure all Task Master modules can properly create and access user files in new locations. Test configuration loading with the new path structure."
        },
        {
          "id": 3,
          "title": "Update task file generation system",
          "description": "Modify the task file generation system to use the new directory structure",
          "dependencies": [
            1
          ],
          "details": "Update the task file generation system to create and read task files from .taskmaster/tasks/ instead of tasks/. Ensure all template paths are updated. Modify any path resolution logic specific to task file handling.",
          "status": "done",
          "testStrategy": "Test creating new tasks and verify they're saved to the correct location. Verify existing tasks can be read from the new location."
        },
        {
          "id": 4,
          "title": "Implement backward compatibility logic",
          "description": "Add fallback mechanisms to support both old and new file locations during transition",
          "dependencies": [
            2,
            3
          ],
          "details": "Implement path fallback logic that checks both old and new locations when files aren't found. Add deprecation warnings when old paths are used, informing users about the new structure. Ensure error messages are clear about the transition.",
          "status": "done",
          "testStrategy": "Test with both old and new directory structures to verify fallback works correctly. Verify deprecation warnings appear when using old paths."
        },
        {
          "id": 5,
          "title": "Create migration command for users",
          "description": "Develop a Task Master command to help users transition their existing projects to the new structure",
          "dependencies": [
            1,
            4
          ],
          "details": "Create a 'taskmaster migrate' command that automatically moves user files from old locations to the new .taskmaster structure. Move tasks/ to .taskmaster/tasks/, scripts/prd.txt to .taskmaster/docs/, reports to .taskmaster/reports/, and .taskmasterconfig to .taskmaster/config.json. Include backup functionality and validation to ensure migration completed successfully.",
          "status": "done",
          "testStrategy": "Test the migration command on various user project configurations. Verify it handles edge cases like missing directories or partial existing structures."
        },
        {
          "id": 6,
          "title": "Update project initialization process",
          "description": "Modify the init command to create the new directory structure for new projects",
          "dependencies": [
            1
          ],
          "details": "Update the init command to create the .taskmaster directory and its subdirectories (tasks/, docs/, reports/, templates/). Modify default file creation to use the new paths. Ensure new projects are created with the correct structure from the start.",
          "status": "done",
          "testStrategy": "Test initializing new projects and verify the correct .taskmaster directory structure is created. Check that default configurations are properly set up in the new location."
        },
        {
          "id": 7,
          "title": "Update PRD and report file handling",
          "description": "Modify PRD file creation and report generation to use the new directory structure",
          "dependencies": [
            2,
            6
          ],
          "details": "Update PRD file handling to create and read files from .taskmaster/docs/ instead of scripts/. Modify report generation (like task-complexity-report.json) to save to .taskmaster/reports/. Ensure all file operations use the new paths consistently.",
          "status": "done",
          "testStrategy": "Test PRD file creation and updates in the new location. Verify reports are generated and saved to .taskmaster/reports/. Test reading existing PRD files from new location."
        },
        {
          "id": 8,
          "title": "Update documentation and create migration guide",
          "description": "Update all documentation to reflect the new directory structure and provide migration guidance",
          "dependencies": [
            5,
            6,
            7
          ],
          "details": "Update README.md and other documentation to reflect the new .taskmaster structure for user projects. Create a comprehensive migration guide explaining the benefits of the new structure and how to migrate existing projects. Include examples of the new directory layout and explain how it keeps user project directories clean.",
          "status": "done",
          "testStrategy": "Review documentation for accuracy and completeness. Have users follow the migration guide to verify it's clear and effective."
        },
        {
          "id": 9,
          "title": "Add templates directory support",
          "description": "Implement support for user templates in the .taskmaster/templates/ directory",
          "dependencies": [
            2,
            6
          ],
          "details": "Create functionality to support user-defined templates in .taskmaster/templates/. Allow users to store custom task templates, PRD templates, or other reusable files. Update Task Master commands to recognize and use templates from this directory when available.",
          "status": "done",
          "testStrategy": "Test creating and using custom templates from .taskmaster/templates/. Verify template discovery and usage works correctly. Test that missing templates directory doesn't break functionality."
        },
        {
          "id": 10,
          "title": "Verify clean user project directories",
          "description": "Ensure the new structure keeps user project root directories clean and organized",
          "dependencies": [
            8,
            9
          ],
          "details": "Validate that after implementing the new structure, user project root directories only contain their actual project files plus the single .taskmaster/ directory. Verify that no Task Master files are created outside of .taskmaster/. Test that users can easily add .taskmaster/ to .gitignore if they choose to exclude Task Master files from version control.",
          "status": "done",
          "testStrategy": "Test complete workflows and verify only .taskmaster/ directory is created in project root. Check that all Task Master operations respect the new file organization. Verify .gitignore compatibility."
        }
      ]
    },
    {
      "id": 96,
      "title": "Create Export Command for On-Demand Task File and PDF Generation",
      "description": "Develop an 'export' CLI command that generates task files and comprehensive PDF exports on-demand, replacing automatic file generation and providing users with flexible export options.",
      "details": "Implement a new 'export' command in the CLI that supports two primary modes: (1) generating individual task files on-demand (superseding the current automatic generation system), and (2) producing a comprehensive PDF export. The PDF should include: a first page with the output of 'tm list --with-subtasks', followed by individual pages for each task (using 'tm show <task_id>') and each subtask (using 'tm show <subtask_id>'). Integrate PDF generation using a robust library (e.g., pdfkit, Puppeteer, or jsPDF) to ensure high-quality output and proper pagination. Refactor or disable any existing automatic file generation logic to avoid performance overhead. Ensure the command supports flexible output paths and options for exporting only files, only PDF, or both. Update documentation and help output to reflect the new export capabilities. Consider concurrency and error handling for large projects. Ensure the export process is efficient and does not block the main CLI thread unnecessarily.",
      "testStrategy": "1. Run the 'export' command with various options and verify that task files are generated only on-demand, not automatically. 2. Generate a PDF export and confirm that the first page contains the correct 'tm list --with-subtasks' output, and that each subsequent page accurately reflects the output of 'tm show <task_id>' and 'tm show <subtask_id>' for all tasks and subtasks. 3. Test exporting in projects with large numbers of tasks and subtasks to ensure performance and correctness. 4. Attempt exports with invalid paths or missing data to verify robust error handling. 5. Confirm that no automatic file generation occurs during normal task operations. 6. Review CLI help output and documentation for accuracy regarding the new export functionality.",
      "status": "pending",
      "dependencies": [
        2,
        4,
        95
      ],
      "priority": "medium",
      "subtasks": [
        {
          "id": 1,
          "title": "Remove Automatic Task File Generation from Task Operations",
          "description": "Eliminate all calls to generateTaskFiles() from task operations such as add-task, remove-task, set-status, and similar commands to prevent unnecessary performance overhead.",
          "dependencies": [],
          "details": "Audit the codebase for any automatic invocations of generateTaskFiles() and remove or refactor them to ensure task files are not generated automatically during task operations.",
          "status": "pending",
          "testStrategy": "Verify that no task file generation occurs during any task operation by running the CLI and monitoring file system changes.",
          "parentTaskId": 96
        },
        {
          "id": 2,
          "title": "Implement Export Command Infrastructure with On-Demand Task File Generation",
          "description": "Develop the CLI 'export' command infrastructure, enabling users to generate task files on-demand by invoking the preserved generateTaskFiles function only when requested.",
          "dependencies": [
            1
          ],
          "details": "Create the export command with options for output paths and modes (files, PDF, or both). Ensure generateTaskFiles is only called within this command and not elsewhere.",
          "status": "pending",
          "testStrategy": "Test the export command to confirm task files are generated only when explicitly requested and that output paths and options function as intended.",
          "parentTaskId": 96
        },
        {
          "id": 3,
          "title": "Implement Comprehensive PDF Export Functionality",
          "description": "Add PDF export capability to the export command, generating a structured PDF with a first page listing all tasks and subtasks, followed by individual pages for each task and subtask, using a robust PDF library.",
          "dependencies": [
            2
          ],
          "details": "Integrate a PDF generation library (e.g., pdfkit, Puppeteer, or jsPDF). Ensure the PDF includes the output of 'tm list --with-subtasks' on the first page, and uses 'tm show <task_id>' and 'tm show <subtask_id>' for subsequent pages. Handle pagination, concurrency, and error handling for large projects.",
          "status": "pending",
          "testStrategy": "Generate PDFs for projects of varying sizes and verify layout, content accuracy, and performance. Test error handling and concurrency under load.",
          "parentTaskId": 96
        },
        {
          "id": 4,
          "title": "Update Documentation, Tests, and CLI Help for Export Workflow",
          "description": "Revise all relevant documentation, automated tests, and CLI help output to reflect the new export-based workflow and available options.",
          "dependencies": [
            2,
            3
          ],
          "details": "Update user guides, README files, and CLI help text. Add or modify tests to cover the new export command and its options. Ensure all documentation accurately describes the new workflow and usage.",
          "status": "pending",
          "testStrategy": "Review documentation for completeness and accuracy. Run all tests to ensure coverage of the new export command and verify CLI help output.",
          "parentTaskId": 96
        }
      ]
    }
  ]
}