Compare commits

...

28 Commits

Author SHA1 Message Date
Ralph Khreish
8852831807 Merge pull request #810 from eyaltoledano/changeset-release/main
Version Packages
2025-06-18 21:35:39 +03:00
Ralph Khreish
661d3e04ba chore: fix package.json 2025-06-18 21:14:27 +03:00
github-actions[bot]
0dba2cb2da Version Packages 2025-06-18 16:02:39 +00:00
Ralph Khreish
9ee7a94056 Release 0.17.1 (#790)
* fix(contextGatherer): cannot read properties of undefined reading forEach (#789)

* docs: Update configuration.md (#782)

---------

Co-authored-by: Bartu OZEL <bartuozel@gmail.com>
2025-06-18 19:02:16 +03:00
Bartu OZEL
636fb3f680 docs: Update configuration.md (#782) 2025-06-16 20:12:54 +02:00
Ralph Khreish
8cde6c2708 fix(contextGatherer): cannot read properties of undefined reading forEach (#789) 2025-06-16 10:32:34 +02:00
Ralph Khreish
246acd1035 Merge Release 0.17.0 pull request #780 from eyaltoledano/changeset-release/main
Version Packages
2025-06-15 03:16:16 +02:00
Ralph Khreish
de5acbc6c9 chore: fix formatting 2025-06-15 04:12:13 +03:00
Ralph Khreish
664eb5b896 cleanup release 2025-06-15 04:10:51 +03:00
github-actions[bot]
dbaf492bdb Version Packages 2025-06-15 00:59:24 +00:00
Ralph Khreish
0c8a0b81a0 Merge pull request #779 from eyaltoledano/next
Release 0.17.0
2025-06-15 02:59:01 +02:00
github-actions[bot]
46d4f273f5 docs: Auto-update and format models.md 2025-06-15 00:50:10 +00:00
github-actions[bot]
aa7396d65e Version Packages 2025-06-15 03:47:56 +03:00
Eyal Toledano
5119cd2d8e v017 polish (#778)
* fix(research, tasks): Make research command and task updates tag-aware

* refactor(tasks): Prevent automatic task file generation across other locations

This commit refactors several core task management functions to prevent them from automatically regenerating individual task files after modifying the main `tasks.json`.

Previously, operations like `add-task`, `clear-subtasks`, `expand-task`, and `update-task-by-id` would immediately trigger `generateTaskFiles`. This could be slow and was often unnecessary.

The calls to `generateTaskFiles` have been removed or commented out from the core task functions. Users should now run `task-master generate` explicitly to update their individual task files.

Additionally, this commit includes fixes to the `move` command to make it fully tag-aware.

* fix: move and clear subtasks mcp commands

* chore: fix format

* chore: fix unit tests

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-06-15 03:47:56 +03:00
github-actions[bot]
44eba3f7d1 chore: rc version bump 2025-06-15 03:47:56 +03:00
Eyal Toledano
e82b093dce docs: Update taskmaster.mdc and dev_workflow.mdc with missing CLI fla… (#775)
* docs: Update taskmaster.mdc and dev_workflow.mdc with missing CLI flags and enhanced workflow guidance

- Add missing --tag flags to commands that were implemented but not documented
- Add missing --file flags to tag management commands
- Add --bedrock flag to models command documentation
- Synchronize CLI documentation with actual implementation in commands.js
- Enhance dev_workflow.mdc with comprehensive tagged task lists guidance
- Add patterns for when to introduce tags (git branching, team collaboration, experiments)
- Consolidate and refine changesets for upcoming release

* chore: package-lock fixup

* chore: fix format

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-06-15 03:47:56 +03:00
Ralph Khreish
ad3acd874d chore: rc version bump (#776)
* Version Packages

* chore: update package-lock.json

* chore: fix format

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eyal Toledano <eyal@microangel.so>
2025-06-15 03:47:56 +03:00
github-actions[bot]
52022d370b chore: rc version bump 2025-06-15 03:47:56 +03:00
Eyal Toledano
957af5253b chore: v017 linting (#773) 2025-06-15 03:47:28 +03:00
Ralph Khreish
c0b3f432a6 chore: v0.17 features and improvements (#771)
* chore: task management and small bug fix.

* chore: task management

* feat: implement research command with enhanced context gathering - Add comprehensive research command with AI-powered queries - Implement ContextGatherer utility for reusable context extraction - Support multiple context types: tasks, files, custom text, project tree - Add fuzzy search integration for automatic task discovery - Implement detailed token breakdown display with syntax highlighting - Add enhanced UI with boxed output and code block formatting - Support different detail levels (low, medium, high) for responses - Include project-specific context for more relevant AI responses - Add token counting with gpt-tokens library integration - Create reusable patterns for future context-aware commands - Task 94.4 completed

* docs: add context gathering rule and update existing rules

- Create comprehensive context_gathering.mdc rule documenting ContextGatherer utility patterns, FuzzyTaskSearch integration, token breakdown display, code block syntax highlighting, and enhanced result display patterns
- Update new_features.mdc to include context gathering step
- Update commands.mdc with context-aware command pattern
- Update ui.mdc with enhanced display patterns and syntax highlighting
- Update utilities.mdc to document new context gathering utilities
- Update glossary.mdc to include new context_gathering rule
- Establishes standardized patterns for building intelligent, context-aware commands that can leverage project knowledge for better AI assistance

* feat(fuzzy): improves fuzzy search to introspect into subtasks as well. might still need improvement.

* fix(move): adjusts logic to prevent an issue when moving from parent to subtask if the target parent has no subtasks.

* fix(move-task): Fix critical bugs in task move functionality

- Fixed parent-to-parent task moves where original task would remain as duplicate
- Fixed moving tasks to become subtasks of empty parents (validation errors)
- Fixed moving subtasks between different parent tasks
- Improved comma-separated batch moves with proper error handling
- Updated MCP tool to use core logic instead of custom implementation
- Resolves task duplication issues and enables proper task hierarchy reorganization

* feat(research): Add subtasks to fuzzy search and follow-up questions

- Enhanced fuzzy search to include subtasks in discovery - Added interactive follow-up question functionality using inquirer
- Improved context discovery by including both tasks and subtasks
- Follow-up option for research with default to 'n' for quick workflow

* chore: removes task004 chat that had like 11k lines lol.

* chore: formatting

* feat(show): add comma-separated ID support for multi-task viewing

- Enhanced get-task/show command to support comma-separated task IDs for efficient batch operations.
- New features include multiple task retrieval, smart display logic, interactive action menu with batch operations, MCP array response for AI agent efficiency, and support for mixed parent tasks and subtasks.
- Implementation includes updated CLI show command, enhanced MCP get_task tool, modified showTaskDirect function, and maintained full backward compatibility.
- Documentation updated across all relevant files.

Benefits include faster context gathering for AI agents, improved workflow with interactive batch operations, better UX with responsive layout, and enhanced API efficiency.

* feat(research): Adds MCP tool for  command

- New MCP Tool: research tool enables AI-powered research with project context
- Context Integration: Supports task IDs, file paths, custom context, and project tree
- Fuzzy Task Discovery: Automatically finds relevant tasks using semantic search
- Token Management: Detailed token counting and breakdown by context type
- Multiple Detail Levels: Support for low, medium, and high detail research responses
- Telemetry Integration: Full cost tracking and usage analytics
- Direct Function: researchDirect with comprehensive parameter validation
- Silent Mode: Prevents console output interference with MCP JSON responses
- Error Handling: Robust error handling with proper MCP response formatting

This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.

Updated documentation across taskmaster.mdc, README.md, command-reference.md, examples.md, tutorial.md, and docs/README.md to highlight research capabilities and usage patterns.

* chore: task management

* chore: task management and removes mistakenly staged changes

* fix(move): Fix move command bug that left duplicate tasks

- Fixed logic in moveTaskToNewId function that was incorrectly treating task-to-task moves as subtask creation instead of task replacement
- Updated moveTaskToNewId to properly handle replacing existing destination tasks instead of just placeholders
- The move command now correctly replaces destination tasks and cleans up properly without leaving duplicates

- Task Management: Moved task 93 (Google Vertex AI Provider) to position 88, Moved task 94 (Azure OpenAI Provider) to position 89, Updated task dependencies and regenerated task files, Cleaned up orphaned task files automatically
- All important validations remain in place: Prevents moving tasks to themselves, Prevents moving parent tasks to their own subtasks, Prevents circular dependencies
- Resolves the issue where moving tasks would leave both source and destination tasks in tasks.json and file system

* chore: formatting

* feat: Add .taskmaster directory (#619)

* chore: apply requested changes from next branch (#629)

* chore: rc version bump

* chore: cleanup migration-guide

* fix: bedrock set model and other fixes (#641)

* Fix: MCP log errors (#648)

* fix: projectRoot duplicate .taskmaster directory (#655)

* Version Packages

* chore: add package-lock.json

* Version Packages

* Version Packages

* fix: markdown format (#622)

* Version Packages

* Version Packages

* Fixed the Typo in cursor rules Issue:#675 (#677)

Fixed the typo in the Api keys

* Add one-click MCP server installation for Cursor (#671)

* Update README.md - Remove trailing commas (#673)

JSON doesn't allow for trailing commas, so these need to be removed in order for this to work

* chore: rc version bump

* fix: findTasksPath function

* fix: update MCP tool

* feat(ui): replace emoji complexity indicators with clean filled circle characters

Replace 🟢, 🟡, 🔴 emojis with ● character in getComplexityWithColor function

Update corresponding unit tests to expect ● instead of emojis

Improves UI continuity

* fix(ai-providers): change generateObject mode from 'tool' to 'auto' for better provider compatibility

Fixes Perplexity research role failing with 'tool-mode object generation' error

The hardcoded 'tool' mode was incompatible with providers like Perplexity that support structured JSON output but not function calling/tool use

Using 'auto' mode allows the AI SDK to choose the best approach for each provider

* Adds qwen3-235n-a22b:free to supported models. Closes #687)

* chore: adds a warning when custom openrouter model is a free model which suffers from lower rate limits, restricted context, and, worst of all, no access to tool_use.

* refactor: enhance add-task fuzzy search and fix duplicate banner display

- **Remove hardcoded category system** in add-task that always matched 'Task management'
- **Eliminate arbitrary limits** in fuzzy search results (5→25 high relevance, 3→10 medium relevance, 8→20 detailed tasks)
- **Improve semantic weighting** in Fuse.js search (details=3, description=2, title=1.5) for better relevance
- **Fix duplicate banner issue** by removing console.clear() and redundant displayBanner() calls from UI functions
- **Enhance context generation** to rely on semantic similarity rather than rigid pattern matching
- **Preserve terminal history** to address GitHub issue #553 about eating terminal lines
- **Remove displayBanner() calls** from: displayHelp, displayNextTask, displayTaskById, displayComplexityReport, set-task-status, clear-subtasks, dependency-manager functions

The add-task system now provides truly relevant task context based on semantic similarity rather than arbitrary categories and limits, while maintaining a cleaner terminal experience.

Changes span: add-task.js, ui.js, set-task-status.js, clear-subtasks.js, list-tasks.js, dependency-manager.js

Closes #553

* chore: changeset

* chore: passes tests and linting

* chore: more linting

* ninja(sync): add sync-readme command for GitHub README export with UTM tracking and professional markdown formatting. Experimental

* chore: changeset adjustment

* docs: Auto-update and format models.md

* chore: updates readme with npm download badges and mentions AI Jason who is joining the taskmaster core team.

* chore: fixes urls in readme npm packages

* chore: fixes urls in readme npm packages again

* fix: readme typo

* readme: fix twitter urls.

* readme: removes the taskmaster list output which is too overwhelming given its size with subtasks. may re-add later. fixes likely issues in the json for manual config in cursor and windsurf in the readme.

* chore: small readme nitpicks

* chore: adjusts changeset from minor to patch to avoid version bump to 0.17

* readme: moves up the documentation links higher up in the readme. same with the cursor one-click install.

* Fix Cursor deeplink installation with copy-paste instructions (#723)

* solve merge conflics with next. not gonna deal with these much longer.

* chore: update task files during rebase

* chore: task management

* feat: implement research command with enhanced context gathering - Add comprehensive research command with AI-powered queries - Implement ContextGatherer utility for reusable context extraction - Support multiple context types: tasks, files, custom text, project tree - Add fuzzy search integration for automatic task discovery - Implement detailed token breakdown display with syntax highlighting - Add enhanced UI with boxed output and code block formatting - Support different detail levels (low, medium, high) for responses - Include project-specific context for more relevant AI responses - Add token counting with gpt-tokens library integration - Create reusable patterns for future context-aware commands - Task 94.4 completed

* fix(move): adjusts logic to prevent an issue when moving from parent to subtask if the target parent has no subtasks.

* fix(move-task): Fix critical bugs in task move functionality

- Fixed parent-to-parent task moves where original task would remain as duplicate
- Fixed moving tasks to become subtasks of empty parents (validation errors)
- Fixed moving subtasks between different parent tasks
- Improved comma-separated batch moves with proper error handling
- Updated MCP tool to use core logic instead of custom implementation
- Resolves task duplication issues and enables proper task hierarchy reorganization

* chore: removes task004 chat that had like 11k lines lol.

* feat(show): add comma-separated ID support for multi-task viewing

- Enhanced get-task/show command to support comma-separated task IDs for efficient batch operations.
- New features include multiple task retrieval, smart display logic, interactive action menu with batch operations, MCP array response for AI agent efficiency, and support for mixed parent tasks and subtasks.
- Implementation includes updated CLI show command, enhanced MCP get_task tool, modified showTaskDirect function, and maintained full backward compatibility.
- Documentation updated across all relevant files.

Benefits include faster context gathering for AI agents, improved workflow with interactive batch operations, better UX with responsive layout, and enhanced API efficiency.

* feat(research): Adds MCP tool for  command

- New MCP Tool: research tool enables AI-powered research with project context
- Context Integration: Supports task IDs, file paths, custom context, and project tree
- Fuzzy Task Discovery: Automatically finds relevant tasks using semantic search
- Token Management: Detailed token counting and breakdown by context type
- Multiple Detail Levels: Support for low, medium, and high detail research responses
- Telemetry Integration: Full cost tracking and usage analytics
- Direct Function: researchDirect with comprehensive parameter validation
- Silent Mode: Prevents console output interference with MCP JSON responses
- Error Handling: Robust error handling with proper MCP response formatting

This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.

Updated documentation across taskmaster.mdc, README.md, command-reference.md, examples.md, tutorial.md, and docs/README.md to highlight research capabilities and usage patterns.

* chore: task management

* fix(move): Fix move command bug that left duplicate tasks

- Fixed logic in moveTaskToNewId function that was incorrectly treating task-to-task moves as subtask creation instead of task replacement
- Updated moveTaskToNewId to properly handle replacing existing destination tasks instead of just placeholders
- The move command now correctly replaces destination tasks and cleans up properly without leaving duplicates

- Task Management: Moved task 93 (Google Vertex AI Provider) to position 88, Moved task 94 (Azure OpenAI Provider) to position 89, Updated task dependencies and regenerated task files, Cleaned up orphaned task files automatically
- All important validations remain in place: Prevents moving tasks to themselves, Prevents moving parent tasks to their own subtasks, Prevents circular dependencies
- Resolves the issue where moving tasks would leave both source and destination tasks in tasks.json and file system

* chore: moves to new task master config setup

* feat: add comma-separated status filtering to list-tasks

- supports multiple statuses like 'blocked,deferred' with comprehensive test coverage and backward compatibility

- also adjusts biome.json to stop bitching about templating.

* chore: linting ffs

* fix(generate): Fix generate command creating tasks in legacy location

- Update generate command default output directory from 'tasks' to '.taskmaster/tasks'
- Fix path.dirname() usage to properly derive output directory from tasks file location
- Update MCP tool description and documentation to reflect new structure
- Disable Biome linting rules for noUnusedTemplateLiteral and useArrowFunction
- Fixes issue where generate command was creating task files in the old 'tasks/' directory instead of the new '.taskmaster/tasks/' structure after the refactor

* chore: task management

* chore: task management some more

* fix(get-task): makes the projectRoot argument required to prevent errors when getting tasks.

* feat(tags): Implement tagged task lists migration system (Part 1/2)

This commit introduces the foundational infrastructure for tagged task lists,
enabling multi-context task management without remote storage to prevent merge conflicts.

CORE ARCHITECTURE:
• Silent migration system transforms tasks.json from old format { "tasks": [...] }
  to new tagged format { "master": { "tasks": [...] } }
• Tag resolution layer provides complete backward compatibility - existing code continues to work
• Automatic configuration and state management for seamless user experience

SILENT MIGRATION SYSTEM:
• Automatic detection and migration of legacy tasks.json format
• Complete project migration: tasks.json + config.json + state.json
• Transparent tag resolution returns old format to maintain compatibility
• Zero breaking changes - all existing functionality preserved

CONFIGURATION MANAGEMENT:
• Added global.defaultTag setting (defaults to 'master')
• New tags section with gitIntegration placeholders for future features
• Automatic config.json migration during first run
• Proper state.json creation with migration tracking

USER EXPERIENCE:
• Clean, one-time FYI notice after migration (no emojis, professional styling)
• Notice appears after 'Suggested Next Steps' and is tracked in state.json
• Silent operation - users unaware migration occurred unless explicitly shown

TECHNICAL IMPLEMENTATION:
• Enhanced readJSON() with automatic migration detection and processing
• New utility functions: getCurrentTag(), resolveTag(), getTasksForTag(), setTasksForTag()
• Complete migration orchestration via performCompleteTagMigration()
• Robust error handling and fallback mechanisms

BACKWARD COMPATIBILITY:
• 100% backward compatibility maintained
• Existing CLI commands and MCP tools continue to work unchanged
• Legacy tasks.json format automatically upgraded on first read
• All existing workflows preserved

TESTING VERIFIED:
• Complete migration from legacy state works correctly
• Config.json properly updated with tagged system settings
• State.json created with correct initial values
• Migration notice system functions as designed
• All existing functionality continues to work normally

Part 2 will implement tag management commands (add-tag, use-tag, list-tags)
and MCP tool updates for full tagged task system functionality.

Related: Task 103 - Implement Tagged Task Lists System for Multi-Context Task Management

* docs: Update documentation and rules for tagged task lists system

- Updated task-structure.md with comprehensive tagged format explanation
- Updated all .cursor/rules/*.mdc files to reflect tagged system
- Completed subtask 103.16: Update Documentation for Tagged Task Lists System

* feat(mcp): Add tagInfo to responses and integrate ContextGatherer

Enhances the MCP server to include 'tagInfo' (currentTag, availableTags) in all tool responses, providing better client-side context.

- Introduces a new 'ContextGatherer' utility to standardize the collection of file, task, and project context for AI-powered commands. This refactors several task-manager modules ('expand-task', 'research', 'update-task', etc.) to use the new utility.

- Fixes an issue in 'get-task' and 'get-tasks' MCP tools where the 'projectRoot' was not being passed correctly, preventing tag information from being included in their responses.

- Adds subtask '103.17' to track the implementation of the task template importing feature.

- Updates documentation ('.cursor/rules', 'docs/') to align with the new tagged task system and context gatherer logic.

* fix: include tagInfo in AI service responses for MCP tools

- Update all core functions that call AI services to extract and return tagInfo
- Update all direct functions to include tagInfo in MCP response data
- Fixes issue where add_task, expand_task, and other AI commands were not including current tag and available tags information
- tagInfo includes currentTag from state.json and availableTags list
- Ensures tagged task lists system information is properly propagated through the full chain: AI service -> core function -> direct function -> MCP client

* fix(move-task): Update move functionality for tagged task system compatibility

- incorporate GitHub commit fixes and resolve readJSON data handling

* feat(tagged-tasks): Complete core tag management system implementation

- Implements comprehensive tagged task lists system for multi-context task management including core tag management functions (Task 103.11), MCP integration updates, and foundational infrastructure for tagged task operations. Features tag CRUD operations, validation, metadata tracking, deep task copying, and full backward compatibility.

* fix(core): Fixed move-task.js writing _rawTaggedData directly, updated writeJSON to filter tag fields, fixed CLI move command missing projectRoot, added ensureTagMetadata utility

* fix(tasks): ensure list tasks triggers silent migration if necessary.

* feat(tags): Complete show and add-task command tag support
- show command: Added --tag flag, fixed projectRoot passing to UI functions
- add-task command: Already had proper tag support and projectRoot handling
- Both commands now work correctly with tagged task lists system
- Migration logic works properly when viewing and adding tasks
- Updated subtask 103.5 with progress on high-priority command fixes

* fix(tags): Clean up rogue created properties and fix taskCount calculation
- Enhanced writeJSON to automatically filter rogue created/description properties from tag objects
- Fixed tags command error by making taskCount calculation dynamic instead of hardcoded
- Cleaned up existing rogue created property in master tag through forced write operation
- All created properties now properly located in metadata objects only
- Tags command working perfectly with proper task count display
- Data integrity maintained with automatic cleanup during write operations

* fix(tags): Resolve critical tag deletion and migration notice bugs

Major Issues Fixed:

1. Tag Deletion Bug: Fixed critical issue where creating subtasks would delete other tags

   - Root cause: writeJSON function wasn't accepting projectRoot/tag parameters

   - Fixed writeJSON signature and logic to handle tagged data structure

   - Added proper merging of resolved tag data back into full tagged structure

2. Persistent Migration Notice: Fixed FYI notice showing after every command

   - Root cause: markMigrationForNotice was resetting migrationNoticeShown to false

   - Fixed migration logic to only trigger on actual legacy->tagged migrations

   - Added proper _rawTaggedData checks to prevent false migration detection

3. Data Corruption Prevention: Enhanced data integrity safeguards

   - Fixed writeJSON to filter out internal properties

   - Added automatic cleanup of rogue properties

   - Improved hasTaggedStructure detection logic

Commands Fixed: add-subtask, remove-subtask, and all commands now preserve tags correctly

* fix(tags): Resolve tag deletion bug in remove-task command

Refactored the core 'removeTask' function to be fully tag-aware, preventing data corruption.

- The function now correctly reads the full tagged data structure by prioritizing '_rawTaggedData' instead of operating on a resolved single-tag view.

- All subsequent operations (task removal, dependency cleanup, file writing) now correctly reference the full multi-tag data object, preserving the integrity of 'tasks.json'.

- This resolves the critical bug where removing a task would delete all other tags.

* fix(tasks): Ensure new task IDs are sequential within the target tag

Modified the ID generation logic in 'add-task.js' to calculate the next task ID based on the highest ID within the specified tag, rather than globally across all tags.

This fixes a critical bug where creating a task in a new tag would result in a high, non-sequential ID, such as ID 105 for the first task in a tag.

* fix(commands): Add missing context parameters to dependency and remove-subtask commands

- Add projectRoot and tag context to all dependency commands
- Add projectRoot and tag context to remove-subtask command
- Add --tag option to remove-subtask command
- Fixes critical bug where remove-subtask was deleting other tags due to missing context
- All dependency and subtask commands now properly handle tagged task lists

* feat(tags): Add --tag flag support to core commands for multi-context task management
- parse-prd now supports creating tasks in specific contexts
- Fixed tag preservation logic to prevent data loss
- analyze-complexity generates tag-specific reports
- Non-existent tags created automatically
- Enables rapid prototyping and parallel development workflows

* feat(tags): Complete tagged task lists system with enhanced use-tag command

- Multi-context task management with full CLI support
- Enhanced use-tag command shows next available task after switching
- Universal --tag flag support across all commands
- Seamless migration with zero disruption
- Complete tag management suite (add, delete, rename, copy, list)
- Smart confirmation logic and data integrity protection
- State management and configuration integration
- Real-world use cases for teams, features, and releases

* feat(tags): Complete tag support for remaining CLI commands

- Add --tag flag to update, move, and set-status commands
- Ensure all task operation commands now support tag context
- Fix missing tag context passing to core functions
- Complete comprehensive tag-aware command coverage

* feat(ui): add tag indicator to all CLI commands
- shows 🏷️ tag: tagname for complete context visibility across 15+ commands

* fix(ui): resolve dependency 'Not found' issue when filtering

- now correctly displays dependencies that exist but are filtered out of view

* feat(research): Add comprehensive AI-powered research command with interactive follow-ups, save functionality, intelligent context gathering, fuzzy task discovery, multi-source context support, enhanced display with syntax highlighting, clean inquirer menus, comprehensive help, and MCP integration with saveTo parameter

* feat(tags): Implement full MCP support for Tagged Task Lists and update-task append mode

* chore: task management

* feat(research): Enhance research command with follow-up menu, save functionality, and fix ContextGatherer token counting

* feat(git-workflow): Add automatic git branch-tag integration

- Implement automatic tag creation when switching to new git branches

- Add branch-tag mapping system for seamless context switching

- Enable auto-switch of task contexts based on current git branch

- Provide isolated task contexts per branch to prevent merge conflicts

- Add configuration support for enabling/disabling git workflow features

- Fix ES module compatibility issues in git-utils module

- Maintain zero migration impact with automatic 'master' tag creation

- Support parallel development with branch-specific task contexts

The git workflow system automatically detects branch changes and creates corresponding empty task tags, enabling developers to maintain separate task contexts for different features/branches while preventing task-related merge conflicts during collaborative development.

Resolves git workflow integration requirements for multi-context development.

* feat(git-workflow): Simplify git integration with --from-branch option

- Remove automatic git workflow and branch-tag switching - we are not ready for it yet

- Add --from-branch option to add-tag command for manual tag creation from git branch

- Remove git workflow configuration from config.json and assets

- Disable automatic tag switching functions in git-utils.js

- Add createTagFromBranch function for branch-based tag creation

- Support both CLI and MCP interfaces for --from-branch functionality

- Fix ES module imports in git-utils.js and utils.js

- Maintain user control over tag contexts without forced automation

The simplified approach allows users to create tags from their current git branch when desired, without the complexity and rigidity of automatic branch-tag synchronization. Users maintain full control over their tag contexts while having convenient tools for git-based workflows when needed.

* docs: Update rule files to reflect simplified git integration approach

- Remove automatic git workflow features, update to manual --from-branch option, change Part 2 references to completed status

* fix(commands): Fix add-tag --from-branch requiring tagName argument
- Made tagName optional when using --from-branch - Added validation for either tagName or --from-branch
- Fixes 'missing required argument' error with --from-branch option

* fix(mcp): Prevent tag deletion on subtask update

Adds a safety net to the writeJSON utility to prevent data loss when updating subtasks via the MCP server.

The MCP process was inadvertently causing the _rawTaggedData property, which holds the complete multi-tag structure, to be lost. When writeJSON received the data for only a single tag, it would overwrite the entire tasks.json file, deleting all other tags.

This fix makes writeJSON more robust. If it receives data that looks like a single, resolved tag without the complete structure, it re-reads the full tasks.json file from disk. It then carefully merges the updated data back into the correct tag within the full structure, preserving all other tags.

* fix: resolve all remaining test failures and improve test reliability

- Fix clear-subtasks test by implementing deep copy of mock data to prevent mutation issues between tests
- Fix add-task test by uncommenting and properly configuring generateTaskFiles call with correct parameters
- Fix analyze-task-complexity tests by properly mocking fs.writeFileSync with shared mock function
- Update test expectations to match actual function signatures and data structures
- Improve mock setup consistency across all test suites
- Ensure all tests now pass (329 total: 318 passed, 11 skipped, 0 failed)

* chore: task management

---------

Co-authored-by: Eyal Toledano <eyal@microangel.so>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Ibrahim H. <bitsnaps@yahoo.fr>
Co-authored-by: Saksham Goel <sakshamgoel1107@gmail.com>
Co-authored-by: Joe Danziger <joe@ticc.net>
Co-authored-by: Aaron Gabriel Neyer <ag@unforced.org>
2025-06-15 03:47:28 +03:00
github-actions[bot]
12bed2b307 docs: Auto-update and format models.md 2025-06-15 03:47:28 +03:00
Volodymyr Zahorniak
d76bea49b3 docs: Update o3 model price (#751) 2025-06-15 03:47:28 +03:00
Ralph Khreish
0849c0c2ce fix: expand-task (#755) 2025-06-15 03:47:28 +03:00
Joe Danziger
5ec1f61c13 Fix Cursor deeplink installation with copy-paste instructions (#723) 2025-06-15 03:47:28 +03:00
Eyal Toledano
292c2caf7f Merge pull request #722 from eyaltoledano/changeset-release/main
Version Packages
2025-06-08 17:43:43 -04:00
github-actions[bot]
526d64fb8a Version Packages 2025-06-08 20:39:20 +00:00
Ralph Khreish
1b86ce6c83 Merge pull request #721 from eyaltoledano/next 2025-06-08 22:38:49 +02:00
Ralph Khreish
cf01fbedcf Merge pull request #686 from eyaltoledano/next 2025-06-08 19:37:46 +02:00
247 changed files with 24236 additions and 21709 deletions

View File

@@ -1,5 +0,0 @@
---
"task-master-ai": patch
---
improve findTasks algorithm for resolving tasks path

View File

@@ -1,5 +0,0 @@
---
"task-master-ai": patch
---
Fix update tool on MCP giving `No valid tasks found`

View File

@@ -1,39 +0,0 @@
---
"task-master-ai": patch
---
Enhanced add-task fuzzy search intelligence and improved user experience
**Smarter Task Discovery:**
- Remove hardcoded category system that always matched "Task management"
- Eliminate arbitrary limits on fuzzy search results (5→25 high relevance, 3→10 medium relevance, 8→20 detailed tasks)
- Improve semantic weighting in Fuse.js search (details=3, description=2, title=1.5) for better relevance
- Generate context-driven task recommendations based on true semantic similarity
**Enhanced Terminal Experience:**
- Fix duplicate banner display issue that was "eating" terminal history (closes #553)
- Remove console.clear() and redundant displayBanner() calls from UI functions
- Preserve command history for better development workflow
- Streamline banner display across all commands (list, next, show, set-status, clear-subtasks, dependency commands)
**Visual Improvements:**
- Replace emoji complexity indicators with clean filled circle characters (●) for professional appearance
- Improve consistency and readability of task complexity display
**AI Provider Compatibility:**
- Change generateObject mode from 'tool' to 'auto' for better cross-provider compatibility
- Add qwen3-235n-a22b:free model support (closes #687)
- Add smart warnings for free OpenRouter models with limitations (rate limits, restricted context, no tool_use)
**Technical Improvements:**
- Enhanced context generation in add-task to rely on semantic similarity rather than rigid pattern matching
- Improved dependency analysis and common pattern detection
- Better handling of task relationships and relevance scoring
- More intelligent task suggestion algorithms
The add-task system now provides truly relevant task context based on semantic understanding rather than arbitrary categories and limits, while maintaining a cleaner and more professional terminal experience.

View File

@@ -1,7 +0,0 @@
---
"task-master-ai": patch
---
Fix double .taskmaster directory paths in file resolution utilities
- Closes #636

View File

@@ -1,5 +0,0 @@
---
"task-master-ai": patch
---
Add one-click MCP server installation for Cursor

View File

@@ -1,11 +0,0 @@
{
"mode": "exit",
"tag": "rc",
"initialVersions": {
"task-master-ai": "0.16.1"
},
"changesets": [
"pink-houses-lay",
"polite-areas-shave"
]
}

View File

@@ -1,22 +0,0 @@
---
"task-master-ai": patch
---
Add sync-readme command for a task export to GitHub README
Introduces a new `sync-readme` command that exports your task list to your project's README.md file.
**Features:**
- **Flexible filtering**: Supports `--status` filtering (e.g., pending, done) and `--with-subtasks` flag
- **Smart content management**: Automatically replaces existing exports or appends to new READMEs
- **Metadata display**: Shows export timestamp, subtask inclusion status, and filter settings
**Usage:**
- `task-master sync-readme` - Export tasks without subtasks
- `task-master sync-readme --with-subtasks` - Include subtasks in export
- `task-master sync-readme --status=pending` - Only export pending tasks
- `task-master sync-readme --status=done --with-subtasks` - Export completed tasks with subtasks
Perfect for showcasing project progress on GitHub. Experimental. Open to feedback.

View File

@@ -12,7 +12,8 @@
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE",
"GITHUB_API_KEY": "GITHUB_API_KEY_HERE"
}
}
}

View File

@@ -20,19 +20,21 @@ alwaysApply: false
- **[`task-manager.js`](mdc:scripts/modules/task-manager.js) & `task-manager/` directory: Task Data & Core Logic**
- **Purpose**: Contains core functions for task data manipulation (CRUD), AI interactions, and related logic.
- **Responsibilities**:
- Reading/writing `tasks.json`.
- Reading/writing `tasks.json` with tagged task lists support.
- Implementing functions for task CRUD, parsing PRDs, expanding tasks, updating status, etc.
- **Tagged Task Lists**: Handles task organization across multiple contexts (tags) like "master", branch names, or project phases.
- **Tag Resolution**: Provides backward compatibility by resolving tagged format to legacy format transparently.
- **Delegating AI interactions** to the `ai-services-unified.js` layer.
- Accessing non-AI configuration via `config-manager.js` getters.
- **Key Files**: Individual files within `scripts/modules/task-manager/` handle specific actions (e.g., `add-task.js`, `expand-task.js`).
- **[`dependency-manager.js`](mdc:scripts/modules/dependency-manager.js): Dependency Management**
- **Purpose**: Manages task dependencies.
- **Responsibilities**: Add/remove/validate/fix dependencies.
- **Responsibilities**: Add/remove/validate/fix dependencies across tagged task contexts.
- **[`ui.js`](mdc:scripts/modules/ui.js): User Interface Components**
- **Purpose**: Handles CLI output formatting (tables, colors, boxes, spinners).
- **Responsibilities**: Displaying tasks, reports, progress, suggestions.
- **Responsibilities**: Displaying tasks, reports, progress, suggestions, and migration notices for tagged systems.
- **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js): Unified AI Service Layer**
- **Purpose**: Centralized interface for all LLM interactions using Vercel AI SDK.
@@ -53,6 +55,7 @@ alwaysApply: false
- **Responsibilities** (See also: [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)):
- Reads and merges `.taskmasterconfig` with defaults.
- Provides getters (e.g., `getMainProvider`, `getLogLevel`, `getDefaultSubtasks`) for accessing settings.
- **Tag Configuration**: Manages `global.defaultTag` and `tags` section for tag system settings.
- **Note**: Does **not** store or directly handle API keys (keys are in `.env` or MCP `session.env`).
- **[`utils.js`](mdc:scripts/modules/utils.js): Core Utility Functions**
@@ -62,6 +65,8 @@ alwaysApply: false
- Task utils (`findTaskById`), Dependency utils (`findCycles`).
- API Key Resolution (`resolveEnvVariable`).
- Silent Mode Control (`enableSilentMode`, `disableSilentMode`).
- **Tagged Task Lists**: Silent migration system, tag resolution, current tag management.
- **Migration System**: `performCompleteTagMigration`, `migrateConfigJson`, `createStateJson`.
- **[`mcp-server/`](mdc:mcp-server/): MCP Server Integration**
- **Purpose**: Provides MCP interface using FastMCP.
@@ -71,16 +76,42 @@ alwaysApply: false
- Tool `execute` methods call **direct function wrappers** (`mcp-server/src/core/direct-functions/*.js`), passing the normalized `projectRoot` and other args.
- Direct functions use path utilities (`mcp-server/src/core/utils/`) to resolve paths based on `projectRoot` from session.
- Direct functions implement silent mode, logger wrappers, and call core logic functions from `scripts/modules/`.
- **Tagged Task Lists**: MCP tools fully support the tagged format with complete tag management capabilities.
- Manages MCP caching and response formatting.
- **[`init.js`](mdc:scripts/init.js): Project Initialization Logic**
- **Purpose**: Sets up new Task Master project structure.
- **Responsibilities**: Creates directories, copies templates, manages `package.json`, sets up `.cursor/mcp.json`.
- **Responsibilities**: Creates directories, copies templates, manages `package.json`, sets up `.cursor/mcp.json`, initializes state.json for tagged system.
## Tagged Task Lists System Architecture
**Data Structure**: Task Master now uses a tagged task lists system where the `tasks.json` file contains multiple named task lists as top-level keys:
```json
{
"master": {
"tasks": [/* standard task objects */]
},
"feature-branch": {
"tasks": [/* separate task context */]
}
}
```
**Key Components:**
- **Silent Migration**: Automatically transforms legacy `{"tasks": [...]}` format to tagged format `{"master": {"tasks": [...]}}` on first read
- **Tag Resolution Layer**: Provides 100% backward compatibility by intercepting tagged format and returning legacy format to existing code
- **Configuration Integration**: `global.defaultTag` and `tags` section in config.json manage tag system settings
- **State Management**: `.taskmaster/state.json` tracks current tag, migration status, and tag-branch mappings
- **Migration Notice**: User-friendly notification system for seamless migration experience
**Backward Compatibility**: All existing CLI commands and MCP tools continue to work unchanged. The tag resolution layer ensures that existing code receives the expected legacy format while the underlying storage uses the new tagged structure.
- **Data Flow and Module Dependencies (Updated)**:
- **CLI**: `bin/task-master.js` -> `scripts/dev.js` (loads `.env`) -> `scripts/modules/commands.js` -> Core Logic (`scripts/modules/*`) -> Unified AI Service (`ai-services-unified.js`) -> Provider Adapters -> LLM API.
- **MCP**: External Tool -> `mcp-server/server.js` -> Tool (`mcp-server/src/tools/*`) -> Direct Function (`mcp-server/src/core/direct-functions/*`) -> Core Logic (`scripts/modules/*`) -> Unified AI Service (`ai-services-unified.js`) -> Provider Adapters -> LLM API.
- **CLI**: `bin/task-master.js` -> `scripts/dev.js` (loads `.env`) -> `scripts/modules/commands.js` -> Core Logic (`scripts/modules/*`) -> **Tag Resolution Layer** -> Unified AI Service (`ai-services-unified.js`) -> Provider Adapters -> LLM API.
- **MCP**: External Tool -> `mcp-server/server.js` -> Tool (`mcp-server/src/tools/*`) -> Direct Function (`mcp-server/src/core/direct-functions/*`) -> Core Logic (`scripts/modules/*`) -> **Tag Resolution Layer** -> Unified AI Service (`ai-services-unified.js`) -> Provider Adapters -> LLM API.
- **Configuration**: Core logic needing non-AI settings calls `config-manager.js` getters (passing `session.env` via `explicitRoot` if from MCP). Unified AI Service internally calls `config-manager.js` getters (using `role`) for AI params and `utils.js` (`resolveEnvVariable` with `session.env`) for API keys.
## Silent Mode Implementation Pattern in MCP Direct Functions
@@ -197,6 +228,7 @@ By following these patterns consistently, direct functions will properly manage
- **Integration Tests**: Located in `tests/integration/`, test interactions between modules
- **End-to-End Tests**: Located in `tests/e2e/`, test complete workflows from a user perspective
- **Test Fixtures**: Located in `tests/fixtures/`, provide reusable test data
- **Tagged System Tests**: Test migration, tag resolution, and multi-context functionality
- **Module Design for Testability**:
- **Explicit Dependencies**: Functions accept their dependencies as parameters rather than using globals
@@ -205,12 +237,14 @@ By following these patterns consistently, direct functions will properly manage
- **Clear Module Interfaces**: Each module has well-defined exports that can be mocked in tests
- **Callback Isolation**: Callbacks are defined as separate functions for easier testing
- **Stateless Design**: Modules avoid maintaining internal state where possible
- **Tag Resolution Testing**: Test both tagged and legacy format handling
- **Mock Integration Patterns**:
- **External Libraries**: Libraries like `fs`, `commander`, and `@anthropic-ai/sdk` are mocked at module level
- **Internal Modules**: Application modules are mocked with appropriate spy functions
- **Testing Function Callbacks**: Callbacks are extracted from mock call arguments and tested in isolation
- **UI Elements**: Output functions from `ui.js` are mocked to verify display calls
- **Tagged Data Mocking**: Test both legacy and tagged task data structures
- **Testing Flow**:
- Module dependencies are mocked (following Jest's hoisting behavior)
@@ -218,6 +252,7 @@ By following these patterns consistently, direct functions will properly manage
- Spy functions are set up on module methods
- Tests call the functions under test and verify behavior
- Mocks are reset between test cases to maintain isolation
- Tagged system behavior is tested for both migration and normal operation
- **Benefits of this Architecture**:
@@ -226,8 +261,11 @@ By following these patterns consistently, direct functions will properly manage
- **Mocking Support**: The clear dependency boundaries make mocking straightforward
- **Test Isolation**: Each component can be tested without affecting others
- **Callback Testing**: Function callbacks can be extracted and tested independently
- **Multi-Context Testing**: Tagged system enables testing different task contexts independently
- **Reusability**: Utility functions and UI components can be reused across different parts of the application.
- **Scalability**: New features can be added as new modules or by extending existing ones without significantly impacting other parts of the application.
- **Multi-Context Support**: Tagged task lists enable working across different contexts (branches, environments, phases) without conflicts.
- **Backward Compatibility**: Seamless migration and tag resolution ensure existing workflows continue unchanged.
- **Clarity**: The modular structure provides a clear separation of concerns, making the codebase easier to navigate and understand for developers.
This architectural overview should help AI models understand the structure and organization of the Task Master CLI codebase, enabling them to more effectively assist with code generation, modification, and understanding.
@@ -249,6 +287,7 @@ Follow these steps to add MCP support for an existing Task Master command (see [
- Call core logic.
- Return `{ success: true/false, data/error, fromCache: boolean }`.
- Export the wrapper function.
- **Note**: Tag-aware MCP tools are fully implemented with complete tag management support.
3. **Update `task-master-core.js` with Import/Export**: Add imports/exports for the new `*Direct` function.
@@ -275,12 +314,8 @@ The `initialize_project` command provides a way to set up a new Task Master proj
- **MCP Tool**: `initialize_project`
- **Functionality**:
- Creates necessary directories and files for a new project
- Sets up `tasks.json` and initial task files
- Configures project metadata (name, description, version)
- Handles shell alias creation if requested
- Works in both interactive and non-interactive modes
- Creates necessary directories and files for a new project
- Sets up `tasks.json` and initial task files
- Sets up `tasks.json` with tagged structure and initial task files
- Configures project metadata (name, description, version)
- Initializes state.json for tag system
- Handles shell alias creation if requested
- Works in both interactive and non-interactive modes

View File

@@ -329,6 +329,60 @@ When implementing commands that delete or remove data (like `remove-task` or `re
};
```
## Context-Aware Command Pattern
For AI-powered commands that benefit from project context, follow the research command pattern:
- **Context Integration**:
- ✅ DO: Use `ContextGatherer` utility for multi-source context extraction
- ✅ DO: Support task IDs, file paths, custom context, and project tree
- ✅ DO: Implement fuzzy search for automatic task discovery
- ✅ DO: Display detailed token breakdown for transparency
```javascript
// ✅ DO: Follow this pattern for context-aware commands
programInstance
.command('research')
.description('Perform AI-powered research queries with project context')
.argument('<prompt>', 'Research prompt to investigate')
.option('-i, --id <ids>', 'Comma-separated task/subtask IDs to include as context')
.option('-f, --files <paths>', 'Comma-separated file paths to include as context')
.option('-c, --context <text>', 'Additional custom context')
.option('--tree', 'Include project file tree structure')
.option('-d, --detail <level>', 'Output detail level: low, medium, high', 'medium')
.action(async (prompt, options) => {
// 1. Parameter validation and parsing
const taskIds = options.id ? parseTaskIds(options.id) : [];
const filePaths = options.files ? parseFilePaths(options.files) : [];
// 2. Initialize context gatherer
const projectRoot = findProjectRoot() || '.';
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// 3. Auto-discover relevant tasks if none specified
if (taskIds.length === 0) {
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const discoveredIds = fuzzySearch.getTaskIds(
fuzzySearch.findRelevantTasks(prompt)
);
taskIds.push(...discoveredIds);
}
// 4. Gather context with token breakdown
const contextResult = await gatherer.gather({
tasks: taskIds,
files: filePaths,
customContext: options.context,
includeProjectTree: options.projectTree,
format: 'research',
includeTokenCounts: true
});
// 5. Display token breakdown and execute AI call
// Implementation continues...
});
```
## Error Handling
- **Exception Management**:

View File

@@ -0,0 +1,268 @@
---
description: Standardized patterns for gathering and processing context from multiple sources in Task Master commands, particularly for AI-powered features.
globs:
alwaysApply: false
---
# Context Gathering Patterns and Utilities
This document outlines the standardized patterns for gathering and processing context from multiple sources in Task Master commands, particularly for AI-powered features.
## Core Context Gathering Utility
The `ContextGatherer` class (`scripts/modules/utils/contextGatherer.js`) provides a centralized, reusable utility for extracting context from multiple sources:
### **Key Features**
- **Multi-source Context**: Tasks, files, custom text, project file tree
- **Token Counting**: Detailed breakdown using `gpt-tokens` library
- **Format Support**: Different output formats (research, chat, system-prompt)
- **Error Handling**: Graceful handling of missing files, invalid task IDs
- **Performance**: File size limits, depth limits for tree generation
### **Usage Pattern**
```javascript
import { ContextGatherer } from '../utils/contextGatherer.js';
// Initialize with project paths
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// Gather context with detailed token breakdown
const result = await gatherer.gather({
tasks: ['15', '16.2'], // Task and subtask IDs
files: ['src/api.js', 'README.md'], // File paths
customContext: 'Additional context text',
includeProjectTree: true, // Include file tree
format: 'research', // Output format
includeTokenCounts: true // Get detailed token breakdown
});
// Access results
const contextString = result.context;
const tokenBreakdown = result.tokenBreakdown;
```
### **Token Breakdown Structure**
```javascript
{
customContext: { tokens: 150, characters: 800 },
tasks: [
{ id: '15', type: 'task', title: 'Task Title', tokens: 245, characters: 1200 },
{ id: '16.2', type: 'subtask', title: 'Subtask Title', tokens: 180, characters: 900 }
],
files: [
{ path: 'src/api.js', tokens: 890, characters: 4500, size: '4.5 KB' }
],
projectTree: { tokens: 320, characters: 1600 },
total: { tokens: 1785, characters: 8000 }
}
```
## Fuzzy Search Integration
The `FuzzyTaskSearch` class (`scripts/modules/utils/fuzzyTaskSearch.js`) provides intelligent task discovery:
### **Key Features**
- **Semantic Matching**: Uses Fuse.js for similarity scoring
- **Purpose Categories**: Pattern-based task categorization
- **Relevance Scoring**: High/medium/low relevance thresholds
- **Context-Aware**: Different search configurations for different use cases
### **Usage Pattern**
```javascript
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
// Initialize with tasks data and context
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
// Find relevant tasks
const searchResults = fuzzySearch.findRelevantTasks(query, {
maxResults: 8,
includeRecent: true,
includeCategoryMatches: true
});
// Get task IDs for context gathering
const taskIds = fuzzySearch.getTaskIds(searchResults);
```
## Implementation Patterns for Commands
### **1. Context-Aware Command Structure**
```javascript
// In command action handler
async function commandAction(prompt, options) {
// 1. Parameter validation and parsing
const taskIds = options.id ? parseTaskIds(options.id) : [];
const filePaths = options.files ? parseFilePaths(options.files) : [];
// 2. Initialize context gatherer
const projectRoot = findProjectRoot() || '.';
const tasksPath = path.join(projectRoot, 'tasks', 'tasks.json');
const gatherer = new ContextGatherer(projectRoot, tasksPath);
// 3. Auto-discover relevant tasks if none specified
if (taskIds.length === 0) {
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const discoveredIds = fuzzySearch.getTaskIds(
fuzzySearch.findRelevantTasks(prompt)
);
taskIds.push(...discoveredIds);
}
// 4. Gather context with token breakdown
const contextResult = await gatherer.gather({
tasks: taskIds,
files: filePaths,
customContext: options.context,
includeProjectTree: options.projectTree,
format: 'research',
includeTokenCounts: true
});
// 5. Display token breakdown (for CLI)
if (outputFormat === 'text') {
displayDetailedTokenBreakdown(contextResult.tokenBreakdown);
}
// 6. Use context in AI call
const aiResult = await generateTextService(role, session, systemPrompt, userPrompt);
// 7. Display results with enhanced formatting
displayResults(aiResult, contextResult.tokenBreakdown);
}
```
### **2. Token Display Pattern**
```javascript
function displayDetailedTokenBreakdown(tokenBreakdown, systemTokens, userTokens) {
const sections = [];
// Build context breakdown
if (tokenBreakdown.tasks?.length > 0) {
const taskDetails = tokenBreakdown.tasks.map(task =>
`${task.type === 'subtask' ? ' ' : ''}${task.id}: ${task.tokens.toLocaleString()}`
).join('\n');
sections.push(`Tasks (${tokenBreakdown.tasks.reduce((sum, t) => sum + t.tokens, 0).toLocaleString()}):\n${taskDetails}`);
}
if (tokenBreakdown.files?.length > 0) {
const fileDetails = tokenBreakdown.files.map(file =>
` ${file.path}: ${file.tokens.toLocaleString()} (${file.size})`
).join('\n');
sections.push(`Files (${tokenBreakdown.files.reduce((sum, f) => sum + f.tokens, 0).toLocaleString()}):\n${fileDetails}`);
}
// Add prompts breakdown
sections.push(`Prompts: system ${systemTokens.toLocaleString()}, user ${userTokens.toLocaleString()}`);
// Display in clean box
const content = sections.join('\n\n');
console.log(boxen(content, {
title: chalk.cyan('Token Usage'),
padding: { top: 1, bottom: 1, left: 2, right: 2 },
borderStyle: 'round',
borderColor: 'cyan'
}));
}
```
### **3. Enhanced Result Display Pattern**
```javascript
function displayResults(result, query, detailLevel, tokenBreakdown) {
// Header with query info
const header = boxen(
chalk.green.bold('Research Results') + '\n\n' +
chalk.gray('Query: ') + chalk.white(query) + '\n' +
chalk.gray('Detail Level: ') + chalk.cyan(detailLevel),
{
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 1, bottom: 0 },
borderStyle: 'round',
borderColor: 'green'
}
);
console.log(header);
// Process and highlight code blocks
const processedResult = processCodeBlocks(result);
// Main content in clean box
const contentBox = boxen(processedResult, {
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderStyle: 'single',
borderColor: 'gray'
});
console.log(contentBox);
console.log(chalk.green('✓ Research complete'));
}
```
## Code Block Enhancement
### **Syntax Highlighting Pattern**
```javascript
import { highlight } from 'cli-highlight';
function processCodeBlocks(text) {
return text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
try {
const highlighted = highlight(code.trim(), {
language: language || 'javascript',
theme: 'default'
});
return `\n${highlighted}\n`;
} catch (error) {
return `\n${code.trim()}\n`;
}
});
}
```
## Integration Guidelines
### **When to Use Context Gathering**
- ✅ **DO**: Use for AI-powered commands that benefit from project context
- ✅ **DO**: Use when users might want to reference specific tasks or files
- ✅ **DO**: Use for research, analysis, or generation commands
- ❌ **DON'T**: Use for simple CRUD operations that don't need AI context
### **Performance Considerations**
- ✅ **DO**: Set reasonable file size limits (50KB default)
- ✅ **DO**: Limit project tree depth (3-5 levels)
- ✅ **DO**: Provide token counts to help users understand context size
- ✅ **DO**: Allow users to control what context is included
### **Error Handling**
- ✅ **DO**: Gracefully handle missing files with warnings
- ✅ **DO**: Validate task IDs and provide helpful error messages
- ✅ **DO**: Continue processing even if some context sources fail
- ✅ **DO**: Provide fallback behavior when context gathering fails
### **Future Command Integration**
Commands that should consider adopting this pattern:
- `analyze-complexity` - Could benefit from file context
- `expand-task` - Could use related task context
- `update-task` - Could reference similar tasks for consistency
- `add-task` - Could use project context for better task generation
## Export Patterns
### **Context Gatherer Module**
```javascript
export {
ContextGatherer,
createContextGatherer // Factory function
};
```
### **Fuzzy Search Module**
```javascript
export {
FuzzyTaskSearch,
PURPOSE_CATEGORIES,
RELEVANCE_THRESHOLDS
};
```
This context gathering system provides a foundation for building more intelligent, context-aware commands that can leverage project knowledge to provide better AI-powered assistance.

View File

@@ -1,23 +1,204 @@
---
description: Guide for using Task Master to manage task-driven development workflows
description: Guide for using Taskmaster to manage task-driven development workflows
globs: **/*
alwaysApply: true
---
# Task Master Development Workflow
This guide outlines the typical process for using Task Master to manage software development projects.
# Taskmaster Development Workflow
This guide outlines the standard process for using Taskmaster to manage software development projects. It is written as a set of instructions for you, the AI agent.
- **Your Default Stance**: For most projects, the user can work directly within the `master` task context. Your initial actions should operate on this default context unless a clear pattern for multi-context work emerges.
- **Your Goal**: Your role is to elevate the user's workflow by intelligently introducing advanced features like **Tagged Task Lists** when you detect the appropriate context. Do not force tags on the user; suggest them as a helpful solution to a specific need.
## The Basic Loop
The fundamental development cycle you will facilitate is:
1. **`list`**: Show the user what needs to be done.
2. **`next`**: Help the user decide what to work on.
3. **`show <id>`**: Provide details for a specific task.
4. **`expand <id>`**: Break down a complex task into smaller, manageable subtasks.
5. **Implement**: The user writes the code and tests.
6. **`update-subtask`**: Log progress and findings on behalf of the user.
7. **`set-status`**: Mark tasks and subtasks as `done` as work is completed.
8. **Repeat**.
All your standard command executions should operate on the user's current task context, which defaults to `master`.
---
## Standard Development Workflow Process
### Simple Workflow (Default Starting Point)
For new projects or when users are getting started, operate within the `master` tag context:
- Start new projects by running `initialize_project` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input='<prd-file.txt>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to generate initial tasks.json with tagged structure
- Begin coding sessions with `get_tasks` / `task-master list` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to see current tasks, status, and IDs
- Determine the next task to work on using `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Analyze task complexity with `analyze_project_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before breaking down tasks
- Review complexity report using `complexity_report` / `task-master complexity-report` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Select tasks based on dependencies (all marked 'done'), priority level, and ID order
- View specific task details using `get_task` / `task-master show <id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to understand implementation requirements
- Break down complex tasks using `expand_task` / `task-master expand --id=<id> --force --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) with appropriate flags like `--force` (to replace existing subtasks) and `--research`
- Implement code following task details, dependencies, and project standards
- Mark completed tasks with `set_task_status` / `task-master set-status --id=<id> --status=done` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Update dependent tasks when implementation differs from original plan using `update` / `task-master update --from=<id> --prompt="..."` or `update_task` / `task-master update-task --id=<id> --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
---
## Leveling Up: Agent-Led Multi-Context Workflows
While the basic workflow is powerful, your primary opportunity to add value is by identifying when to introduce **Tagged Task Lists**. These patterns are your tools for creating a more organized and efficient development environment for the user, especially if you detect agentic or parallel development happening across the same session.
**Critical Principle**: Most users should never see a difference in their experience. Only introduce advanced workflows when you detect clear indicators that the project has evolved beyond simple task management.
### When to Introduce Tags: Your Decision Patterns
Here are the patterns to look for. When you detect one, you should propose the corresponding workflow to the user.
#### Pattern 1: Simple Git Feature Branching
This is the most common and direct use case for tags.
- **Trigger**: The user creates a new git branch (e.g., `git checkout -b feature/user-auth`).
- **Your Action**: Propose creating a new tag that mirrors the branch name to isolate the feature's tasks from `master`.
- **Your Suggested Prompt**: *"I see you've created a new branch named 'feature/user-auth'. To keep all related tasks neatly organized and separate from your main list, I can create a corresponding task tag for you. This helps prevent merge conflicts in your `tasks.json` file later. Shall I create the 'feature-user-auth' tag?"*
- **Tool to Use**: `task-master add-tag --from-branch`
#### Pattern 2: Team Collaboration
- **Trigger**: The user mentions working with teammates (e.g., "My teammate Alice is handling the database schema," or "I need to review Bob's work on the API.").
- **Your Action**: Suggest creating a separate tag for the user's work to prevent conflicts with shared master context.
- **Your Suggested Prompt**: *"Since you're working with Alice, I can create a separate task context for your work to avoid conflicts. This way, Alice can continue working with the master list while you have your own isolated context. When you're ready to merge your work, we can coordinate the tasks back to master. Shall I create a tag for your current work?"*
- **Tool to Use**: `task-master add-tag my-work --copy-from-current --description="My tasks while collaborating with Alice"`
#### Pattern 3: Experiments or Risky Refactors
- **Trigger**: The user wants to try something that might not be kept (e.g., "I want to experiment with switching our state management library," or "Let's refactor the old API module, but I want to keep the current tasks as a reference.").
- **Your Action**: Propose creating a sandboxed tag for the experimental work.
- **Your Suggested Prompt**: *"This sounds like a great experiment. To keep these new tasks separate from our main plan, I can create a temporary 'experiment-zustand' tag for this work. If we decide not to proceed, we can simply delete the tag without affecting the main task list. Sound good?"*
- **Tool to Use**: `task-master add-tag experiment-zustand --description="Exploring Zustand migration"`
#### Pattern 4: Large Feature Initiatives (PRD-Driven)
This is a more structured approach for significant new features or epics.
- **Trigger**: The user describes a large, multi-step feature that would benefit from a formal plan.
- **Your Action**: Propose a comprehensive, PRD-driven workflow.
- **Your Suggested Prompt**: *"This sounds like a significant new feature. To manage this effectively, I suggest we create a dedicated task context for it. Here's the plan: I'll create a new tag called 'feature-xyz', then we can draft a Product Requirements Document (PRD) together to scope the work. Once the PRD is ready, I'll automatically generate all the necessary tasks within that new tag. How does that sound?"*
- **Your Implementation Flow**:
1. **Create an empty tag**: `task-master add-tag feature-xyz --description "Tasks for the new XYZ feature"`. You can also start by creating a git branch if applicable, and then create the tag from that branch.
2. **Collaborate & Create PRD**: Work with the user to create a detailed PRD file (e.g., `.taskmaster/docs/feature-xyz-prd.txt`).
3. **Parse PRD into the new tag**: `task-master parse-prd .taskmaster/docs/feature-xyz-prd.txt --tag feature-xyz`
4. **Prepare the new task list**: Follow up by suggesting `analyze-complexity` and `expand-all` for the newly created tasks within the `feature-xyz` tag.
#### Pattern 5: Version-Based Development
Tailor your approach based on the project maturity indicated by tag names.
- **Prototype/MVP Tags** (`prototype`, `mvp`, `poc`, `v0.x`):
- **Your Approach**: Focus on speed and functionality over perfection
- **Task Generation**: Create tasks that emphasize "get it working" over "get it perfect"
- **Complexity Level**: Lower complexity, fewer subtasks, more direct implementation paths
- **Research Prompts**: Include context like "This is a prototype - prioritize speed and basic functionality over optimization"
- **Example Prompt Addition**: *"Since this is for the MVP, I'll focus on tasks that get core functionality working quickly rather than over-engineering."*
- **Production/Mature Tags** (`v1.0+`, `production`, `stable`):
- **Your Approach**: Emphasize robustness, testing, and maintainability
- **Task Generation**: Include comprehensive error handling, testing, documentation, and optimization
- **Complexity Level**: Higher complexity, more detailed subtasks, thorough implementation paths
- **Research Prompts**: Include context like "This is for production - prioritize reliability, performance, and maintainability"
- **Example Prompt Addition**: *"Since this is for production, I'll ensure tasks include proper error handling, testing, and documentation."*
### Advanced Workflow (Tag-Based & PRD-Driven)
**When to Transition**: Recognize when the project has evolved (or has initiated a project which existing code) beyond simple task management. Look for these indicators:
- User mentions teammates or collaboration needs
- Project has grown to 15+ tasks with mixed priorities
- User creates feature branches or mentions major initiatives
- User initializes Taskmaster on an existing, complex codebase
- User describes large features that would benefit from dedicated planning
**Your Role in Transition**: Guide the user to a more sophisticated workflow that leverages tags for organization and PRDs for comprehensive planning.
#### Master List Strategy (High-Value Focus)
Once you transition to tag-based workflows, the `master` tag should ideally contain only:
- **High-level deliverables** that provide significant business value
- **Major milestones** and epic-level features
- **Critical infrastructure** work that affects the entire project
- **Release-blocking** items
**What NOT to put in master**:
- Detailed implementation subtasks (these go in feature-specific tags' parent tasks)
- Refactoring work (create dedicated tags like `refactor-auth`)
- Experimental features (use `experiment-*` tags)
- Team member-specific tasks (use person-specific tags)
#### PRD-Driven Feature Development
**For New Major Features**:
1. **Identify the Initiative**: When user describes a significant feature
2. **Create Dedicated Tag**: `add_tag feature-[name] --description="[Feature description]"`
3. **Collaborative PRD Creation**: Work with user to create comprehensive PRD in `.taskmaster/docs/feature-[name]-prd.txt`
4. **Parse & Prepare**:
- `parse_prd .taskmaster/docs/feature-[name]-prd.txt --tag=feature-[name]`
- `analyze_project_complexity --tag=feature-[name] --research`
- `expand_all --tag=feature-[name] --research`
5. **Add Master Reference**: Create a high-level task in `master` that references the feature tag
**For Existing Codebase Analysis**:
When users initialize Taskmaster on existing projects:
1. **Codebase Discovery**: Use your native tools for producing deep context about the code base. You may use `research` tool with `--tree` and `--files` to collect up to date information using the existing architecture as context.
2. **Collaborative Assessment**: Work with user to identify improvement areas, technical debt, or new features
3. **Strategic PRD Creation**: Co-author PRDs that include:
- Current state analysis (based on your codebase research)
- Proposed improvements or new features
- Implementation strategy considering existing code
4. **Tag-Based Organization**: Parse PRDs into appropriate tags (`refactor-api`, `feature-dashboard`, `tech-debt`, etc.)
5. **Master List Curation**: Keep only the most valuable initiatives in master
The parse-prd's `--append` flag enables the user to parse multple PRDs within tags or across tags. PRDs should be focused and the number of tasks they are parsed into should be strategically chosen relative to the PRD's complexity and level of detail.
### Workflow Transition Examples
**Example 1: Simple → Team-Based**
```
User: "Alice is going to help with the API work"
Your Response: "Great! To avoid conflicts, I'll create a separate task context for your work. Alice can continue with the master list while you work in your own context. When you're ready to merge, we can coordinate the tasks back together."
Action: add_tag my-api-work --copy-from-current --description="My API tasks while collaborating with Alice"
```
**Example 2: Simple → PRD-Driven**
```
User: "I want to add a complete user dashboard with analytics, user management, and reporting"
Your Response: "This sounds like a major feature that would benefit from detailed planning. Let me create a dedicated context for this work and we can draft a PRD together to ensure we capture all requirements."
Actions:
1. add_tag feature-dashboard --description="User dashboard with analytics and management"
2. Collaborate on PRD creation
3. parse_prd dashboard-prd.txt --tag=feature-dashboard
4. Add high-level "User Dashboard" task to master
```
**Example 3: Existing Project → Strategic Planning**
```
User: "I just initialized Taskmaster on my existing React app. It's getting messy and I want to improve it."
Your Response: "Let me research your codebase to understand the current architecture, then we can create a strategic plan for improvements."
Actions:
1. research "Current React app architecture and improvement opportunities" --tree --files=src/
2. Collaborate on improvement PRD based on findings
3. Create tags for different improvement areas (refactor-components, improve-state-management, etc.)
4. Keep only major improvement initiatives in master
```
---
## Primary Interaction: MCP Server vs. CLI
Task Master offers two primary ways to interact:
Taskmaster offers two primary ways to interact:
1. **MCP Server (Recommended for Integrated Tools)**:
- For AI agents and integrated development environments (like Cursor), interacting via the **MCP server is the preferred method**.
- The MCP server exposes Task Master functionality through a set of tools (e.g., `get_tasks`, `add_subtask`).
- The MCP server exposes Taskmaster functionality through a set of tools (e.g., `get_tasks`, `add_subtask`).
- This method offers better performance, structured data exchange, and richer error handling compared to CLI parsing.
- Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for details on the MCP architecture and available tools.
- A comprehensive list and description of MCP tools and their corresponding CLI commands can be found in [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc).
- **Restart the MCP server** if core logic in `scripts/modules` or MCP tool/direct function definitions change.
- **Note**: MCP tools fully support tagged task lists with complete tag management capabilities.
2. **`task-master` CLI (For Users & Fallback)**:
- The global `task-master` command provides a user-friendly interface for direct terminal interaction.
@@ -25,31 +206,17 @@ Task Master offers two primary ways to interact:
- Install globally with `npm install -g task-master-ai` or use locally via `npx task-master-ai ...`.
- The CLI commands often mirror the MCP tools (e.g., `task-master list` corresponds to `get_tasks`).
- Refer to [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc) for a detailed command reference.
- **Tagged Task Lists**: CLI fully supports the new tagged system with seamless migration.
## Standard Development Workflow Process
## How the Tag System Works (For Your Reference)
- Start new projects by running `initialize_project` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input='<prd-file.txt>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to generate initial tasks.json
- Begin coding sessions with `get_tasks` / `task-master list` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to see current tasks, status, and IDs
- Determine the next task to work on using `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Analyze task complexity with `analyze_project_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before breaking down tasks
- Review complexity report using `complexity_report` / `task-master complexity-report` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Select tasks based on dependencies (all marked 'done'), priority level, and ID order
- Clarify tasks by checking task files in tasks/ directory or asking for user input
- View specific task details using `get_task` / `task-master show <id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to understand implementation requirements
- Break down complex tasks using `expand_task` / `task-master expand --id=<id> --force --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) with appropriate flags like `--force` (to replace existing subtasks) and `--research`.
- Clear existing subtasks if needed using `clear_subtasks` / `task-master clear-subtasks --id=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before regenerating
- Implement code following task details, dependencies, and project standards
- Verify tasks according to test strategies before marking as complete (See [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
- Mark completed tasks with `set_task_status` / `task-master set-status --id=<id> --status=done` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Update dependent tasks when implementation differs from original plan using `update` / `task-master update --from=<id> --prompt="..."` or `update_task` / `task-master update-task --id=<id> --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Add new tasks discovered during implementation using `add_task` / `task-master add-task --prompt="..." --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Add new subtasks as needed using `add_subtask` / `task-master add-subtask --parent=<id> --title="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Append notes or details to subtasks using `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='Add implementation notes here...\nMore details...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Generate task files with `generate` / `task-master generate` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) after updating tasks.json
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
- Respect dependency chains and task priorities when selecting work
- Report progress regularly using `get_tasks` / `task-master list`
- Reorganize tasks as needed using `move_task` / `task-master move --from=<id> --to=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to change task hierarchy or ordering
- **Data Structure**: Tasks are organized into separate contexts (tags) like "master", "feature-branch", or "v2.0".
- **Silent Migration**: Existing projects automatically migrate to use a "master" tag with zero disruption.
- **Context Isolation**: Tasks in different tags are completely separate. Changes in one tag do not affect any other tag.
- **Manual Control**: The user is always in control. There is no automatic switching. You facilitate switching by using `use-tag <name>`.
- **Full CLI & MCP Support**: All tag management commands are available through both the CLI and MCP tools for you to use. Refer to [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc) for a full command list.
---
## Task Complexity Analysis
@@ -107,9 +274,10 @@ Taskmaster configuration is managed through two main mechanisms:
1. **`.taskmaster/config.json` File (Primary):**
* Located in the project root directory.
* Stores most configuration settings: AI model selections (main, research, fallback), parameters (max tokens, temperature), logging level, default subtasks/priority, project name, etc.
* **Tagged System Settings**: Includes `global.defaultTag` (defaults to "master") and `tags` section for tag management configuration.
* **Managed via `task-master models --setup` command.** Do not edit manually unless you know what you are doing.
* **View/Set specific models via `task-master models` command or `models` MCP tool.**
* Created automatically when you run `task-master models --setup` for the first time.
* Created automatically when you run `task-master models --setup` for the first time or during tagged system migration.
2. **Environment Variables (`.env` / `mcp.json`):**
* Used **only** for sensitive API keys and specific endpoint URLs.
@@ -117,6 +285,11 @@ Taskmaster configuration is managed through two main mechanisms:
* For MCP/Cursor integration, configure these keys in the `env` section of `.cursor/mcp.json`.
* Available keys/variables: See `assets/env.example` or the Configuration section in the command reference (previously linked to `taskmaster.mdc`).
3. **`.taskmaster/state.json` File (Tagged System State):**
* Tracks current tag context and migration status.
* Automatically created during tagged system migration.
* Contains: `currentTag`, `lastSwitched`, `migrationNoticeShown`.
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `TASKMASTER_LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
**If AI commands FAIL in MCP** verify that the API key for the selected provider is present in the `env` section of `.cursor/mcp.json`.
**If AI commands FAIL in CLI** verify that the API key for the selected provider is present in the `.env` file in the root of the project.

View File

@@ -0,0 +1,404 @@
---
description: Git workflow integrated with Task Master for feature development and collaboration
globs: "**/*"
alwaysApply: true
---
# Git Workflow with Task Master Integration
## **Branch Strategy**
### **Main Branch Protection**
- **main** branch contains production-ready code
- All feature development happens on task-specific branches
- Direct commits to main are prohibited
- All changes merge via Pull Requests
### **Task Branch Naming**
```bash
# ✅ DO: Use consistent task branch naming
task-001 # For Task 1
task-004 # For Task 4
task-015 # For Task 15
# ❌ DON'T: Use inconsistent naming
feature/user-auth
fix-database-issue
random-branch-name
```
## **Tagged Task Lists Integration**
Task Master's **tagged task lists system** provides significant benefits for Git workflows:
### **Multi-Context Development**
- **Branch-Specific Tasks**: Each branch can have its own task context using tags
- **Merge Conflict Prevention**: Tasks in different tags are completely isolated
- **Context Switching**: Seamlessly switch between different development contexts
- **Parallel Development**: Multiple team members can work on separate task contexts
### **Migration and Compatibility**
- **Seamless Migration**: Existing projects automatically migrate to use a "master" tag
- **Zero Disruption**: All existing Git workflows continue unchanged
- **Backward Compatibility**: Legacy projects work exactly as before
### **Manual Git Integration**
- **Manual Tag Creation**: Use `--from-branch` option to create tags from current git branch
- **Manual Context Switching**: Explicitly switch tag contexts as needed for different branches
- **Simplified Integration**: Focused on manual control rather than automatic workflows
## **Workflow Overview**
```mermaid
flowchart TD
A[Start: On main branch] --> B[Pull latest changes]
B --> C[Create task branch<br/>git checkout -b task-XXX]
C --> D[Set task status: in-progress]
D --> E[Get task context & expand if needed<br/>Tasks automatically use current tag]
E --> F[Identify next subtask]
F --> G[Set subtask: in-progress]
G --> H[Research & collect context<br/>update_subtask with findings]
H --> I[Implement subtask]
I --> J[Update subtask with completion]
J --> K[Set subtask: done]
K --> L[Git commit subtask]
L --> M{More subtasks?}
M -->|Yes| F
M -->|No| N[Run final tests]
N --> O[Commit tests if added]
O --> P[Push task branch]
P --> Q[Create Pull Request]
Q --> R[Human review & merge]
R --> S[Switch to main & pull]
S --> T[Delete task branch]
T --> U[Ready for next task]
style A fill:#e1f5fe
style C fill:#f3e5f5
style G fill:#fff3e0
style L fill:#e8f5e8
style Q fill:#fce4ec
style R fill:#f1f8e9
style U fill:#e1f5fe
```
## **Complete Task Development Workflow**
### **Phase 1: Task Preparation**
```bash
# 1. Ensure you're on main branch and pull latest
git checkout main
git pull origin main
# 2. Check current branch status
git branch # Verify you're on main
# 3. Create task-specific branch
git checkout -b task-004 # For Task 4
# 4. Set task status in Task Master (tasks automatically use current tag context)
# Use: set_task_status tool or `task-master set-status --id=4 --status=in-progress`
```
### **Phase 2: Task Analysis & Planning**
```bash
# 5. Get task context and expand if needed (uses current tag automatically)
# Use: get_task tool or `task-master show 4`
# Use: expand_task tool or `task-master expand --id=4 --research --force` (if complex)
# 6. Identify next subtask to work on
# Use: next_task tool or `task-master next`
```
### **Phase 3: Subtask Implementation Loop**
For each subtask, follow this pattern:
```bash
# 7. Mark subtask as in-progress
# Use: set_task_status tool or `task-master set-status --id=4.1 --status=in-progress`
# 8. Gather context and research (if needed)
# Use: update_subtask tool with research flag or:
# `task-master update-subtask --id=4.1 --prompt="Research findings..." --research`
# 9. Collect code context through AI exploration
# Document findings in subtask using update_subtask
# 10. Implement the subtask
# Write code, tests, documentation
# 11. Update subtask with completion details
# Use: update_subtask tool or:
# `task-master update-subtask --id=4.1 --prompt="Implementation complete..."`
# 12. Mark subtask as done
# Use: set_task_status tool or `task-master set-status --id=4.1 --status=done`
# 13. Commit the subtask implementation
git add .
git commit -m "feat(task-4): Complete subtask 4.1 - [Subtask Title]
- Implementation details
- Key changes made
- Any important notes
Subtask 4.1: [Brief description of what was accomplished]
Relates to Task 4: [Main task title]"
```
### **Phase 4: Task Completion**
```bash
# 14. When all subtasks are complete, run final testing
# Create test file if needed, ensure all tests pass
npm test # or jest, or manual testing
# 15. If tests were added/modified, commit them
git add .
git commit -m "test(task-4): Add comprehensive tests for Task 4
- Unit tests for core functionality
- Integration tests for API endpoints
- All tests passing
Task 4: [Main task title] - Testing complete"
# 16. Push the task branch
git push origin task-004
# 17. Create Pull Request
# Title: "Task 4: [Task Title]"
# Description should include:
# - Task overview
# - Subtasks completed
# - Testing approach
# - Any breaking changes or considerations
```
### **Phase 5: PR Merge & Cleanup**
```bash
# 18. Human reviews and merges PR into main
# 19. Switch back to main and pull merged changes
git checkout main
git pull origin main
# 20. Delete the feature branch (optional cleanup)
git branch -d task-004
git push origin --delete task-004
```
## **Commit Message Standards**
### **Subtask Commits**
```bash
# ✅ DO: Consistent subtask commit format
git commit -m "feat(task-4): Complete subtask 4.1 - Initialize Express server
- Set up Express.js with TypeScript configuration
- Added CORS and body parsing middleware
- Implemented health check endpoints
- Basic error handling middleware
Subtask 4.1: Initialize project with npm and install dependencies
Relates to Task 4: Setup Express.js Server Project"
# ❌ DON'T: Vague or inconsistent commits
git commit -m "fixed stuff"
git commit -m "working on task"
```
### **Test Commits**
```bash
# ✅ DO: Separate test commits when substantial
git commit -m "test(task-4): Add comprehensive tests for Express server setup
- Unit tests for middleware configuration
- Integration tests for health check endpoints
- Mock tests for database connection
- All tests passing with 95% coverage
Task 4: Setup Express.js Server Project - Testing complete"
```
### **Commit Type Prefixes**
- `feat(task-X):` - New feature implementation
- `fix(task-X):` - Bug fixes
- `test(task-X):` - Test additions/modifications
- `docs(task-X):` - Documentation updates
- `refactor(task-X):` - Code refactoring
- `chore(task-X):` - Build/tooling changes
## **Task Master Commands Integration**
### **Essential Commands for Git Workflow**
```bash
# Task management (uses current tag context automatically)
task-master show <id> # Get task/subtask details
task-master next # Find next task to work on
task-master set-status --id=<id> --status=<status>
task-master update-subtask --id=<id> --prompt="..." --research
# Task expansion (for complex tasks)
task-master expand --id=<id> --research --force
# Progress tracking
task-master list # View all tasks and status
task-master list --status=in-progress # View active tasks
```
### **MCP Tool Equivalents**
When using Cursor or other MCP-integrated tools:
- `get_task` instead of `task-master show`
- `next_task` instead of `task-master next`
- `set_task_status` instead of `task-master set-status`
- `update_subtask` instead of `task-master update-subtask`
## **Branch Management Rules**
### **Branch Protection**
```bash
# ✅ DO: Always work on task branches
git checkout -b task-005
# Make changes
git commit -m "..."
git push origin task-005
# ❌ DON'T: Commit directly to main
git checkout main
git commit -m "..." # NEVER do this
```
### **Keeping Branches Updated**
```bash
# ✅ DO: Regularly sync with main (for long-running tasks)
git checkout task-005
git fetch origin
git rebase origin/main # or merge if preferred
# Resolve any conflicts and continue
```
## **Pull Request Guidelines**
### **PR Title Format**
```
Task <ID>: <Task Title>
Examples:
Task 4: Setup Express.js Server Project
Task 7: Implement User Authentication
Task 12: Add Stripe Payment Integration
```
### **PR Description Template**
```markdown
## Task Overview
Brief description of the main task objective.
## Subtasks Completed
- [x] 4.1: Initialize project with npm and install dependencies
- [x] 4.2: Configure TypeScript, ESLint and Prettier
- [x] 4.3: Create basic Express app with middleware and health check route
## Implementation Details
- Key architectural decisions made
- Important code changes
- Any deviations from original plan
## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests passing
- [ ] Manual testing completed
## Breaking Changes
List any breaking changes or migration requirements.
## Related Tasks
Mention any dependent tasks or follow-up work needed.
```
## **Conflict Resolution**
### **Task Conflicts with Tagged System**
```bash
# With tagged task lists, merge conflicts are significantly reduced:
# 1. Different branches can use different tag contexts
# 2. Tasks in separate tags are completely isolated
# 3. Use Task Master's move functionality to reorganize if needed
# Manual git integration available:
# - Use `task-master add-tag --from-branch` to create tags from current branch
# - Manually switch contexts with `task-master use-tag <name>`
# - Simple, predictable workflow without automatic behavior
```
### **Code Conflicts**
```bash
# Standard Git conflict resolution
git fetch origin
git rebase origin/main
# Resolve conflicts in files
git add .
git rebase --continue
```
## **Emergency Procedures**
### **Hotfixes**
```bash
# For urgent production fixes:
git checkout main
git pull origin main
git checkout -b hotfix-urgent-issue
# Make minimal fix
git commit -m "hotfix: Fix critical production issue
- Specific fix description
- Minimal impact change
- Requires immediate deployment"
git push origin hotfix-urgent-issue
# Create emergency PR for immediate review
```
### **Task Abandonment**
```bash
# If task needs to be abandoned or significantly changed:
# 1. Update task status
task-master set-status --id=<id> --status=cancelled
# 2. Clean up branch
git checkout main
git branch -D task-<id>
git push origin --delete task-<id>
# 3. Document reasoning in task
task-master update-task --id=<id> --prompt="Task cancelled due to..."
```
## **Tagged System Benefits for Git Workflows**
### **Multi-Team Development**
- **Isolated Contexts**: Different teams can work on separate tag contexts without conflicts
- **Feature Branches**: Each feature branch can have its own task context
- **Release Management**: Separate tags for different release versions or environments
### **Merge Conflict Prevention**
- **Context Separation**: Tasks in different tags don't interfere with each other
- **Clean Merges**: Reduced likelihood of task-related merge conflicts
- **Parallel Development**: Multiple developers can work simultaneously without task conflicts
### **Manual Git Integration**
- **Branch-Based Tag Creation**: Use `--from-branch` option to create tags from current git branch
- **Manual Context Management**: Explicitly switch tag contexts as needed
- **Predictable Workflow**: Simple, manual control without automatic behavior
---
**References:**
- [Task Master Workflow](mdc:.cursor/rules/dev_workflow.mdc)
- [Architecture Guidelines](mdc:.cursor/rules/architecture.mdc)
- [Task Master Commands](mdc:.cursor/rules/taskmaster.mdc)

View File

@@ -7,20 +7,20 @@ alwaysApply: true
This file provides a quick reference to the purpose of each rule file located in the `.cursor/rules` directory.
- **[`architecture.mdc`](mdc:.cursor/rules/architecture.mdc)**: Describes the high-level architecture of the Task Master CLI application.
- **[`architecture.mdc`](mdc:.cursor/rules/architecture.mdc)**: Describes the high-level architecture of the Task Master CLI application, including the new tagged task lists system.
- **[`changeset.mdc`](mdc:.cursor/rules/changeset.mdc)**: Guidelines for using Changesets (npm run changeset) to manage versioning and changelogs.
- **[`commands.mdc`](mdc:.cursor/rules/commands.mdc)**: Guidelines for implementing CLI commands using Commander.js.
- **[`cursor_rules.mdc`](mdc:.cursor/rules/cursor_rules.mdc)**: Guidelines for creating and maintaining Cursor rules to ensure consistency and effectiveness.
- **[`dependencies.mdc`](mdc:.cursor/rules/dependencies.mdc)**: Guidelines for managing task dependencies and relationships.
- **[`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc)**: Guide for using Task Master to manage task-driven development workflows.
- **[`dependencies.mdc`](mdc:.cursor/rules/dependencies.mdc)**: Guidelines for managing task dependencies and relationships across tagged task contexts.
- **[`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc)**: Guide for using Task Master to manage task-driven development workflows with tagged task lists support.
- **[`glossary.mdc`](mdc:.cursor/rules/glossary.mdc)**: This file; provides a glossary of other Cursor rules.
- **[`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)**: Guidelines for implementing and interacting with the Task Master MCP Server.
- **[`new_features.mdc`](mdc:.cursor/rules/new_features.mdc)**: Guidelines for integrating new features into the Task Master CLI.
- **[`new_features.mdc`](mdc:.cursor/rules/new_features.mdc)**: Guidelines for integrating new features into the Task Master CLI with tagged system considerations.
- **[`self_improve.mdc`](mdc:.cursor/rules/self_improve.mdc)**: Guidelines for continuously improving Cursor rules based on emerging code patterns and best practices.
- **[`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)**: Comprehensive reference for Taskmaster MCP tools and CLI commands.
- **[`tasks.mdc`](mdc:.cursor/rules/tasks.mdc)**: Guidelines for implementing task management operations.
- **[`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)**: Comprehensive reference for Taskmaster MCP tools and CLI commands with tagged task lists information.
- **[`tasks.mdc`](mdc:.cursor/rules/tasks.mdc)**: Guidelines for implementing task management operations with tagged task lists system support.
- **[`tests.mdc`](mdc:.cursor/rules/tests.mdc)**: Guidelines for implementing and maintaining tests for Task Master CLI.
- **[`ui.mdc`](mdc:.cursor/rules/ui.mdc)**: Guidelines for implementing and maintaining user interface components.
- **[`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)**: Guidelines for implementing utility functions.
- **[`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)**: Guidelines for implementing utility functions including tagged task lists utilities.
- **[`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc)**: Guidelines for integrating AI usage telemetry across Task Master.

View File

@@ -24,17 +24,22 @@ alwaysApply: false
The standard pattern for adding a feature follows this workflow:
1. **Core Logic**: Implement the business logic in the appropriate module (e.g., [`task-manager.js`](mdc:scripts/modules/task-manager.js)).
2. **AI Integration (If Applicable)**:
2. **Context Gathering (If Applicable)**:
- For AI-powered commands that benefit from project context, use the standardized context gathering patterns from [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc).
- Import `ContextGatherer` and `FuzzyTaskSearch` utilities for reusable context extraction.
- Support multiple context types: tasks, files, custom text, project tree.
- Implement detailed token breakdown display for transparency.
3. **AI Integration (If Applicable)**:
- Import necessary service functions (e.g., `generateTextService`, `streamTextService`) from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
- Prepare parameters (`role`, `session`, `systemPrompt`, `prompt`).
- Call the service function.
- Handle the response (direct text or stream object).
- **Important**: Prefer `generateTextService` for calls sending large context (like stringified JSON) where incremental display is not needed. See [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc) for detailed usage patterns and cautions.
3. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc).
4. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
5. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
6. **Configuration**: Update configuration settings or add new ones in [`config-manager.js`](mdc:scripts/modules/config-manager.js) and ensure getters/setters are appropriate. Update documentation in [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc). Update the `.taskmasterconfig` structure if needed.
7. **Documentation**: Update help text and documentation in [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc).
4. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc). Consider enhanced formatting with syntax highlighting for code blocks.
5. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
6. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
7. **Configuration**: Update configuration settings or add new ones in [`config-manager.js`](mdc:scripts/modules/config-manager.js) and ensure getters/setters are appropriate. Update documentation in [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc). Update the `.taskmasterconfig` structure if needed.
8. **Documentation**: Update help text and documentation in [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc).
## Critical Checklist for New Features
@@ -629,3 +634,287 @@ When implementing project initialization commands:
});
}
```
## Feature Planning
- **Core Logic First**:
- ✅ DO: Implement core logic in `scripts/modules/` before CLI or MCP interfaces
- ✅ DO: Consider tagged task lists system compatibility from the start
- ✅ DO: Design functions to work with both legacy and tagged data formats
- ✅ DO: Use tag resolution functions (`getTasksForTag`, `setTasksForTag`) for task data access
- ❌ DON'T: Directly manipulate tagged data structure in new features
```javascript
// ✅ DO: Design tagged-aware core functions
async function newFeatureCore(tasksPath, featureParams, options = {}) {
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Perform feature logic on tasks array
const result = performFeatureLogic(tasks, featureParams);
// Save back using tag resolution
setTasksForTag(tasksData, currentTag, tasks);
writeJSON(tasksPath, tasksData);
return result;
}
```
- **Backward Compatibility**:
- ✅ DO: Ensure new features work with existing projects seamlessly
- ✅ DO: Test with both legacy and tagged task data formats
- ✅ DO: Support silent migration during feature usage
- ❌ DON'T: Break existing workflows when adding tagged system features
## CLI Command Implementation
- **Command Structure**:
- ✅ DO: Follow the established pattern in [`commands.js`](mdc:scripts/modules/commands.js)
- ✅ DO: Use Commander.js for argument parsing
- ✅ DO: Include comprehensive help text and examples
- ✅ DO: Support tagged task context awareness
```javascript
// ✅ DO: Implement CLI commands with tagged system awareness
program
.command('new-feature')
.description('Description of the new feature with tagged task lists support')
.option('-t, --tag <tag>', 'Specify tag context (defaults to current tag)')
.option('-p, --param <value>', 'Feature-specific parameter')
.option('--force', 'Force operation without confirmation')
.action(async (options) => {
try {
const projectRoot = findProjectRoot();
if (!projectRoot) {
console.error('Not in a Task Master project directory');
process.exit(1);
}
// Use specified tag or current tag
const targetTag = options.tag || getCurrentTag() || 'master';
const result = await newFeatureCore(
path.join(projectRoot, '.taskmaster', 'tasks', 'tasks.json'),
{ param: options.param },
{
force: options.force,
targetTag: targetTag,
outputFormat: 'text'
}
);
console.log('Feature executed successfully');
} catch (error) {
console.error(`Error: ${error.message}`);
process.exit(1);
}
});
```
- **Error Handling**:
- ✅ DO: Provide clear error messages for common failures
- ✅ DO: Handle tagged system migration errors gracefully
- ✅ DO: Include suggestion for resolution when possible
- ✅ DO: Exit with appropriate codes for scripting
## MCP Tool Implementation
- **Direct Function Pattern**:
- ✅ DO: Create direct function wrappers in `mcp-server/src/core/direct-functions/`
- ✅ DO: Follow silent mode patterns to prevent console output interference
- ✅ DO: Use `findTasksJsonPath` for consistent path resolution
- ✅ DO: Ensure tagged system compatibility
```javascript
// ✅ DO: Implement MCP direct functions with tagged awareness
export async function newFeatureDirect(args, log, context = {}) {
try {
const tasksPath = findTasksJsonPath(args, log);
// Enable silent mode for clean MCP responses
enableSilentMode();
try {
const result = await newFeatureCore(
tasksPath,
{ param: args.param },
{
force: args.force,
targetTag: args.tag || 'master', // Support tag specification
mcpLog: log,
session: context.session,
outputFormat: 'json'
}
);
return {
success: true,
data: result,
fromCache: false
};
} finally {
disableSilentMode();
}
} catch (error) {
log.error(`Error in newFeatureDirect: ${error.message}`);
return {
success: false,
error: { code: 'FEATURE_ERROR', message: error.message },
fromCache: false
};
}
}
```
- **Tool Registration**:
- ✅ DO: Create tool definitions in `mcp-server/src/tools/`
- ✅ DO: Use Zod for parameter validation
- ✅ DO: Include optional tag parameter for multi-context support
- ✅ DO: Follow established naming conventions
```javascript
// ✅ DO: Register MCP tools with tagged system support
export function registerNewFeatureTool(server) {
server.addTool({
name: "new_feature",
description: "Description of the new feature with tagged task lists support",
inputSchema: z.object({
param: z.string().describe("Feature-specific parameter"),
tag: z.string().optional().describe("Target tag context (defaults to current tag)"),
force: z.boolean().optional().describe("Force operation without confirmation"),
projectRoot: z.string().optional().describe("Project root directory")
}),
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
const result = await newFeatureDirect(
{ ...args, projectRoot: args.projectRoot },
log,
{ session }
);
return handleApiResult(result, log);
} catch (error) {
return handleApiResult({
success: false,
error: { code: 'EXECUTION_ERROR', message: error.message }
}, log);
}
})
});
}
```
## Testing Strategy
- **Unit Tests**:
- ✅ DO: Test core logic independently with both data formats
- ✅ DO: Mock file system operations appropriately
- ✅ DO: Test tag resolution behavior
- ✅ DO: Verify migration compatibility
```javascript
// ✅ DO: Test new features with tagged system awareness
describe('newFeature', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should work with legacy task format', async () => {
const legacyData = { tasks: [/* test data */] };
fs.readFileSync.mockReturnValue(JSON.stringify(legacyData));
const result = await newFeatureCore('/test/tasks.json', { param: 'test' });
expect(result).toBeDefined();
// Test legacy format handling
});
it('should work with tagged task format', async () => {
const taggedData = {
master: { tasks: [/* test data */] },
feature: { tasks: [/* test data */] }
};
fs.readFileSync.mockReturnValue(JSON.stringify(taggedData));
const result = await newFeatureCore('/test/tasks.json', { param: 'test' });
expect(result).toBeDefined();
// Test tagged format handling
});
it('should handle tag migration during feature usage', async () => {
const legacyData = { tasks: [/* test data */] };
fs.readFileSync.mockReturnValue(JSON.stringify(legacyData));
await newFeatureCore('/test/tasks.json', { param: 'test' });
// Verify migration occurred
expect(fs.writeFileSync).toHaveBeenCalledWith(
'/test/tasks.json',
expect.stringContaining('"master"')
);
});
});
```
- **Integration Tests**:
- ✅ DO: Test CLI and MCP interfaces with real task data
- ✅ DO: Verify end-to-end workflows across tag contexts
- ✅ DO: Test error scenarios and recovery
## Documentation Updates
- **Rule Updates**:
- ✅ DO: Update relevant `.cursor/rules/*.mdc` files
- ✅ DO: Include tagged system considerations in architecture docs
- ✅ DO: Add examples showing multi-context usage
- ✅ DO: Update workflow documentation as needed
- **User Documentation**:
- ✅ DO: Add feature documentation to `/docs` folder
- ✅ DO: Include tagged system usage examples
- ✅ DO: Update command reference documentation
- ✅ DO: Provide migration notes if relevant
## Migration Considerations
- **Silent Migration Support**:
- ✅ DO: Ensure new features trigger migration when needed
- ✅ DO: Handle migration errors gracefully in feature code
- ✅ DO: Test feature behavior with pre-migration projects
- ❌ DON'T: Assume projects are already migrated
- **Tag Context Handling**:
- ✅ DO: Default to current tag when not specified
- ✅ DO: Support explicit tag selection in advanced features
- ✅ DO: Validate tag existence before operations
- ✅ DO: Provide clear messaging about tag context
## Performance Considerations
- **Efficient Tag Operations**:
- ✅ DO: Minimize file I/O operations per feature execution
- ✅ DO: Cache tag resolution results when appropriate
- ✅ DO: Use streaming for large task datasets
- ❌ DON'T: Load all tags when only one is needed
- **Memory Management**:
- ✅ DO: Process large task lists efficiently
- ✅ DO: Clean up temporary data structures
- ✅ DO: Avoid keeping all tag data in memory simultaneously
## Deployment and Versioning
- **Changesets**:
- ✅ DO: Create appropriate changesets for new features
- ✅ DO: Use semantic versioning (minor for new features)
- ✅ DO: Include tagged system information in release notes
- ✅ DO: Document breaking changes if any
- **Feature Flags**:
- ✅ DO: Consider feature flags for experimental functionality
- ✅ DO: Ensure tagged system features work with flags
- ✅ DO: Provide clear documentation about flag usage
By following these guidelines, new features will integrate smoothly with the Task Master ecosystem while supporting the enhanced tagged task lists system for multi-context development workflows.

229
.cursor/rules/tags.mdc Normal file
View File

@@ -0,0 +1,229 @@
---
description:
globs: scripts/modules/*
alwaysApply: false
---
# Tagged Task Lists Command Patterns
This document outlines the standardized patterns that **ALL** Task Master commands must follow to properly support the tagged task lists system.
## Core Principles
- **Every command** that reads or writes tasks.json must be tag-aware
- **Consistent tag resolution** across all commands using `getCurrentTag(projectRoot)`
- **Proper context passing** to core functions with `{ projectRoot, tag }`
- **Standardized CLI options** with `--tag <tag>` flag
## Required Imports
All command files must import `getCurrentTag`:
```javascript
// ✅ DO: Import getCurrentTag in commands.js
import {
log,
readJSON,
writeJSON,
findProjectRoot,
getCurrentTag
} from './utils.js';
// ✅ DO: Import getCurrentTag in task-manager files
import {
readJSON,
writeJSON,
getCurrentTag
} from '../utils.js';
```
## CLI Command Pattern
Every CLI command that operates on tasks must follow this exact pattern:
```javascript
// ✅ DO: Standard tag-aware CLI command pattern
programInstance
.command('command-name')
.description('Command description')
.option('-f, --file <file>', 'Path to the tasks file', TASKMASTER_TASKS_FILE)
.option('--tag <tag>', 'Specify tag context for task operations') // REQUIRED
.action(async (options) => {
// 1. Find project root
const projectRoot = findProjectRoot();
if (!projectRoot) {
console.error(chalk.red('Error: Could not find project root.'));
process.exit(1);
}
// 2. Resolve tag using standard pattern
const tag = options.tag || getCurrentTag(projectRoot) || 'master';
// 3. Call core function with proper context
await coreFunction(
tasksPath,
// ... other parameters ...
{ projectRoot, tag } // REQUIRED context object
);
});
```
## Core Function Pattern
All core functions in `scripts/modules/task-manager/` must follow this pattern:
```javascript
// ✅ DO: Standard tag-aware core function pattern
async function coreFunction(
tasksPath,
// ... other parameters ...
context = {} // REQUIRED context parameter
) {
const { projectRoot, tag } = context;
// Use tag-aware readJSON/writeJSON
const data = readJSON(tasksPath, projectRoot, tag);
// ... function logic ...
writeJSON(tasksPath, data, projectRoot, tag);
}
```
## Tag Resolution Priority
The tag resolution follows this exact priority order:
1. **Explicit `--tag` flag**: `options.tag`
2. **Current active tag**: `getCurrentTag(projectRoot)`
3. **Default fallback**: `'master'`
```javascript
// ✅ DO: Standard tag resolution pattern
const tag = options.tag || getCurrentTag(projectRoot) || 'master';
```
## Commands Requiring Updates
### High Priority (Core Task Operations)
- [x] `add-task` - ✅ Fixed
- [x] `list` - ✅ Fixed
- [x] `update-task` - ✅ Fixed
- [x] `update-subtask` - ✅ Fixed
- [x] `set-status` - ✅ Already correct
- [x] `remove-task` - ✅ Already correct
- [x] `remove-subtask` - ✅ Fixed
- [x] `add-subtask` - ✅ Already correct
- [x] `clear-subtasks` - ✅ Fixed
- [x] `move-task` - ✅ Already correct
### Medium Priority (Analysis & Expansion)
- [x] `expand` - ✅ Fixed
- [ ] `next` - ✅ Fixed
- [ ] `show` (get-task) - Needs checking
- [ ] `analyze-complexity` - Needs checking
- [ ] `generate` - ✅ Fixed
### Lower Priority (Utilities)
- [ ] `research` - Needs checking
- [ ] `complexity-report` - Needs checking
- [ ] `validate-dependencies` - ✅ Fixed
- [ ] `fix-dependencies` - ✅ Fixed
- [ ] `add-dependency` - ✅ Fixed
- [ ] `remove-dependency` - ✅ Fixed
## MCP Integration Pattern
MCP direct functions must also follow the tag-aware pattern:
```javascript
// ✅ DO: Tag-aware MCP direct function
export async function coreActionDirect(args, log, context = {}) {
const { session } = context;
const { projectRoot, tag } = args; // MCP passes these in args
try {
const result = await coreAction(
tasksPath,
// ... other parameters ...
{ projectRoot, tag, session, mcpLog: logWrapper }
);
return { success: true, data: result };
} catch (error) {
return { success: false, error: { code: 'ERROR_CODE', message: error.message } };
}
}
```
## File Generation Tag-Aware Naming
The `generate` command must use tag-aware file naming:
```javascript
// ✅ DO: Tag-aware file naming
const taskFileName = targetTag === 'master'
? `task_${task.id.toString().padStart(3, '0')}.txt`
: `task_${task.id.toString().padStart(3, '0')}_${targetTag}.txt`;
```
**Examples:**
- Master tag: `task_001.txt`, `task_002.txt`
- Other tags: `task_001_feature.txt`, `task_002_feature.txt`
## Common Anti-Patterns
```javascript
// ❌ DON'T: Missing getCurrentTag import
import { readJSON, writeJSON } from '../utils.js'; // Missing getCurrentTag
// ❌ DON'T: Hard-coded tag resolution
const tag = options.tag || 'master'; // Missing getCurrentTag
// ❌ DON'T: Missing --tag option
.option('-f, --file <file>', 'Path to tasks file') // Missing --tag option
// ❌ DON'T: Missing context parameter
await coreFunction(tasksPath, param1, param2); // Missing { projectRoot, tag }
// ❌ DON'T: Incorrect readJSON/writeJSON calls
const data = readJSON(tasksPath); // Missing projectRoot and tag
writeJSON(tasksPath, data); // Missing projectRoot and tag
```
## Validation Checklist
For each command, verify:
- [ ] Imports `getCurrentTag` from utils.js
- [ ] Has `--tag <tag>` CLI option
- [ ] Uses standard tag resolution: `options.tag || getCurrentTag(projectRoot) || 'master'`
- [ ] Finds `projectRoot` with error handling
- [ ] Passes `{ projectRoot, tag }` context to core functions
- [ ] Core functions accept and use context parameter
- [ ] Uses `readJSON(tasksPath, projectRoot, tag)` and `writeJSON(tasksPath, data, projectRoot, tag)`
## Testing Tag Resolution
Test each command with:
```bash
# Test with explicit tag
node bin/task-master command-name --tag test-tag
# Test with active tag (should use current active tag)
node bin/task-master use-tag test-tag
node bin/task-master command-name
# Test with master tag (default)
node bin/task-master use-tag master
node bin/task-master command-name
```
## Migration Strategy
1. **Audit Phase**: Systematically check each command against the checklist
2. **Fix Phase**: Apply the standard patterns to non-compliant commands
3. **Test Phase**: Verify tag resolution works correctly
4. **Document Phase**: Update command documentation with tag support
This ensures consistent, predictable behavior across all Task Master commands and prevents tag deletion bugs.

View File

@@ -11,6 +11,8 @@ This document provides a detailed reference for interacting with Taskmaster, cov
**Important:** Several MCP tools involve AI processing... The AI-powered tools include `parse_prd`, `analyze_project_complexity`, `update_subtask`, `update_task`, `update`, `expand_all`, `expand_task`, and `add_task`.
**🏷️ Tagged Task Lists System:** Task Master now supports **tagged task lists** for multi-context task management. This allows you to maintain separate, isolated lists of tasks for different features, branches, or experiments. Existing projects are seamlessly migrated to use a default "master" tag. Most commands now support a `--tag <name>` flag to specify which context to operate on. If omitted, commands use the currently active tag.
---
## Initialization & Setup
@@ -37,6 +39,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `yes`: `Skip prompts and use defaults/provided arguments. Default is false.` (CLI: `-y, --yes`)
* **Usage:** Run this once at the beginning of a new project, typically via an integrated tool like Cursor. Operates on the current working directory of the MCP server.
* **Important:** Once complete, you *MUST* parse a prd in order to generate tasks. There will be no tasks files until then. The next step after initializing should be to create a PRD using the example PRD in .taskmaster/templates/example_prd.txt.
* **Tagging:** Use the `--tag` option to parse the PRD into a specific, non-default tag context. If the tag doesn't exist, it will be created automatically. Example: `task-master parse-prd spec.txt --tag=new-feature`.
### 2. Parse PRD (`parse_prd`)
@@ -74,6 +77,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `--set-fallback <model_id>`: `Set the fallback model.`
* `--ollama`: `Specify that the provided model ID is for Ollama (use with --set-*).`
* `--openrouter`: `Specify that the provided model ID is for OpenRouter (use with --set-*). Validates against OpenRouter API.`
* `--bedrock`: `Specify that the provided model ID is for AWS Bedrock (use with --set-*).`
* `--setup`: `Run interactive setup to configure models, including custom Ollama/OpenRouter IDs.`
* **Usage (MCP):** Call without set flags to get current config. Use `setMain`, `setResearch`, or `setFallback` with a valid model ID to update the configuration. Use `listAvailableModels: true` to get a list of unassigned models. To set a custom model, provide the model ID and set `ollama: true` or `openrouter: true`.
* **Usage (CLI):** Run without flags to view current configuration and available models. Use set flags to update specific roles. Use `--setup` for guided configuration, including custom models. To set a custom model via flags, use `--set-<role>=<model_id>` along with either `--ollama` or `--openrouter`.
@@ -92,8 +96,9 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master list [options]`
* **Description:** `List your Taskmaster tasks, optionally filtering by status and showing subtasks.`
* **Key Parameters/Options:**
* `status`: `Show only Taskmaster tasks matching this status, e.g., 'pending' or 'done'.` (CLI: `-s, --status <status>`)
* `status`: `Show only Taskmaster tasks matching this status (or multiple statuses, comma-separated), e.g., 'pending' or 'done,in-progress'.` (CLI: `-s, --status <status>`)
* `withSubtasks`: `Include subtasks indented under their parent tasks in the list.` (CLI: `--with-subtasks`)
* `tag`: `Specify which tag context to list tasks from. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Get an overview of the project status, often used at the start of a work session.
@@ -104,17 +109,20 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Description:** `Ask Taskmaster to show the next available task you can work on, based on status and completed dependencies.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `tag`: `Specify which tag context to use. Defaults to the current active tag.` (CLI: `--tag <name>`)
* **Usage:** Identify what to work on next according to the plan.
### 5. Get Task Details (`get_task`)
* **MCP Tool:** `get_task`
* **CLI Command:** `task-master show [id] [options]`
* **Description:** `Display detailed information for a specific Taskmaster task or subtask by its ID.`
* **Description:** `Display detailed information for one or more specific Taskmaster tasks or subtasks by ID.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task, e.g., '15', or subtask, e.g., '15.2', you want to view.` (CLI: `[id]` positional or `-i, --id <id>`)
* `id`: `Required. The ID of the Taskmaster task (e.g., '15'), subtask (e.g., '15.2'), or a comma-separated list of IDs ('1,5,10.2') you want to view.` (CLI: `[id]` positional or `-i, --id <id>`)
* `tag`: `Specify which tag context to get the task(s) from. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Understand the full details, implementation notes, and test strategy for a specific task before starting work.
* **Usage:** Understand the full details for a specific task. When multiple IDs are provided, a summary table is shown.
* **CRITICAL INFORMATION** If you need to collect information from multiple tasks, use comma-separated IDs (i.e. 1,2,3) to receive an array of tasks. Do not needlessly get tasks one at a time if you need to get many as that is wasteful.
---
@@ -130,6 +138,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `dependencies`: `Specify the IDs of any Taskmaster tasks that must be completed before this new one can start, e.g., '12,14'.` (CLI: `-d, --dependencies <ids>`)
* `priority`: `Set the priority for the new task: 'high', 'medium', or 'low'. Default is 'medium'.` (CLI: `--priority <priority>`)
* `research`: `Enable Taskmaster to use the research role for potentially more informed task creation.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to add the task to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Quickly add newly identified tasks during development.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -148,6 +157,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `dependencies`: `Specify IDs of other tasks or subtasks, e.g., '15' or '16.1', that must be done before this new subtask.` (CLI: `--dependencies <ids>`)
* `status`: `Set the initial status for the new subtask. Default is 'pending'.` (CLI: `-s, --status <status>`)
* `skipGenerate`: `Prevent Taskmaster from automatically regenerating markdown task files after adding the subtask.` (CLI: `--skip-generate`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Break down tasks manually or reorganize existing tasks.
@@ -160,6 +170,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `from`: `Required. The ID of the first task Taskmaster should update. All tasks with this ID or higher that are not 'done' will be considered.` (CLI: `--from <id>`)
* `prompt`: `Required. Explain the change or new context for Taskmaster to apply to the tasks, e.g., "We are now using React Query instead of Redux Toolkit for data fetching".` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Handle significant implementation changes or pivots that affect multiple future tasks. Example CLI: `task-master update --from='18' --prompt='Switching to React Query.\nNeed to refactor data fetching...'`
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -168,13 +179,15 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **MCP Tool:** `update_task`
* **CLI Command:** `task-master update-task [options]`
* **Description:** `Modify a specific Taskmaster task or subtask by its ID, incorporating new information or changes.`
* **Description:** `Modify a specific Taskmaster task by ID, incorporating new information or changes. By default, this replaces the existing task details.`
* **Key Parameters/Options:**
* `id`: `Required. The specific ID of the Taskmaster task, e.g., '15', or subtask, e.g., '15.2', you want to update.` (CLI: `-i, --id <id>`)
* `id`: `Required. The specific ID of the Taskmaster task, e.g., '15', you want to update.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. Explain the specific changes or provide the new information Taskmaster should incorporate into this task.` (CLI: `-p, --prompt <text>`)
* `append`: `If true, appends the prompt content to the task's details with a timestamp, rather than replacing them. Behaves like update-subtask.` (CLI: `--append`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context the task belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Refine a specific task based on new understanding or feedback. Example CLI: `task-master update-task --id='15' --prompt='Clarification: Use PostgreSQL instead of MySQL.\nUpdate schema details...'`
* **Usage:** Refine a specific task based on new understanding. Use `--append` to log progress without creating subtasks.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 10. Update Subtask (`update_subtask`)
@@ -183,11 +196,12 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master update-subtask [options]`
* **Description:** `Append timestamped notes or details to a specific Taskmaster subtask without overwriting existing content. Intended for iterative implementation logging.`
* **Key Parameters/Options:**
* `id`: `Required. The specific ID of the Taskmaster subtask, e.g., '15.2', you want to add information to.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. Provide the information or notes Taskmaster should append to the subtask's details. Ensure this adds *new* information not already present.` (CLI: `-p, --prompt <text>`)
* `id`: `Required. The ID of the Taskmaster subtask, e.g., '5.2', to update with new information.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. The information, findings, or progress notes to append to the subtask's details with a timestamp.` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context the subtask belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Add implementation notes, code snippets, or clarifications to a subtask during development. Before calling, review the subtask's current details to append only fresh insights, helping to build a detailed log of the implementation journey and avoid redundancy. Example CLI: `task-master update-subtask --id='15.2' --prompt='Discovered that the API requires header X.\nImplementation needs adjustment...'`
* **Usage:** Log implementation progress, findings, and discoveries during subtask development. Each update is timestamped and appended to preserve the implementation journey.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 11. Set Task Status (`set_task_status`)
@@ -198,6 +212,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id`: `Required. The ID(s) of the Taskmaster task(s) or subtask(s), e.g., '15', '15.2', or '16,17.1', to update.` (CLI: `-i, --id <id>`)
* `status`: `Required. The new status to set, e.g., 'done', 'pending', 'in-progress', 'review', 'cancelled'.` (CLI: `-s, --status <status>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Mark progress as tasks move through the development cycle.
@@ -209,6 +224,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task, e.g., '5', or subtask, e.g., '5.2', to permanently remove.` (CLI: `-i, --id <id>`)
* `yes`: `Skip the confirmation prompt and immediately delete the task.` (CLI: `-y, --yes`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Permanently delete tasks or subtasks that are no longer needed in the project.
* **Notes:** Use with caution as this operation cannot be undone. Consider using 'blocked', 'cancelled', or 'deferred' status instead if you just want to exclude a task from active planning but keep it for reference. The command automatically cleans up dependency references in other tasks.
@@ -228,6 +244,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `research`: `Enable Taskmaster to use the research role for more informed subtask generation. Requires appropriate API key.` (CLI: `-r, --research`)
* `prompt`: `Optional: Provide extra context or specific instructions to Taskmaster for generating the subtasks.` (CLI: `-p, --prompt <text>`)
* `force`: `Optional: If true, clear existing subtasks before generating new ones. Default is false (append).` (CLI: `--force`)
* `tag`: `Specify which tag context the task belongs to. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Generate a detailed implementation plan for a complex task before starting coding. Automatically uses complexity report recommendations if available and `num` is not specified.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -242,6 +259,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `research`: `Enable research role for more informed subtask generation. Requires appropriate API key.` (CLI: `-r, --research`)
* `prompt`: `Optional: Provide extra context for Taskmaster to apply generally during expansion.` (CLI: `-p, --prompt <text>`)
* `force`: `Optional: If true, clear existing subtasks before generating new ones for each eligible task. Default is false (append).` (CLI: `--force`)
* `tag`: `Specify which tag context to expand. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Useful after initial task generation or complexity analysis to break down multiple tasks at once.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -254,6 +272,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id`: `The ID(s) of the Taskmaster parent task(s) whose subtasks you want to remove, e.g., '15' or '16,18'. Required unless using `all`.) (CLI: `-i, --id <ids>`)
* `all`: `Tell Taskmaster to remove subtasks from all parent tasks.` (CLI: `--all`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Used before regenerating subtasks with `expand_task` if the previous breakdown needs replacement.
@@ -266,6 +285,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `id`: `Required. The ID(s) of the Taskmaster subtask(s) to remove, e.g., '15.2' or '16.1,16.3'.` (CLI: `-i, --id <id>`)
* `convert`: `If used, Taskmaster will turn the subtask into a regular top-level task instead of deleting it.` (CLI: `-c, --convert`)
* `skipGenerate`: `Prevent Taskmaster from automatically regenerating markdown task files after removing the subtask.` (CLI: `--skip-generate`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Delete unnecessary subtasks or promote a subtask to a top-level task.
@@ -277,6 +297,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `from`: `Required. ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated for multiple tasks.` (CLI: `--from <id>`)
* `to`: `Required. ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated.` (CLI: `--to <id>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Reorganize tasks by moving them within the hierarchy. Supports various scenarios like:
* Moving a task to become a subtask
@@ -306,6 +327,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task that will depend on another.` (CLI: `-i, --id <id>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that must be completed first, the prerequisite.` (CLI: `-d, --depends-on <id>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`)
* **Usage:** Establish the correct order of execution between tasks.
@@ -317,6 +339,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task you want to remove a prerequisite from.` (CLI: `-i, --id <id>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that should no longer be a prerequisite.` (CLI: `-d, --depends-on <id>`)
* `tag`: `Specify which tag context to operate on. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Update task relationships when the order of execution changes.
@@ -326,6 +349,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master validate-dependencies [options]`
* **Description:** `Check your Taskmaster tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.`
* **Key Parameters/Options:**
* `tag`: `Specify which tag context to validate. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Audit the integrity of your task dependencies.
@@ -335,6 +359,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master fix-dependencies [options]`
* **Description:** `Automatically fix dependency issues (like circular references or links to non-existent tasks) in your Taskmaster tasks.`
* **Key Parameters/Options:**
* `tag`: `Specify which tag context to fix dependencies in. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Clean up dependency errors automatically.
@@ -348,9 +373,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master analyze-complexity [options]`
* **Description:** `Have Taskmaster analyze your tasks to determine their complexity and suggest which ones need to be broken down further.`
* **Key Parameters/Options:**
* `output`: `Where to save the complexity analysis report (default: '.taskmaster/reports/task-complexity-report.json').` (CLI: `-o, --output <file>`)
* `output`: `Where to save the complexity analysis report. Default is '.taskmaster/reports/task-complexity-report.json' (or '..._tagname.json' if a tag is used).` (CLI: `-o, --output <file>`)
* `threshold`: `The minimum complexity score (1-10) that should trigger a recommendation to expand a task.` (CLI: `-t, --threshold <number>`)
* `research`: `Enable research role for more accurate complexity analysis. Requires appropriate API key.` (CLI: `-r, --research`)
* `tag`: `Specify which tag context to analyze. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Used before breaking down tasks to identify which ones need the most attention.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -361,6 +387,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master complexity-report [options]`
* **Description:** `Display the task complexity analysis report in a readable format.`
* **Key Parameters/Options:**
* `tag`: `Specify which tag context to show the report for. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to the complexity report (default: '.taskmaster/reports/task-complexity-report.json').` (CLI: `-f, --file <file>`)
* **Usage:** Review and understand the complexity analysis results after running analyze-complexity.
@@ -375,8 +402,131 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Description:** `Create or update individual Markdown files for each task based on your tasks.json.`
* **Key Parameters/Options:**
* `output`: `The directory where Taskmaster should save the task files (default: in a 'tasks' directory).` (CLI: `-o, --output <directory>`)
* `tag`: `Specify which tag context to generate files for. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Run this after making changes to tasks.json to keep individual task files up to date.
* **Usage:** Run this after making changes to tasks.json to keep individual task files up to date. This command is now manual and no longer runs automatically.
---
## AI-Powered Research
### 25. Research (`research`)
* **MCP Tool:** `research`
* **CLI Command:** `task-master research [options]`
* **Description:** `Perform AI-powered research queries with project context to get fresh, up-to-date information beyond the AI's knowledge cutoff.`
* **Key Parameters/Options:**
* `query`: `Required. Research query/prompt (e.g., "What are the latest best practices for React Query v5?").` (CLI: `[query]` positional or `-q, --query <text>`)
* `taskIds`: `Comma-separated list of task/subtask IDs from the current tag context (e.g., "15,16.2,17").` (CLI: `-i, --id <ids>`)
* `filePaths`: `Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md").` (CLI: `-f, --files <paths>`)
* `customContext`: `Additional custom context text to include in the research.` (CLI: `-c, --context <text>`)
* `includeProjectTree`: `Include project file tree structure in context (default: false).` (CLI: `--tree`)
* `detailLevel`: `Detail level for the research response: 'low', 'medium', 'high' (default: medium).` (CLI: `--detail <level>`)
* `saveTo`: `Task or subtask ID (e.g., "15", "15.2") to automatically save the research conversation to.` (CLI: `--save-to <id>`)
* `saveFile`: `If true, saves the research conversation to a markdown file in '.taskmaster/docs/research/'.` (CLI: `--save-file`)
* `noFollowup`: `Disables the interactive follow-up question menu in the CLI.` (CLI: `--no-followup`)
* `tag`: `Specify which tag context to use for task-based context gathering. Defaults to the current active tag.` (CLI: `--tag <name>`)
* `projectRoot`: `The directory of the project. Must be an absolute path.` (CLI: Determined automatically)
* **Usage:** **This is a POWERFUL tool that agents should use FREQUENTLY** to:
* Get fresh information beyond knowledge cutoff dates
* Research latest best practices, library updates, security patches
* Find implementation examples for specific technologies
* Validate approaches against current industry standards
* Get contextual advice based on project files and tasks
* **When to Consider Using Research:**
* **Before implementing any task** - Research current best practices
* **When encountering new technologies** - Get up-to-date implementation guidance (libraries, apis, etc)
* **For security-related tasks** - Find latest security recommendations
* **When updating dependencies** - Research breaking changes and migration guides
* **For performance optimization** - Get current performance best practices
* **When debugging complex issues** - Research known solutions and workarounds
* **Research + Action Pattern:**
* Use `research` to gather fresh information
* Use `update_subtask` to commit findings with timestamps
* Use `update_task` to incorporate research into task details
* Use `add_task` with research flag for informed task creation
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. The research provides FRESH data beyond the AI's training cutoff, making it invaluable for current best practices and recent developments.
---
## Tag Management
This new suite of commands allows you to manage different task contexts (tags).
### 26. List Tags (`tags`)
* **MCP Tool:** `list_tags`
* **CLI Command:** `task-master tags [options]`
* **Description:** `List all available tags with task counts, completion status, and other metadata.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `--show-metadata`: `Include detailed metadata in the output (e.g., creation date, description).` (CLI: `--show-metadata`)
### 27. Add Tag (`add_tag`)
* **MCP Tool:** `add_tag`
* **CLI Command:** `task-master add-tag <tagName> [options]`
* **Description:** `Create a new, empty tag context, or copy tasks from another tag.`
* **Key Parameters/Options:**
* `tagName`: `Name of the new tag to create (alphanumeric, hyphens, underscores).` (CLI: `<tagName>` positional)
* `--from-branch`: `Creates a tag with a name derived from the current git branch, ignoring the <tagName> argument.` (CLI: `--from-branch`)
* `--copy-from-current`: `Copy tasks from the currently active tag to the new tag.` (CLI: `--copy-from-current`)
* `--copy-from <tag>`: `Copy tasks from a specific source tag to the new tag.` (CLI: `--copy-from <tag>`)
* `--description <text>`: `Provide an optional description for the new tag.` (CLI: `-d, --description <text>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 28. Delete Tag (`delete_tag`)
* **MCP Tool:** `delete_tag`
* **CLI Command:** `task-master delete-tag <tagName> [options]`
* **Description:** `Permanently delete a tag and all of its associated tasks.`
* **Key Parameters/Options:**
* `tagName`: `Name of the tag to delete.` (CLI: `<tagName>` positional)
* `--yes`: `Skip the confirmation prompt.` (CLI: `-y, --yes`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 29. Use Tag (`use_tag`)
* **MCP Tool:** `use_tag`
* **CLI Command:** `task-master use-tag <tagName>`
* **Description:** `Switch your active task context to a different tag.`
* **Key Parameters/Options:**
* `tagName`: `Name of the tag to switch to.` (CLI: `<tagName>` positional)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 30. Rename Tag (`rename_tag`)
* **MCP Tool:** `rename_tag`
* **CLI Command:** `task-master rename-tag <oldName> <newName>`
* **Description:** `Rename an existing tag.`
* **Key Parameters/Options:**
* `oldName`: `The current name of the tag.` (CLI: `<oldName>` positional)
* `newName`: `The new name for the tag.` (CLI: `<newName>` positional)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
### 31. Copy Tag (`copy_tag`)
* **MCP Tool:** `copy_tag`
* **CLI Command:** `task-master copy-tag <sourceName> <targetName> [options]`
* **Description:** `Copy an entire tag context, including all its tasks and metadata, to a new tag.`
* **Key Parameters/Options:**
* `sourceName`: `Name of the tag to copy from.` (CLI: `<sourceName>` positional)
* `targetName`: `Name of the new tag to create.` (CLI: `<targetName>` positional)
* `--description <text>`: `Optional description for the new tag.` (CLI: `-d, --description <text>`)
---
## Miscellaneous
### 32. Sync Readme (`sync-readme`) -- experimental
* **MCP Tool:** N/A
* **CLI Command:** `task-master sync-readme [options]`
* **Description:** `Exports your task list to your project's README.md file, useful for showcasing progress.`
* **Key Parameters/Options:**
* `status`: `Filter tasks by status (e.g., 'pending', 'done').` (CLI: `-s, --status <status>`)
* `withSubtasks`: `Include subtasks in the export.` (CLI: `--with-subtasks`)
* `tag`: `Specify which tag context to export from. Defaults to the current active tag.` (CLI: `--tag <name>`)
---

View File

@@ -3,9 +3,19 @@ description: Guidelines for implementing task management operations
globs: scripts/modules/task-manager.js
alwaysApply: false
---
# Task Management Guidelines
## Tagged Task Lists System
Task Master now uses a **tagged task lists system** for multi-context task management:
- **Data Structure**: Tasks are organized into separate contexts (tags) within `tasks.json`
- **Legacy Format**: `{"tasks": [...]}`
- **Tagged Format**: `{"master": {"tasks": [...]}, "feature-branch": {"tasks": [...]}}`
- **Silent Migration**: Legacy format automatically converts to tagged format on first use
- **Tag Resolution**: Core functions receive legacy format for 100% backward compatibility
- **Default Tag**: "master" is used for all existing and new tasks unless otherwise specified
## Task Structure Standards
- **Core Task Properties**:
@@ -28,6 +38,25 @@ alwaysApply: false
};
```
- **Tagged Data Structure**:
- ✅ DO: Access tasks through tag resolution layer
- ✅ DO: Use `getTasksForTag(data, tagName)` to retrieve tasks for a specific tag
- ✅ DO: Use `setTasksForTag(data, tagName, tasks)` to update tasks for a specific tag
- ❌ DON'T: Directly manipulate the tagged structure in core functions
```javascript
// ✅ DO: Use tag resolution functions
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Manipulate tasks as normal...
// Save back to the tagged structure
setTasksForTag(tasksData, currentTag, tasks);
writeJSON(tasksPath, tasksData);
```
- **Subtask Structure**:
- ✅ DO: Use consistent properties across subtasks
- ✅ DO: Maintain simple numeric IDs within parent tasks
@@ -48,53 +77,56 @@ alwaysApply: false
## Task Creation and Parsing
- **ID Management**:
- ✅ DO: Assign unique sequential IDs to tasks
- ✅ DO: Calculate the next ID based on existing tasks
- ❌ DON'T: Hardcode or reuse IDs
- ✅ DO: Assign unique sequential IDs to tasks within each tag context
- ✅ DO: Calculate the next ID based on existing tasks in the current tag
- ❌ DON'T: Hardcode or reuse IDs within the same tag
```javascript
// ✅ DO: Calculate the next available ID
const highestId = Math.max(...data.tasks.map(t => t.id));
// ✅ DO: Calculate the next available ID within the current tag
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
const highestId = Math.max(...tasks.map(t => t.id));
const nextTaskId = highestId + 1;
```
- **PRD Parsing**:
- ✅ DO: Extract tasks from PRD documents using AI
- ✅ DO: Create tasks in the current tag context (defaults to "master")
- ✅ DO: Provide clear prompts to guide AI task generation
- ✅ DO: Validate and clean up AI-generated tasks
```javascript
// ✅ DO: Validate AI responses
try {
// Parse the JSON response
taskData = JSON.parse(jsonContent);
// Check that we have the required fields
if (!taskData.title || !taskData.description) {
throw new Error("Missing required fields in the generated task");
}
} catch (error) {
log('error', "Failed to parse AI's response as valid task JSON:", error);
process.exit(1);
}
// ✅ DO: Parse into current tag context
const tasksData = readJSON(tasksPath) || {};
const currentTag = getCurrentTag() || 'master';
// Parse tasks and add to current tag
const newTasks = await parseTasksFromPRD(prdContent);
setTasksForTag(tasksData, currentTag, newTasks);
writeJSON(tasksPath, tasksData);
```
## Task Updates and Modifications
- **Status Management**:
- ✅ DO: Provide functions for updating task status
- ✅ DO: Provide functions for updating task status within current tag context
- ✅ DO: Handle both individual tasks and subtasks
- ✅ DO: Consider subtask status when updating parent tasks
```javascript
// ✅ DO: Handle status updates for both tasks and subtasks
// ✅ DO: Handle status updates within tagged context
async function setTaskStatus(tasksPath, taskIdInput, newStatus) {
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Check if it's a subtask (e.g., "1.2")
if (taskIdInput.includes('.')) {
const [parentId, subtaskId] = taskIdInput.split('.').map(id => parseInt(id, 10));
// Find the parent task and subtask
const parentTask = data.tasks.find(t => t.id === parentId);
const parentTask = tasks.find(t => t.id === parentId);
const subtask = parentTask.subtasks.find(st => st.id === subtaskId);
// Update subtask status
@@ -109,7 +141,7 @@ alwaysApply: false
}
} else {
// Handle regular task
const task = data.tasks.find(t => t.id === parseInt(taskIdInput, 10));
const task = tasks.find(t => t.id === parseInt(taskIdInput, 10));
task.status = newStatus;
// If marking as done, also mark subtasks
@@ -119,16 +151,24 @@ alwaysApply: false
});
}
}
// Save updated tasks back to tagged structure
setTasksForTag(tasksData, currentTag, tasks);
writeJSON(tasksPath, tasksData);
}
```
- **Task Expansion**:
- ✅ DO: Use AI to generate detailed subtasks
- ✅ DO: Use AI to generate detailed subtasks within current tag context
- ✅ DO: Consider complexity analysis for subtask counts
- ✅ DO: Ensure proper IDs for newly created subtasks
```javascript
// ✅ DO: Generate appropriate subtasks based on complexity
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
if (taskAnalysis) {
log('info', `Found complexity analysis for task ${taskId}: Score ${taskAnalysis.complexityScore}/10`);
@@ -138,6 +178,11 @@ alwaysApply: false
log('info', `Using recommended number of subtasks: ${numSubtasks}`);
}
}
// Generate subtasks and save back
// ... subtask generation logic ...
setTasksForTag(tasksData, currentTag, tasks);
writeJSON(tasksPath, tasksData);
```
## Task File Generation
@@ -155,67 +200,65 @@ alwaysApply: false
// Format dependencies with their status
if (task.dependencies && task.dependencies.length > 0) {
content += `# Dependencies: ${formatDependenciesWithStatus(task.dependencies, data.tasks)}\n`;
content += `# Dependencies: ${formatDependenciesWithStatus(task.dependencies, tasks)}\n`;
} else {
content += '# Dependencies: None\n';
}
```
- **Subtask Inclusion**:
- ✅ DO: Include subtasks in parent task files
- ✅ DO: Use consistent indentation for subtask sections
- DO: Display subtask dependencies with proper formatting
- **Tagged Context Awareness**:
- ✅ DO: Generate task files from current tag context
- ✅ DO: Include tag information in generated files
- DON'T: Mix tasks from different tags in file generation
```javascript
// ✅ DO: Format subtasks correctly in task files
if (task.subtasks && task.subtasks.length > 0) {
content += '\n# Subtasks:\n';
// ✅ DO: Generate files for current tag context
async function generateTaskFiles(tasksPath, outputDir) {
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
task.subtasks.forEach(subtask => {
content += `## ${subtask.id}. ${subtask.title} [${subtask.status || 'pending'}]\n`;
// Format subtask dependencies
if (subtask.dependencies && subtask.dependencies.length > 0) {
// Format the dependencies
content += `### Dependencies: ${formattedDeps}\n`;
} else {
content += '### Dependencies: None\n';
}
content += `### Description: ${subtask.description || ''}\n`;
content += '### Details:\n';
content += (subtask.details || '').split('\n').map(line => line).join('\n');
content += '\n\n';
});
// Add tag context to file header
let content = `# Tag Context: ${currentTag}\n`;
content += `# Task ID: ${task.id}\n`;
// ... rest of file generation
}
```
## Task Listing and Display
- **Filtering and Organization**:
- ✅ DO: Allow filtering tasks by status
- ✅ DO: Allow filtering tasks by status within current tag context
- ✅ DO: Handle subtask display in lists
- ✅ DO: Use consistent table formats
```javascript
// ✅ DO: Implement clear filtering and organization
// ✅ DO: Implement clear filtering within tag context
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Filter tasks by status if specified
const filteredTasks = statusFilter
? data.tasks.filter(task =>
? tasks.filter(task =>
task.status && task.status.toLowerCase() === statusFilter.toLowerCase())
: data.tasks;
: tasks;
```
- **Progress Tracking**:
- ✅ DO: Calculate and display completion statistics
- ✅ DO: Calculate and display completion statistics for current tag
- ✅ DO: Track both task and subtask completion
- ✅ DO: Use visual progress indicators
```javascript
// ✅ DO: Track and display progress
// ✅ DO: Track and display progress within tag context
const tasksData = readJSON(tasksPath);
const currentTag = getCurrentTag() || 'master';
const tasks = getTasksForTag(tasksData, currentTag);
// Calculate completion statistics
const totalTasks = data.tasks.length;
const completedTasks = data.tasks.filter(task =>
const totalTasks = tasks.length;
const completedTasks = tasks.filter(task =>
task.status === 'done' || task.status === 'completed').length;
const completionPercentage = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;
@@ -223,7 +266,7 @@ alwaysApply: false
let totalSubtasks = 0;
let completedSubtasks = 0;
data.tasks.forEach(task => {
tasks.forEach(task => {
if (task.subtasks && task.subtasks.length > 0) {
totalSubtasks += task.subtasks.length;
completedSubtasks += task.subtasks.filter(st =>
@@ -232,99 +275,52 @@ alwaysApply: false
});
```
## Complexity Analysis
## Migration and Compatibility
- **Scoring System**:
- ✅ DO: Use AI to analyze task complexity
- ✅ DO: Include complexity scores (1-10)
- ✅ DO: Generate specific expansion recommendations
- **Silent Migration Handling**:
- ✅ DO: Implement silent migration in `readJSON()` function
- ✅ DO: Detect legacy format and convert automatically
- ✅ DO: Preserve all existing task data during migration
```javascript
// ✅ DO: Handle complexity analysis properly
const report = {
meta: {
generatedAt: new Date().toISOString(),
tasksAnalyzed: tasksData.tasks.length,
thresholdScore: thresholdScore,
projectName: tasksData.meta?.projectName || 'Your Project Name',
usedResearch: useResearch
},
complexityAnalysis: complexityAnalysis
};
```
- **Analysis-Based Workflow**:
- ✅ DO: Use complexity reports to guide task expansion
- ✅ DO: Prioritize complex tasks for more detailed breakdown
- ✅ DO: Use expansion prompts from complexity analysis
```javascript
// ✅ DO: Apply complexity analysis to workflow
// Sort tasks by complexity if report exists, otherwise by ID
if (complexityReport && complexityReport.complexityAnalysis) {
log('info', 'Sorting tasks by complexity...');
// ✅ DO: Handle silent migration (implemented in utils.js)
function readJSON(filepath) {
let data = JSON.parse(fs.readFileSync(filepath, 'utf8'));
// Create a map of task IDs to complexity scores
const complexityMap = new Map();
complexityReport.complexityAnalysis.forEach(analysis => {
complexityMap.set(analysis.taskId, analysis.complexityScore);
});
// Silent migration for tasks.json files
if (data.tasks && Array.isArray(data.tasks) && !data.master && isTasksFile) {
const migratedData = {
master: {
tasks: data.tasks
}
};
writeJSON(filepath, migratedData);
data = migratedData;
}
// Sort tasks by complexity score (high to low)
tasksToExpand.sort((a, b) => {
const scoreA = complexityMap.get(a.id) || 0;
const scoreB = complexityMap.get(b.id) || 0;
return scoreB - scoreA;
});
return data;
}
```
## Next Task Selection
- **Eligibility Criteria**:
- DO: Consider dependencies when finding next tasks
- ✅ DO: Prioritize by task priority and dependency count
- ✅ DO: Skip completed tasks
- **Tag Resolution**:
- ✅ DO: Use tag resolution functions to maintain backward compatibility
- ✅ DO: Return legacy format to core functions
- DON'T: Expose tagged structure to existing core logic
```javascript
// ✅ DO: Use proper task prioritization logic
function findNextTask(tasks) {
// Get all completed task IDs
const completedTaskIds = new Set(
tasks
.filter(t => t.status === 'done' || t.status === 'completed')
.map(t => t.id)
);
// ✅ DO: Use tag resolution layer
function getTasksForTag(data, tagName) {
if (data.tasks && Array.isArray(data.tasks)) {
// Legacy format - return as-is
return data.tasks;
}
// Filter for pending tasks whose dependencies are all satisfied
const eligibleTasks = tasks.filter(task =>
(task.status === 'pending' || task.status === 'in-progress') &&
task.dependencies &&
task.dependencies.every(depId => completedTaskIds.has(depId))
);
if (data[tagName] && data[tagName].tasks) {
// Tagged format - return tasks for specified tag
return data[tagName].tasks;
}
// Sort by priority, dependency count, and ID
const priorityValues = { 'high': 3, 'medium': 2, 'low': 1 };
const nextTask = eligibleTasks.sort((a, b) => {
// Priority first
const priorityA = priorityValues[a.priority || 'medium'] || 2;
const priorityB = priorityValues[b.priority || 'medium'] || 2;
if (priorityB !== priorityA) {
return priorityB - priorityA; // Higher priority first
}
// Dependency count next
if (a.dependencies.length !== b.dependencies.length) {
return a.dependencies.length - b.dependencies.length; // Fewer dependencies first
}
// ID last
return a.id - b.id; // Lower ID first
})[0];
return nextTask;
return [];
}
```

View File

@@ -150,4 +150,91 @@ alwaysApply: false
));
```
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.
## Enhanced Display Patterns
### **Token Breakdown Display**
- Use detailed, granular token breakdowns for AI-powered commands
- Display context sources with individual token counts
- Show both token count and character count for transparency
```javascript
// ✅ DO: Display detailed token breakdown
function displayDetailedTokenBreakdown(tokenBreakdown, systemTokens, userTokens) {
const sections = [];
if (tokenBreakdown.tasks?.length > 0) {
const taskDetails = tokenBreakdown.tasks.map(task =>
`${task.type === 'subtask' ? ' ' : ''}${task.id}: ${task.tokens.toLocaleString()}`
).join('\n');
sections.push(`Tasks (${tokenBreakdown.tasks.reduce((sum, t) => sum + t.tokens, 0).toLocaleString()}):\n${taskDetails}`);
}
const content = sections.join('\n\n');
console.log(boxen(content, {
title: chalk.cyan('Token Usage'),
padding: { top: 1, bottom: 1, left: 2, right: 2 },
borderStyle: 'round',
borderColor: 'cyan'
}));
}
```
### **Code Block Syntax Highlighting**
- Use `cli-highlight` library for syntax highlighting in terminal output
- Process code blocks in AI responses for better readability
```javascript
// ✅ DO: Enhance code blocks with syntax highlighting
import { highlight } from 'cli-highlight';
function processCodeBlocks(text) {
return text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
try {
const highlighted = highlight(code.trim(), {
language: language || 'javascript',
theme: 'default'
});
return `\n${highlighted}\n`;
} catch (error) {
return `\n${code.trim()}\n`;
}
});
}
```
### **Multi-Section Result Display**
- Use separate boxes for headers, content, and metadata
- Maintain consistent styling across different result types
```javascript
// ✅ DO: Use structured result display
function displayResults(result, query, detailLevel) {
// Header with query info
const header = boxen(
chalk.green.bold('Research Results') + '\n\n' +
chalk.gray('Query: ') + chalk.white(query) + '\n' +
chalk.gray('Detail Level: ') + chalk.cyan(detailLevel),
{
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 1, bottom: 0 },
borderStyle: 'round',
borderColor: 'green'
}
);
console.log(header);
// Process and display main content
const processedResult = processCodeBlocks(result);
const contentBox = boxen(processedResult, {
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderStyle: 'single',
borderColor: 'gray'
});
console.log(contentBox);
console.log(chalk.green('✓ Operation complete'));
}
```
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples, [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc) for context display patterns, and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.

View File

@@ -1,6 +1,6 @@
---
description: Guidelines for implementing utility functions
globs: scripts/modules/utils.js, mcp-server/src/**/*
description:
globs:
alwaysApply: false
---
# Utility Function Guidelines
@@ -46,7 +46,7 @@ alwaysApply: false
- **Location**:
- **Core CLI Utilities**: Place utilities used primarily by the core `task-master` CLI logic and command modules (`scripts/modules/*`) into [`scripts/modules/utils.js`](mdc:scripts/modules/utils.js).
- **MCP Server Utilities**: Place utilities specifically designed to support the MCP server implementation into the appropriate subdirectories within `mcp-server/src/`.
- Path/Core Logic Helpers: [`mcp-server/src/core/utils/`](mdc:mcp-server/src/core/utils/) (e.g., `path-utils.js`).
- Path/Core Logic Helpers: [`mcp-server/src/core/utils/`](mdc:mcp-server/src/core/utils) (e.g., `path-utils.js`).
- Tool Execution/Response Helpers: [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
## Documentation Standards
@@ -110,7 +110,7 @@ Taskmaster configuration (excluding API keys) is primarily managed through the `
- ✅ DO: Use appropriate icons for different log levels
- ✅ DO: Respect the configured log level
- ❌ DON'T: Add direct console.log calls outside the logging utility
- **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions.
- **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](mdc:...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions.
- **Logger Wrapper Pattern**:
- ✅ DO: Use the logger wrapper pattern when passing loggers to prevent `mcpLog[level] is not a function` errors:
@@ -548,4 +548,628 @@ export {
};
```
Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for more context on MCP server architecture and integration.
## Context Gathering Utilities
### **ContextGatherer** (`scripts/modules/utils/contextGatherer.js`)
- **Multi-Source Context Extraction**:
- ✅ DO: Use for AI-powered commands that need project context
- ✅ DO: Support tasks, files, custom text, and project tree context
- ✅ DO: Implement detailed token counting with `gpt-tokens` library
- ✅ DO: Provide multiple output formats (research, chat, system-prompt)
```javascript
// ✅ DO: Use ContextGatherer for consistent context extraction
import { ContextGatherer } from '../utils/contextGatherer.js';
const gatherer = new ContextGatherer(projectRoot, tasksPath);
const result = await gatherer.gather({
tasks: ['15', '16.2'],
files: ['src/api.js'],
customContext: 'Additional context',
includeProjectTree: true,
format: 'research',
includeTokenCounts: true
});
```
### **FuzzyTaskSearch** (`scripts/modules/utils/fuzzyTaskSearch.js`)
- **Intelligent Task Discovery**:
- ✅ DO: Use for automatic task relevance detection
- ✅ DO: Configure search parameters based on use case context
- ✅ DO: Implement purpose-based categorization for better matching
- ✅ DO: Sort results by relevance score and task ID
```javascript
// ✅ DO: Use FuzzyTaskSearch for intelligent task discovery
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
const searchResults = fuzzySearch.findRelevantTasks(query, {
maxResults: 8,
includeRecent: true,
includeCategoryMatches: true
});
const taskIds = fuzzySearch.getTaskIds(searchResults);
```
- **Integration Guidelines**:
- ✅ DO: Use fuzzy search to supplement user-provided task IDs
- ✅ DO: Display discovered task IDs to users for transparency
- ✅ DO: Sort discovered task IDs numerically for better readability
- ❌ DON'T: Replace explicit user task selections with fuzzy results
Refer to [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc) for detailed implementation patterns, [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for more context on MCP server architecture and integration.
## File System Operations
- **JSON File Handling**:
- ✅ DO: Use `readJSON` and `writeJSON` for all JSON operations
- ✅ DO: Include error handling for file operations
- ✅ DO: Validate JSON structure after reading
- ❌ DON'T: Use raw `fs.readFileSync` or `fs.writeFileSync` for JSON
```javascript
// ✅ DO: Use utility functions with error handling
function readJSON(filepath) {
try {
if (!fs.existsSync(filepath)) {
return null; // or appropriate default
}
let data = JSON.parse(fs.readFileSync(filepath, 'utf8'));
// Silent migration for tasks.json files: Transform old format to tagged format
const isTasksFile = filepath.includes('tasks.json') || path.basename(filepath) === 'tasks.json';
if (data && data.tasks && Array.isArray(data.tasks) && !data.master && isTasksFile) {
// Migrate from old format { "tasks": [...] } to new format { "master": { "tasks": [...] } }
const migratedData = {
master: {
tasks: data.tasks
}
};
writeJSON(filepath, migratedData);
// Set global flag for CLI notice and perform complete migration
global.taskMasterMigrationOccurred = true;
performCompleteTagMigration(filepath);
data = migratedData;
}
return data;
} catch (error) {
log('error', `Failed to read JSON from ${filepath}: ${error.message}`);
return null;
}
}
function writeJSON(filepath, data) {
try {
const dirPath = path.dirname(filepath);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
fs.writeFileSync(filepath, JSON.stringify(data, null, 2));
} catch (error) {
log('error', `Failed to write JSON to ${filepath}: ${error.message}`);
throw error;
}
}
```
- **Path Resolution**:
- ✅ DO: Use `path.join()` for cross-platform path construction
- ✅ DO: Use `path.resolve()` for absolute paths
- ✅ DO: Validate paths before file operations
```javascript
// ✅ DO: Handle paths correctly
function findProjectRoot(startPath = process.cwd()) {
let currentPath = path.resolve(startPath);
const rootPath = path.parse(currentPath).root;
while (currentPath !== rootPath) {
const taskMasterPath = path.join(currentPath, '.taskmaster');
if (fs.existsSync(taskMasterPath)) {
return currentPath;
}
currentPath = path.dirname(currentPath);
}
return null; // Not found
}
```
## Tagged Task Lists System Utilities
- **Tag Resolution Functions**:
- ✅ DO: Use tag resolution layer for all task data access
- ✅ DO: Provide backward compatibility with legacy format
- ✅ DO: Default to "master" tag when no tag is specified
```javascript
// ✅ DO: Implement tag resolution functions
function getTasksForTag(data, tagName = 'master') {
if (!data) {
return [];
}
// Handle legacy format - direct tasks array
if (data.tasks && Array.isArray(data.tasks)) {
return data.tasks;
}
// Handle tagged format - tasks under specific tag
if (data[tagName] && data[tagName].tasks && Array.isArray(data[tagName].tasks)) {
return data[tagName].tasks;
}
return [];
}
function setTasksForTag(data, tagName = 'master', tasks) {
// Ensure data object exists
if (!data) {
data = {};
}
// Create tag structure if it doesn't exist
if (!data[tagName]) {
data[tagName] = {};
}
// Set tasks for the tag
data[tagName].tasks = tasks;
return data;
}
function getCurrentTag() {
// Get current tag from state.json or default to 'master'
try {
const projectRoot = findProjectRoot();
if (!projectRoot) return 'master';
const statePath = path.join(projectRoot, '.taskmaster', 'state.json');
if (fs.existsSync(statePath)) {
const state = readJSON(statePath);
return state.currentTag || 'master';
}
} catch (error) {
log('debug', `Error reading current tag: ${error.message}`);
}
return 'master';
}
```
- **Migration Functions**:
- ✅ DO: Implement complete migration for all related files
- ✅ DO: Handle configuration and state file creation
- ✅ DO: Provide migration status tracking
```javascript
// ✅ DO: Implement complete migration system
function performCompleteTagMigration(tasksJsonPath) {
try {
// Derive project root from tasks.json path
const projectRoot = findProjectRoot(path.dirname(tasksJsonPath)) || path.dirname(tasksJsonPath);
// 1. Migrate config.json - add defaultTag and tags section
const configPath = path.join(projectRoot, '.taskmaster', 'config.json');
if (fs.existsSync(configPath)) {
migrateConfigJson(configPath);
}
// 2. Create state.json if it doesn't exist
const statePath = path.join(projectRoot, '.taskmaster', 'state.json');
if (!fs.existsSync(statePath)) {
createStateJson(statePath);
}
if (getDebugFlag()) {
log('debug', 'Completed tagged task lists migration for project');
}
} catch (error) {
if (getDebugFlag()) {
log('warn', `Error during complete tag migration: ${error.message}`);
}
}
}
function migrateConfigJson(configPath) {
try {
const config = readJSON(configPath);
if (!config) return;
let modified = false;
// Add global.defaultTag if missing
if (!config.global) {
config.global = {};
}
if (!config.global.defaultTag) {
config.global.defaultTag = 'master';
modified = true;
}
// Add tags section if missing
if (!config.tags) {
config.tags = {
// Git integration settings removed - now manual only
};
modified = true;
}
if (modified) {
writeJSON(configPath, config);
if (getDebugFlag()) {
log('debug', 'Updated config.json with tagged task system settings');
}
}
} catch (error) {
if (getDebugFlag()) {
log('warn', `Error migrating config.json: ${error.message}`);
}
}
}
function createStateJson(statePath) {
try {
const initialState = {
currentTag: 'master',
lastSwitched: new Date().toISOString(),
migrationNoticeShown: false
};
writeJSON(statePath, initialState);
if (getDebugFlag()) {
log('debug', 'Created initial state.json for tagged task system');
}
} catch (error) {
if (getDebugFlag()) {
log('warn', `Error creating state.json: ${error.message}`);
}
}
}
function markMigrationForNotice() {
try {
const projectRoot = findProjectRoot();
if (!projectRoot) return;
const statePath = path.join(projectRoot, '.taskmaster', 'state.json');
const state = readJSON(statePath) || {};
state.migrationNoticeShown = false; // Reset to show notice
writeJSON(statePath, state);
} catch (error) {
if (getDebugFlag()) {
log('warn', `Error marking migration for notice: ${error.message}`);
}
}
}
```
## Logging Functions
- **Consistent Logging**:
- ✅ DO: Use the central `log` function for all output
- ✅ DO: Use appropriate log levels (info, warn, error, debug)
- ✅ DO: Support silent mode for programmatic usage
```javascript
// ✅ DO: Implement consistent logging with silent mode
let silentMode = false;
function log(level, ...messages) {
if (silentMode && level !== 'error') {
return; // Suppress non-error logs in silent mode
}
const timestamp = new Date().toISOString();
const formattedMessage = messages.join(' ');
switch (level) {
case 'error':
console.error(`[ERROR] ${formattedMessage}`);
break;
case 'warn':
console.warn(`[WARN] ${formattedMessage}`);
break;
case 'info':
console.log(`[INFO] ${formattedMessage}`);
break;
case 'debug':
if (getDebugFlag()) {
console.log(`[DEBUG] ${formattedMessage}`);
}
break;
default:
console.log(formattedMessage);
}
}
function enableSilentMode() {
silentMode = true;
}
function disableSilentMode() {
silentMode = false;
}
function isSilentMode() {
return silentMode;
}
```
## Task Utilities
- **Task Finding and Manipulation**:
- ✅ DO: Use tagged task system aware functions
- ✅ DO: Handle both task and subtask operations
- ✅ DO: Validate task IDs before operations
```javascript
// ✅ DO: Implement tag-aware task utilities
function findTaskById(tasks, taskId) {
if (!Array.isArray(tasks)) {
return null;
}
return tasks.find(task => task.id === taskId) || null;
}
function findSubtaskById(tasks, parentId, subtaskId) {
const parentTask = findTaskById(tasks, parentId);
if (!parentTask || !parentTask.subtasks) {
return null;
}
return parentTask.subtasks.find(subtask => subtask.id === subtaskId) || null;
}
function getNextTaskId(tasks) {
if (!Array.isArray(tasks) || tasks.length === 0) {
return 1;
}
const maxId = Math.max(...tasks.map(task => task.id));
return maxId + 1;
}
function getNextSubtaskId(parentTask) {
if (!parentTask.subtasks || parentTask.subtasks.length === 0) {
return 1;
}
const maxId = Math.max(...parentTask.subtasks.map(subtask => subtask.id));
return maxId + 1;
}
```
## String Utilities
- **Text Processing**:
- ✅ DO: Handle text truncation appropriately
- ✅ DO: Provide consistent formatting functions
- ✅ DO: Support different output formats
```javascript
// ✅ DO: Implement useful string utilities
function truncate(str, maxLength = 50) {
if (!str || typeof str !== 'string') {
return '';
}
if (str.length <= maxLength) {
return str;
}
return str.substring(0, maxLength - 3) + '...';
}
function formatDuration(ms) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
} else if (minutes > 0) {
return `${minutes}m ${seconds % 60}s`;
} else {
return `${seconds}s`;
}
}
function capitalizeFirst(str) {
if (!str || typeof str !== 'string') {
return '';
}
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
```
## Dependency Management Utilities
- **Dependency Analysis**:
- ✅ DO: Detect circular dependencies
- ✅ DO: Validate dependency references
- ✅ DO: Support cross-tag dependency checking (future enhancement)
```javascript
// ✅ DO: Implement dependency utilities
function findCycles(tasks) {
const cycles = [];
const visited = new Set();
const recStack = new Set();
function dfs(taskId, path = []) {
if (recStack.has(taskId)) {
// Found a cycle
const cycleStart = path.indexOf(taskId);
const cycle = path.slice(cycleStart).concat([taskId]);
cycles.push(cycle);
return;
}
if (visited.has(taskId)) {
return;
}
visited.add(taskId);
recStack.add(taskId);
const task = findTaskById(tasks, taskId);
if (task && task.dependencies) {
task.dependencies.forEach(depId => {
dfs(depId, path.concat([taskId]));
});
}
recStack.delete(taskId);
}
tasks.forEach(task => {
if (!visited.has(task.id)) {
dfs(task.id);
}
});
return cycles;
}
function validateDependencies(tasks) {
const validationErrors = [];
const taskIds = new Set(tasks.map(task => task.id));
tasks.forEach(task => {
if (task.dependencies) {
task.dependencies.forEach(depId => {
if (!taskIds.has(depId)) {
validationErrors.push({
taskId: task.id,
invalidDependency: depId,
message: `Task ${task.id} depends on non-existent task ${depId}`
});
}
});
}
});
return validationErrors;
}
```
## Environment and Configuration Utilities
- **Environment Variable Resolution**:
- ✅ DO: Support both `.env` files and MCP session environment
- ✅ DO: Provide fallbacks for missing values
- ✅ DO: Handle API key resolution correctly
```javascript
// ✅ DO: Implement flexible environment resolution
function resolveEnvVariable(key, sessionEnv = null) {
// First check session environment (for MCP)
if (sessionEnv && sessionEnv[key]) {
return sessionEnv[key];
}
// Then check process environment
if (process.env[key]) {
return process.env[key];
}
// Finally try .env file if in project root
try {
const projectRoot = findProjectRoot();
if (projectRoot) {
const envPath = path.join(projectRoot, '.env');
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, 'utf8');
const lines = envContent.split('\n');
for (const line of lines) {
const [envKey, envValue] = line.split('=');
if (envKey && envKey.trim() === key) {
return envValue ? envValue.trim().replace(/^["']|["']$/g, '') : undefined;
}
}
}
}
} catch (error) {
log('debug', `Error reading .env file: ${error.message}`);
}
return undefined;
}
function getDebugFlag() {
const debugFlag = resolveEnvVariable('TASKMASTER_DEBUG') ||
resolveEnvVariable('DEBUG') ||
'false';
return debugFlag.toLowerCase() === 'true';
}
```
## Export Pattern
- **Module Exports**:
- ✅ DO: Export all utility functions explicitly
- ✅ DO: Group related functions logically
- ✅ DO: Include new tagged system utilities
```javascript
// ✅ DO: Export utilities in logical groups
module.exports = {
// File system utilities
readJSON,
writeJSON,
findProjectRoot,
// Tagged task system utilities
getTasksForTag,
setTasksForTag,
getCurrentTag,
performCompleteTagMigration,
migrateConfigJson,
createStateJson,
markMigrationForNotice,
// Logging utilities
log,
enableSilentMode,
disableSilentMode,
isSilentMode,
// Task utilities
findTaskById,
findSubtaskById,
getNextTaskId,
getNextSubtaskId,
// String utilities
truncate,
formatDuration,
capitalizeFirst,
// Dependency utilities
findCycles,
validateDependencies,
// Environment utilities
resolveEnvVariable,
getDebugFlag,
// Legacy utilities (maintained for compatibility)
aggregateTelemetry
};
```
Refer to [`utils.js`](mdc:scripts/modules/utils.js) for implementation examples and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for integration patterns.

19
.gitignore vendored
View File

@@ -19,13 +19,26 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
tests/e2e/_runs/
tests/e2e/log/
# Coverage directory used by tools like istanbul
coverage
coverage/
*.lcov
# Jest cache
.jest/
# Test temporary files and directories
tests/temp/
tests/e2e/_runs/
tests/e2e/log/
tests/**/*.log
tests/**/coverage/
# Test database files (if any)
tests/**/*.db
tests/**/*.sqlite
tests/**/*.sqlite3
# Optional npm cache directory
.npm

View File

@@ -28,6 +28,7 @@
"projectName": "Taskmaster",
"ollamaBaseURL": "http://localhost:11434/api",
"bedrockBaseURL": "https://bedrock.us-east-1.amazonaws.com",
"azureBaseURL": "https://your-endpoint.azure.com/"
"azureBaseURL": "https://your-endpoint.azure.com/",
"defaultTag": "master"
}
}

View File

@@ -0,0 +1,128 @@
---
title: Research Session
query: "how can i improve the scope-up and scope-down command"
date: 6/14/2025
time: 4:35:03 PM
timestamp: 2025-06-14T20:35:03.231Z
exchanges: 2
---
# Research Session
## Initial Query
**Question:** how can i improve the scope-up and scope-down command
**Response:**
## Improving the `scope-up` and `scope-down` Commands
**Clarify Command Purpose and User Experience**
- Ensure the commands have clear, intuitive behavior. For example, `scope-up` should consistently broaden the context or task view, while `scope-down` should reliably narrow it.
- Provide immediate, user-friendly feedback after each command, indicating what changed (e.g., "Now viewing parent task and all subtasks" or "Focused on subtask: X").
- Document the commands with examples in your `docs/command-reference.md` and `docs/examples.md` to help users understand their effects and use cases.
**Enhance Context Awareness**
- Make the commands context-sensitive: if the user is already at the top or bottom of the scope hierarchy, return a helpful message instead of failing silently.
- Allow optional arguments to specify the exact level or target (e.g., `scope-up 2` to move up two levels, or `scope-down <subtask-id>` to jump directly to a subtask).
**Robust Error Handling and Validation**
- Implement checks to prevent invalid operations, such as attempting to scope up from the root or scope down when no subtasks exist.
- Provide clear error messages and suggestions for next steps, improving user trust and reducing confusion[1][5].
**Integrate with Task and Tag Systems**
- Ensure `scope-up` and `scope-down` interact smoothly with your tagging and task hierarchy features. For example, scoping up from a subtask should show the parent task and its context, while scoping down should allow selection from available subtasks or related tags.
- Consider supporting batch operations, such as scoping down into all subtasks and displaying them in a summarized view.
**Improve Performance and Synchronization**
- Optimize the underlying logic to minimize delays, especially in large task trees. Use asynchronous operations where possible to keep the UI responsive.
- If the commands trigger data loading or context switching, ensure synchronization so that subsequent commands operate on the correct, updated context[2][4].
**Testing and Stakeholder Feedback**
- Add or expand unit and integration tests for these commands (see `tests/unit/commands.test.js` and `integration/cli/commands.test.js`) to cover edge cases and ensure reliability.
- Gather feedback from users and stakeholders to identify pain points and desired enhancements, then iterate on the command design and implementation[1][5].
**Example Improvements Table**
| Area | Current Issue | Suggested Improvement |
|---------------------|-----------------------------|----------------------------------------------|
| User Feedback | Minimal or unclear output | Add explicit, contextual messages |
| Error Handling | Silent failures | Informative errors and recovery suggestions |
| Flexibility | Only single-level movement | Support multi-level and targeted navigation |
| Integration | Limited context awareness | Sync with tags, parent/child relationships |
| Performance | Slow on large hierarchies | Optimize data access and UI updates |
By focusing on these areas, you can make `scope-up` and `scope-down` more robust, user-friendly, and aligned with best practices in scope management and command design[1][5].
---
## Follow-up 1
**Question:** how might i do this relative to the tag system?
**Response:**
## Integrating Scope-Up and Scope-Down with the Tag System
**Conceptual Mapping**
- In your project, *scope-up* and *scope-down* commands currently operate on the task hierarchy, broadening or narrowing the context by moving between parent and child tasks.
- The tag system provides a parallel, orthogonal way to group and filter tasks—tags can represent categories, priorities, or any custom grouping, independent of strict parent/child relationships.
**How to Make Scope Commands Tag-Aware**
- **Scoping by Tag**: Allow users to "scope-down" into a tag, viewing only tasks associated with that tag. Conversely, "scope-up" could move from a specific tag context back to the broader task list or to a parent tag grouping if you support tag hierarchies.
- **Tag-Scoped Views**: When a tag is active as the current scope, all navigation and operations (listing, editing, etc.) are limited to tasks with that tag. This is similar to how some systems let you set the "Tag Scope" to filter navigation and search to only tagged items[1][5].
- **Combining Hierarchy and Tags**: Enable compound scoping, such as "all subtasks of Task X that also have Tag Y." This can be implemented by intersecting the results of hierarchical and tag-based queries.
**Implementation Strategies**
- **Scope Stack or Context Object**: Maintain a stack or context object that tracks both the current task scope and any active tag filters. Each scope change (up/down or tag in/out) updates this context.
- **Commands**:
- `scope-down --tag <tag>`: Narrows the view to tasks with the specified tag.
- `scope-up --tag`: Removes the tag filter, broadening the view.
- `scope-down <subtask-id> --tag <tag>`: Narrows to a specific subtask *and* applies a tag filter.
- **Tag Hierarchies (Optional)**: If your tag system supports parent/child tags or tag groups, allow "scope-up" to move from a specific tag to its parent tag or group, and "scope-down" to move into a child tag[4][5].
**Example User Flows**
- *Scoping Down by Tag*:
User runs `scope-down --tag urgent` → Only tasks tagged "urgent" are shown.
- *Combining Task and Tag*:
User runs `scope-down <task-id> --tag frontend` → Only subtasks of `<task-id>` that are tagged "frontend" are shown.
- *Scoping Up from Tag*:
User runs `scope-up --tag` → Removes the tag filter, returning to the previous broader context.
**Technical Considerations**
- **Efficient Filtering**: Use indexed queries or in-memory filtering to efficiently combine tag and hierarchy filters, especially for large task sets.
- **Feedback and UI**: Always display the current scope context (e.g., "Viewing tasks tagged 'urgent' under 'Feature X'") so users understand what they're seeing.
- **Extensibility**: Design the scope system so new types of scopes (e.g., by status, assignee) can be added in the future, not just tags and hierarchy.
**Relevant Precedents**
- Tag-based file systems and management tools often implement "scopes" as dynamic groups defined by tag criteria, allowing users to build up complex views by combining tags and other filters[5].
- Some systems allow scoping into tag management itself, where you can create, edit, or view tags and their associated objects, which could be mirrored in your CLI or UI[4].
**Summary Table**
| Command Example | Resulting Scope |
|----------------------------------|--------------------------------------------------|
| `scope-down --tag bug` | All tasks tagged "bug" |
| `scope-down <task-id> --tag api` | Subtasks of `<task-id>` tagged "api" |
| `scope-up --tag` | Removes tag filter, returns to previous scope |
| `scope-down --tag frontend` | All tasks tagged "frontend" |
By integrating tag-based scoping, you make your scope commands more flexible and powerful, supporting both hierarchical and ad-hoc organizational strategies[1][5].
---
*Generated by Task Master Research Command*
*Timestamp: 2025-06-14T20:35:03.231Z*

View File

@@ -0,0 +1,158 @@
---
title: Research Session
query: "should i be using any specific libraries for this?"
date: 6/14/2025
time: 5:20:00 PM
timestamp: 2025-06-14T21:20:00.561Z
exchanges: 2
---
# Research Session
## Initial Query
**Question:** should i be using any specific libraries for this?
**Response:**
HELL YEAH PARTNER
For implementing a GitHub Issue export feature with bidirectional linking in your project, you absolutely should use a dedicated library for interacting with the GitHub API. This will save you a ton of time, reduce boilerplate, and help you avoid common pitfalls with authentication, pagination, and error handling.
## Recommended Library: PyGithub
- **PyGithub** is the most widely used and well-documented Python library for accessing the GitHub REST API v3. It allows you to manage repositories, issues, user profiles, and more, all with a clean, object-oriented interface[1][2][3][5].
- It supports all the operations youll need for your export feature, including creating issues, updating them, and managing references for bidirectional linking.
### Key Features
- **Authentication**: Easily authenticate with a personal access token.
- **Issue Management**: Create, update, and link issues programmatically.
- **Repository Access**: Fetch and manipulate repository data.
- **User/Org Support**: Works for both user and organization repos.
- **Pagination & Rate Limiting**: Handles these for you.
### Example Usage
```python
from github import Github, Auth
# Authenticate with a personal access token
auth = Auth.Token("your_github_token")
g = Github(auth=auth)
# Get the repo
repo = g.get_repo("owner/repo_name")
# Create a new issue
issue = repo.create_issue(
title="Exported from Task Master",
body="This issue was created by Task Master. [Task ID: 123]"
)
# Add a comment or update the issue to include a backlink
issue.create_comment("Linked to Task Master task #123")
```
[3][5]
## Why Not Use Raw Requests?
- While you *can* use the `requests` library to call the GitHub API directly[4], PyGithub abstracts away authentication, error handling, and pagination, making your code much cleaner and less error-prone[2][5].
## Integration Tips
- Store your GitHub token securely (e.g., in environment variables).
- Use PyGithubs objects to fetch, create, and update issues.
- For bidirectional linking, store the GitHub issue URL in your task data and the Task Master task ID in the GitHub issue body or as a label/comment.
- PyGithub is actively maintained and widely used, so youll find plenty of support and documentation.
## Installation
```bash
pip install PyGithub
```
[3]
## Summary Table
| Library | Language | API Coverage | Ease of Use | Maintained | Docs/Support |
|-----------|----------|--------------|-------------|------------|--------------|
| PyGithub | Python | Full | High | Yes | Excellent |
| requests | Python | Full (manual)| Medium | Yes | Good |
**Use PyGithub for all GitHub API interactions in your export/import features.** Its the standard for Python projects and will make your implementation faster, safer, and more maintainable[1][2][3][5].
---
## Follow-up 1
**Question:** we don't want to use py github because we have a node project
**Response:**
HELL YEAH PARTNER
For a Node.js project, you should use a Node-native library to interact with the GitHub API instead of PyGithub, which is Python-only. The industry standard for Node.js is **Octokit**, the official GitHub SDK for JavaScript/TypeScript[1][2].
## Why Use Octokit?
- **Official & Complete**: Octokit is maintained by GitHub and covers all REST and GraphQL API endpoints, including issues, repositories, users, and more[1][2].
- **Universal**: Works in Node.js, browsers, and Deno environments[2].
- **Typed & Tested**: Comes with TypeScript declarations and 100% test coverage[2].
- **Authentication**: Supports personal access tokens, GitHub Apps, OAuth, and more.
- **Pagination & Error Handling**: Handles pagination and common error scenarios out of the box.
- **Extendable**: Supports plugins and custom hooks for advanced use cases[2].
## How to Use Octokit for GitHub Issue Export
Install Octokit in your Node.js project:
```bash
npm install @octokit/rest
```
Basic usage for creating and linking issues:
```js
const { Octokit } = require("@octokit/rest");
// Authenticate with a personal access token
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
// Create a new issue
const { data: issue } = await octokit.issues.create({
owner: "owner",
repo: "repo_name",
title: "Exported from Task Master",
body: "This issue was created by Task Master. [Task ID: 123]"
});
// Add a comment for bidirectional linking
await octokit.issues.createComment({
owner: "owner",
repo: "repo_name",
issue_number: issue.number,
body: "Linked to Task Master task #123"
});
```
## Alternatives
- **node-github**: An older library, less maintained than Octokit, but still functional for basic API access[5].
- **Raw HTTP Requests**: You can use `node-fetch` or `axios` to call the GitHub API directly, but youll need to handle authentication, pagination, and error handling yourself[3]. Octokit abstracts all of this for you.
## Summary Table
| Library | Language | API Coverage | Maintained | TypeScript | Docs/Support |
|-----------------|----------|--------------|------------|------------|--------------|
| Octokit | Node.js | Full | Yes | Yes | Excellent |
| node-github | Node.js | Full | No | No | Limited |
| Raw HTTP | Node.js | Full (manual)| N/A | N/A | N/A |
**Recommendation:** Use Octokit for all GitHub API interactions in your Node.js project. Its the official, most robust, and best-supported option for your use case[1][2].
---
*Generated by Task Master Research Command*
*Timestamp: 2025-06-14T21:20:00.561Z*

View File

@@ -0,0 +1,76 @@
---
title: Research Session
query: "test save functionality"
date: 6/14/2025
time: 5:50:23 PM
timestamp: 2025-06-14T21:50:23.797Z
exchanges: 1
---
# Research Session
## Initial Query
**Question:** test save functionality
**Response:**
## Testing Save Functionality in a Task Management System
**Core Steps for Testing Save Functionality**
- Create or update a task in the system using the CLI or UI.
- Trigger the save operation (e.g., by issuing a command or clicking a save button).
- Verify that the data is correctly written to the persistent storage (e.g., `tasks.json`).
- Reload or re-query the data to ensure the saved changes persist and are accurately reflected.
- Validate that all required fields and relationships (such as dependencies and subtasks) are preserved and correctly structured.
**Key Test Scenarios**
- **Basic Save:** Add a new task and confirm it appears in `tasks.json` with all fields populated.
- **Update Save:** Modify an existing task (e.g., change status, description, or priority) and verify the changes are saved.
- **Subtask and Dependency Preservation:** Update a parent task and ensure that completed subtasks and dependency links remain intact, especially after using commands like `updateTask`.
- **Batch Operations:** Perform bulk updates or additions and confirm all affected tasks are saved correctly, with no data loss or corruption.
- **Validation:** Attempt to save invalid data and ensure the system rejects it or provides meaningful error messages, confirming validation logic is enforced.
**Recommended Practices**
- Use automated tests to simulate save operations for various scenarios, including edge cases (e.g., circular dependencies, missing required fields).
- After each save, reload the data and compare it to the expected state to ensure integrity.
- Log all save operations and errors for traceability and debugging.
- Regularly back up the `tasks.json` file to prevent data loss during testing and development.
**Relevant Features from Industry Standards**
- Task management systems typically provide robust save and update mechanisms, ensuring that all task attributes (including dependencies, subtasks, and comments) are consistently maintained[1][2][5].
- Validation and error handling are critical to prevent corrupt or incomplete saves, especially when handling complex relationships or batch operations[1][5].
- User feedback (such as success messages or error alerts) is important for confirming save actions and guiding users in case of issues[1][2].
**Example Test Case**
1. Create a task with subtasks and dependencies.
2. Mark some subtasks as complete.
3. Use the `updateTask` command to modify the parent task.
4. Save and reload the data.
5. Assert that:
- The parent task reflects the updates.
- Completed subtasks remain marked as complete.
- Dependencies are unchanged and valid.
**Summary Table: Save Functionality Test Aspects**
| Aspect | What to Test | Expected Outcome |
|-----------------------|---------------------------------------------------|-----------------------------------------|
| Basic Save | Add/update task, save, reload | Data persists and matches expectations |
| Subtask Preservation | Update parent, check subtask status | Completed subtasks remain complete |
| Dependency Handling | Save with dependencies, reload | Dependencies are intact and valid |
| Batch Operations | Bulk save/update, reload | All changes persist, no data loss |
| Validation | Save invalid data | Error is raised, data not corrupted |
These steps and scenarios ensure that the save functionality is robust, reliable, and meets the requirements of a modern task management system[1][2][5].
---
*Generated by Task Master Research Command*
*Timestamp: 2025-06-14T21:50:23.797Z*

View File

@@ -0,0 +1,81 @@
---
title: Research Session
query: "test the fix for duplicate saves - final test"
date: 6/14/2025
time: 6:10:00 PM
timestamp: 2025-06-14T22:10:00.394Z
exchanges: 1
---
# Research Session
## Initial Query
**Question:** test the fix for duplicate saves - final test
**Response:**
## Steps to Test the Fix for Duplicate Saves
**1. Prepare a Clean Test Environment**
- Ensure the tasks.json file and any related data stores are in a known, clean state with no pre-existing duplicate entries.
- Back up the current tasks.json in case rollback is needed.
**2. Define Test Scenarios**
- Attempt to save a new task with unique data.
- Attempt to save a task with the same ID or unique identifier as an existing task (simulate a duplicate).
- Attempt to save a task with the same title or content but a different ID (to test if the fix is based on ID or content).
- Simultaneously trigger multiple save operations (if the system supports concurrency) to test race conditions.
**3. Execute Manual and Automated Tests**
- Use the application's UI or API to create and save tasks as per the scenarios above.
- For each save operation, check the tasks.json file or the data store to verify:
- No duplicate entries are created.
- Existing tasks are not overwritten unless intended (e.g., for updates).
- The system returns appropriate error messages or warnings when a duplicate save is attempted.
**4. Validate System Behavior**
- Confirm that after all test operations, each task in tasks.json is unique according to the defined criteria (ID, title, or other unique fields).
- If the system is designed to merge duplicates, verify that merging occurs as expected.
- If the system is designed to reject duplicates, ensure that the rejection is clear and no duplicate is present.
**5. Test Edge Cases**
- Attempt to save tasks with minor variations (e.g., whitespace differences, case sensitivity) to ensure the duplicate detection logic is robust.
- Test with large numbers of tasks to ensure performance and correctness at scale.
**6. Review Logs and Error Handling**
- Check application logs for any errors or warnings related to duplicate saves.
- Ensure that error handling is user-friendly and provides actionable feedback.
**7. Regression Testing**
- Run the full suite of task operations (create, update, delete) to ensure the fix for duplicate saves does not introduce new issues elsewhere in the system.
## Additional Best Practices
- Communicate test results with the team to confirm the fix is effective and to prevent future regressions[1][2][5].
- Consider implementing automated duplicate detection as part of the save operation to prevent future issues[2][3].
- Document the test cases and results for future reference and audits.
## Example Test Case Table
| Test Scenario | Expected Result | Actual Result | Pass/Fail |
|--------------------------------------|-------------------------------|---------------|-----------|
| Save unique task | Task saved | | |
| Save duplicate task (same ID) | Duplicate rejected/merged | | |
| Save duplicate task (same title) | Duplicate rejected/merged | | |
| Simultaneous saves (race condition) | Only one unique task present | | |
| Save with minor variations | No false positives/negatives | | |
Fill in the "Actual Result" and "Pass/Fail" columns during testing.
## Action Items
- Complete all test scenarios above.
- Document any issues found and retest after fixes.
- Confirm with stakeholders before closing the issue.
---
*Generated by Task Master Research Command*
*Timestamp: 2025-06-14T22:10:00.394Z*

View File

@@ -0,0 +1,471 @@
# Task Template Importing System - Product Requirements Document
<context>
# Overview
The Task Template Importing system enables seamless integration of external task templates into the Task Master CLI through automatic file discovery. This system allows users to drop task template files into the tasks directory and immediately access them as new tag contexts without manual import commands or configuration. The solution addresses the need for multi-project task management, team collaboration through shared templates, and clean separation between permanent tasks and temporary project contexts.
# Core Features
## Silent Task Template Discovery
- **What it does**: Automatically scans for `tasks_*.json` files in the tasks directory during tag operations
- **Why it's important**: Eliminates friction in adding new task contexts and enables zero-configuration workflow
- **How it works**: File pattern matching extracts tag names from filenames and validates against internal tag keys
## External Tag Resolution System
- **What it does**: Provides fallback mechanism to external files when tags are not found in main tasks.json
- **Why it's important**: Maintains clean separation between core tasks and project-specific templates
- **How it works**: Tag resolution logic checks external files as secondary source while preserving main file precedence
## Read-Only External Tag Access
- **What it does**: Allows viewing and switching to external tags while preventing modifications
- **Why it's important**: Protects template integrity and prevents accidental changes to shared templates
- **How it works**: All task modifications route to main tasks.json regardless of current tag context
## Tag Precedence Management
- **What it does**: Ensures main tasks.json tags override external files with same tag names
- **Why it's important**: Prevents conflicts and maintains data integrity
- **How it works**: Priority system where main file tags take precedence over external file tags
# User Experience
## User Personas
- **Solo Developer**: Manages multiple projects with different task contexts
- **Team Lead**: Shares standardized task templates across team members
- **Project Manager**: Organizes tasks by project phases or feature branches
## Key User Flows
### Template Addition Flow
1. User receives or creates a `tasks_projectname.json` file
2. User drops file into `.taskmaster/tasks/` directory
3. Tag becomes immediately available via `task-master use-tag projectname`
4. User can list, view, and switch to external tag without configuration
### Template Usage Flow
1. User runs `task-master tags` to see available tags including external ones
2. External tags display with `(imported)` indicator
3. User switches to external tag with `task-master use-tag projectname`
4. User can view tasks but modifications are routed to main tasks.json
## UI/UX Considerations
- External tags clearly marked with `(imported)` suffix in listings
- Visual indicators distinguish between main and external tags
- Error messages guide users when external files are malformed
- Read-only warnings when attempting to modify external tag contexts
</context>
<PRD>
# Technical Architecture
## System Components
1. **External File Discovery Engine**
- File pattern scanner for `tasks_*.json` files
- Tag name extraction from filenames using regex
- Dynamic tag registry combining main and external sources
- Error handling for malformed external files
2. **Enhanced Tag Resolution System**
- Fallback mechanism to external files when tags not found in main tasks.json
- Precedence management ensuring main file tags override external files
- Read-only access enforcement for external tags
- Tag metadata preservation during discovery operations
3. **Silent Discovery Integration**
- Automatic scanning during tag-related operations
- Seamless integration with existing tag management functions
- Zero-configuration workflow requiring no manual import commands
- Dynamic tag availability without restart requirements
## Data Models
### External Task File Structure
```json
{
"meta": {
"projectName": "External Project Name",
"version": "1.0.0",
"templateSource": "external",
"createdAt": "ISO-8601 timestamp"
},
"tags": {
"projectname": {
"meta": {
"name": "Project Name",
"description": "Project description",
"createdAt": "ISO-8601 timestamp"
},
"tasks": [
// Array of task objects
]
},
"master": {
// This section is ignored to prevent conflicts
}
}
}
```
### Enhanced Tag Registry Model
```json
{
"mainTags": [
{
"name": "master",
"source": "main",
"taskCount": 150,
"isActive": true
}
],
"externalTags": [
{
"name": "projectname",
"source": "external",
"filename": "tasks_projectname.json",
"taskCount": 25,
"isReadOnly": true
}
]
}
```
## APIs and Integrations
1. **File System Discovery API**
- Directory scanning with pattern matching
- JSON file validation and parsing
- Error handling for corrupted or malformed files
- File modification time tracking for cache invalidation
2. **Enhanced Tag Management API**
- `scanForExternalTaskFiles(projectRoot)` - Discover external template files
- `getExternalTagsFromFiles(projectRoot)` - Extract tag names from external files
- `readExternalTagData(projectRoot, tagName)` - Read specific external tag data
- `getAvailableTags(projectRoot)` - Combined main and external tag listing
3. **Tag Resolution Enhancement**
- Modified `readJSON()` with external file fallback
- Enhanced `tags()` function with external tag display
- Updated `useTag()` function supporting external tag switching
- Read-only enforcement for external tag operations
## Infrastructure Requirements
1. **File System Access**
- Read permissions for tasks directory
- JSON parsing capabilities
- Pattern matching and regex support
- Error handling for file system operations
2. **Backward Compatibility**
- Existing tag operations continue unchanged
- Main tasks.json structure preserved
- No breaking changes to current workflows
- Graceful degradation when external files unavailable
# Development Roadmap
## Phase 1: Core External File Discovery (Foundation)
1. **External File Scanner Implementation**
- Create `scanForExternalTaskFiles()` function in utils.js
- Implement file pattern matching for `tasks_*.json` files
- Add error handling for file system access issues
- Test with various filename patterns and edge cases
2. **Tag Name Extraction System**
- Implement `getExternalTagsFromFiles()` function
- Create regex pattern for extracting tag names from filenames
- Add validation to ensure tag names match internal tag key format
- Handle special characters and invalid filename patterns
3. **External Tag Data Reader**
- Create `readExternalTagData()` function
- Implement JSON parsing with error handling
- Add validation for required tag structure
- Ignore 'master' key in external files to prevent conflicts
## Phase 2: Tag Resolution Enhancement (Core Integration)
1. **Enhanced Tag Registry**
- Implement `getAvailableTags()` function combining main and external sources
- Create tag metadata structure including source information
- Add deduplication logic prioritizing main tags over external
- Implement caching mechanism for performance optimization
2. **Modified readJSON Function**
- Add external file fallback when tag not found in main tasks.json
- Maintain precedence rule: main tasks.json overrides external files
- Preserve existing error handling and validation patterns
- Ensure read-only access for external tags
3. **Tag Listing Enhancement**
- Update `tags()` function to display external tags with `(imported)` indicator
- Show external tag metadata and task counts
- Maintain current tag highlighting and sorting functionality
- Add visual distinction between main and external tags
## Phase 3: User Interface Integration (User Experience)
1. **Tag Switching Enhancement**
- Update `useTag()` function to support external tag switching
- Add read-only warnings when switching to external tags
- Update state.json with external tag context information
- Maintain current tag switching behavior for main tags
2. **Error Handling and User Feedback**
- Implement comprehensive error messages for malformed external files
- Add user guidance for proper external file structure
- Create warnings for read-only operations on external tags
- Ensure graceful degradation when external files are corrupted
3. **Documentation and Help Integration**
- Update command help text to include external tag information
- Add examples of external file structure and usage
- Create troubleshooting guide for common external file issues
- Document file naming conventions and best practices
## Phase 4: Advanced Features and Optimization (Enhancement)
1. **Performance Optimization**
- Implement file modification time caching
- Add lazy loading for external tag data
- Optimize file scanning for directories with many files
- Create efficient tag resolution caching mechanism
2. **Advanced External File Features**
- Support for nested external file directories
- Batch external file validation and reporting
- External file metadata display and management
- Integration with version control ignore patterns
3. **Team Collaboration Features**
- Shared external file validation
- External file conflict detection and resolution
- Team template sharing guidelines and documentation
- Integration with git workflows for template management
# Logical Dependency Chain
## Foundation Layer (Must Be Built First)
1. **External File Scanner**
- Core requirement for all other functionality
- Provides the discovery mechanism for external template files
- Must handle file system access and pattern matching reliably
2. **Tag Name Extraction**
- Depends on file scanner functionality
- Required for identifying available external tags
- Must validate tag names against internal format requirements
3. **External Tag Data Reader**
- Depends on tag name extraction
- Provides access to external tag content
- Must handle JSON parsing and validation safely
## Integration Layer (Builds on Foundation)
4. **Enhanced Tag Registry**
- Depends on all foundation components
- Combines main and external tag sources
- Required for unified tag management across the system
5. **Modified readJSON Function**
- Depends on enhanced tag registry
- Provides fallback mechanism for tag resolution
- Critical for maintaining backward compatibility
6. **Tag Listing Enhancement**
- Depends on enhanced tag registry
- Provides user visibility into external tags
- Required for user discovery of available templates
## User Experience Layer (Completes the Feature)
7. **Tag Switching Enhancement**
- Depends on modified readJSON and tag listing
- Enables user interaction with external tags
- Must enforce read-only access properly
8. **Error Handling and User Feedback**
- Can be developed in parallel with other UX components
- Enhances reliability and user experience
- Should be integrated throughout development process
9. **Documentation and Help Integration**
- Should be developed alongside implementation
- Required for user adoption and proper usage
- Can be completed in parallel with advanced features
## Optimization Layer (Performance and Advanced Features)
10. **Performance Optimization**
- Can be developed after core functionality is stable
- Improves user experience with large numbers of external files
- Not blocking for initial release
11. **Advanced External File Features**
- Can be developed independently after core features
- Enhances power user workflows
- Optional for initial release
12. **Team Collaboration Features**
- Depends on stable core functionality
- Enhances team workflows and template sharing
- Can be prioritized based on user feedback
# Risks and Mitigations
## Technical Challenges
### File System Performance
**Risk**: Scanning for external files on every tag operation could impact performance with large directories.
**Mitigation**:
- Implement file modification time caching to avoid unnecessary rescans
- Use lazy loading for external tag data - only read when accessed
- Add configurable limits on number of external files to scan
- Optimize file pattern matching with efficient regex patterns
### External File Corruption
**Risk**: Malformed or corrupted external JSON files could break tag operations.
**Mitigation**:
- Implement robust JSON parsing with comprehensive error handling
- Add file validation before attempting to parse external files
- Gracefully skip corrupted files and continue with valid ones
- Provide clear error messages guiding users to fix malformed files
### Tag Name Conflicts
**Risk**: External files might contain tag names that conflict with main tasks.json tags.
**Mitigation**:
- Implement strict precedence rule: main tasks.json always overrides external files
- Add warnings when external tags are ignored due to conflicts
- Document naming conventions to avoid common conflicts
- Provide validation tools to check for potential conflicts
## MVP Definition
### Core Feature Scope
**Risk**: Including too many advanced features could delay the core functionality.
**Mitigation**:
- Define MVP as basic external file discovery + tag switching
- Focus on the silent discovery mechanism as the primary value proposition
- Defer advanced features like nested directories and batch operations
- Ensure each phase delivers complete, usable functionality
### User Experience Complexity
**Risk**: The read-only nature of external tags might confuse users.
**Mitigation**:
- Provide clear visual indicators for external tags in all interfaces
- Add explicit warnings when users attempt to modify external tag contexts
- Document the read-only behavior and its rationale clearly
- Consider future enhancement for external tag modification workflows
### Backward Compatibility
**Risk**: Changes to tag resolution logic might break existing workflows.
**Mitigation**:
- Maintain existing tag operations unchanged for main tasks.json
- Add external file support as enhancement, not replacement
- Test thoroughly with existing task structures and workflows
- Provide migration path if any breaking changes are necessary
## Resource Constraints
### Development Complexity
**Risk**: Integration with existing tag management system could be complex.
**Mitigation**:
- Phase implementation to minimize risk of breaking existing functionality
- Create comprehensive test suite covering both main and external tag scenarios
- Use feature flags to enable/disable external file support during development
- Implement thorough error handling to prevent system failures
### File System Dependencies
**Risk**: Different operating systems might handle file operations differently.
**Mitigation**:
- Use Node.js built-in file system APIs for cross-platform compatibility
- Test on multiple operating systems (Windows, macOS, Linux)
- Handle file path separators and naming conventions properly
- Add fallback mechanisms for file system access issues
### User Adoption
**Risk**: Users might not understand or adopt the external file template system.
**Mitigation**:
- Create clear documentation with practical examples
- Provide sample external template files for common use cases
- Integrate help and guidance directly into the CLI interface
- Gather user feedback early and iterate on the user experience
# Appendix
## External File Naming Convention
### Filename Pattern
- **Format**: `tasks_[tagname].json`
- **Examples**: `tasks_feature-auth.json`, `tasks_v2-migration.json`, `tasks_project-alpha.json`
- **Validation**: Tag name must match internal tag key format (alphanumeric, hyphens, underscores)
### File Structure Requirements
```json
{
"meta": {
"projectName": "Required: Human-readable project name",
"version": "Optional: Template version",
"templateSource": "Optional: Source identifier",
"createdAt": "Optional: ISO-8601 timestamp"
},
"tags": {
"[tagname]": {
"meta": {
"name": "Required: Tag display name",
"description": "Optional: Tag description",
"createdAt": "Optional: ISO-8601 timestamp"
},
"tasks": [
// Required: Array of task objects following standard task structure
]
}
}
}
```
## Implementation Functions Specification
### Core Discovery Functions
```javascript
// Scan tasks directory for external template files
function scanForExternalTaskFiles(projectRoot) {
// Returns: Array of external file paths
}
// Extract tag names from external filenames
function getExternalTagsFromFiles(projectRoot) {
// Returns: Array of external tag names
}
// Read specific external tag data
function readExternalTagData(projectRoot, tagName) {
// Returns: Tag data object or null if not found
}
// Get combined main and external tags
function getAvailableTags(projectRoot) {
// Returns: Combined tag registry with metadata
}
```
### Integration Points
```javascript
// Enhanced readJSON with external fallback
function readJSON(projectRoot, tag = null) {
// Modified to check external files when tag not found in main
}
// Enhanced tags listing with external indicators
function tags(projectRoot, options = {}) {
// Modified to display external tags with (imported) suffix
}
// Enhanced tag switching with external support
function useTag(projectRoot, tagName) {
// Modified to support switching to external tags (read-only)
}
```
## Error Handling Specifications
### File System Errors
- **ENOENT**: External file not found - gracefully skip and continue
- **EACCES**: Permission denied - warn user and continue with available files
- **EISDIR**: Directory instead of file - skip and continue scanning
### JSON Parsing Errors
- **SyntaxError**: Malformed JSON - skip file and log warning with filename
- **Missing required fields**: Skip file and provide specific error message
- **Invalid tag structure**: Skip file and guide user to correct format
### Tag Conflict Resolution
- **Duplicate tag names**: Main tasks.json takes precedence, log warning
- **Invalid tag names**: Skip external file and provide naming guidance
- **Master key in external**: Ignore master key, process other tags normally
</PRD>

View File

@@ -1,9 +1,9 @@
{
"meta": {
"generatedAt": "2025-05-22T05:48:33.026Z",
"tasksAnalyzed": 6,
"totalTasks": 88,
"analysisCount": 43,
"generatedAt": "2025-05-27T16:34:53.088Z",
"tasksAnalyzed": 1,
"totalTasks": 84,
"analysisCount": 45,
"thresholdScore": 5,
"projectName": "Taskmaster",
"usedResearch": true
@@ -313,14 +313,6 @@
"expansionPrompt": "Break down the update of ai-services-unified.js for dynamic token limits into subtasks such as: (1) Import and integrate the token counting utility, (2) Refactor _unifiedServiceRunner to calculate and enforce dynamic token limits, (3) Update error handling for token limit violations, (4) Add and verify logging for token usage, (5) Write and execute tests for various prompt and model scenarios.",
"reasoning": "This task involves significant code changes to a core function, integration of a new utility, dynamic logic for multiple models, and robust error handling. It also requires comprehensive testing for edge cases and integration, making it moderately complex and best managed by splitting into focused subtasks."
},
{
"taskId": 86,
"taskTitle": "Update .taskmasterconfig schema and user guide",
"complexityScore": 6,
"recommendedSubtasks": 4,
"expansionPrompt": "Expand this task into subtasks: (1) Draft a migration guide for users, (2) Update user documentation to explain new config fields, (3) Modify schema validation logic in config-manager.js, (4) Test and validate backward compatibility and error messaging.",
"reasoning": "The task spans documentation, schema changes, migration guidance, and validation logic. While not algorithmically complex, it requires careful coordination and thorough testing to ensure a smooth user transition and robust validation."
},
{
"taskId": 87,
"taskTitle": "Implement validation and error handling",
@@ -352,6 +344,30 @@
"recommendedSubtasks": 5,
"expansionPrompt": "Expand this task into: (1) Implement move logic for tasks and subtasks, (2) Handle edge cases (invalid ids, non-existent parents, circular dependencies), (3) Update CLI to support move command with flags, (4) Ensure data integrity and update relationships, (5) Write and execute tests for various move scenarios.",
"reasoning": "Moving tasks and subtasks requires careful handling of hierarchical data, edge cases, and data integrity. The command must be robust and user-friendly, necessitating multiple focused subtasks for safe implementation."
},
{
"taskId": 92,
"taskTitle": "Add Global Joke Flag to All CLI Commands",
"complexityScore": 8,
"recommendedSubtasks": 7,
"expansionPrompt": "Break down the implementation of the global --joke flag into the following subtasks: (1) Update CLI foundation to support global flags, (2) Develop the joke-service module with joke management and category support, (3) Integrate joke output into existing output utilities, (4) Update all CLI commands for joke flag compatibility, (5) Add configuration options for joke categories and custom jokes, (6) Implement comprehensive testing (flag recognition, output, content, integration, performance, regression), (7) Update documentation and usage examples.",
"reasoning": "This task requires changes across the CLI foundation, output utilities, all command modules, and configuration management. It introduces a new service module, global flag handling, and output logic that must not interfere with existing features (including JSON output). The need for robust testing and backward compatibility further increases complexity. The scope spans multiple code areas and requires careful integration, justifying a high complexity score and a detailed subtask breakdown to manage risk and ensure maintainability.[2][3][5]"
},
{
"taskId": 94,
"taskTitle": "Implement Standalone 'research' CLI Command for AI-Powered Queries",
"complexityScore": 7,
"recommendedSubtasks": 6,
"expansionPrompt": "Break down the implementation of the 'research' CLI command into logical subtasks covering command registration, parameter handling, context gathering, AI service integration, output formatting, and documentation.",
"reasoning": "This task has moderate to high complexity (7/10) due to multiple interconnected components: CLI argument parsing, integration with AI services, context gathering from various sources, and output formatting with different modes. The cyclomatic complexity would be significant with multiple decision paths for handling different flags and options. The task requires understanding existing patterns and extending the codebase in a consistent manner, suggesting the need for careful decomposition into manageable subtasks."
},
{
"taskId": 86,
"taskTitle": "Implement GitHub Issue Export Feature",
"complexityScore": 9,
"recommendedSubtasks": 10,
"expansionPrompt": "Break down the implementation of the GitHub Issue Export Feature into detailed subtasks covering: command structure and CLI integration, GitHub API client development, authentication and error handling, task-to-issue mapping logic, content formatting and markdown conversion, bidirectional linking and metadata management, extensible architecture and adapter interfaces, configuration and settings management, documentation, and comprehensive testing (unit, integration, edge cases, performance).",
"reasoning": "This task involves designing and implementing a robust, extensible export system with deep integration into GitHub, including bidirectional workflows, complex data mapping, error handling, and support for future platforms. The requirements span CLI design, API integration, content transformation, metadata management, extensibility, configuration, and extensive testing. The breadth and depth of these requirements, along with the need for maintainability and future extensibility, place this task at a high complexity level. Breaking it into at least 10 subtasks will ensure each major component and concern is addressed systematically, reducing risk and improving quality."
}
]
}

View File

@@ -0,0 +1,53 @@
{
"meta": {
"generatedAt": "2025-06-13T06:52:00.611Z",
"tasksAnalyzed": 5,
"totalTasks": 5,
"analysisCount": 5,
"thresholdScore": 5,
"projectName": "Taskmaster",
"usedResearch": true
},
"complexityAnalysis": [
{
"taskId": 1,
"taskTitle": "Setup Project Repository and Node.js Environment",
"complexityScore": 4,
"recommendedSubtasks": 6,
"expansionPrompt": "Break down the setup process into subtasks such as initializing npm, creating directory structure, installing dependencies, configuring package.json, adding configuration files, and setting up the main entry point.",
"reasoning": "This task involves several standard setup steps that are well-defined and sequential, with low algorithmic complexity but moderate procedural detail. Each step is independent and can be assigned as a subtask, making the overall complexity moderate."
},
{
"taskId": 2,
"taskTitle": "Implement Core Functionality and CLI Interface",
"complexityScore": 7,
"recommendedSubtasks": 7,
"expansionPrompt": "Expand into subtasks for implementing main logic, designing CLI commands, creating the CLI entry point, integrating business logic, adding error handling, formatting output, and ensuring CLI executability.",
"reasoning": "This task requires both application logic and user interface (CLI) development, including error handling and integration. The need to coordinate between core logic and CLI, plus ensuring usability, increases complexity and warrants detailed subtasking."
},
{
"taskId": 3,
"taskTitle": "Implement Testing Suite and Validation",
"complexityScore": 6,
"recommendedSubtasks": 6,
"expansionPrompt": "Divide into subtasks for configuring Jest, writing unit tests, writing integration tests, testing CLI commands, setting up coverage reporting, and preparing test fixtures/mocks.",
"reasoning": "Comprehensive testing involves multiple types of tests and configuration steps. While each is straightforward, the breadth of coverage and need for automation and validation increases the overall complexity."
},
{
"taskId": 4,
"taskTitle": "Setup Node.js Project with CLI Interface",
"complexityScore": 5,
"recommendedSubtasks": 7,
"expansionPrompt": "Break down into subtasks for npm initialization, package.json setup, directory structure creation, dependency installation, CLI entry point creation, package.json bin configuration, and CLI executability.",
"reasoning": "This task combines project setup with initial CLI implementation. While each step is standard, the integration of CLI elements adds a layer of complexity beyond a basic setup."
},
{
"taskId": 5,
"taskTitle": "Implement Core Functionality with Testing",
"complexityScore": 8,
"recommendedSubtasks": 8,
"expansionPrompt": "Expand into subtasks for implementing each feature (A, B, C), setting up the testing framework, writing tests for each feature, integrating CLI with core logic, and adding coverage reporting.",
"reasoning": "This task requires simultaneous development of multiple features, integration with CLI, and comprehensive testing. The coordination and depth required for both implementation and validation make it the most complex among the listed tasks."
}
]
}

9
.taskmaster/state.json Normal file
View File

@@ -0,0 +1,9 @@
{
"currentTag": "master",
"lastSwitched": "2025-06-14T20:37:15.456Z",
"branchTagMapping": {
"v017-adds": "v017-adds",
"next": "next"
},
"migrationNoticeShown": true
}

View File

@@ -1,16 +0,0 @@
# Task ID: 1
# Title: Implement Task Data Structure
# Status: done
# Dependencies: None
# Priority: high
# Description: Design and implement the core tasks.json structure that will serve as the single source of truth for the system.
# Details:
Create the foundational data structure including:
- JSON schema for tasks.json
- Task model with all required fields (id, title, description, status, dependencies, priority, details, testStrategy, subtasks)
- Validation functions for the task model
- Basic file system operations for reading/writing tasks.json
- Error handling for file operations
# Test Strategy:
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.

View File

@@ -0,0 +1,23 @@
# Task ID: 1
# Title: Implement TTS Flag for Taskmaster Commands
# Status: pending
# Dependencies: 16 (Not found)
# Priority: medium
# Description: Add text-to-speech functionality to taskmaster commands with configurable voice options and audio output settings.
# Details:
Implement TTS functionality including:
- Add --tts flag to all relevant taskmaster commands (list, show, generate, etc.)
- Integrate with system TTS engines (Windows SAPI, macOS say command, Linux espeak/festival)
- Create TTS configuration options in the configuration management system
- Add voice selection options (male/female, different languages if available)
- Implement audio output settings (volume, speed, pitch)
- Add TTS-specific error handling for cases where TTS is unavailable
- Create fallback behavior when TTS fails (silent failure or text output)
- Support for reading task titles, descriptions, and status updates aloud
- Add option to read entire task lists or individual task details
- Implement TTS for command confirmations and error messages
- Create TTS output formatting to make spoken text more natural (removing markdown, formatting numbers/dates appropriately)
- Add configuration option to enable/disable TTS globally
# Test Strategy:
Test TTS functionality across different operating systems (Windows, macOS, Linux). Verify that the --tts flag works with all major commands. Test voice configuration options and ensure audio output settings are properly applied. Test error handling when TTS services are unavailable. Verify that text formatting for speech is natural and understandable. Test with various task content types including special characters, code snippets, and long descriptions. Ensure TTS can be disabled and enabled through configuration.

View File

@@ -1,16 +0,0 @@
# Task ID: 2
# Title: Develop Command Line Interface Foundation
# Status: done
# Dependencies: 1
# Priority: high
# Description: Create the basic CLI structure using Commander.js with command parsing and help documentation.
# Details:
Implement the CLI foundation including:
- Set up Commander.js for command parsing
- Create help documentation for all commands
- Implement colorized console output for better readability
- Add logging system with configurable levels
- Handle global options (--help, --version, --file, --quiet, --debug, --json)
# Test Strategy:
Test each command with various parameters to ensure proper parsing. Verify help documentation is comprehensive and accurate. Test logging at different verbosity levels.

View File

@@ -1,18 +0,0 @@
# Task ID: 3
# Title: Implement Basic Task Operations
# Status: done
# Dependencies: 1
# Priority: high
# Description: Create core functionality for managing tasks including listing, creating, updating, and deleting tasks.
# Details:
Implement the following task operations:
- List tasks with filtering options
- Create new tasks with required fields
- Update existing task properties
- Delete tasks
- Change task status (pending/done/deferred)
- Handle dependencies between tasks
- Manage task priorities
# Test Strategy:
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.

View File

@@ -1,65 +0,0 @@
# Task ID: 4
# Title: Create Task File Generation System
# Status: done
# Dependencies: 1, 3
# Priority: medium
# Description: Implement the system for generating individual task files from the tasks.json data structure.
# Details:
Build the task file generation system including:
- Create task file templates
- Implement generation of task files from tasks.json
- Add bi-directional synchronization between task files and tasks.json
- Implement proper file naming and organization
- Handle updates to task files reflecting back to tasks.json
# Test Strategy:
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:
## 1. Design Task File Template Structure [done]
### Dependencies: None
### 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.
### Details:
## 2. Implement Task File Generation Logic [done]
### Dependencies: 4.1
### 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.
### Details:
## 3. Implement File Naming and Organization System [done]
### Dependencies: 4.1
### 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.
### Details:
## 4. Implement Task File to JSON Synchronization [done]
### Dependencies: 4.1, 4.3, 4.2
### 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.
### Details:
## 5. Implement Change Detection and Update Handling [done]
### Dependencies: 4.1, 4.3, 4.4, 4.2
### 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.
### Details:
<info added on 2025-05-01T21:59:10.551Z>
{
"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": "[2025-05-01 21:59:07] Adding another note via MCP test."
}
</info added on 2025-05-01T21:59:10.551Z>

View File

@@ -1,55 +0,0 @@
# Task ID: 5
# Title: Integrate Anthropic Claude API
# Status: done
# Dependencies: 1
# Priority: high
# Description: Set up the integration with Claude API for AI-powered task generation and expansion.
# Details:
Implement Claude API integration including:
- API authentication using environment variables
- Create prompt templates for various operations
- Implement response handling and parsing
- Add error management with retries and exponential backoff
- Implement token usage tracking
- Create configurable model parameters
# Test Strategy:
Test API connectivity with sample prompts. Verify authentication works correctly with different API keys. Test error handling by simulating API failures.
# Subtasks:
## 1. Configure API Authentication System [done]
### Dependencies: None
### 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.
### Details:
## 2. Develop Prompt Template System [done]
### Dependencies: 5.1
### 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.
### Details:
## 3. Implement Response Handling and Parsing [done]
### Dependencies: 5.1, 5.2
### 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.
### Details:
## 4. Build Error Management with Retry Logic [done]
### Dependencies: 5.1, 5.3
### 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.
### Details:
## 5. Implement Token Usage Tracking [done]
### Dependencies: 5.1, 5.3
### 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.
### Details:
## 6. Create Model Parameter Configuration System [done]
### Dependencies: 5.1, 5.5
### 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.).
### Details:

View File

@@ -1,55 +0,0 @@
# Task ID: 6
# Title: Build PRD Parsing System
# Status: done
# Dependencies: 1, 5
# Priority: high
# Description: Create the system for parsing Product Requirements Documents into structured task lists.
# Details:
Implement PRD parsing functionality including:
- PRD file reading from specified path
- Prompt engineering for effective PRD parsing
- Convert PRD content to task structure via Claude API
- Implement intelligent dependency inference
- Add priority assignment logic
- Handle large PRDs by chunking if necessary
# Test Strategy:
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:
## 1. Implement PRD File Reading Module [done]
### Dependencies: None
### 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.
### Details:
## 2. Design and Engineer Effective PRD Parsing Prompts [done]
### Dependencies: None
### 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.
### Details:
## 3. Implement PRD to Task Conversion System [done]
### Dependencies: 6.1
### 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.
### Details:
## 4. Build Intelligent Dependency Inference System [done]
### Dependencies: 6.1, 6.3
### 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).
### Details:
## 5. Implement Priority Assignment Logic [done]
### Dependencies: 6.1, 6.3
### 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.
### Details:
## 6. Implement PRD Chunking for Large Documents [done]
### Dependencies: 6.1, 6.5, 6.3
### 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.
### Details:

View File

@@ -1,49 +0,0 @@
# Task ID: 7
# Title: Implement Task Expansion with Claude
# Status: done
# Dependencies: 3, 5
# Priority: medium
# Description: Create functionality to expand tasks into subtasks using Claude's AI capabilities.
# Details:
Build task expansion functionality including:
- Create subtask generation prompts
- Implement workflow for expanding a task into subtasks
- Add context-aware expansion capabilities
- Implement parent-child relationship management
- Allow specification of number of subtasks to generate
- Provide mechanism to regenerate unsatisfactory subtasks
# Test Strategy:
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:
## 1. Design and Implement Subtask Generation Prompts [done]
### Dependencies: None
### 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.
### Details:
## 2. Develop Task Expansion Workflow and UI [done]
### Dependencies: 7.5
### 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.
### Details:
## 3. Implement Context-Aware Expansion Capabilities [done]
### Dependencies: 7.1
### 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.
### Details:
## 4. Build Parent-Child Relationship Management [done]
### Dependencies: 7.3
### 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.
### Details:
## 5. Implement Subtask Regeneration Mechanism [done]
### Dependencies: 7.1, 7.2, 7.4
### 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.
### Details:

View File

@@ -1,48 +0,0 @@
# Task ID: 8
# Title: Develop Implementation Drift Handling
# Status: done
# Dependencies: 3, 5, 7
# Priority: medium
# Description: Create system to handle changes in implementation that affect future tasks.
# Details:
Implement drift handling including:
- Add capability to update future tasks based on completed work
- Implement task rewriting based on new context
- Create dependency chain updates when tasks change
- Preserve completed work while updating future tasks
- Add command to analyze and suggest updates to future tasks
# Test Strategy:
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:
## 1. Create Task Update Mechanism Based on Completed Work [done]
### Dependencies: None
### 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.
### Details:
## 2. Implement AI-Powered Task Rewriting [done]
### Dependencies: None
### 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.
### Details:
## 3. Build Dependency Chain Update System [done]
### Dependencies: None
### 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.
### Details:
## 4. Implement Completed Work Preservation [done]
### Dependencies: 8.3
### 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.
### Details:
## 5. Create Update Analysis and Suggestion Command [done]
### Dependencies: 8.3
### 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.
### Details:

View File

@@ -1,49 +0,0 @@
# Task ID: 9
# Title: Integrate Perplexity API
# Status: done
# Dependencies: 5
# Priority: low
# Description: Add integration with Perplexity API for research-backed task generation.
# Details:
Implement Perplexity integration including:
- API authentication via OpenAI client
- Create research-oriented prompt templates
- Implement response handling for Perplexity
- Add fallback to Claude when Perplexity is unavailable
- Implement response quality comparison logic
- Add configuration for model selection
# Test Strategy:
Test connectivity to Perplexity API. Verify research-oriented prompts return useful information. Test fallback mechanism by simulating Perplexity API unavailability.
# Subtasks:
## 1. Implement Perplexity API Authentication Module [done]
### Dependencies: None
### 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.
### Details:
## 2. Develop Research-Oriented Prompt Templates [done]
### Dependencies: None
### 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.
### Details:
## 3. Create Perplexity Response Handler [done]
### Dependencies: None
### 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.
### Details:
## 4. Implement Claude Fallback Mechanism [done]
### Dependencies: None
### 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.
### Details:
## 5. Develop Response Quality Comparison and Model Selection [done]
### Dependencies: None
### 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.
### Details:

View File

@@ -1,54 +0,0 @@
# Task ID: 10
# Title: Create Research-Backed Subtask Generation
# Status: done
# Dependencies: 7, 9
# Priority: low
# Description: Enhance subtask generation with research capabilities from Perplexity API.
# Details:
Implement research-backed generation including:
- Create specialized research prompts for different domains
- Implement context enrichment from research results
- Add domain-specific knowledge incorporation
- Create more detailed subtask generation with best practices
- Include references to relevant libraries and tools
# Test Strategy:
Compare subtasks generated with and without research backing. Verify that research-backed subtasks include more specific technical details and best practices.
# Subtasks:
## 1. Design Domain-Specific Research Prompt Templates [done]
### Dependencies: None
### 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.
### Details:
## 2. Implement Research Query Execution and Response Processing [done]
### Dependencies: None
### 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.
### Details:
## 3. Develop Context Enrichment Pipeline [done]
### Dependencies: 10.2
### 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.
### Details:
## 4. Implement Domain-Specific Knowledge Incorporation [done]
### Dependencies: 10.3
### 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.
### Details:
## 5. Enhance Subtask Generation with Technical Details [done]
### Dependencies: 10.3, 10.4
### 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.
### Details:
## 6. Implement Reference and Resource Inclusion [done]
### Dependencies: 10.3, 10.5
### 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.
### Details:

View File

@@ -1,49 +0,0 @@
# Task ID: 11
# Title: Implement Batch Operations
# Status: done
# Dependencies: 3
# Priority: medium
# Description: Add functionality for performing operations on multiple tasks simultaneously.
# Details:
Create batch operations including:
- Implement multi-task status updates
- Add bulk subtask generation
- Create task filtering and querying capabilities
- Implement advanced dependency management
- Add batch prioritization
- Create commands for operating on filtered task sets
# Test Strategy:
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:
## 1. Implement Multi-Task Status Update Functionality [done]
### Dependencies: 11.3
### 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.
### Details:
## 2. Develop Bulk Subtask Generation System [done]
### Dependencies: 11.3, 11.4
### 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.
### Details:
## 3. Implement Advanced Task Filtering and Querying [done]
### Dependencies: None
### 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.
### Details:
## 4. Create Advanced Dependency Management System [done]
### Dependencies: 11.3
### 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.
### Details:
## 5. Implement Batch Task Prioritization and Command System [done]
### Dependencies: 11.3
### 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.
### Details:

View File

@@ -1,55 +0,0 @@
# Task ID: 12
# Title: Develop Project Initialization System
# Status: done
# Dependencies: 1, 3, 4, 6
# Priority: medium
# Description: Create functionality for initializing new projects with task structure and configuration.
# Details:
Implement project initialization including:
- Create project templating system
- Implement interactive setup wizard
- Add environment configuration generation
- Create initial directory structure
- Generate example tasks.json
- Set up default configuration
# Test Strategy:
Test project initialization in empty directories. Verify that all required files and directories are created correctly. Test the interactive setup with various inputs.
# Subtasks:
## 1. Create Project Template Structure [done]
### Dependencies: 12.4
### 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.
### Details:
## 2. Implement Interactive Setup Wizard [done]
### Dependencies: 12.3
### 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.
### Details:
## 3. Generate Environment Configuration [done]
### Dependencies: 12.2
### 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.
### Details:
## 4. Implement Directory Structure Creation [done]
### Dependencies: 12.1
### 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.
### Details:
## 5. Generate Example Tasks.json [done]
### Dependencies: 12.6
### 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.
### Details:
## 6. Implement Default Configuration Setup [done]
### Dependencies: None
### 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.
### Details:

View File

@@ -1,49 +0,0 @@
# Task ID: 13
# Title: Create Cursor Rules Implementation
# Status: done
# Dependencies: 1, 3
# Priority: medium
# Description: Develop the Cursor AI integration rules and documentation.
# Details:
Implement Cursor rules including:
- Create dev_workflow.mdc documentation
- Implement cursor_rules.mdc
- Add self_improve.mdc
- Design rule integration documentation
- Set up .cursor directory structure
- Document how Cursor AI should interact with the system
# Test Strategy:
Review rules documentation for clarity and completeness. Test with Cursor AI to verify the rules are properly interpreted and followed.
# Subtasks:
## 1. Set up .cursor Directory Structure [done]
### Dependencies: None
### 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.
### Details:
## 2. Create dev_workflow.mdc Documentation [done]
### Dependencies: 13.1
### 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.
### Details:
## 3. Implement cursor_rules.mdc [done]
### Dependencies: 13.1
### 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.
### Details:
## 4. Add self_improve.mdc Documentation [done]
### Dependencies: 13.1, 13.2, 13.3
### 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.
### Details:
## 5. Create Cursor AI Integration Documentation [done]
### Dependencies: 13.1, 13.2, 13.3, 13.4
### 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.
### Details:

View File

@@ -1,49 +0,0 @@
# Task ID: 14
# Title: Develop Agent Workflow Guidelines
# Status: done
# Dependencies: 13
# Priority: medium
# Description: Create comprehensive guidelines for how AI agents should interact with the task system.
# Details:
Create agent workflow guidelines including:
- Document task discovery workflow
- Create task selection guidelines
- Implement implementation guidance
- Add verification procedures
- Define how agents should prioritize work
- Create guidelines for handling dependencies
# Test Strategy:
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:
## 1. Document Task Discovery Workflow [done]
### Dependencies: None
### 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.
### Details:
## 2. Implement Task Selection Algorithm [done]
### Dependencies: 14.1
### 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.
### Details:
## 3. Create Implementation Guidance Generator [done]
### Dependencies: 14.5
### 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.
### Details:
## 4. Develop Verification Procedure Framework [done]
### Dependencies: 14.1, 14.2
### 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.
### Details:
## 5. Implement Dynamic Task Prioritization System [done]
### Dependencies: 14.1, 14.2, 14.3
### 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.
### Details:

View File

@@ -1,54 +0,0 @@
# Task ID: 15
# Title: Optimize Agent Integration with Cursor and dev.js Commands
# Status: done
# Dependencies: 14
# Priority: medium
# Description: Document and enhance existing agent interaction patterns through Cursor rules and dev.js commands.
# Details:
Optimize agent integration including:
- Document and improve existing agent interaction patterns in Cursor rules
- Enhance integration between Cursor agent capabilities and dev.js commands
- Improve agent workflow documentation in cursor rules (dev_workflow.mdc, cursor_rules.mdc)
- Add missing agent-specific features to existing commands
- Leverage existing infrastructure rather than building a separate system
# Test Strategy:
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:
## 1. Document Existing Agent Interaction Patterns [done]
### Dependencies: None
### 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.
### Details:
## 2. Enhance Integration Between Cursor Agents and dev.js Commands [done]
### Dependencies: None
### 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.
### Details:
## 3. Optimize Command Responses for Agent Consumption [done]
### Dependencies: 15.2
### 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.
### Details:
## 4. Improve Agent Workflow Documentation in Cursor Rules [done]
### Dependencies: 15.1, 15.3
### 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.
### Details:
## 5. Add Agent-Specific Features to Existing Commands [done]
### Dependencies: 15.2
### 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.
### Details:
## 6. Create Agent Usage Examples and Patterns [done]
### Dependencies: 15.3, 15.4
### 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.
### Details:

View File

@@ -1,56 +0,0 @@
# Task ID: 16
# Title: Create Configuration Management System
# Status: done
# Dependencies: 1
# Priority: high
# Description: Implement robust configuration handling with environment variables and .env files.
# Details:
Build configuration management including:
- Environment variable handling
- .env file support
- Configuration validation
- Sensible defaults with overrides
- Create .env.example template
- Add configuration documentation
- Implement secure handling of API keys
# Test Strategy:
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:
## 1. Implement Environment Variable Loading [done]
### Dependencies: None
### 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.
### Details:
## 2. Implement .env File Support [done]
### Dependencies: 16.1
### 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.
### Details:
## 3. Implement Configuration Validation [done]
### Dependencies: 16.1, 16.2
### 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.
### Details:
## 4. Create Configuration Defaults and Override System [done]
### Dependencies: 16.1, 16.2, 16.3
### 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.
### Details:
## 5. Create .env.example Template [done]
### Dependencies: 16.1, 16.2, 16.3, 16.4
### 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.
### Details:
## 6. Implement Secure API Key Handling [done]
### Dependencies: 16.1, 16.2, 16.3, 16.4
### 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.
### Details:

View File

@@ -1,50 +0,0 @@
# Task ID: 17
# Title: Implement Comprehensive Logging System
# Status: done
# Dependencies: 16
# Priority: medium
# Description: Create a flexible logging system with configurable levels and output formats.
# Details:
Implement logging system including:
- Multiple log levels (debug, info, warn, error)
- Configurable output destinations
- Command execution logging
- API interaction logging
- Error tracking
- Performance metrics
- Log file rotation
# Test Strategy:
Test logging at different verbosity levels. Verify that logs contain appropriate information for debugging. Test log file rotation with large volumes of logs.
# Subtasks:
## 1. Implement Core Logging Framework with Log Levels [done]
### Dependencies: None
### 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.
### Details:
## 2. Implement Configurable Output Destinations [done]
### Dependencies: 17.1
### 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.
### Details:
## 3. Implement Command and API Interaction Logging [done]
### Dependencies: 17.1, 17.2
### 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.
### Details:
## 4. Implement Error Tracking and Performance Metrics [done]
### Dependencies: 17.1
### 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.
### Details:
## 5. Implement Log File Rotation and Management [done]
### Dependencies: 17.2
### 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.
### Details:

View File

@@ -1,57 +0,0 @@
# Task ID: 18
# Title: Create Comprehensive User Documentation
# Status: done
# Dependencies: 1, 3, 4, 5, 6, 7, 11, 12, 16
# Priority: medium
# Description: Develop complete user documentation including README, examples, and troubleshooting guides.
# Details:
Create user documentation including:
- Detailed README with installation and usage instructions
- Command reference documentation
- Configuration guide
- Example workflows
- Troubleshooting guides
- API integration documentation
- Best practices
- Advanced usage scenarios
# Test Strategy:
Review documentation for clarity and completeness. Have users unfamiliar with the system attempt to follow the documentation and note any confusion or issues.
# Subtasks:
## 1. Create Detailed README with Installation and Usage Instructions [done]
### Dependencies: 18.3
### 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.
### Details:
## 2. Develop Command Reference Documentation [done]
### Dependencies: 18.3
### 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.
### Details:
## 3. Create Configuration and Environment Setup Guide [done]
### Dependencies: None
### 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.
### Details:
## 4. Develop Example Workflows and Use Cases [done]
### Dependencies: 18.3, 18.6
### 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.
### Details:
## 5. Create Troubleshooting Guide and FAQ [done]
### Dependencies: 18.1, 18.2, 18.3
### 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.
### Details:
## 6. Develop API Integration and Extension Documentation [done]
### Dependencies: 18.5
### 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.
### Details:

View File

@@ -1,56 +0,0 @@
# Task ID: 19
# Title: Implement Error Handling and Recovery
# Status: done
# Dependencies: 1, 3, 5, 9, 16, 17
# Priority: high
# Description: Create robust error handling throughout the system with helpful error messages and recovery options.
# Details:
Implement error handling including:
- Consistent error message format
- Helpful error messages with recovery suggestions
- API error handling with retries
- File system error recovery
- Data validation errors with specific feedback
- Command syntax error guidance
- System state recovery after failures
# Test Strategy:
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:
## 1. Define Error Message Format and Structure [done]
### Dependencies: None
### 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.
### Details:
## 2. Implement API Error Handling with Retry Logic [done]
### Dependencies: None
### 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.
### Details:
## 3. Develop File System Error Recovery Mechanisms [done]
### Dependencies: 19.1
### 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.
### Details:
## 4. Enhance Data Validation with Detailed Error Feedback [done]
### Dependencies: 19.1, 19.3
### 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.
### Details:
## 5. Implement Command Syntax Error Handling and Guidance [done]
### Dependencies: 19.2
### 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.
### Details:
## 6. Develop System State Recovery After Critical Failures [done]
### Dependencies: 19.1, 19.3
### 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.
### Details:

View File

@@ -1,50 +0,0 @@
# Task ID: 20
# Title: Create Token Usage Tracking and Cost Management
# Status: done
# Dependencies: 5, 9, 17
# Priority: medium
# Description: Implement system for tracking API token usage and managing costs.
# Details:
Implement token tracking including:
- Track token usage for all API calls
- Implement configurable usage limits
- Add reporting on token consumption
- Create cost estimation features
- Implement caching to reduce API calls
- Add token optimization for prompts
- Create usage alerts when approaching limits
# Test Strategy:
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:
## 1. Implement Token Usage Tracking for API Calls [done]
### Dependencies: 20.5
### 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.
### Details:
## 2. Develop Configurable Usage Limits [done]
### Dependencies: None
### 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).
### Details:
## 3. Implement Token Usage Reporting and Cost Estimation [done]
### Dependencies: 20.1, 20.2
### 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.
### Details:
## 4. Optimize Token Usage in Prompts [done]
### Dependencies: None
### 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.
### Details:
## 5. Develop Token Usage Alert System [done]
### Dependencies: 20.2, 20.3
### 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.
### Details:

View File

@@ -1,90 +0,0 @@
# Task ID: 21
# Title: Refactor dev.js into Modular Components
# Status: done
# Dependencies: 3, 16, 17
# Priority: high
# Description: Restructure the monolithic dev.js file into separate modular components to improve code maintainability, readability, and testability while preserving all existing functionality.
# Details:
This task involves breaking down the current dev.js file into logical modules with clear responsibilities:
1. Create the following module files:
- commands.js: Handle all CLI command definitions and execution logic
- ai-services.js: Encapsulate all AI service interactions (OpenAI, etc.)
- task-manager.js: Manage task operations (create, read, update, delete)
- ui.js: Handle all console output formatting, colors, and user interaction
- utils.js: Contain helper functions, utilities, and shared code
2. Refactor dev.js to serve as the entry point that:
- Imports and initializes all modules
- Handles command-line argument parsing
- Sets up the execution environment
- Orchestrates the flow between modules
3. Ensure proper dependency injection between modules to avoid circular dependencies
4. Maintain consistent error handling across modules
5. Update import/export statements throughout the codebase
6. Document each module with clear JSDoc comments explaining purpose and usage
7. Ensure configuration and logging systems are properly integrated into each module
The refactoring should not change any existing functionality - this is purely a code organization task.
# Test Strategy:
Testing should verify that functionality remains identical after refactoring:
1. Automated Testing:
- Create unit tests for each new module to verify individual functionality
- Implement integration tests that verify modules work together correctly
- Test each command to ensure it works exactly as before
2. Manual Testing:
- Execute all existing CLI commands and verify outputs match pre-refactoring behavior
- Test edge cases like error handling and invalid inputs
- Verify that configuration options still work as expected
3. Code Quality Verification:
- Run linting tools to ensure code quality standards are maintained
- Check for any circular dependencies between modules
- Verify that each module has a single, clear responsibility
4. Performance Testing:
- Compare execution time before and after refactoring to ensure no performance regression
5. Documentation Check:
- Verify that each module has proper documentation
- Ensure README is updated if necessary to reflect architectural changes
# Subtasks:
## 1. Analyze Current dev.js Structure and Plan Module Boundaries [done]
### Dependencies: None
### 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.
### Details:
## 2. Create Core Module Structure and Entry Point Refactoring [done]
### Dependencies: 21.1
### 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.
### Details:
## 3. Implement Core Module Functionality with Dependency Injection [done]
### Dependencies: 21.2
### 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.
### Details:
## 4. Implement Error Handling and Complete Module Migration [done]
### Dependencies: 21.3
### 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.
### Details:
## 5. Test, Document, and Finalize Modular Structure [done]
### Dependencies: 21.4
### 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.
### Details:

View File

@@ -1,77 +0,0 @@
# Task ID: 22
# Title: Create Comprehensive Test Suite for Task Master CLI
# Status: done
# Dependencies: 21
# Priority: high
# 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.
# Details:
Implement a comprehensive test suite using Jest as the testing framework. The test suite should be organized into three main categories:
1. Unit Tests:
- Create tests for all utility functions and core logic components
- Test task creation, parsing, and manipulation functions
- Test data storage and retrieval functions
- Test formatting and display functions
2. Integration Tests:
- Test all CLI commands (create, expand, update, list, etc.)
- Verify command options and parameters work correctly
- Test interactions between different components
- Test configuration loading and application settings
3. End-to-End Tests:
- Test complete workflows (e.g., creating a task, expanding it, updating status)
- Test error scenarios and recovery
- Test edge cases like handling large numbers of tasks
Implement proper mocking for:
- Claude API interactions (using Jest mock functions)
- File system operations (using mock-fs or similar)
- User input/output (using mock stdin/stdout)
Ensure 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.
# Test Strategy:
Verification will involve:
1. Code Review:
- Verify test organization follows the unit/integration/end-to-end structure
- Check that all major functions have corresponding tests
- Verify mocks are properly implemented for external dependencies
2. Test Coverage Analysis:
- Run test coverage tools to ensure at least 80% code coverage
- Verify critical paths have 100% coverage
- Identify any untested code paths
3. Test Quality Verification:
- Manually review test cases to ensure they test meaningful behavior
- Verify both positive and negative test cases exist
- Check that tests are deterministic and don't have false positives/negatives
4. CI Integration:
- Verify tests run successfully in the CI environment
- Ensure tests run in a reasonable amount of time
- Check that test failures provide clear, actionable information
The task will be considered complete when all tests pass consistently, coverage meets targets, and the test suite can detect intentionally introduced bugs.
# Subtasks:
## 1. Set Up Jest Testing Environment [done]
### Dependencies: None
### 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.
### Details:
## 2. Implement Unit Tests for Core Components [done]
### Dependencies: 22.1
### 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.
### Details:
## 3. Develop Integration and End-to-End Tests [deferred]
### Dependencies: 22.1, 22.2
### 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.
### Details:

File diff suppressed because it is too large Load Diff

View File

@@ -1,603 +0,0 @@
# Task ID: 24
# Title: Implement AI-Powered Test Generation Command
# Status: pending
# Dependencies: 22
# Priority: high
# 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.
# 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:
1. Accept a task ID parameter to identify which task to generate tests for
2. Retrieve the task and its subtasks from the task store
3. Analyze the task description, details, and subtasks to understand implementation requirements
4. Construct an appropriate prompt for the AI service using Claude API
5. Process the AI response to create a well-formatted test file named 'task_XXX.test.ts' where XXX is the zero-padded task ID
6. Include appropriate test cases that cover the main functionality described in the task
7. Generate mocks for external dependencies identified in the task description
8. Create assertions that validate the expected behavior
9. Handle both parent tasks and subtasks appropriately (for subtasks, name the file 'task_XXX_YYY.test.ts' where YYY is the subtask ID)
10. Include error handling for API failures, invalid task IDs, etc.
11. Add appropriate documentation for the command in the help system
The 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.
# Test Strategy:
Testing for this feature should include:
1. Unit tests for the command handler function to verify it correctly processes arguments and options
2. Mock tests for the Claude API integration to ensure proper prompt construction and response handling
3. Integration tests that verify the end-to-end flow using a mock Claude API response
4. Tests for error conditions including:
- Invalid task IDs
- Network failures when contacting the AI service
- Malformed AI responses
- File system permission issues
5. Verification that generated test files follow Jest conventions and can be executed
6. Tests for both parent task and subtask handling
7. Manual verification of the quality of generated tests by running them against actual task implementations
Create 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:
## 1. Create command structure for 'generate-test' [pending]
### Dependencies: None
### Description: Implement the basic structure for the 'generate-test' command, including command registration, parameter validation, and help documentation.
### Details:
Implementation steps:
1. Create a new file `src/commands/generate-test.ts`
2. Implement the command structure following the pattern of existing commands
3. Register the new command in the CLI framework
4. Add command options for task ID (--id=X) parameter
5. Implement parameter validation to ensure a valid task ID is provided
6. Add help documentation for the command
7. Create the basic command flow that retrieves the task from the task store
8. Implement error handling for invalid task IDs and other basic errors
Testing approach:
- Test command registration
- Test parameter validation (missing ID, invalid ID format)
- Test error handling for non-existent task IDs
- Test basic command flow with a mock task store
<info added on 2025-05-23T21:02:03.909Z>
## Updated Implementation Approach
Based on code review findings, the implementation approach needs to be revised:
1. Implement the command in `scripts/modules/commands.js` instead of creating a new file
2. Add command registration in the `registerCommands()` function (around line 482)
3. Follow existing command structure pattern:
```javascript
programInstance
.command('generate-test')
.description('Generate test cases for a task using AI')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-i, --id <id>', 'Task ID parameter')
.option('-p, --prompt <text>', 'Additional prompt context')
.option('-r, --research', 'Use research model')
.action(async (options) => {
// Implementation
});
```
4. Use the following utilities:
- `findProjectRoot()` for resolving project paths
- `findTaskById()` for retrieving task data
- `chalk` for formatted console output
5. Implement error handling following the pattern:
```javascript
try {
// Implementation
} catch (error) {
console.error(chalk.red(`Error generating test: ${error.message}`));
if (error.details) {
console.error(chalk.red(error.details));
}
process.exit(1);
}
```
6. Required imports:
- chalk for colored output
- path for file path operations
- findProjectRoot and findTaskById from './utils.js'
</info added on 2025-05-23T21:02:03.909Z>
## 2. Implement AI prompt construction and FastMCP integration [pending]
### Dependencies: 24.1
### Description: Develop the logic to analyze tasks, construct appropriate AI prompts, and interact with the AI service using FastMCP to generate test content.
### Details:
Implementation steps:
1. Create a utility function to analyze task descriptions and subtasks for test requirements
2. Implement a prompt builder that formats task information into an effective AI prompt
3. Use FastMCP to send the prompt and receive the response
4. Process the FastMCP response to extract the generated test code
5. Implement error handling for FastMCP failures, rate limits, and malformed responses
6. Add appropriate logging for the FastMCP interaction process
Testing approach:
- Test prompt construction with various task types
- Test FastMCP integration with mocked responses
- Test error handling for FastMCP failures
- Test response processing with sample FastMCP outputs
<info added on 2025-05-23T21:04:33.890Z>
## AI Integration Implementation
### AI Service Integration
- Use the unified AI service layer, not FastMCP directly
- Implement with `generateObjectService` from '../ai-services-unified.js'
- Define Zod schema for structured test generation output:
- testContent: Complete Jest test file content
- fileName: Suggested filename for the test file
- mockRequirements: External dependencies that need mocking
### Prompt Construction
- Create system prompt defining AI's role as test generator
- Build user prompt with task context (ID, title, description, details)
- Include test strategy and subtasks context in the prompt
- Follow patterns from add-task.js for prompt structure
### Task Analysis
- Retrieve task data using `findTaskById()` from utils.js
- Build context by analyzing task description, details, and testStrategy
- Examine project structure for import patterns
- Parse specific testing requirements from task.testStrategy field
### File System Operations
- Determine output path in same directory as tasks.json
- Generate standardized filename based on task ID
- Use fs.writeFileSync for writing test content to file
### Error Handling & UI
- Implement try/catch blocks for AI service calls
- Display user-friendly error messages with chalk
- Use loading indicators during AI processing
- Support both research and main AI models
### Telemetry
- Pass through telemetryData from AI service response
- Display AI usage summary for CLI output
### Required Dependencies
- generateObjectService from ai-services-unified.js
- UI components (loading indicators, display functions)
- Zod for schema validation
- Chalk for formatted console output
</info added on 2025-05-23T21:04:33.890Z>
## 3. Implement test file generation and output [pending]
### Dependencies: 24.2
### Description: Create functionality to format AI-generated tests into proper Jest test files and save them to the appropriate location.
### Details:
Implementation steps:
1. Create a utility to format the FastMCP response into a well-structured Jest test file
2. Implement naming logic for test files (task_XXX.test.ts for parent tasks, task_XXX_YYY.test.ts for subtasks)
3. Add logic to determine the appropriate file path for saving the test
4. Implement file system operations to write the test file
5. Add validation to ensure the generated test follows Jest conventions
6. Implement formatting of the test file for consistency with project coding standards
7. Add user feedback about successful test generation and file location
8. Implement handling for both parent tasks and subtasks
Testing approach:
- Test file naming logic for various task/subtask combinations
- Test file content formatting with sample FastMCP outputs
- Test file system operations with mocked fs module
- Test the complete flow from command input to file output
- Verify generated tests can be executed by Jest
<info added on 2025-05-23T21:06:32.457Z>
## Detailed Implementation Guidelines
### File Naming Convention Implementation
```javascript
function generateTestFileName(taskId, isSubtask = false) {
if (isSubtask) {
// For subtasks like "24.1", generate "task_024_001.test.js"
const [parentId, subtaskId] = taskId.split('.');
return `task_${parentId.padStart(3, '0')}_${subtaskId.padStart(3, '0')}.test.js`;
} else {
// For parent tasks like "24", generate "task_024.test.js"
return `task_${taskId.toString().padStart(3, '0')}.test.js`;
}
}
```
### File Location Strategy
- Place generated test files in the `tasks/` directory alongside task files
- This ensures co-location with task documentation and simplifies implementation
### File Content Structure Template
```javascript
/**
* Test file for Task ${taskId}: ${taskTitle}
* Generated automatically by Task Master
*/
import { jest } from '@jest/globals';
// Additional imports based on task requirements
describe('Task ${taskId}: ${taskTitle}', () => {
beforeEach(() => {
// Setup code
});
afterEach(() => {
// Cleanup code
});
test('should ${testDescription}', () => {
// Test implementation
});
});
```
### Code Formatting Standards
- Follow project's .prettierrc configuration:
- Tab width: 2 spaces (useTabs: true)
- Print width: 80 characters
- Semicolons: Required (semi: true)
- Quotes: Single quotes (singleQuote: true)
- Trailing commas: None (trailingComma: "none")
- Bracket spacing: True
- Arrow parens: Always
### File System Operations Implementation
```javascript
import fs from 'fs';
import path from 'path';
// Determine output path
const tasksDir = path.dirname(tasksPath); // Same directory as tasks.json
const fileName = generateTestFileName(task.id, isSubtask);
const filePath = path.join(tasksDir, fileName);
// Ensure directory exists
if (!fs.existsSync(tasksDir)) {
fs.mkdirSync(tasksDir, { recursive: true });
}
// Write test file with proper error handling
try {
fs.writeFileSync(filePath, formattedTestContent, 'utf8');
} catch (error) {
throw new Error(`Failed to write test file: ${error.message}`);
}
```
### Error Handling for File Operations
```javascript
try {
// File writing operation
fs.writeFileSync(filePath, testContent, 'utf8');
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`Directory does not exist: ${path.dirname(filePath)}`);
} else if (error.code === 'EACCES') {
throw new Error(`Permission denied writing to: ${filePath}`);
} else if (error.code === 'ENOSPC') {
throw new Error('Insufficient disk space to write test file');
} else {
throw new Error(`Failed to write test file: ${error.message}`);
}
}
```
### User Feedback Implementation
```javascript
// Success feedback
console.log(chalk.green('✅ Test file generated successfully:'));
console.log(chalk.cyan(` File: ${fileName}`));
console.log(chalk.cyan(` Location: ${filePath}`));
console.log(chalk.gray(` Size: ${testContent.length} characters`));
// Additional info
if (mockRequirements && mockRequirements.length > 0) {
console.log(chalk.yellow(` Mocks needed: ${mockRequirements.join(', ')}`));
}
```
### Content Validation Requirements
1. Jest Syntax Validation:
- Ensure proper describe/test structure
- Validate import statements
- Check for balanced brackets and parentheses
2. Code Quality Checks:
- Verify no syntax errors
- Ensure proper indentation
- Check for required imports
3. Test Completeness:
- At least one test case
- Proper test descriptions
- Appropriate assertions
### Required Dependencies
```javascript
import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import { log } from '../utils.js';
```
### Integration with Existing Patterns
Follow the pattern from `generate-task-files.js`:
1. Read task data using existing utilities
2. Process content with proper formatting
3. Write files with error handling
4. Provide feedback to user
5. Return success data for MCP integration
</info added on 2025-05-23T21:06:32.457Z>
<info added on 2025-05-23T21:18:25.369Z>
## Corrected Implementation Approach
### Updated File Location Strategy
**CORRECTION**: Tests should go in `/tests/` directory, not `/tasks/` directory.
Based on Jest configuration analysis:
- Jest is configured with `roots: ['<rootDir>/tests']`
- Test pattern: `**/?(*.)+(spec|test).js`
- Current test structure has `/tests/unit/`, `/tests/integration/`, etc.
### Recommended Directory Structure:
```
tests/
├── unit/ # Manual unit tests
├── integration/ # Manual integration tests
├── generated/ # AI-generated tests
│ ├── tasks/ # Generated task tests
│ │ ├── task_024.test.js
│ │ └── task_024_001.test.js
│ └── README.md # Explains generated tests
└── fixtures/ # Test fixtures
```
### Updated File Path Logic:
```javascript
// Determine output path - place in tests/generated/tasks/
const projectRoot = findProjectRoot() || '.';
const testsDir = path.join(projectRoot, 'tests', 'generated', 'tasks');
const fileName = generateTestFileName(task.id, isSubtask);
const filePath = path.join(testsDir, fileName);
// Ensure directory structure exists
if (!fs.existsSync(testsDir)) {
fs.mkdirSync(testsDir, { recursive: true });
}
```
### Testing Framework Configuration
The generate-test command should read the configured testing framework from `.taskmasterconfig`:
```javascript
// Read testing framework from config
const config = getConfig(projectRoot);
const testingFramework = config.testingFramework || 'jest'; // Default to Jest
// Generate different templates based on framework
switch (testingFramework) {
case 'jest':
return generateJestTest(task, context);
case 'mocha':
return generateMochaTest(task, context);
case 'vitest':
return generateVitestTest(task, context);
default:
throw new Error(`Unsupported testing framework: ${testingFramework}`);
}
```
### Framework-Specific Templates
**Jest Template** (current):
```javascript
/**
* Test file for Task ${taskId}: ${taskTitle}
* Generated automatically by Task Master
*/
import { jest } from '@jest/globals';
// Task-specific imports
describe('Task ${taskId}: ${taskTitle}', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('should ${testDescription}', () => {
// Test implementation
});
});
```
**Mocha Template**:
```javascript
/**
* Test file for Task ${taskId}: ${taskTitle}
* Generated automatically by Task Master
*/
import { expect } from 'chai';
import sinon from 'sinon';
// Task-specific imports
describe('Task ${taskId}: ${taskTitle}', () => {
beforeEach(() => {
sinon.restore();
});
it('should ${testDescription}', () => {
// Test implementation
});
});
```
**Vitest Template**:
```javascript
/**
* Test file for Task ${taskId}: ${taskTitle}
* Generated automatically by Task Master
*/
import { describe, test, expect, vi, beforeEach } from 'vitest';
// Task-specific imports
describe('Task ${taskId}: ${taskTitle}', () => {
beforeEach(() => {
vi.clearAllMocks();
});
test('should ${testDescription}', () => {
// Test implementation
});
});
```
### AI Prompt Enhancement for Mocking
To address the mocking challenge, enhance the AI prompt with project context:
```javascript
const systemPrompt = `You are an expert at generating comprehensive test files. When generating tests, pay special attention to mocking external dependencies correctly.
CRITICAL MOCKING GUIDELINES:
1. Analyze the task requirements to identify external dependencies (APIs, databases, file system, etc.)
2. Mock external dependencies at the module level, not inline
3. Use the testing framework's mocking utilities (jest.mock(), sinon.stub(), vi.mock())
4. Create realistic mock data that matches the expected API responses
5. Test both success and error scenarios for mocked dependencies
6. Ensure mocks are cleared between tests to prevent test pollution
Testing Framework: ${testingFramework}
Project Structure: ${projectStructureContext}
`;
```
### Integration with Future Features
This primitive command design enables:
1. **Automatic test generation**: `task-master add-task --with-test`
2. **Batch test generation**: `task-master generate-tests --all`
3. **Framework-agnostic**: Support multiple testing frameworks
4. **Smart mocking**: LLM analyzes dependencies and generates appropriate mocks
### Updated Implementation Requirements:
1. **Read testing framework** from `.taskmasterconfig`
2. **Create tests directory structure** if it doesn't exist
3. **Generate framework-specific templates** based on configuration
4. **Enhanced AI prompts** with mocking best practices
5. **Project structure analysis** for better import resolution
6. **Mock dependency detection** from task requirements
</info added on 2025-05-23T21:18:25.369Z>
## 4. Implement MCP tool integration for generate-test command [pending]
### Dependencies: 24.3
### Description: Create MCP server tool support for the generate-test command to enable integration with Claude Code and other MCP clients.
### Details:
Implementation steps:
1. Create direct function wrapper in mcp-server/src/core/direct-functions/
2. Create MCP tool registration in mcp-server/src/tools/
3. Add tool to the main tools index
4. Implement proper parameter validation and error handling
5. Ensure telemetry data is properly passed through
6. Add tool to MCP server registration
The MCP tool should support the same parameters as the CLI command:
- id: Task ID to generate tests for
- file: Path to tasks.json file
- research: Whether to use research model
- prompt: Additional context for test generation
Follow the existing pattern from other MCP tools like add-task.js and expand-task.js.
## 5. Add testing framework configuration to project initialization [pending]
### Dependencies: 24.3
### 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:
1. **Add Testing Framework Prompt to init.js**:
- Add interactive prompt asking users to choose testing framework
- Support Jest (default), Mocha + Chai, Vitest, Ava, Jasmine
- Include brief descriptions of each framework
- Allow --testing-framework flag for non-interactive mode
2. **Update .taskmasterconfig Template**:
- Add testingFramework field to configuration file
- Include default dependencies for each framework
- Store framework-specific configuration options
3. **Framework-Specific Setup**:
- Generate appropriate config files (jest.config.js, vitest.config.ts, etc.)
- Add framework dependencies to package.json suggestions
- Create sample test file for the chosen framework
4. **Integration Points**:
- Ensure generate-test command reads testingFramework from config
- Add validation to prevent conflicts between framework choices
- Support switching frameworks later via models command or separate config command
This makes the generate-test command truly framework-agnostic and sets up the foundation for --with-test flags in other commands.
<info added on 2025-05-23T21:22:02.048Z>
# Implementation Plan for Testing Framework Integration
## Code Structure
### 1. Update init.js
- Add testing framework prompt after addAliases prompt
- Implement framework selection with descriptions
- Support non-interactive mode with --testing-framework flag
- Create setupTestingFramework() function to handle framework-specific setup
### 2. Create New Module Files
- Create `scripts/modules/testing-frameworks.js` for framework templates and setup
- Add sample test generators for each supported framework
- Implement config file generation for each framework
### 3. Update Configuration Templates
- Modify `assets/.taskmasterconfig` to include testing fields:
```json
"testingFramework": "{{testingFramework}}",
"testingConfig": {
"framework": "{{testingFramework}}",
"setupFiles": [],
"testDirectory": "tests",
"testPattern": "**/*.test.js",
"coverage": {
"enabled": false,
"threshold": 80
}
}
```
### 4. Create Framework-Specific Templates
- `assets/jest.config.template.js`
- `assets/vitest.config.template.ts`
- `assets/.mocharc.template.json`
- `assets/ava.config.template.js`
- `assets/jasmine.json.template`
### 5. Update commands.js
- Add `--testing-framework <framework>` option to init command
- Add validation for supported frameworks
## Error Handling
- Validate selected framework against supported list
- Handle existing config files gracefully with warning/overwrite prompt
- Provide recovery options if framework setup fails
- Add conflict detection for multiple testing frameworks
## Integration Points
- Ensure generate-test command reads testingFramework from config
- Prepare for future --with-test flag in other commands
- Support framework switching via config command
## Testing Requirements
- Unit tests for framework selection logic
- Integration tests for config file generation
- Validation tests for each supported framework
</info added on 2025-05-23T21:22:02.048Z>

View File

@@ -1,118 +0,0 @@
# Task ID: 25
# Title: Implement 'add-subtask' Command for Task Hierarchy Management
# Status: done
# Dependencies: 3
# Priority: medium
# Description: Create a command-line interface command that allows users to manually add subtasks to existing tasks, establishing a parent-child relationship between tasks.
# Details:
Implement the 'add-subtask' command that enables users to create hierarchical relationships between tasks. The command should:
1. 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
2. Validate that the parent task exists before proceeding
3. If creating a new subtask, collect all necessary task information (title, description, due date, etc.)
4. If converting an existing task, ensure it's not already a subtask of another task
5. Update the data model to support parent-child relationships between tasks
6. Modify the task storage mechanism to persist these relationships
7. Ensure that when a parent task is marked complete, there's appropriate handling of subtasks (prompt user or provide options)
8. Update the task listing functionality to display subtasks with appropriate indentation or visual hierarchy
9. Implement proper error handling for cases like circular dependencies (a task cannot be a subtask of its own subtask)
10. Document the command syntax and options in the help system
# Test Strategy:
Testing should verify both the functionality and edge cases of the subtask implementation:
1. Unit tests:
- Test adding a new subtask to an existing task
- Test converting an existing task to a subtask
- Test validation logic for parent task existence
- Test prevention of circular dependencies
- Test error handling for invalid inputs
2. Integration tests:
- Verify subtask relationships are correctly persisted to storage
- Verify subtasks appear correctly in task listings
- Test the complete workflow from adding a subtask to viewing it in listings
3. Edge cases:
- Attempt to add a subtask to a non-existent parent
- Attempt to make a task a subtask of itself
- Attempt to create circular dependencies (A → B → A)
- Test with a deep hierarchy of subtasks (A → B → C → D)
- Test handling of subtasks when parent tasks are deleted
- Verify behavior when marking parent tasks as complete
4. Manual testing:
- Verify command usability and clarity of error messages
- Test the command with various parameter combinations
# Subtasks:
## 1. Update Data Model to Support Parent-Child Task Relationships [done]
### Dependencies: None
### Description: Modify the task data structure to support hierarchical relationships between tasks
### Details:
1. Examine the current task data structure in scripts/modules/task-manager.js
2. Add a 'parentId' field to the task object schema to reference parent tasks
3. Add a 'subtasks' array field to store references to child tasks
4. Update any relevant validation functions to account for these new fields
5. Ensure serialization and deserialization of tasks properly handles these new fields
6. Update the storage mechanism to persist these relationships
7. Test by manually creating tasks with parent-child relationships and verifying they're saved correctly
8. Write unit tests to verify the updated data model works as expected
## 2. Implement Core addSubtask Function in task-manager.js [done]
### Dependencies: 25.1
### Description: Create the core function that handles adding subtasks to parent tasks
### Details:
1. Create a new addSubtask function in scripts/modules/task-manager.js
2. Implement logic to validate that the parent task exists
3. Add functionality to handle both creating new subtasks and converting existing tasks
4. For new subtasks: collect task information and create a new task with parentId set
5. For existing tasks: validate it's not already a subtask and update its parentId
6. Add validation to prevent circular dependencies (a task cannot be a subtask of its own subtask)
7. Update the parent task's subtasks array
8. Ensure proper error handling with descriptive error messages
9. Export the function for use by the command handler
10. Write unit tests to verify all scenarios (new subtask, converting task, error cases)
## 3. Implement add-subtask Command in commands.js [done]
### Dependencies: 25.2
### Description: Create the command-line interface for the add-subtask functionality
### Details:
1. Add a new command registration in scripts/modules/commands.js following existing patterns
2. Define command syntax: 'add-subtask <parentId> [--task-id=<taskId> | --title=<title>]'
3. Implement command handler that calls the addSubtask function from task-manager.js
4. Add interactive prompts to collect required information when not provided as arguments
5. Implement validation for command arguments
6. Add appropriate success and error messages
7. Document the command syntax and options in the help system
8. Test the command with various input combinations
9. Ensure the command follows the same patterns as other commands like add-dependency
## 4. Create Unit Test for add-subtask [done]
### Dependencies: 25.2, 25.3
### Description: Develop comprehensive unit tests for the add-subtask functionality
### Details:
1. Create a test file in tests/unit/ directory for the add-subtask functionality
2. Write tests for the addSubtask function in task-manager.js
3. Test all key scenarios: adding new subtasks, converting existing tasks to subtasks
4. Test error cases: non-existent parent task, circular dependencies, invalid input
5. Use Jest mocks to isolate the function from file system operations
6. Test the command handler in isolation using mock functions
7. Ensure test coverage for all branches and edge cases
8. Document the testing approach for future reference
## 5. Implement remove-subtask Command [done]
### Dependencies: 25.2, 25.3
### Description: Create functionality to remove a subtask from its parent, following the same approach as add-subtask
### Details:
1. Create a removeSubtask function in scripts/modules/task-manager.js
2. Implement logic to validate the subtask exists and is actually a subtask
3. Add options to either delete the subtask completely or convert it to a standalone task
4. Update the parent task's subtasks array to remove the reference
5. If converting to standalone task, clear the parentId reference
6. Implement the remove-subtask command in scripts/modules/commands.js following patterns from add-subtask
7. Add appropriate validation and error messages
8. Document the command in the help system
9. Export the function in task-manager.js
10. Ensure proper error handling for all scenarios

View File

@@ -1,90 +0,0 @@
# Task ID: 26
# Title: Implement Context Foundation for AI Operations
# Status: pending
# Dependencies: 5, 6, 7
# Priority: high
# 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.
# Details:
Create a Phase 1 foundation for context integration in Task Master that provides immediate practical value:
1. Add `--context-file` Flag to AI Commands:
- Add a consistent `--context-file <file>` option to all AI-related commands (expand, update, add-task, etc.)
- Implement file reading functionality that loads content from the specified file
- Add content integration into Claude API prompts with appropriate formatting
- Handle error conditions such as file not found gracefully
- Update help documentation to explain the new option
2. Implement Cursor Rules Integration for Context:
- Create a `--context-rules <rules>` option for all AI commands
- Implement functionality to extract content from specified .cursor/rules/*.mdc files
- Support comma-separated lists of rule names and "all" option
- Add validation and error handling for non-existent rules
- Include helpful examples in command help output
3. Implement Basic Context File Extraction Utility:
- Create utility functions in utils.js for reading context from files
- Add proper error handling and logging
- Implement content validation to ensure reasonable size limits
- Add content truncation if files exceed token limits
- Create helper functions for formatting context additions properly
4. Update Command Handler Logic:
- Modify command handlers to support the new context options
- Update prompt construction to incorporate context content
- Ensure backwards compatibility with existing commands
- Add logging for context inclusion to aid troubleshooting
The focus of this phase is to provide immediate value with straightforward implementations that enable users to include relevant context in their AI operations.
# Test Strategy:
Testing should verify that the context foundation works as expected and adds value:
1. Functional Tests:
- Verify `--context-file` flag correctly reads and includes content from specified files
- Test that `--context-rules` correctly extracts and formats content from cursor rules
- Test with both existing and non-existent files/rules to verify error handling
- Verify content truncation works appropriately for large files
2. Integration Tests:
- Test each AI-related command with context options
- Verify context is properly included in API calls to Claude
- Test combinations of multiple context options
- Verify help documentation includes the new options
3. Usability Testing:
- Create test scenarios that show clear improvement in AI output quality with context
- Compare outputs with and without context to measure impact
- Document examples of effective context usage for the user documentation
4. Error Handling:
- Test invalid file paths and rule names
- Test oversized context files
- Verify appropriate error messages guide users to correct usage
The testing focus should be on proving immediate value to users while ensuring robust error handling.
# Subtasks:
## 1. Implement --context-file Flag for AI Commands [pending]
### Dependencies: None
### 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
## 2. Implement --context Flag for AI Commands [pending]
### Dependencies: None
### 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
## 3. Implement Cursor Rules Integration for Context [pending]
### Dependencies: None
### 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
## 4. Implement Basic Context File Extraction Utility [pending]
### Dependencies: None
### 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

View File

@@ -1,95 +0,0 @@
# Task ID: 27
# Title: Implement Context Enhancements for AI Operations
# Status: pending
# Dependencies: 26
# Priority: high
# 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.
# Details:
Building upon the foundational context implementation in Task #26, implement Phase 2 context enhancements:
1. Add Code Context Extraction Feature:
- Create a `--context-code <pattern>` option for all AI commands
- Implement glob-based file matching to extract code from specified patterns
- Create intelligent code parsing to extract most relevant sections (function signatures, classes, exports)
- Implement token usage optimization by selecting key structural elements
- Add formatting for code context with proper file paths and syntax indicators
2. Implement Task History Context:
- Add a `--context-tasks <ids>` option for AI commands
- Support comma-separated task IDs and a "similar" option to find related tasks
- Create functions to extract context from specified tasks or find similar tasks
- Implement formatting for task context with clear section markers
- Add validation and error handling for non-existent task IDs
3. Add PRD Context Integration:
- Create a `--context-prd <file>` option for AI commands
- Implement PRD text extraction and intelligent summarization
- Add formatting for PRD context with appropriate section markers
- Integrate with the existing PRD parsing functionality from Task #6
4. Improve Context Formatting and Integration:
- Create a standardized context formatting system
- Implement type-based sectioning for different context sources
- Add token estimation for different context types to manage total prompt size
- Enhance prompt templates to better integrate various context types
These enhancements will provide significantly richer context for AI operations, resulting in more accurate and relevant outputs while remaining practical to implement.
# Test Strategy:
Testing should verify the enhanced context functionality:
1. Code Context Testing:
- Verify pattern matching works for different glob patterns
- Test code extraction with various file types and sizes
- Verify intelligent parsing correctly identifies important code elements
- Test token optimization by comparing full file extraction vs. optimized extraction
- Check code formatting in prompts sent to Claude API
2. Task History Testing:
- Test with different combinations of task IDs
- Verify "similar" option correctly identifies relevant tasks
- Test with non-existent task IDs to ensure proper error handling
- Verify formatting and integration in prompts
3. PRD Context Testing:
- Test with various PRD files of different sizes
- Verify summarization functions correctly when PRDs are too large
- Test integration with prompts and formatting
4. Performance Testing:
- Measure the impact of context enrichment on command execution time
- Test with large code bases to ensure reasonable performance
- Verify token counting and optimization functions work as expected
5. Quality Assessment:
- Compare AI outputs with Phase 1 vs. Phase 2 context to measure improvements
- Create test cases that specifically benefit from code context
- Create test cases that benefit from task history context
Focus testing on practical use cases that demonstrate clear improvements in AI-generated outputs.
# Subtasks:
## 1. Implement Code Context Extraction Feature [pending]
### Dependencies: None
### Description: Create a --context-code <pattern> option for AI commands and implement glob-based file matching to extract relevant code sections
### Details:
## 2. Implement Task History Context Integration [pending]
### Dependencies: None
### Description: Add a --context-tasks option for AI commands that supports finding and extracting context from specified or similar tasks
### Details:
## 3. Add PRD Context Integration [pending]
### Dependencies: None
### Description: Implement a --context-prd option for AI commands that extracts and formats content from PRD files
### Details:
## 4. Create Standardized Context Formatting System [pending]
### Dependencies: None
### Description: Implement a consistent formatting system for different context types with section markers and token optimization
### Details:

View File

@@ -1,112 +0,0 @@
# Task ID: 28
# Title: Implement Advanced ContextManager System
# Status: pending
# Dependencies: 26, 27
# Priority: high
# Description: Create a comprehensive ContextManager class to unify context handling with advanced features like context optimization, prioritization, and intelligent context selection.
# Details:
Building on Phase 1 and Phase 2 context implementations, develop Phase 3 advanced context management:
1. Implement the ContextManager Class:
- Create a unified `ContextManager` class that encapsulates all context functionality
- Implement methods for gathering context from all supported sources
- Create a configurable context priority system to favor more relevant context types
- Add token management to ensure context fits within API limits
- Implement caching for frequently used context to improve performance
2. Create Context Optimization Pipeline:
- Develop intelligent context optimization algorithms
- Implement type-based truncation strategies (code vs. text)
- Create relevance scoring to prioritize most useful context portions
- Add token budget allocation that divides available tokens among context types
- Implement dynamic optimization based on operation type
3. Add Command Interface Enhancements:
- Create the `--context-all` flag to include all available context
- Add the `--context-max-tokens <tokens>` option to control token allocation
- Implement unified context options across all AI commands
- Add intelligent default values for different command types
4. Integrate with AI Services:
- Update the AI service integration to use the ContextManager
- Create specialized context assembly for different AI operations
- Add post-processing to capture new context from AI responses
- Implement adaptive context selection based on operation success
5. Add Performance Monitoring:
- Create context usage statistics tracking
- Implement logging for context selection decisions
- Add warnings for context token limits
- Create troubleshooting utilities for context-related issues
The 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.
# Test Strategy:
Testing should verify both the functionality and performance of the advanced context management:
1. Unit Testing:
- Test all ContextManager class methods with various inputs
- Verify optimization algorithms maintain critical information
- Test caching mechanisms for correctness and efficiency
- Verify token allocation and budgeting functions
- Test each context source integration separately
2. Integration Testing:
- Verify ContextManager integration with AI services
- Test with all AI-related commands
- Verify backward compatibility with existing context options
- Test context prioritization across multiple context types
- Verify logging and error handling
3. Performance Testing:
- Benchmark context gathering and optimization times
- Test with large and complex context sources
- Measure impact of caching on repeated operations
- Verify memory usage remains acceptable
- Test with token limits of different sizes
4. Quality Assessment:
- Compare AI outputs using Phase 3 vs. earlier context handling
- Measure improvements in context relevance and quality
- Test complex scenarios requiring multiple context types
- Quantify the impact on token efficiency
5. User Experience Testing:
- Verify CLI options are intuitive and well-documented
- Test error messages are helpful for troubleshooting
- Ensure log output provides useful insights
- Test all convenience options like `--context-all`
Create automated test suites for regression testing of the complete context system.
# Subtasks:
## 1. Implement Core ContextManager Class Structure [pending]
### Dependencies: None
### Description: Create a unified ContextManager class that encapsulates all context functionality with methods for gathering context from supported sources
### Details:
## 2. Develop Context Optimization Pipeline [pending]
### Dependencies: None
### Description: Create intelligent algorithms for context optimization including type-based truncation, relevance scoring, and token budget allocation
### Details:
## 3. Create Command Interface Enhancements [pending]
### Dependencies: None
### Description: Add unified context options to all AI commands including --context-all flag and --context-max-tokens for controlling allocation
### Details:
## 4. Integrate ContextManager with AI Services [pending]
### Dependencies: None
### Description: Update AI service integration to use the ContextManager with specialized context assembly for different operations
### Details:
## 5. Implement Performance Monitoring and Metrics [pending]
### Dependencies: None
### Description: Create a system for tracking context usage statistics, logging selection decisions, and providing troubleshooting utilities
### Details:

View File

@@ -1,33 +0,0 @@
# Task ID: 29
# Title: Update Claude 3.7 Sonnet Integration with Beta Header for 128k Token Output
# Status: done
# Dependencies: None
# Priority: medium
# 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.
# 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:
1. Locate the Claude 3.7 Sonnet API request configuration in ai-services.js
2. Add the beta header 'output-128k-2025-02-19' to the request headers
3. Update any related configuration parameters that might need adjustment for the increased token limit
4. Ensure that token counting and management logic is updated to account for the new 128k token output limit
5. Update any documentation comments in the code to reflect the new capability
6. Consider implementing a configuration option to enable/disable this feature, as it may be a beta feature subject to change
7. Verify that the token management logic correctly handles the increased limit without causing unexpected behavior
8. Ensure backward compatibility with existing code that might assume lower token limits
The implementation should be clean and maintainable, with appropriate error handling for cases where the beta header might not be supported in the future.
# Test Strategy:
Testing should verify that the beta header is correctly included and that the system properly handles the increased token limit:
1. Unit test: Verify that the API request to Claude 3.7 Sonnet includes the 'output-128k-2025-02-19' header
2. Integration test: Make an actual API call to Claude 3.7 Sonnet with the beta header and confirm a successful response
3. Test with a prompt designed to generate a very large response (>20k tokens but <128k tokens) and verify it completes successfully
4. Test the token counting logic with mock responses of various sizes to ensure it correctly handles responses approaching the 128k limit
5. Verify error handling by simulating API errors related to the beta header
6. Test any configuration options for enabling/disabling the feature
7. Performance test: Measure any impact on response time or system resources when handling very large responses
8. Regression test: Ensure existing functionality using Claude 3.7 Sonnet continues to work as expected
Document all test results, including any limitations or edge cases discovered during testing.

View File

@@ -1,40 +0,0 @@
# Task ID: 30
# Title: Enhance parse-prd Command to Support Default PRD Path
# Status: done
# Dependencies: None
# Priority: medium
# 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.
# Details:
Currently, the parse-prd command requires users to explicitly specify the path to the PRD document. This enhancement should:
1. Implement a default PRD path configuration that can be set in the application settings or configuration file.
2. Update the parse-prd command to check for this default path when no path argument is provided.
3. Add a configuration option that allows users to set/update the default PRD path through a command like `config set default-prd-path <path>`.
4. Ensure backward compatibility by maintaining support for explicit path specification.
5. Add appropriate error handling for cases where the default path is not set or the file doesn't exist.
6. Update the command's help text to indicate that a default path will be used if none is specified.
7. Consider implementing path validation to ensure the default path points to a valid PRD document.
8. If multiple PRD formats are supported (Markdown, PDF, etc.), ensure the default path handling works with all supported formats.
9. Add logging for default path usage to help with debugging and usage analytics.
# Test Strategy:
1. Unit tests:
- Test that the command correctly uses the default path when no path is provided
- Test that explicit paths override the default path
- Test error handling when default path is not set
- Test error handling when default path is set but file doesn't exist
2. Integration tests:
- Test the full workflow of setting a default path and then using the parse-prd command without arguments
- Test with various file formats if multiple are supported
3. Manual testing:
- Verify the command works in a real environment with actual PRD documents
- Test the user experience of setting and using default paths
- Verify help text correctly explains the default path behavior
4. Edge cases to test:
- Relative vs. absolute paths for default path setting
- Path with special characters or spaces
- Very long paths approaching system limits
- Permissions issues with the default path location

View File

@@ -1,42 +0,0 @@
# Task ID: 31
# Title: Add Config Flag Support to task-master init Command
# Status: done
# Dependencies: None
# Priority: low
# 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.
# 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.
Implementation steps:
1. Identify all configuration options that are currently collected through CLI prompts during initialization
2. Create corresponding command-line flags for each configuration option (e.g., --project-name, --ai-provider, etc.)
3. Modify the init command handler to check for these flags before starting the interactive prompts
4. If a flag is provided, skip the corresponding prompt and use the provided value instead
5. If all required configuration values are provided via flags, skip the interactive process entirely
6. Update the command's help text to document all available flags and their usage
7. Ensure backward compatibility so the command still works with the interactive approach when no flags are provided
8. 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)
The 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.
# Test Strategy:
Testing should verify both the interactive and non-interactive paths work correctly:
1. Unit tests:
- Test each flag individually to ensure it correctly overrides the corresponding prompt
- Test combinations of flags to ensure they work together properly
- Test validation of flag values to ensure invalid values are rejected
- Test the --non-interactive flag to ensure it fails when required values are missing
2. Integration tests:
- Test a complete initialization with all flags provided
- Test partial initialization with some flags and some interactive prompts
- Test initialization with no flags (fully interactive)
3. Manual testing scenarios:
- Run 'task-master init --project-name="Test Project" --ai-provider="openai"' and verify it skips those prompts
- Run 'task-master init --help' and verify all flags are documented
- Run 'task-master init --non-interactive' without required flags and verify it fails with a helpful error message
- Run a complete non-interactive initialization and verify the resulting configuration file matches expectations
Ensure the command's documentation is updated to reflect the new functionality, and verify that the help text accurately describes all available options.

View File

@@ -1,231 +0,0 @@
# Task ID: 32
# Title: Implement "learn" Command for Automatic Cursor Rule Generation
# Status: deferred
# Dependencies: None
# Priority: high
# 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.
# Details:
Implement a new command in the task-master CLI that enables Cursor to learn from successful coding patterns and chat interactions:
Key Components:
1. Cursor Data Analysis
- Access and parse Cursor's chat history from ~/Library/Application Support/Cursor/User/History
- Extract relevant patterns, corrections, and successful implementations
- Track file changes and their associated chat context
2. Rule Management
- Use cursor_rules.mdc as the template for all rule file formatting
- Manage rule files in .cursor/rules directory
- Support both creation and updates of rule files
- Categorize rules based on context (testing, components, API, etc.)
3. AI Integration
- Utilize ai-services.js to interact with Claude
- Provide comprehensive context including:
* Relevant chat history showing the evolution of solutions
* Code changes and their outcomes
* Existing rules and template structure
- Generate or update rules while maintaining template consistency
4. Implementation Requirements:
- Automatic triggering after task completion (configurable)
- Manual triggering via CLI command
- Proper error handling for missing or corrupt files
- Validation against cursor_rules.mdc template
- Performance optimization for large histories
- Clear logging and progress indication
5. Key Files:
- commands/learn.js: Main command implementation
- rules/cursor-rules-manager.js: Rule file management
- utils/chat-history-analyzer.js: Cursor chat analysis
- index.js: Command registration
6. Security Considerations:
- Safe file system operations
- Proper error handling for inaccessible files
- Validation of generated rules
- Backup of existing rules before updates
# Test Strategy:
1. Unit Tests:
- Test each component in isolation:
* Chat history extraction and analysis
* Rule file management and validation
* Pattern detection and categorization
* Template validation logic
- Mock file system operations and AI responses
- Test error handling and edge cases
2. Integration Tests:
- End-to-end command execution
- File system interactions
- AI service integration
- Rule generation and updates
- Template compliance validation
3. Manual Testing:
- Test after completing actual development tasks
- Verify rule quality and usefulness
- Check template compliance
- Validate performance with large histories
- Test automatic and manual triggering
4. Validation Criteria:
- Generated rules follow cursor_rules.mdc format
- Rules capture meaningful patterns
- Performance remains acceptable
- Error handling works as expected
- Generated rules improve Cursor's effectiveness
# Subtasks:
## 1. Create Initial File Structure [pending]
### Dependencies: None
### Description: Set up the basic file structure for the learn command implementation
### Details:
Create the following files with basic exports:
- commands/learn.js
- rules/cursor-rules-manager.js
- utils/chat-history-analyzer.js
- utils/cursor-path-helper.js
## 2. Implement Cursor Path Helper [pending]
### Dependencies: None
### Description: Create utility functions to handle Cursor's application data paths
### Details:
In utils/cursor-path-helper.js implement:
- getCursorAppDir(): Returns ~/Library/Application Support/Cursor
- getCursorHistoryDir(): Returns User/History path
- getCursorLogsDir(): Returns logs directory path
- validatePaths(): Ensures required directories exist
## 3. Create Chat History Analyzer Base [pending]
### Dependencies: None
### Description: Create the base structure for analyzing Cursor's chat history
### Details:
In utils/chat-history-analyzer.js create:
- ChatHistoryAnalyzer class
- readHistoryDir(): Lists all history directories
- readEntriesJson(): Parses entries.json files
- parseHistoryEntry(): Extracts relevant data from .js files
## 4. Implement Chat History Extraction [pending]
### Dependencies: None
### Description: Add core functionality to extract relevant chat history
### Details:
In ChatHistoryAnalyzer add:
- extractChatHistory(startTime): Gets history since task start
- parseFileChanges(): Extracts code changes
- parseAIInteractions(): Extracts AI responses
- filterRelevantHistory(): Removes irrelevant entries
## 5. Create CursorRulesManager Base [pending]
### Dependencies: None
### Description: Set up the base structure for managing Cursor rules
### Details:
In rules/cursor-rules-manager.js create:
- CursorRulesManager class
- readTemplate(): Reads cursor_rules.mdc
- listRuleFiles(): Lists all .mdc files
- readRuleFile(): Reads specific rule file
## 6. Implement Template Validation [pending]
### Dependencies: None
### Description: Add validation logic for rule files against cursor_rules.mdc
### Details:
In CursorRulesManager add:
- validateRuleFormat(): Checks against template
- parseTemplateStructure(): Extracts template sections
- validateAgainstTemplate(): Validates content structure
- getRequiredSections(): Lists mandatory sections
## 7. Add Rule Categorization Logic [pending]
### Dependencies: None
### Description: Implement logic to categorize changes into rule files
### Details:
In CursorRulesManager add:
- categorizeChanges(): Maps changes to rule files
- detectRuleCategories(): Identifies relevant categories
- getRuleFileForPattern(): Maps patterns to files
- createNewRuleFile(): Initializes new rule files
## 8. Implement Pattern Analysis [pending]
### Dependencies: None
### Description: Create functions to analyze implementation patterns
### Details:
In ChatHistoryAnalyzer add:
- extractPatterns(): Finds success patterns
- extractCorrections(): Finds error corrections
- findSuccessfulPaths(): Tracks successful implementations
- analyzeDecisions(): Extracts key decisions
## 9. Create AI Prompt Builder [pending]
### Dependencies: None
### Description: Implement prompt construction for Claude
### Details:
In learn.js create:
- buildRuleUpdatePrompt(): Builds Claude prompt
- formatHistoryContext(): Formats chat history
- formatRuleContext(): Formats current rules
- buildInstructions(): Creates specific instructions
## 10. Implement Learn Command Core [pending]
### Dependencies: None
### Description: Create the main learn command implementation
### Details:
In commands/learn.js implement:
- learnCommand(): Main command function
- processRuleUpdates(): Handles rule updates
- generateSummary(): Creates learning summary
- handleErrors(): Manages error cases
## 11. Add Auto-trigger Support [pending]
### Dependencies: None
### Description: Implement automatic learning after task completion
### Details:
Update task-manager.js:
- Add autoLearnConfig handling
- Modify completeTask() to trigger learning
- Add learning status tracking
- Implement learning queue
## 12. Implement CLI Integration [pending]
### Dependencies: None
### Description: Add the learn command to the CLI
### Details:
Update index.js to:
- Register learn command
- Add command options
- Handle manual triggers
- Process command flags
## 13. Add Progress Logging [pending]
### Dependencies: None
### Description: Implement detailed progress logging
### Details:
Create utils/learn-logger.js with:
- logLearningProgress(): Tracks overall progress
- logRuleUpdates(): Tracks rule changes
- logErrors(): Handles error logging
- createSummary(): Generates final report
## 14. Implement Error Recovery [pending]
### Dependencies: None
### Description: Add robust error handling throughout the system
### Details:
Create utils/error-handler.js with:
- handleFileErrors(): Manages file system errors
- handleParsingErrors(): Manages parsing failures
- handleAIErrors(): Manages Claude API errors
- implementRecoveryStrategies(): Adds recovery logic
## 15. Add Performance Optimization [pending]
### Dependencies: None
### Description: Optimize performance for large histories
### Details:
Add to utils/performance-optimizer.js:
- implementCaching(): Adds result caching
- optimizeFileReading(): Improves file reading
- addProgressiveLoading(): Implements lazy loading
- addMemoryManagement(): Manages memory usage

View File

@@ -1,44 +0,0 @@
# Task ID: 33
# Title: Create and Integrate Windsurf Rules Document from MDC Files
# Status: done
# Dependencies: None
# Priority: medium
# 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.
# 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:
1. Identify and locate the three primary .mdc files used for Cursor Rules
2. Extract content from these files and merge them into a single document
3. Refactor the content to make it Windsurf-specific, replacing Cursor-specific terminology and adapting guidelines as needed
4. Create a function that generates a .windsurfrules document from this content
5. Integrate this function into the initialization pipeline
6. Implement logic to check if a .windsurfrules document already exists:
- If it exists, append the new content to it
- If it doesn't exist, create a new document
7. Ensure proper error handling for file operations
8. Add appropriate logging to track the generation and modification of the .windsurfrules document
The implementation should be modular and maintainable, with clear separation of concerns between content extraction, refactoring, and file operations.
# Test Strategy:
Testing should verify both the content generation and the integration with the initialization pipeline:
1. Unit Tests:
- Test the content extraction function with mock .mdc files
- Test the content refactoring function to ensure Cursor-specific terms are properly replaced
- Test the file operation functions with mock filesystem
2. Integration Tests:
- Test the creation of a new .windsurfrules document when none exists
- Test appending to an existing .windsurfrules document
- Test the complete initialization pipeline with the new functionality
3. Manual Verification:
- Inspect the generated .windsurfrules document to ensure content is properly combined and refactored
- Verify that Cursor-specific terminology has been replaced with Windsurf-specific terminology
- Run the initialization process multiple times to verify idempotence (content isn't duplicated on multiple runs)
4. Edge Cases:
- Test with missing or corrupted .mdc files
- Test with an existing but empty .windsurfrules document
- Test with an existing .windsurfrules document that already contains some of the content

View File

@@ -1,156 +0,0 @@
# Task ID: 34
# Title: Implement updateTask Command for Single Task Updates
# Status: done
# Dependencies: None
# Priority: high
# 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.
# 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:
1. Accept a single task ID as a required parameter
2. Use the same AI-driven approach as the existing update command to refine the task
3. Preserve the completion status of any subtasks that were previously marked as complete
4. Support all options from the existing update command including:
- The research flag for Perplexity integration
- Any formatting or refinement options
- Task context options
5. Update the CLI help documentation to include this new command
6. Ensure the command follows the same pattern as other commands in the codebase
7. Add appropriate error handling for cases where the specified task ID doesn't exist
8. Implement the ability to update task title, description, and details separately if needed
9. Ensure the command returns appropriate success/failure messages
10. Optimize the implementation to only process the single task rather than scanning through all tasks
The command should reuse existing AI prompt templates where possible but modify them to focus on refining a single task rather than multiple tasks.
# Test Strategy:
Testing should verify the following aspects:
1. **Basic Functionality Test**: Verify that the command successfully updates a single task when given a valid task ID
2. **Preservation Test**: Create a task with completed subtasks, update it, and verify the completion status remains intact
3. **Research Flag Test**: Test the command with the research flag and verify it correctly integrates with Perplexity
4. **Error Handling Tests**:
- Test with non-existent task ID and verify appropriate error message
- Test with invalid parameters and verify helpful error messages
5. **Integration Test**: Run a complete workflow that creates a task, updates it with updateTask, and then verifies the changes are persisted
6. **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
7. **Performance Test**: Measure execution time compared to the full update command to verify efficiency gains
8. **CLI Help Test**: Verify the command appears correctly in help documentation with appropriate descriptions
Create unit tests for the core functionality and integration tests for the complete workflow. Document any edge cases discovered during testing.
# Subtasks:
## 1. Create updateTaskById function in task-manager.js [done]
### Dependencies: None
### 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.
### Details:
Implementation steps:
1. Create a new `updateTaskById` function in task-manager.js that accepts parameters: taskId, options object (containing research flag, formatting options, etc.)
2. Implement logic to find a specific task by ID in the tasks array
3. Add appropriate error handling for cases where the task ID doesn't exist (throw a custom error)
4. Reuse existing AI prompt templates but modify them to focus on refining a single task
5. Implement logic to preserve completion status of subtasks that were previously marked as complete
6. Add support for updating task title, description, and details separately based on options
7. Optimize the implementation to only process the single task rather than scanning through all tasks
8. Return the updated task and appropriate success/failure messages
Testing approach:
- Unit test the function with various scenarios including:
- Valid task ID with different update options
- Non-existent task ID
- Task with completed subtasks to verify preservation
- Different combinations of update options
## 2. Implement updateTask command in commands.js [done]
### Dependencies: 34.1
### Description: Create a new command called 'updateTask' in commands.js that leverages the updateTaskById function to update a specific task by ID.
### Details:
Implementation steps:
1. Create a new command object for 'updateTask' in commands.js following the Command pattern
2. Define command parameters including a required taskId parameter
3. Support all options from the existing update command:
- Research flag for Perplexity integration
- Formatting and refinement options
- Task context options
4. Implement the command handler function that calls the updateTaskById function from task-manager.js
5. Add appropriate error handling to catch and display user-friendly error messages
6. Ensure the command follows the same pattern as other commands in the codebase
7. Implement proper validation of input parameters
8. Format and return appropriate success/failure messages to the user
Testing approach:
- Unit test the command handler with various input combinations
- Test error handling scenarios
- Verify command options are correctly passed to the updateTaskById function
## 3. Add comprehensive error handling and validation [done]
### Dependencies: 34.1, 34.2
### Description: Implement robust error handling and validation for the updateTask command to ensure proper user feedback and system stability.
### Details:
Implementation steps:
1. Create custom error types for different failure scenarios (TaskNotFoundError, ValidationError, etc.)
2. Implement input validation for the taskId parameter and all options
3. Add proper error handling for AI service failures with appropriate fallback mechanisms
4. Implement concurrency handling to prevent conflicts when multiple updates occur simultaneously
5. Add comprehensive logging for debugging and auditing purposes
6. Ensure all error messages are user-friendly and actionable
7. Implement proper HTTP status codes for API responses if applicable
8. Add validation to ensure the task exists before attempting updates
Testing approach:
- Test various error scenarios including invalid inputs, non-existent tasks, and API failures
- Verify error messages are clear and helpful
- Test concurrency scenarios with multiple simultaneous updates
- Verify logging captures appropriate information for troubleshooting
## 4. Write comprehensive tests for updateTask command [done]
### Dependencies: 34.1, 34.2, 34.3
### Description: Create a comprehensive test suite for the updateTask command to ensure it works correctly in all scenarios and maintains backward compatibility.
### Details:
Implementation steps:
1. Create unit tests for the updateTaskById function in task-manager.js
- Test finding and updating tasks with various IDs
- Test preservation of completed subtasks
- Test different update options combinations
- Test error handling for non-existent tasks
2. Create unit tests for the updateTask command in commands.js
- Test command parameter parsing
- Test option handling
- Test error scenarios and messages
3. Create integration tests that verify the end-to-end flow
- Test the command with actual AI service integration
- Test with mock AI responses for predictable testing
4. Implement test fixtures and mocks for consistent testing
5. Add performance tests to ensure the command is efficient
6. Test edge cases such as empty tasks, tasks with many subtasks, etc.
Testing approach:
- Use Jest or similar testing framework
- Implement mocks for external dependencies like AI services
- Create test fixtures for consistent test data
- Use snapshot testing for command output verification
## 5. Update CLI documentation and help text [done]
### Dependencies: 34.2
### Description: Update the CLI help documentation to include the new updateTask command and ensure users understand its purpose and options.
### Details:
Implementation steps:
1. Add comprehensive help text for the updateTask command including:
- Command description
- Required and optional parameters
- Examples of usage
- Description of all supported options
2. Update the main CLI help documentation to include the new command
3. Add the command to any relevant command groups or categories
4. Create usage examples that demonstrate common scenarios
5. Update README.md and other documentation files to include information about the new command
6. Add inline code comments explaining the implementation details
7. Update any API documentation if applicable
8. Create or update user guides with the new functionality
Testing approach:
- Verify help text is displayed correctly when running `--help`
- Review documentation for clarity and completeness
- Have team members review the documentation for usability
- Test examples to ensure they work as documented

View File

@@ -1,48 +0,0 @@
# Task ID: 35
# Title: Integrate Grok3 API for Research Capabilities
# Status: cancelled
# Dependencies: None
# Priority: medium
# Description: Replace the current Perplexity API integration with Grok3 API for all research-related functionalities while maintaining existing feature parity.
# Details:
This task involves migrating from Perplexity to Grok3 API for research capabilities throughout the application. Implementation steps include:
1. Create a new API client module for Grok3 in `src/api/grok3.ts` that handles authentication, request formatting, and response parsing
2. Update the research service layer to use the new Grok3 client instead of Perplexity
3. Modify the request payload structure to match Grok3's expected format (parameters like temperature, max_tokens, etc.)
4. Update response handling to properly parse and extract Grok3's response format
5. Implement proper error handling for Grok3-specific error codes and messages
6. Update environment variables and configuration files to include Grok3 API keys and endpoints
7. Ensure rate limiting and quota management are properly implemented according to Grok3's specifications
8. Update any UI components that display research provider information to show Grok3 instead of Perplexity
9. Maintain backward compatibility for any stored research results from Perplexity
10. Document the new API integration in the developer documentation
Grok3 API has different parameter requirements and response formats compared to Perplexity, so careful attention must be paid to these differences during implementation.
# Test Strategy:
Testing should verify that the Grok3 API integration works correctly and maintains feature parity with the previous Perplexity implementation:
1. Unit tests:
- Test the Grok3 API client with mocked responses
- Verify proper error handling for various error scenarios (rate limits, authentication failures, etc.)
- Test the transformation of application requests to Grok3-compatible format
2. Integration tests:
- Perform actual API calls to Grok3 with test credentials
- Verify that research results are correctly parsed and returned
- Test with various types of research queries to ensure broad compatibility
3. End-to-end tests:
- Test the complete research flow from UI input to displayed results
- Verify that all existing research features work with the new API
4. Performance tests:
- Compare response times between Perplexity and Grok3
- Ensure the application handles any differences in response time appropriately
5. Regression tests:
- Verify that existing features dependent on research capabilities continue to work
- Test that stored research results from Perplexity are still accessible and displayed correctly
Create a test environment with both APIs available to compare results and ensure quality before fully replacing Perplexity with Grok3.

View File

@@ -1,48 +0,0 @@
# Task ID: 36
# Title: Add Ollama Support for AI Services as Claude Alternative
# Status: deferred
# Dependencies: None
# Priority: medium
# 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.
# Details:
This task involves creating a comprehensive Ollama integration that can replace Claude across all main AI services in the application. Implementation should include:
1. Create an OllamaService class that implements the same interface as the ClaudeService to ensure compatibility
2. Add configuration options to specify Ollama endpoint URL (default: http://localhost:11434)
3. Implement model selection functionality to allow users to choose which Ollama model to use (e.g., llama3, mistral, etc.)
4. Handle prompt formatting specific to Ollama models, ensuring proper system/user message separation
5. Implement proper error handling for cases where Ollama server is unavailable or returns errors
6. Add fallback mechanism to Claude when Ollama fails or isn't configured
7. Update the AI service factory to conditionally create either Claude or Ollama service based on configuration
8. Ensure token counting and rate limiting are appropriately handled for Ollama models
9. Add documentation for users explaining how to set up and use Ollama with the application
10. Optimize prompt templates specifically for Ollama models if needed
The implementation should be toggled through a configuration option (useOllama: true/false) and should maintain all existing functionality currently provided by Claude.
# Test Strategy:
Testing should verify that Ollama integration works correctly as a drop-in replacement for Claude:
1. Unit tests:
- Test OllamaService class methods in isolation with mocked responses
- Verify proper error handling when Ollama server is unavailable
- Test fallback mechanism to Claude when configured
2. Integration tests:
- Test with actual Ollama server running locally with at least two different models
- Verify all AI service functions work correctly with Ollama
- Compare outputs between Claude and Ollama for quality assessment
3. Configuration tests:
- Verify toggling between Claude and Ollama works as expected
- Test with various model configurations
4. Performance tests:
- Measure and compare response times between Claude and Ollama
- Test with different load scenarios
5. Manual testing:
- Verify all main AI features work correctly with Ollama
- Test edge cases like very long inputs or specialized tasks
Create a test document comparing output quality between Claude and various Ollama models to help users understand the tradeoffs.

View File

@@ -1,49 +0,0 @@
# Task ID: 37
# Title: Add Gemini Support for Main AI Services as Claude Alternative
# Status: done
# Dependencies: None
# Priority: medium
# 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.
# Details:
This task involves integrating Google's Gemini API across all main AI services that currently use Claude:
1. Create a new GeminiService class that implements the same interface as the existing ClaudeService
2. Implement authentication and API key management for Gemini API
3. Map our internal prompt formats to Gemini's expected input format
4. Handle Gemini-specific parameters (temperature, top_p, etc.) and response parsing
5. Update the AI service factory/provider to support selecting Gemini as an alternative
6. Add configuration options in settings to allow users to select Gemini as their preferred provider
7. Implement proper error handling for Gemini-specific API errors
8. Ensure streaming responses are properly supported if Gemini offers this capability
9. Update documentation to reflect the new Gemini option
10. Consider implementing model selection if Gemini offers multiple models (e.g., Gemini Pro, Gemini Ultra)
11. Ensure all existing AI capabilities (summarization, code generation, etc.) maintain feature parity when using Gemini
The implementation should follow the same pattern as the recent Ollama integration (Task #36) to maintain consistency in how alternative AI providers are supported.
# Test Strategy:
Testing should verify Gemini integration works correctly across all AI services:
1. Unit tests:
- Test GeminiService class methods with mocked API responses
- Verify proper error handling for common API errors
- Test configuration and model selection functionality
2. Integration tests:
- Verify authentication and API connection with valid credentials
- Test each AI service with Gemini to ensure proper functionality
- Compare outputs between Claude and Gemini for the same inputs to verify quality
3. End-to-end tests:
- Test the complete user flow of switching to Gemini and using various AI features
- Verify streaming responses work correctly if supported
4. Performance tests:
- Measure and compare response times between Claude and Gemini
- Test with various input lengths to verify handling of context limits
5. Manual testing:
- Verify the quality of Gemini responses across different use cases
- Test edge cases like very long inputs or specialized domain knowledge
All tests should pass with Gemini selected as the provider, and the user experience should be consistent regardless of which provider is selected.

View File

@@ -1,56 +0,0 @@
# Task ID: 38
# Title: Implement Version Check System with Upgrade Notifications
# Status: done
# Dependencies: None
# Priority: high
# 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.
# Details:
Implement a version check mechanism that runs automatically with every command execution:
1. Create a new module (e.g., `versionChecker.js`) that will:
- Fetch the latest version from npm registry using the npm registry API (https://registry.npmjs.org/task-master-ai/latest)
- Compare it with the current installed version (from package.json)
- Store the last check timestamp to avoid excessive API calls (check once per day)
- Cache the result to minimize network requests
2. The notification should:
- Use colored text (e.g., yellow background with black text) to be noticeable
- Include the current version and latest version
- Show the exact upgrade command: 'npm i task-master-ai@latest'
- Be displayed at the beginning or end of command output, not interrupting the main content
- Include a small separator line to distinguish it from command output
3. Implementation considerations:
- Handle network failures gracefully (don't block command execution if version check fails)
- Add a configuration option to disable update checks if needed
- Ensure the check is lightweight and doesn't significantly impact command performance
- Consider using a package like 'semver' for proper version comparison
- Implement a cooldown period (e.g., only check once per day) to avoid excessive API calls
4. The version check should be integrated into the main command execution flow so it runs for all commands automatically.
# Test Strategy:
1. Manual testing:
- Install an older version of the package
- Run various commands and verify the update notification appears
- Update to the latest version and confirm the notification no longer appears
- Test with network disconnected to ensure graceful handling of failures
2. Unit tests:
- Mock the npm registry response to test different scenarios:
- When a newer version exists
- When using the latest version
- When the registry is unavailable
- Test the version comparison logic with various version strings
- Test the cooldown/caching mechanism works correctly
3. Integration tests:
- Create a test that runs a command and verifies the notification appears in the expected format
- Test that the notification appears for all commands
- Verify the notification doesn't interfere with normal command output
4. Edge cases to test:
- Pre-release versions (alpha/beta)
- Very old versions
- When package.json is missing or malformed
- When npm registry returns unexpected data

View File

@@ -1,128 +0,0 @@
# Task ID: 39
# Title: Update Project Licensing to Dual License Structure
# Status: done
# Dependencies: None
# Priority: high
# 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.
# Details:
This task requires implementing a comprehensive licensing update across the project:
1. Remove all instances of the MIT license from the codebase, including any MIT license files, headers in source files, and references in documentation.
2. Create a dual license structure with:
- Business Source License (BSL) 1.1 or similar for commercial use, explicitly stating that commercial rights are exclusively reserved for Ralph & Eyal
- Apache 2.0 for non-commercial use, allowing the community to use, modify, and distribute the code for non-commercial purposes
3. Update the license field in package.json to reflect the dual license structure (e.g., "BSL 1.1 / Apache 2.0")
4. Add a clear, concise explanation of the licensing terms in the README.md, including:
- A summary of what users can and cannot do with the code
- Who holds commercial rights
- How to obtain commercial use permission if needed
- Links to the full license texts
5. Create a detailed LICENSE.md file that includes:
- Full text of both licenses
- Clear delineation between commercial and non-commercial use
- Specific definitions of what constitutes commercial use
- Any additional terms or clarifications specific to this project
6. Create a CONTRIBUTING.md file that explicitly states:
- Contributors must agree that their contributions will be subject to the project's dual licensing
- Commercial rights for all contributions are assigned to Ralph & Eyal
- Guidelines for acceptable contributions
7. Ensure all source code files include appropriate license headers that reference the dual license structure.
# Test Strategy:
To verify correct implementation, perform the following checks:
1. File verification:
- Confirm the MIT license file has been removed
- Verify LICENSE.md exists and contains both BSL and Apache 2.0 license texts
- Confirm README.md includes the license section with clear explanation
- Verify CONTRIBUTING.md exists with proper contributor guidelines
- Check package.json for updated license field
2. Content verification:
- Review LICENSE.md to ensure it properly describes the dual license structure with clear terms
- Verify README.md license section is concise yet complete
- Check that commercial rights are explicitly reserved for Ralph & Eyal in all relevant documents
- Ensure CONTRIBUTING.md clearly explains the licensing implications for contributors
3. Legal review:
- Have a team member not involved in the implementation review all license documents
- Verify that the chosen BSL terms properly protect commercial interests
- Confirm the Apache 2.0 implementation is correct and compatible with the BSL portions
4. Source code check:
- Sample at least 10 source files to ensure they have updated license headers
- Verify no MIT license references remain in any source files
5. Documentation check:
- Ensure any documentation that mentioned licensing has been updated to reflect the new structure
# Subtasks:
## 1. Remove MIT License and Create Dual License Files [done]
### Dependencies: None
### Description: Remove all MIT license references from the codebase and create the new license files for the dual license structure.
### Details:
Implementation steps:
1. Scan the entire codebase to identify all instances of MIT license references (license files, headers in source files, documentation mentions).
2. Remove the MIT license file and all direct references to it.
3. Create a LICENSE.md file containing:
- Full text of Business Source License (BSL) 1.1 with explicit commercial rights reservation for Ralph & Eyal
- Full text of Apache 2.0 license for non-commercial use
- Clear definitions of what constitutes commercial vs. non-commercial use
- Specific terms for obtaining commercial use permission
4. Create a CONTRIBUTING.md file that explicitly states the contribution terms:
- Contributors must agree to the dual licensing structure
- Commercial rights for all contributions are assigned to Ralph & Eyal
- Guidelines for acceptable contributions
Testing approach:
- Verify all MIT license references have been removed using a grep or similar search tool
- Have legal review of the LICENSE.md and CONTRIBUTING.md files to ensure they properly protect commercial rights
- Validate that the license files are properly formatted and readable
## 2. Update Source Code License Headers and Package Metadata [done]
### Dependencies: 39.1
### Description: Add appropriate dual license headers to all source code files and update package metadata to reflect the new licensing structure.
### Details:
Implementation steps:
1. Create a template for the new license header that references the dual license structure (BSL 1.1 / Apache 2.0).
2. Systematically update all source code files to include the new license header, replacing any existing MIT headers.
3. Update the license field in package.json to "BSL 1.1 / Apache 2.0".
4. Update any other metadata files (composer.json, setup.py, etc.) that contain license information.
5. Verify that any build scripts or tools that reference licensing information are updated.
Testing approach:
- Write a script to verify that all source files contain the new license header
- Validate package.json and other metadata files have the correct license field
- Ensure any build processes that depend on license information still function correctly
- Run a sample build to confirm license information is properly included in any generated artifacts
## 3. Update Documentation and Create License Explanation [done]
### Dependencies: 39.1, 39.2
### Description: Update project documentation to clearly explain the dual license structure and create comprehensive licensing guidance.
### Details:
Implementation steps:
1. Update the README.md with a clear, concise explanation of the licensing terms:
- Summary of what users can and cannot do with the code
- Who holds commercial rights (Ralph & Eyal)
- How to obtain commercial use permission
- Links to the full license texts
2. Create a dedicated LICENSING.md or similar document with detailed explanations of:
- The rationale behind the dual licensing approach
- Detailed examples of what constitutes commercial vs. non-commercial use
- FAQs addressing common licensing questions
3. Update any other documentation references to licensing throughout the project.
4. Create visual aids (if appropriate) to help users understand the licensing structure.
5. Ensure all documentation links to licensing information are updated.
Testing approach:
- Have non-technical stakeholders review the documentation for clarity and understanding
- Verify all links to license files work correctly
- Ensure the explanation is comprehensive but concise enough for users to understand quickly
- Check that the documentation correctly addresses the most common use cases and questions

View File

@@ -1,65 +0,0 @@
# Task ID: 40
# Title: Implement 'plan' Command for Task Implementation Planning
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
Implement a new 'plan' command that will append a structured implementation plan to existing tasks or subtasks. The implementation should:
1. Accept an '--id' parameter that can reference either a task or subtask ID
2. Determine whether the ID refers to a task or subtask and retrieve the appropriate content from tasks.json and/or individual task files
3. Generate a step-by-step implementation plan using AI (Claude by default)
4. Support a '--research' flag to use Perplexity instead of Claude when needed
5. Format the generated plan within XML tags like `<implementation_plan as of timestamp>...</implementation_plan>`
6. Append this plan to the implementation details section of the task/subtask
7. Display a confirmation card indicating the implementation plan was successfully created
The 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.
Reference 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.
# Test Strategy:
Testing should verify:
1. Command correctly identifies and retrieves content for both task and subtask IDs
2. Implementation plans are properly generated and formatted with XML tags and timestamps
3. Plans are correctly appended to the implementation details section without overwriting existing content
4. The '--research' flag successfully switches the backend from Claude to Perplexity
5. Appropriate error messages are displayed for invalid IDs or API failures
6. Confirmation card is displayed after successful plan creation
Test cases should include:
- Running 'plan --id 123' on an existing task
- Running 'plan --id 123.1' on an existing subtask
- Running 'plan --id 123 --research' to test the Perplexity integration
- Running 'plan --id 999' with a non-existent ID to verify error handling
- Running the command on tasks with existing implementation plans to ensure proper appending
Manually review the quality of generated plans to ensure they provide actionable, step-by-step guidance that accurately reflects the task requirements.
# Subtasks:
## 1. Retrieve Task Content [in-progress]
### Dependencies: None
### Description: Fetch the content of the specified task from the task management system. This includes the task title, description, and any associated details.
### Details:
Implement a function to retrieve task details based on a task ID. Handle cases where the task does not exist.
## 2. Generate Implementation Plan with AI [pending]
### Dependencies: 40.1
### 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.
### 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.
## 3. Format Plan in XML [pending]
### Dependencies: 40.2, 40.2
### Description: Format the generated implementation plan within XML tags. Each step in the plan should be represented as an XML element with appropriate attributes.
### 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.
## 4. Error Handling and Output [pending]
### Dependencies: 40.3
### 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.
### 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.

View File

@@ -1,373 +0,0 @@
# Task ID: 41
# Title: Implement Visual Task Dependency Graph in Terminal
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
This implementation should include:
1. Create a new command `graph` or `visualize` that displays the dependency graph.
2. Design an ASCII/Unicode-based graph rendering system that:
- Represents each task as a node with its ID and abbreviated title
- Shows dependencies as directional lines between nodes (→, ↑, ↓, etc.)
- Uses color coding for different task statuses (e.g., green for completed, yellow for in-progress, red for blocked)
- Handles complex dependency chains with proper spacing and alignment
3. Implement layout algorithms to:
- Minimize crossing lines for better readability
- Properly space nodes to avoid overlapping
- Support both vertical and horizontal graph orientations (as a configurable option)
4. Add detection and highlighting of circular dependencies with a distinct color/pattern
5. Include a legend explaining the color coding and symbols used
6. Ensure the graph is responsive to terminal width, with options to:
- Automatically scale to fit the current terminal size
- Allow zooming in/out of specific sections for large graphs
- Support pagination or scrolling for very large dependency networks
7. Add options to filter the graph by:
- Specific task IDs or ranges
- Task status
- Dependency depth (e.g., show only direct dependencies or N levels deep)
8. Ensure accessibility by using distinct patterns in addition to colors for users with color vision deficiencies
9. Optimize performance for projects with many tasks and complex dependency relationships
# Test Strategy:
1. Unit Tests:
- Test the graph generation algorithm with various dependency structures
- Verify correct node placement and connection rendering
- Test circular dependency detection
- Verify color coding matches task statuses
2. Integration Tests:
- Test the command with projects of varying sizes (small, medium, large)
- Verify correct handling of different terminal sizes
- Test all filtering options
3. Visual Verification:
- Create test cases with predefined dependency structures and verify the visual output matches expected patterns
- Test with terminals of different sizes, including very narrow terminals
- Verify readability of complex graphs
4. Edge Cases:
- Test with no dependencies (single nodes only)
- Test with circular dependencies
- Test with very deep dependency chains
- Test with wide dependency networks (many parallel tasks)
- Test with the maximum supported number of tasks
5. Usability Testing:
- Have team members use the feature and provide feedback on readability and usefulness
- Test in different terminal emulators to ensure compatibility
- Verify the feature works in terminals with limited color support
6. Performance Testing:
- Measure rendering time for large projects
- Ensure reasonable performance with 100+ interconnected tasks
# Subtasks:
## 1. CLI Command Setup [pending]
### Dependencies: None
### Description: Design and implement the command-line interface for the dependency graph tool, including argument parsing and help documentation.
### Details:
Define commands for input file specification, output options, filtering, and other user-configurable parameters.
<info added on 2025-05-23T21:02:26.442Z>
Implement a new 'diagram' command (with 'graph' alias) in commands.js following the Commander.js pattern. The command should:
1. Import diagram-generator.js module functions for generating visual representations
2. Support multiple visualization types with --type option:
- dependencies: show task dependency relationships
- subtasks: show task/subtask hierarchy
- flow: show task workflow
- gantt: show timeline visualization
3. Include the following options:
- --task <id>: Filter diagram to show only specified task and its relationships
- --mermaid: Output raw Mermaid markdown for external rendering
- --visual: Render diagram directly in terminal
- --format <format>: Output format (text, svg, png)
4. Implement proper error handling and validation:
- Validate task IDs using existing taskExists() function
- Handle invalid option combinations
- Provide descriptive error messages
5. Integrate with UI components:
- Use ui.js display functions for consistent output formatting
- Apply chalk coloring for terminal output
- Use boxen formatting consistent with other commands
6. Handle file operations:
- Resolve file paths using findProjectRoot() pattern
- Support saving diagrams to files when appropriate
7. Include comprehensive help text following the established pattern in other commands
</info added on 2025-05-23T21:02:26.442Z>
## 2. Graph Layout Algorithms [pending]
### Dependencies: 41.1
### Description: Develop or integrate algorithms to compute optimal node and edge placement for clear and readable graph layouts in a terminal environment.
### Details:
Consider topological sorting, hierarchical, and force-directed layouts suitable for ASCII/Unicode rendering.
<info added on 2025-05-23T21:02:49.434Z>
Create a new diagram-generator.js module in the scripts/modules/ directory following Task Master's module architecture pattern. The module should include:
1. Core functions for generating Mermaid diagrams:
- generateDependencyGraph(tasks, options) - creates flowchart showing task dependencies
- generateSubtaskDiagram(task, options) - creates hierarchy diagram for subtasks
- generateProjectFlow(tasks, options) - creates overall project workflow
- generateGanttChart(tasks, options) - creates timeline visualization
2. Integration with existing Task Master data structures:
- Use the same task object format from task-manager.js
- Leverage dependency analysis from dependency-manager.js
- Support complexity scores from analyze-complexity functionality
- Handle both main tasks and subtasks with proper ID notation (parentId.subtaskId)
3. Layout algorithm considerations for Mermaid:
- Topological sorting for dependency flows
- Hierarchical layouts for subtask trees
- Circular dependency detection and highlighting
- Terminal width-aware formatting for ASCII fallback
4. Export functions following the existing module pattern at the bottom of the file
</info added on 2025-05-23T21:02:49.434Z>
## 3. ASCII/Unicode Rendering Engine [pending]
### Dependencies: 41.2
### Description: Implement rendering logic to display the dependency graph using ASCII and Unicode characters in the terminal.
### Details:
Support for various node and edge styles, and ensure compatibility with different terminal types.
<info added on 2025-05-23T21:03:10.001Z>
Extend ui.js with diagram display functions that integrate with Task Master's existing UI patterns:
1. Implement core diagram display functions:
- displayTaskDiagram(tasksPath, diagramType, options) as the main entry point
- displayMermaidCode(mermaidCode, title) for formatted code output with boxen
- displayDiagramLegend() to explain symbols and colors
2. Ensure UI consistency by:
- Using established chalk color schemes (blue/green/yellow/red)
- Applying boxen for consistent component formatting
- Following existing display function patterns (displayTaskById, displayComplexityReport)
- Utilizing cli-table3 for any diagram metadata tables
3. Address terminal rendering challenges:
- Implement ASCII/Unicode fallback when Mermaid rendering isn't available
- Respect terminal width constraints using process.stdout.columns
- Integrate with loading indicators via startLoadingIndicator/stopLoadingIndicator
4. Update task file generation to include Mermaid diagram sections in individual task files
5. Support both CLI and MCP output formats through the outputFormat parameter
</info added on 2025-05-23T21:03:10.001Z>
## 4. Color Coding Support [pending]
### Dependencies: 41.3
### Description: Add color coding to nodes and edges to visually distinguish types, statuses, or other attributes in the graph.
### Details:
Use ANSI escape codes for color; provide options for colorblind-friendly palettes.
<info added on 2025-05-23T21:03:35.762Z>
Integrate color coding with Task Master's existing status system:
1. Extend getStatusWithColor() in ui.js to support diagram contexts:
- Add 'diagram' parameter to determine rendering context
- Modify color intensity for better visibility in graph elements
2. Implement Task Master's established color scheme using ANSI codes:
- Green (\x1b[32m) for 'done'/'completed' tasks
- Yellow (\x1b[33m) for 'pending' tasks
- Orange (\x1b[38;5;208m) for 'in-progress' tasks
- Red (\x1b[31m) for 'blocked' tasks
- Gray (\x1b[90m) for 'deferred'/'cancelled' tasks
- Magenta (\x1b[35m) for 'review' tasks
3. Create diagram-specific color functions:
- getDependencyLineColor(fromTaskStatus, toTaskStatus) - color dependency arrows based on relationship status
- getNodeBorderColor(task) - style node borders using priority/complexity indicators
- getSubtaskGroupColor(parentTask) - visually group related subtasks
4. Integrate complexity visualization:
- Use getComplexityWithColor() for node background or border thickness
- Map complexity scores to visual weight in the graph
5. Ensure accessibility:
- Add text-based indicators (symbols like ✓, ⚠, ⏳) alongside colors
- Implement colorblind-friendly palettes as user-selectable option
- Include shape variations for different statuses
6. Follow existing ANSI patterns:
- Maintain consistency with terminal UI color usage
- Reuse color constants from the codebase
7. Support graceful degradation:
- Check terminal capabilities using existing detection
- Provide monochrome fallbacks with distinctive patterns
- Use bold/underline as alternatives when colors unavailable
</info added on 2025-05-23T21:03:35.762Z>
## 5. Circular Dependency Detection [pending]
### Dependencies: 41.2
### Description: Implement algorithms to detect and highlight circular dependencies within the graph.
### Details:
Clearly mark cycles in the rendered output and provide warnings or errors as appropriate.
<info added on 2025-05-23T21:04:20.125Z>
Integrate with Task Master's existing circular dependency detection:
1. Import the dependency detection logic from dependency-manager.js module
2. Utilize the findCycles function from utils.js or dependency-manager.js
3. Extend validateDependenciesCommand functionality to highlight cycles in diagrams
Visual representation in Mermaid diagrams:
- Apply red/bold styling to nodes involved in dependency cycles
- Add warning annotations to cyclic edges
- Implement cycle path highlighting with distinctive line styles
Integration with validation workflow:
- Execute dependency validation before diagram generation
- Display cycle warnings consistent with existing CLI error messaging
- Utilize chalk.red and boxen for error highlighting following established patterns
Add diagram legend entries that explain cycle notation and warnings
Ensure detection of cycles in both:
- Main task dependencies
- Subtask dependencies within parent tasks
Follow Task Master's error handling patterns for graceful cycle reporting and user notification
</info added on 2025-05-23T21:04:20.125Z>
## 6. Filtering and Search Functionality [pending]
### Dependencies: 41.1, 41.2
### Description: Enable users to filter nodes and edges by criteria such as name, type, or dependency depth.
### Details:
Support command-line flags for filtering and interactive search if feasible.
<info added on 2025-05-23T21:04:57.811Z>
Implement MCP tool integration for task dependency visualization:
1. Create task_diagram.js in mcp-server/src/tools/ following existing tool patterns
2. Implement taskDiagramDirect.js in mcp-server/src/core/direct-functions/
3. Use Zod schema for parameter validation:
- diagramType (dependencies, subtasks, flow, gantt)
- taskId (optional string)
- format (mermaid, text, json)
- includeComplexity (boolean)
4. Structure response data with:
- mermaidCode for client-side rendering
- metadata (nodeCount, edgeCount, cycleWarnings)
- support for both task-specific and project-wide diagrams
5. Integrate with session management and project root handling
6. Implement error handling using handleApiResult pattern
7. Register the tool in tools/index.js
Maintain compatibility with existing command-line flags for filtering and interactive search.
</info added on 2025-05-23T21:04:57.811Z>
## 7. Accessibility Features [pending]
### Dependencies: 41.3, 41.4
### Description: Ensure the tool is accessible, including support for screen readers, high-contrast modes, and keyboard navigation.
### Details:
Provide alternative text output and ensure color is not the sole means of conveying information.
<info added on 2025-05-23T21:05:54.584Z>
# Accessibility and Export Integration
## Accessibility Features
- Provide alternative text output for visual elements
- Ensure color is not the sole means of conveying information
- Support keyboard navigation through the dependency graph
- Add screen reader compatible node descriptions
## Export Integration
- Extend generateTaskFiles function in task-manager.js to include Mermaid diagram sections
- Add Mermaid code blocks to task markdown files under ## Diagrams header
- Follow existing task file generation patterns and markdown structure
- Support multiple diagram types per task file:
* Task dependencies (prerequisite relationships)
* Subtask hierarchy visualization
* Task flow context in project workflow
- Integrate with existing fs module file writing operations
- Add diagram export options to the generate command in commands.js
- Support SVG and PNG export using Mermaid CLI when available
- Implement error handling for diagram generation failures
- Reference exported diagrams in task markdown with proper paths
- Update CLI generate command with options like --include-diagrams
</info added on 2025-05-23T21:05:54.584Z>
## 8. Performance Optimization [pending]
### Dependencies: 41.2, 41.3, 41.4, 41.5, 41.6
### Description: Profile and optimize the tool for large graphs to ensure responsive rendering and low memory usage.
### Details:
Implement lazy loading, efficient data structures, and parallel processing where appropriate.
<info added on 2025-05-23T21:06:14.533Z>
# Mermaid Library Integration and Terminal-Specific Handling
## Package Dependencies
- Add mermaid package as an optional dependency in package.json for generating raw Mermaid diagram code
- Consider mermaid-cli for SVG/PNG conversion capabilities
- Evaluate terminal-image or similar libraries for terminals with image support
- Explore ascii-art-ansi or box-drawing character libraries for text-only terminals
## Terminal Capability Detection
- Leverage existing terminal detection from ui.js to assess rendering capabilities
- Implement detection for:
- iTerm2 and other terminals with image protocol support
- Terminals with Unicode/extended character support
- Basic terminals requiring pure ASCII output
## Rendering Strategy with Fallbacks
1. Primary: Generate raw Mermaid code for user copy/paste
2. Secondary: Render simplified ASCII tree/flow representation using box characters
3. Tertiary: Present dependencies in tabular format for minimal terminals
## Implementation Approach
- Use dynamic imports for optional rendering libraries to maintain lightweight core
- Implement graceful degradation when optional packages aren't available
- Follow Task Master's philosophy of minimal dependencies
- Ensure performance optimization through lazy loading where appropriate
- Design modular rendering components that can be swapped based on terminal capabilities
</info added on 2025-05-23T21:06:14.533Z>
## 9. Documentation [pending]
### Dependencies: 41.1, 41.2, 41.3, 41.4, 41.5, 41.6, 41.7, 41.8
### Description: Write comprehensive user and developer documentation covering installation, usage, configuration, and extension.
### Details:
Include examples, troubleshooting, and contribution guidelines.
## 10. Testing and Validation [pending]
### Dependencies: 41.1, 41.2, 41.3, 41.4, 41.5, 41.6, 41.7, 41.8, 41.9
### Description: Develop automated tests for all major features, including CLI parsing, layout correctness, rendering, color coding, filtering, and cycle detection.
### Details:
Include unit, integration, and regression tests; validate accessibility and performance claims.
<info added on 2025-05-23T21:08:36.329Z>
# Documentation Tasks for Visual Task Dependency Graph
## User Documentation
1. Update README.md with diagram command documentation following existing command reference format
2. Add examples to CLI command help text in commands.js matching patterns from other commands
3. Create docs/diagrams.md with detailed usage guide including:
- Command examples for each diagram type
- Mermaid code samples and output
- Terminal compatibility notes
- Integration with task workflow examples
- Troubleshooting section for common diagram rendering issues
- Accessibility features and terminal fallback options
## Developer Documentation
1. Update MCP tool documentation to include the new task_diagram tool
2. Add JSDoc comments to all new functions following existing code standards
3. Create contributor documentation for extending diagram types
4. Update API documentation for any new MCP interface endpoints
## Integration Documentation
1. Document integration with existing commands (analyze-complexity, generate, etc.)
2. Provide examples showing how diagrams complement other Task Master features
</info added on 2025-05-23T21:08:36.329Z>

View File

@@ -1,91 +0,0 @@
# Task ID: 42
# Title: Implement MCP-to-MCP Communication Protocol
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
This task involves creating a standardized way for Taskmaster to communicate with external MCP implementations and tools. The implementation should:
1. Define a standard protocol for communication with MCP servers, including authentication, request/response formats, and error handling.
2. Leverage the existing `fastmcp` server logic to enable interaction with external MCP tools programmatically, focusing on creating a modular and reusable system.
3. Implement an adapter pattern that allows Taskmaster to connect to any MCP-compliant tool or server.
4. Build a client module capable of discovering, connecting to, and exchanging data with external MCP tools, ensuring compatibility with various implementations.
5. Provide a reference implementation for interacting with a specific MCP tool (e.g., GitHub-MCP or Postgres-MCP) to demonstrate the protocol's functionality.
6. Ensure the protocol supports versioning to maintain compatibility as MCP tools evolve.
7. Implement rate limiting and backoff strategies to prevent overwhelming external MCP tools.
8. Create a configuration system that allows users to specify connection details for external MCP tools and servers.
9. Add support for two operational modes:
- **Solo/Local Mode**: Tasks are managed locally using a `tasks.json` file.
- **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.
10. 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.
11. Document the protocol thoroughly to enable other developers to implement it in their MCP tools.
The 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.
# Test Strategy:
Testing should verify both the protocol design and implementation:
1. Unit tests for the adapter pattern, ensuring it correctly translates between Taskmaster's internal models and the MCP protocol.
2. Integration tests with a mock MCP tool or server to validate the full request/response cycle.
3. Specific tests for the reference implementation (e.g., GitHub-MCP or Postgres-MCP), including authentication flows.
4. Error handling tests that simulate network failures, timeouts, and malformed responses.
5. Performance tests to ensure the communication does not introduce significant latency.
6. Security tests to verify that authentication and encryption mechanisms are functioning correctly.
7. End-to-end tests demonstrating Taskmaster's ability to programmatically interact with external MCP tools and execute tasks.
8. Compatibility tests with different versions of the protocol to ensure backward compatibility.
9. Tests for mode switching:
- Validate that Taskmaster correctly operates in solo/local mode using the `tasks.json` file.
- Validate that Taskmaster correctly operates in multiplayer/remote mode with external MCP integrations (e.g., GitHub-MCP or Postgres-MCP).
- Ensure seamless switching between modes without data loss or corruption.
10. 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:
## 42-1. Define MCP-to-MCP communication protocol [pending]
### Dependencies: None
### Description:
### Details:
## 42-2. Implement adapter pattern for MCP integration [pending]
### Dependencies: None
### Description:
### Details:
## 42-3. Develop client module for MCP tool discovery and interaction [pending]
### Dependencies: None
### Description:
### Details:
## 42-4. Provide reference implementation for GitHub-MCP integration [pending]
### Dependencies: None
### Description:
### Details:
## 42-5. Add support for solo/local and multiplayer/remote modes [pending]
### Dependencies: None
### Description:
### Details:
## 42-6. Update core modules to support dynamic mode-based operations [pending]
### Dependencies: None
### Description:
### Details:
## 42-7. Document protocol and mode-switching functionality [pending]
### Dependencies: None
### Description:
### Details:
## 42-8. Update terminology to reflect MCP server-based communication [pending]
### Dependencies: None
### Description:
### Details:

View File

@@ -1,46 +0,0 @@
# Task ID: 43
# Title: Add Research Flag to Add-Task Command
# Status: done
# Dependencies: None
# Priority: medium
# Description: Implement a '--research' flag for the add-task command that enables users to automatically generate research-related subtasks when creating a new task.
# 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:
1. Background Investigation: Research existing solutions and approaches
2. Requirements Analysis: Define specific requirements and constraints
3. Technology/Tool Evaluation: Compare potential technologies or tools for implementation
4. Proof of Concept: Create a minimal implementation to validate approach
5. Documentation: Document findings and recommendations
The implementation should:
- Update the command-line argument parser to recognize the new flag
- Create a dedicated function to generate the research subtasks with appropriate descriptions
- Ensure subtasks are properly linked to the parent task
- Update help documentation to explain the new flag
- Maintain backward compatibility with existing add-task functionality
The research subtasks should be customized based on the main task's title and description when possible, rather than using generic templates.
# Test Strategy:
Testing should verify both the functionality and usability of the new feature:
1. Unit tests:
- Test that the '--research' flag is properly parsed
- Verify the correct number and structure of subtasks are generated
- Ensure subtask IDs are correctly assigned and linked to the parent task
2. Integration tests:
- Create a task with the research flag and verify all subtasks appear in the task list
- Test that the research flag works with other existing flags (e.g., --priority, --depends-on)
- Verify the task and subtasks are properly saved to the storage backend
3. Manual testing:
- Run 'taskmaster add-task "Test task" --research' and verify the output
- Check that the help documentation correctly describes the new flag
- Verify the research subtasks have meaningful descriptions
- Test the command with and without the flag to ensure backward compatibility
4. Edge cases:
- Test with very short or very long task descriptions
- Verify behavior when maximum task/subtask limits are reached

View File

@@ -1,94 +0,0 @@
# Task ID: 44
# Title: Implement Task Automation with Webhooks and Event Triggers
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
This feature will enable users to create automated workflows based on task events and external triggers. Implementation should include:
1. A webhook registration system that allows users to specify URLs to be called when specific task events occur (creation, status change, completion, etc.)
2. An event system that captures and processes all task-related events
3. A trigger definition interface where users can define conditions for automation (e.g., 'When task X is completed, create task Y')
4. Support for both incoming webhooks (external services triggering actions in Taskmaster) and outgoing webhooks (Taskmaster notifying external services)
5. A secure authentication mechanism for webhook calls
6. Rate limiting and retry logic for failed webhook deliveries
7. Integration with the existing task management system
8. Command-line interface for managing webhooks and triggers
9. Payload templating system allowing users to customize the data sent in webhooks
10. Logging system for webhook activities and failures
The 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.
# Test Strategy:
Testing should verify both the functionality and security of the webhook system:
1. Unit tests:
- Test webhook registration, modification, and deletion
- Verify event capturing for all task operations
- Test payload generation and templating
- Validate authentication logic
2. Integration tests:
- Set up a mock server to receive webhooks and verify payload contents
- Test the complete flow from task event to webhook delivery
- Verify rate limiting and retry behavior with intentionally failing endpoints
- Test webhook triggers creating new tasks and modifying existing ones
3. Security tests:
- Verify that authentication tokens are properly validated
- Test for potential injection vulnerabilities in webhook payloads
- Verify that sensitive information is not leaked in webhook payloads
- Test rate limiting to prevent DoS attacks
4. Mode-specific tests:
- Verify correct operation in both solo/local and multiplayer/remote modes
- Test the interaction with MCP protocol when in multiplayer mode
5. Manual verification:
- Set up integrations with common services (GitHub, Slack, etc.) to verify real-world functionality
- Verify that the CLI interface for managing webhooks works as expected
# Subtasks:
## 1. Design webhook registration API endpoints [pending]
### Dependencies: None
### Description: Create API endpoints for registering, updating, and deleting webhook subscriptions
### 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.
## 2. Implement webhook authentication and security measures [pending]
### Dependencies: 44.1
### Description: Develop security mechanisms for webhook verification and payload signing
### 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.
## 3. Create event trigger definition interface [pending]
### Dependencies: None
### Description: Design and implement the interface for defining event triggers and conditions
### 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.
## 4. Build event processing and queuing system [pending]
### Dependencies: 44.1, 44.3
### Description: Implement a robust system for processing and queuing events before webhook delivery
### 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.
## 5. Develop webhook delivery and retry mechanism [pending]
### Dependencies: 44.2, 44.4
### Description: Create a reliable system for webhook delivery with retry logic and failure handling
### 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.
## 6. Implement comprehensive error handling and logging [pending]
### Dependencies: 44.5
### Description: Create robust error handling, logging, and monitoring for the webhook system
### 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.
## 7. Create webhook testing and simulation tools [pending]
### Dependencies: 44.3, 44.5, 44.6
### Description: Develop tools for testing webhook integrations and simulating event triggers
### 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.

View File

@@ -1,87 +0,0 @@
# Task ID: 45
# Title: Implement GitHub Issue Import Feature
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# 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:
1. Accept a GitHub issue URL as an argument (e.g., 'taskmaster add-task --from-github https://github.com/owner/repo/issues/123')
2. Parse the URL to extract the repository owner, name, and issue number
3. Use the GitHub API to fetch the issue details including:
- Issue title (to be used as task title)
- Issue description (to be used as task description)
- Issue labels (to be potentially used as tags)
- Issue assignees (for reference)
- Issue status (open/closed)
4. Generate a well-formatted task with this information
5. Include a reference link back to the original GitHub issue
6. Handle authentication for private repositories using GitHub tokens from environment variables or config file
7. Implement proper error handling for:
- Invalid URLs
- Non-existent issues
- API rate limiting
- Authentication failures
- Network issues
8. Allow users to override or supplement the imported details with additional command-line arguments
9. Add appropriate documentation in help text and user guide
# Test Strategy:
Testing should cover the following scenarios:
1. Unit tests:
- Test URL parsing functionality with valid and invalid GitHub issue URLs
- Test GitHub API response parsing with mocked API responses
- Test error handling for various failure cases
2. Integration tests:
- Test with real GitHub public issues (use well-known repositories)
- Test with both open and closed issues
- Test with issues containing various elements (labels, assignees, comments)
3. Error case tests:
- Invalid URL format
- Non-existent repository
- Non-existent issue number
- API rate limit exceeded
- Authentication failures for private repos
4. End-to-end tests:
- Verify that a task created from a GitHub issue contains all expected information
- Verify that the task can be properly managed after creation
- Test the interaction with other flags and commands
Create 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:
## 1. Design GitHub API integration architecture [pending]
### Dependencies: None
### Description: Create a technical design document outlining the architecture for GitHub API integration, including authentication flow, rate limiting considerations, and error handling strategies.
### 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.
## 2. Implement GitHub URL parsing and validation [pending]
### Dependencies: 45.1
### Description: Create a module to parse and validate GitHub issue URLs, extracting repository owner, repository name, and issue number.
### 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.
## 3. Develop GitHub API client for issue fetching [pending]
### Dependencies: 45.1, 45.2
### Description: Create a service to authenticate with GitHub and fetch issue details using the GitHub REST API.
### 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.
## 4. Create task formatter for GitHub issues [pending]
### Dependencies: 45.3
### Description: Develop a formatter to convert GitHub issue data into the application's task format.
### 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.
## 5. Implement end-to-end import flow with UI [pending]
### Dependencies: 45.4
### Description: Create the user interface and workflow for importing GitHub issues, including progress indicators and error handling.
### 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.

View File

@@ -1,87 +0,0 @@
# Task ID: 46
# Title: Implement ICE Analysis Command for Task Prioritization
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Create a new command that analyzes and ranks tasks based on Impact, Confidence, and Ease (ICE) scoring methodology, generating a comprehensive prioritization report.
# 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:
1. Core functionality:
- Calculate an Impact score (how much value the task will deliver)
- Calculate a Confidence score (how certain we are about the impact)
- Calculate an Ease score (how easy it is to implement)
- Compute a total ICE score (sum or product of the three components)
2. Implementation details:
- Reuse the filtering logic from `analyze-complexity` to select relevant tasks
- Leverage the LLM to generate scores for each dimension on a scale of 1-10
- For each task, prompt the LLM to evaluate and justify each score based on task description and details
- Create an `ice_report.md` file similar to the complexity report
- Sort tasks by total ICE score in descending order
3. CLI rendering:
- Implement a sister command `show-ice-report` that displays the report in the terminal
- Format the output with colorized scores and rankings
- Include options to sort by individual components (impact, confidence, or ease)
4. Integration:
- If a complexity report exists, reference it in the ICE report for additional context
- Consider adding a combined view that shows both complexity and ICE scores
The command should follow the same design patterns as `analyze-complexity` for consistency and code reuse.
# Test Strategy:
1. Unit tests:
- Test the ICE scoring algorithm with various mock task inputs
- Verify correct filtering of tasks based on status
- Test the sorting functionality with different ranking criteria
2. Integration tests:
- Create a test project with diverse tasks and verify the generated ICE report
- Test the integration with existing complexity reports
- Verify that changes to task statuses correctly update the ICE analysis
3. CLI tests:
- Verify the `analyze-ice` command generates the expected report file
- Test the `show-ice-report` command renders correctly in the terminal
- Test with various flag combinations and sorting options
4. Validation criteria:
- The ICE scores should be reasonable and consistent
- The report should clearly explain the rationale behind each score
- The ranking should prioritize high-impact, high-confidence, easy-to-implement tasks
- Performance should be acceptable even with a large number of tasks
- The command should handle edge cases gracefully (empty projects, missing data)
# Subtasks:
## 1. Design ICE scoring algorithm [pending]
### Dependencies: None
### Description: Create the algorithm for calculating Impact, Confidence, and Ease scores for tasks
### 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.
## 2. Implement AI integration for ICE scoring [pending]
### Dependencies: 46.1
### Description: Develop the AI component that will analyze tasks and generate ICE scores
### 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.
## 3. Create report file generator [pending]
### Dependencies: 46.2
### Description: Build functionality to generate a structured report file with ICE analysis results
### 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.
## 4. Implement CLI rendering for ICE analysis [pending]
### Dependencies: 46.3
### Description: Develop the command-line interface for displaying ICE analysis results
### 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.
## 5. Integrate with existing complexity reports [pending]
### Dependencies: 46.3, 46.4
### Description: Connect the ICE analysis functionality with the existing complexity reporting system
### 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.

View File

@@ -1,104 +0,0 @@
# Task ID: 47
# Title: Enhance Task Suggestion Actions Card Workflow
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Redesign the suggestion actions card to implement a structured workflow for task expansion, subtask creation, context addition, and task management.
# Details:
Implement a new workflow for the suggestion actions card that guides users through a logical sequence when working with tasks and subtasks:
1. Task Expansion Phase:
- Add a prominent 'Expand Task' button at the top of the suggestion card
- Implement an 'Add Subtask' button that becomes active after task expansion
- Allow users to add multiple subtasks sequentially
- Provide visual indication of the current phase (expansion phase)
2. Context Addition Phase:
- After subtasks are created, transition to the context phase
- Implement an 'Update Subtask' action that allows appending context to each subtask
- Create a UI element showing which subtask is currently being updated
- Provide a progress indicator showing which subtasks have received context
- Include a mechanism to navigate between subtasks for context addition
3. Task Management Phase:
- Once all subtasks have context, enable the 'Set as In Progress' button
- Add a 'Start Working' button that directs the agent to begin with the first subtask
- Implement an 'Update Task' action that consolidates all notes and reorganizes them into improved subtask details
- Provide a confirmation dialog when restructuring task content
4. UI/UX Considerations:
- Use visual cues (colors, icons) to indicate the current phase
- Implement tooltips explaining each action's purpose
- Add a progress tracker showing completion status across all phases
- Ensure the UI adapts responsively to different screen sizes
The implementation should maintain all existing functionality while guiding users through this more structured approach to task management.
# Test Strategy:
Testing should verify the complete workflow functions correctly:
1. Unit Tests:
- Test each button/action individually to ensure it performs its specific function
- Verify state transitions between phases work correctly
- Test edge cases (e.g., attempting to set a task in progress before adding context)
2. Integration Tests:
- Verify the complete workflow from task expansion to starting work
- Test that context added to subtasks is properly saved and displayed
- Ensure the 'Update Task' functionality correctly consolidates and restructures content
3. UI/UX Testing:
- Verify visual indicators correctly show the current phase
- Test responsive design on various screen sizes
- Ensure tooltips and help text are displayed correctly
4. User Acceptance Testing:
- Create test scenarios covering the complete workflow:
a. Expand a task and add 3 subtasks
b. Add context to each subtask
c. Set the task as in progress
d. Use update-task to restructure the content
e. Verify the agent correctly begins work on the first subtask
- Test with both simple and complex tasks to ensure scalability
5. Regression Testing:
- Verify that existing functionality continues to work
- Ensure compatibility with keyboard shortcuts and accessibility features
# Subtasks:
## 1. Design Task Expansion UI Components [pending]
### Dependencies: None
### Description: Create UI components for the expanded task suggestion actions card that allow for task breakdown and additional context input.
### 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.
## 2. Implement State Management for Task Expansion [pending]
### Dependencies: 47.1
### Description: Develop the state management logic to handle expanded task states, subtask creation, and context additions.
### 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.
## 3. Build Context Addition Functionality [pending]
### Dependencies: 47.2
### Description: Create the functionality that allows users to add additional context to tasks and subtasks.
### 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.
## 4. Develop Task Management Controls [pending]
### Dependencies: 47.2
### Description: Implement controls for managing tasks within the expanded card view, including prioritization, scheduling, and assignment.
### 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.
## 5. Integrate with Existing Task Systems [pending]
### Dependencies: 47.3, 47.4
### Description: Ensure the enhanced actions card workflow integrates seamlessly with existing task management functionality.
### 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.
## 6. Test and Optimize User Experience [pending]
### Dependencies: 47.5
### Description: Conduct thorough testing of the enhanced workflow and optimize based on user feedback and performance metrics.
### 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.

View File

@@ -1,64 +0,0 @@
# Task ID: 48
# Title: Refactor Prompts into Centralized Structure
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Create a dedicated 'prompts' folder and move all prompt definitions from inline function implementations to individual files, establishing a centralized prompt management system.
# Details:
This task involves restructuring how prompts are managed in the codebase:
1. Create a new 'prompts' directory at the appropriate level in the project structure
2. For each existing prompt currently embedded in functions:
- Create a dedicated file with a descriptive name (e.g., 'task_suggestion_prompt.js')
- Extract the prompt text/object into this file
- Export the prompt using the appropriate module pattern
3. Modify all functions that currently contain inline prompts to import them from the new centralized location
4. Establish a consistent naming convention for prompt files (e.g., feature_action_prompt.js)
5. Consider creating an index.js file in the prompts directory to provide a clean import interface
6. Document the new prompt structure in the project documentation
7. Ensure that any prompt that requires dynamic content insertion maintains this capability after refactoring
This refactoring will improve maintainability by making prompts easier to find, update, and reuse across the application.
# Test Strategy:
Testing should verify that the refactoring maintains identical functionality while improving code organization:
1. Automated Tests:
- Run existing test suite to ensure no functionality is broken
- Create unit tests for the new prompt import mechanism
- Verify that dynamically constructed prompts still receive their parameters correctly
2. Manual Testing:
- Execute each feature that uses prompts and compare outputs before and after refactoring
- Verify that all prompts are properly loaded from their new locations
- Check that no prompt text is accidentally modified during the migration
3. Code Review:
- Confirm all prompts have been moved to the new structure
- Verify consistent naming conventions are followed
- Check that no duplicate prompts exist
- Ensure imports are correctly implemented in all files that previously contained inline prompts
4. Documentation:
- Verify documentation is updated to reflect the new prompt organization
- Confirm the index.js export pattern works as expected for importing prompts
# Subtasks:
## 1. Create prompts directory structure [pending]
### Dependencies: None
### Description: Create a centralized 'prompts' directory with appropriate subdirectories for different prompt categories
### 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.
## 2. Extract prompts into individual files [pending]
### Dependencies: 48.1
### Description: Identify all hardcoded prompts in the codebase and extract them into individual files in the prompts directory
### 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.
## 3. Update functions to import prompts [pending]
### Dependencies: 48.1, 48.2
### Description: Modify all functions that use hardcoded prompts to import them from the centralized structure
### 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.

View File

@@ -1,104 +0,0 @@
# Task ID: 49
# Title: Implement Code Quality Analysis Command
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
Develop a new command called `analyze-code-quality` that performs the following functions:
1. **Pattern Recognition**:
- Scan the codebase to identify recurring patterns in code structure, function design, and architecture
- Categorize patterns by frequency and impact on maintainability
- Generate a report of common patterns with examples from the codebase
2. **Best Practice Verification**:
- For each function in specified files, extract its purpose, parameters, and implementation details
- Create a verification checklist for each function that includes:
- Function naming conventions
- Parameter handling
- Error handling
- Return value consistency
- Documentation quality
- Complexity metrics
- Use an API integration with Perplexity or similar AI service to evaluate each function against current best practices
3. **Improvement Recommendations**:
- Generate specific refactoring suggestions for functions that don't align with best practices
- Include code examples of the recommended improvements
- Estimate the effort required for each refactoring suggestion
4. **Task Integration**:
- Create a mechanism to convert high-value improvement recommendations into Taskmaster tasks
- Allow users to select which recommendations to convert to tasks
- Generate properly formatted task descriptions that include the current implementation, recommended changes, and justification
The command should accept parameters for targeting specific directories or files, setting the depth of analysis, and filtering by improvement impact level.
# Test Strategy:
Testing should verify all aspects of the code analysis command:
1. **Functionality Testing**:
- Create a test codebase with known patterns and anti-patterns
- Verify the command correctly identifies all patterns in the test codebase
- Check that function verification correctly flags issues in deliberately non-compliant functions
- Confirm recommendations are relevant and implementable
2. **Integration Testing**:
- Test the AI service integration with mock responses to ensure proper handling of API calls
- Verify the task creation workflow correctly generates well-formed tasks
- Test integration with existing Taskmaster commands and workflows
3. **Performance Testing**:
- Measure execution time on codebases of various sizes
- Ensure memory usage remains reasonable even on large codebases
- Test with rate limiting on API calls to ensure graceful handling
4. **User Experience Testing**:
- Have developers use the command on real projects and provide feedback
- Verify the output is actionable and clear
- Test the command with different parameter combinations
5. **Validation Criteria**:
- Command successfully analyzes at least 95% of functions in the codebase
- Generated recommendations are specific and actionable
- Created tasks follow the project's task format standards
- Analysis results are consistent across multiple runs on the same codebase
# Subtasks:
## 1. Design pattern recognition algorithm [pending]
### Dependencies: None
### Description: Create an algorithm to identify common code patterns and anti-patterns in the codebase
### 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.
## 2. Implement best practice verification [pending]
### Dependencies: 49.1
### Description: Build verification checks against established coding standards and best practices
### 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.
## 3. Develop AI integration for code analysis [pending]
### Dependencies: 49.1, 49.2
### Description: Integrate AI capabilities to enhance code analysis and provide intelligent recommendations
### 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.
## 4. Create recommendation generation system [pending]
### Dependencies: 49.2, 49.3
### Description: Build a system to generate actionable improvement recommendations based on analysis results
### Details:
Develop algorithms to transform analysis results into specific, actionable recommendations. Include priority levels, effort estimates, and potential impact assessments for each recommendation.
## 5. Implement task creation functionality [pending]
### Dependencies: 49.4
### Description: Add capability to automatically create tasks from code quality recommendations
### 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.
## 6. Create comprehensive reporting interface [pending]
### Dependencies: 49.4, 49.5
### Description: Develop a user interface to display analysis results and recommendations
### 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.

View File

@@ -1,131 +0,0 @@
# Task ID: 50
# Title: Implement Test Coverage Tracking System by Task
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
Develop a comprehensive test coverage tracking system with the following components:
1. Create a `tests.json` file structure in the `tasks/` directory that associates test suites and individual tests with specific task IDs or subtask IDs.
2. Build a generator that processes code coverage reports and updates the `tests.json` file to maintain an accurate mapping between tests and tasks.
3. 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.
4. Create CLI commands that can:
- Display test coverage for a specific task/subtask
- Identify untested code related to a particular task
- Generate test suggestions for uncovered code using LLMs
5. Extend the MCP (Mission Control Panel) to visualize test coverage by task, showing percentage covered and highlighting areas needing tests.
6. Develop an automated test generation system that uses LLMs to create targeted tests for specific uncovered code sections within a task.
7. Implement a workflow that integrates with the existing task management system, allowing developers to see test requirements alongside implementation requirements.
The 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.
# Test Strategy:
Testing should verify all components of the test coverage tracking system:
1. **File Structure Tests**: Verify the `tests.json` file is correctly created and follows the expected schema with proper task/test relationships.
2. **Coverage Report Processing**: Create mock coverage reports and verify they are correctly parsed and integrated into the `tests.json` file.
3. **CLI Command Tests**: Test each CLI command with various inputs:
- Test coverage display for existing tasks
- Edge cases like tasks with no tests
- Tasks with partial coverage
4. **Integration Tests**: Verify the entire workflow from code changes to coverage reporting to task-based test suggestions.
5. **LLM Test Generation**: Validate that generated tests actually cover the intended code paths by running them against the codebase.
6. **UI/UX Tests**: Ensure the MCP correctly displays coverage information and that the interface for viewing and managing test coverage is intuitive.
7. **Performance Tests**: Measure the performance impact of the coverage tracking system, especially for large codebases.
Create a test suite that can run in CI/CD to ensure the test coverage tracking system itself maintains high coverage and reliability.
# Subtasks:
## 1. Design and implement tests.json data structure [pending]
### Dependencies: None
### 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.
### 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.
2. Implement bidirectional relationships by creating references between tests.json and tasks.json.
3. Define fields for tracking statement coverage, branch coverage, and function coverage per task.
4. Add metadata fields for test quality metrics beyond coverage (complexity, mutation score).
5. Create utility functions to read/write/update the tests.json file.
6. Implement validation logic to ensure data integrity between tasks and tests.
7. Add version control compatibility by using relative paths and stable identifiers.
8. Test the data structure with sample data representing various test scenarios.
9. Document the schema with examples and usage guidelines.
## 2. Develop coverage report parser and adapter system [pending]
### Dependencies: 50.1
### 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.
### Details:
1. Research and document output formats for major coverage tools (Istanbul/nyc, Jest, Pytest, JaCoCo).
2. Design a normalized intermediate coverage format that any test tool can map to.
3. Implement adapter classes for each major testing framework that convert their reports to the intermediate format.
4. Create a parser registry that can automatically detect and use the appropriate parser based on input format.
5. Develop a mapping algorithm that associates coverage data with specific tasks based on file paths and code blocks.
6. Implement file path normalization to handle different operating systems and environments.
7. Add error handling for malformed or incomplete coverage reports.
8. Create unit tests for each adapter using sample coverage reports.
9. Implement a command-line interface for manual parsing and testing.
10. Document the extension points for adding custom coverage tool adapters.
## 3. Build coverage tracking and update generator [pending]
### Dependencies: 50.1, 50.2
### 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.
### Details:
1. Implement a coverage processor that takes parsed coverage data and maps it to task IDs.
2. Create algorithms to calculate aggregate coverage metrics at the task and subtask levels.
3. Develop a change detection system that identifies when tests or code have changed and require updates.
4. Implement incremental update logic to avoid reprocessing unchanged tests.
5. Create a task-code association system that maps specific code blocks to tasks for granular tracking.
6. Add historical tracking to monitor coverage trends over time.
7. Implement hooks for CI/CD integration to automatically update coverage after test runs.
8. Create a conflict resolution strategy for when multiple tests cover the same code areas.
9. Add performance optimizations for large codebases and test suites.
10. Develop unit tests that verify correct aggregation and mapping of coverage data.
11. Document the update workflow with sequence diagrams and examples.
## 4. Implement CLI commands for coverage operations [pending]
### Dependencies: 50.1, 50.2, 50.3
### Description: Create a set of command-line interface tools that allow developers to view, analyze, and manage test coverage at the task level.
### Details:
1. Design a cohesive CLI command structure with subcommands for different coverage operations.
2. Implement 'coverage show' command to display test coverage for a specific task/subtask.
3. Create 'coverage gaps' command to identify untested code related to a particular task.
4. Develop 'coverage history' command to show how coverage has changed over time.
5. Implement 'coverage generate' command that uses LLMs to suggest tests for uncovered code.
6. Add filtering options to focus on specific test types or coverage thresholds.
7. Create formatted output options (JSON, CSV, markdown tables) for integration with other tools.
8. Implement colorized terminal output for better readability of coverage reports.
9. Add batch processing capabilities for running operations across multiple tasks.
10. Create comprehensive help documentation and examples for each command.
11. Develop unit and integration tests for CLI commands.
12. Document command usage patterns and example workflows.
## 5. Develop AI-powered test generation system [pending]
### Dependencies: 50.1, 50.2, 50.3, 50.4
### 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.
### Details:
1. Design prompt templates for different test types (unit, integration, E2E) that incorporate task descriptions and code context.
2. Implement code analysis to extract relevant context from uncovered code sections.
3. Create a test generation pipeline that combines task metadata, code context, and coverage gaps.
4. Develop strategies for maintaining test context across task changes and updates.
5. Implement test quality evaluation to ensure generated tests are meaningful and effective.
6. Create a feedback mechanism to improve prompts based on acceptance or rejection of generated tests.
7. Add support for different testing frameworks and languages through templating.
8. Implement caching to avoid regenerating similar tests.
9. Create a workflow that integrates with the task management system to suggest tests alongside implementation requirements.
10. Develop specialized generation modes for edge cases, regression tests, and performance tests.
11. Add configuration options for controlling test generation style and coverage goals.
12. Create comprehensive documentation on how to use and extend the test generation system.
13. Implement evaluation metrics to track the effectiveness of AI-generated tests.

View File

@@ -1,452 +0,0 @@
# Task ID: 51
# Title: Implement Perplexity Research Command
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Create an interactive REPL-style chat interface for AI-powered research that maintains conversation context, integrates project information, and provides session management capabilities.
# 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:
1. Create an interactive REPL using inquirer that:
- Maintains conversation history and context
- Provides a natural chat-like experience
- Supports special commands with the '/' prefix
2. Integrate with the existing ai-services-unified.js using research mode:
- Leverage our unified AI service architecture
- Configure appropriate system prompts for research context
- Handle streaming responses for real-time feedback
3. Support multiple context sources:
- Task/subtask IDs for project context
- File paths for code or document context
- Custom prompts for specific research directions
- Project file tree for system context
4. Implement chat commands including:
- `/save` - Save conversation to file
- `/task` - Associate with or load context from a task
- `/help` - Show available commands and usage
- `/exit` - End the research session
- `/copy` - Copy last response to clipboard
- `/summary` - Generate summary of conversation
- `/detail` - Adjust research depth level
5. Create session management capabilities:
- Generate and track unique session IDs
- Save/load sessions automatically
- Browse and switch between previous sessions
- Export sessions to portable formats
6. Design a consistent UI using ui.js patterns:
- Color-coded messages for user/AI distinction
- Support for markdown rendering in terminal
- Progressive display of AI responses
- Clear visual hierarchy and readability
7. Follow the "taskmaster way":
- Create something new and exciting
- Focus on usefulness and practicality
- Avoid over-engineering
- Maintain consistency with existing patterns
The REPL should feel like a natural conversation while providing powerful research capabilities that integrate seamlessly with the rest of the system.
# Test Strategy:
1. Unit tests:
- Test the REPL command parsing and execution
- Mock AI service responses to test different scenarios
- Verify context extraction and integration from various sources
- Test session serialization and deserialization
2. Integration tests:
- Test actual AI service integration with the REPL
- Verify session persistence across application restarts
- Test conversation state management with long interactions
- Verify context switching between different tasks and files
3. User acceptance testing:
- Have team members use the REPL for real research needs
- Test the conversation flow and command usability
- Verify the UI is intuitive and responsive
- Test with various terminal sizes and environments
4. Performance testing:
- Measure and optimize response time for queries
- Test behavior with large conversation histories
- Verify performance with complex context sources
- Test under poor network conditions
5. Specific test scenarios:
- Verify markdown rendering for complex formatting
- Test streaming display with various response lengths
- Verify export features create properly formatted files
- Test session recovery from simulated crashes
- Validate handling of special characters and unicode
# Subtasks:
## 1. Create Perplexity API Client Service [cancelled]
### Dependencies: None
### Description: Develop a service module that handles all interactions with the Perplexity AI API, including authentication, request formatting, and response handling.
### Details:
Implementation details:
1. Create a new service file `services/perplexityService.js`
2. Implement authentication using the PERPLEXITY_API_KEY from environment variables
3. Create functions for making API requests to Perplexity with proper error handling:
- `queryPerplexity(searchQuery, options)` - Main function to query the API
- `handleRateLimiting(response)` - Logic to handle rate limits with exponential backoff
4. Implement response parsing and formatting functions
5. Add proper error handling for network issues, authentication problems, and API limitations
6. Create a simple caching mechanism using a Map or object to store recent query results
7. Add configuration options for different detail levels (quick vs comprehensive)
Testing approach:
- Write unit tests using Jest to verify API client functionality with mocked responses
- Test error handling with simulated network failures
- Verify caching mechanism works correctly
- Test with various query types and options
<info added on 2025-05-23T21:06:45.726Z>
DEPRECATION 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.
</info added on 2025-05-23T21:06:45.726Z>
## 2. Implement Task Context Extraction Logic [pending]
### Dependencies: None
### Description: Create utility functions to extract relevant context from tasks and subtasks to enhance research queries with project-specific information.
### Details:
Implementation details:
1. Create a new utility file `utils/contextExtractor.js`
2. Implement a function `extractTaskContext(taskId)` that:
- Loads the task/subtask data from tasks.json
- Extracts relevant information (title, description, details)
- Formats the extracted information into a context string for research
3. Add logic to handle both task and subtask IDs
4. Implement a function to combine extracted context with the user's search query
5. Create a function to identify and extract key terminology from tasks
6. Add functionality to include parent task context when a subtask ID is provided
7. Implement proper error handling for invalid task IDs
Testing approach:
- Write unit tests to verify context extraction from sample tasks
- Test with various task structures and content types
- Verify error handling for missing or invalid tasks
- Test the quality of extracted context with sample queries
<info added on 2025-05-23T21:11:44.560Z>
Updated Implementation Approach:
REFACTORED IMPLEMENTATION:
1. Extract the fuzzy search logic from add-task.js (lines ~240-400) into `utils/contextExtractor.js`
2. Implement a reusable `TaskContextExtractor` class with the following methods:
- `extractTaskContext(taskId)` - Base context extraction
- `performFuzzySearch(query, options)` - Enhanced Fuse.js implementation
- `getRelevanceScore(task, query)` - Scoring mechanism from add-task.js
- `detectPurposeCategories(task)` - Category classification logic
- `findRelatedTasks(taskId)` - Identify dependencies and relationships
- `aggregateMultiQueryContext(queries)` - Support for multiple search terms
3. Add configurable context depth levels:
- Minimal: Just task title and description
- Standard: Include details and immediate relationships
- Comprehensive: Full context with all dependencies and related tasks
4. Implement context formatters:
- `formatForSystemPrompt(context)` - Structured for AI system instructions
- `formatForChatContext(context)` - Conversational format for chat
- `formatForResearchQuery(context, query)` - Optimized for research commands
5. Add caching layer for performance optimization:
- Implement LRU cache for expensive fuzzy search results
- Cache invalidation on task updates
6. Ensure backward compatibility with existing context extraction requirements
This approach leverages our existing sophisticated search logic rather than rebuilding from scratch, while making it more flexible and reusable across the application.
</info added on 2025-05-23T21:11:44.560Z>
## 3. Build Research Command CLI Interface [pending]
### Dependencies: 51.1, 51.2
### Description: Implement the Commander.js command structure for the 'research' command with all required options and parameters.
### Details:
Implementation details:
1. Create a new command file `commands/research.js`
2. Set up the Commander.js command structure with the following options:
- Required search query parameter
- `--task` or `-t` option for task/subtask ID
- `--prompt` or `-p` option for custom research prompt
- `--save` or `-s` option to save results to a file
- `--copy` or `-c` option to copy results to clipboard
- `--summary` or `-m` option to generate a summary
- `--detail` or `-d` option to set research depth (default: medium)
3. Implement command validation logic
4. Connect the command to the Perplexity service created in subtask 1
5. Integrate the context extraction logic from subtask 2
6. Register the command in the main CLI application
7. Add help text and examples
Testing approach:
- Test command registration and option parsing
- Verify command validation logic works correctly
- Test with various combinations of options
- Ensure proper error messages for invalid inputs
<info added on 2025-05-23T21:09:08.478Z>
Implementation details:
1. Create a new module `repl/research-chat.js` for the interactive research experience
2. Implement REPL-style chat interface using inquirer with:
- Persistent conversation history management
- Context-aware prompting system
- Command parsing for special instructions
3. Implement REPL commands:
- `/save` - Save conversation to file
- `/task` - Associate with or load context from a task
- `/help` - Show available commands and usage
- `/exit` - End the research session
- `/copy` - Copy last response to clipboard
- `/summary` - Generate summary of conversation
- `/detail` - Adjust research depth level
4. Create context initialization system:
- Task/subtask context loading
- File content integration
- System prompt configuration
5. Integrate with ai-services-unified.js research mode
6. Implement conversation state management:
- Track message history
- Maintain context window
- Handle context pruning for long conversations
7. Design consistent UI patterns using ui.js library
8. Add entry point in main CLI application
Testing approach:
- Test REPL command parsing and execution
- Verify context initialization with various inputs
- Test conversation state management
- Ensure proper error handling and recovery
- Validate UI consistency across different terminal environments
</info added on 2025-05-23T21:09:08.478Z>
## 4. Implement Results Processing and Output Formatting [pending]
### Dependencies: 51.1, 51.3
### Description: Create functionality to process, format, and display research results in the terminal with options for saving, copying, and summarizing.
### Details:
Implementation details:
1. Create a new module `utils/researchFormatter.js`
2. Implement terminal output formatting with:
- Color-coded sections for better readability
- Proper text wrapping for terminal width
- Highlighting of key points
3. Add functionality to save results to a file:
- Create a `research-results` directory if it doesn't exist
- Save results with timestamp and query in filename
- Support multiple formats (text, markdown, JSON)
4. Implement clipboard copying using a library like `clipboardy`
5. Create a summarization function that extracts key points from research results
6. Add progress indicators during API calls
7. Implement pagination for long results
Testing approach:
- Test output formatting with various result lengths and content types
- Verify file saving functionality creates proper files with correct content
- Test clipboard functionality
- Verify summarization produces useful results
<info added on 2025-05-23T21:10:00.181Z>
Implementation details:
1. Create a new module `utils/chatFormatter.js` for REPL interface formatting
2. Implement terminal output formatting for conversational display:
- Color-coded messages distinguishing user inputs and AI responses
- Proper text wrapping and indentation for readability
- Support for markdown rendering in terminal
- Visual indicators for system messages and status updates
3. Implement streaming/progressive display of AI responses:
- Character-by-character or chunk-by-chunk display
- Cursor animations during response generation
- Ability to interrupt long responses
4. Design chat history visualization:
- Scrollable history with clear message boundaries
- Timestamp display options
- Session identification
5. Create specialized formatters for different content types:
- Code blocks with syntax highlighting
- Bulleted and numbered lists
- Tables and structured data
- Citations and references
6. Implement export functionality:
- Save conversations to markdown or text files
- Export individual responses
- Copy responses to clipboard
7. Adapt existing ui.js patterns for conversational context:
- Maintain consistent styling while supporting chat flow
- Handle multi-turn context appropriately
Testing approach:
- Test streaming display with various response lengths and speeds
- Verify markdown rendering accuracy for complex formatting
- Test history navigation and scrolling functionality
- Verify export features create properly formatted files
- Test display on various terminal sizes and configurations
- Verify handling of special characters and unicode
</info added on 2025-05-23T21:10:00.181Z>
## 5. Implement Caching and Results Management System [cancelled]
### Dependencies: 51.1, 51.4
### Description: Create a persistent caching system for research results and implement functionality to manage, retrieve, and reference previous research.
### Details:
Implementation details:
1. Create a research results database using a simple JSON file or SQLite:
- Store queries, timestamps, and results
- Index by query and related task IDs
2. Implement cache retrieval and validation:
- Check for cached results before making API calls
- Validate cache freshness with configurable TTL
3. Add commands to manage research history:
- List recent research queries
- Retrieve past research by ID or search term
- Clear cache or delete specific entries
4. Create functionality to associate research results with tasks:
- Add metadata linking research to specific tasks
- Implement command to show all research related to a task
5. Add configuration options for cache behavior in user settings
6. Implement export/import functionality for research data
Testing approach:
- Test cache storage and retrieval with various queries
- Verify cache invalidation works correctly
- Test history management commands
- Verify task association functionality
- Test with large cache sizes to ensure performance
<info added on 2025-05-23T21:10:28.544Z>
Implementation details:
1. Create a session management system for the REPL experience:
- Generate and track unique session IDs
- Store conversation history with timestamps
- Maintain context and state between interactions
2. Implement session persistence:
- Save sessions to disk automatically
- Load previous sessions on startup
- Handle graceful recovery from crashes
3. Build session browser and selector:
- List available sessions with preview
- Filter sessions by date, topic, or content
- Enable quick switching between sessions
4. Implement conversation state serialization:
- Capture full conversation context
- Preserve user preferences per session
- Handle state migration during updates
5. Add session sharing capabilities:
- Export sessions to portable formats
- Import sessions from files
- Generate shareable links (if applicable)
6. Create session management commands:
- Create new sessions
- Clone existing sessions
- Archive or delete old sessions
Testing approach:
- Verify session persistence across application restarts
- Test session recovery from simulated crashes
- Validate state serialization with complex conversations
- Ensure session switching maintains proper context
- Test session import/export functionality
- Verify performance with large conversation histories
</info added on 2025-05-23T21:10:28.544Z>
## 6. Implement Project Context Generation [pending]
### Dependencies: 51.2
### Description: Create functionality to generate and include project-level context such as file trees, repository structure, and codebase insights for more informed research.
### Details:
Implementation details:
1. Create a new module `utils/projectContextGenerator.js` for project-level context extraction
2. Implement file tree generation functionality:
- Scan project directory structure recursively
- Filter out irrelevant files (node_modules, .git, etc.)
- Format file tree for AI consumption
- Include file counts and structure statistics
3. Add code analysis capabilities:
- Extract key imports and dependencies
- Identify main modules and their relationships
- Generate high-level architecture overview
4. Implement context summarization:
- Create concise project overview
- Identify key technologies and patterns
- Summarize project purpose and structure
5. Add caching for expensive operations:
- Cache file tree with invalidation on changes
- Store analysis results with TTL
6. Create integration with research REPL:
- Add project context to system prompts
- Support `/project` command to refresh context
- Allow selective inclusion of project components
Testing approach:
- Test file tree generation with various project structures
- Verify filtering logic works correctly
- Test context summarization quality
- Measure performance impact of context generation
- Verify caching mechanism effectiveness
## 7. Create REPL Command System [pending]
### Dependencies: 51.3
### Description: Implement a flexible command system for the research REPL that allows users to control the conversation flow, manage sessions, and access additional functionality.
### Details:
Implementation details:
1. Create a new module `repl/commands.js` for REPL command handling
2. Implement a command parser that:
- Detects commands starting with `/`
- Parses arguments and options
- Handles quoted strings and special characters
3. Create a command registry system:
- Register command handlers with descriptions
- Support command aliases
- Enable command discovery and help
4. Implement core commands:
- `/save [filename]` - Save conversation
- `/task <taskId>` - Load task context
- `/file <path>` - Include file content
- `/help [command]` - Show help
- `/exit` - End session
- `/copy [n]` - Copy nth response
- `/summary` - Generate conversation summary
- `/detail <level>` - Set detail level
- `/clear` - Clear conversation
- `/project` - Refresh project context
- `/session <id|new>` - Switch/create session
5. Add command completion and suggestions
6. Implement error handling for invalid commands
7. Create a help system with examples
Testing approach:
- Test command parsing with various inputs
- Verify command execution and error handling
- Test command completion functionality
- Verify help system provides useful information
- Test with complex command sequences
## 8. Integrate with AI Services Unified [pending]
### Dependencies: 51.3, 51.4
### Description: Integrate the research REPL with the existing ai-services-unified.js to leverage the unified AI service architecture with research mode.
### Details:
Implementation details:
1. Update `repl/research-chat.js` to integrate with ai-services-unified.js
2. Configure research mode in AI service:
- Set appropriate system prompts
- Configure temperature and other parameters
- Enable streaming responses
3. Implement context management:
- Format conversation history for AI context
- Include task and project context
- Handle context window limitations
4. Add support for different research styles:
- Exploratory research with broader context
- Focused research with specific questions
- Comparative analysis between concepts
5. Implement response handling:
- Process streaming chunks
- Format and display responses
- Handle errors and retries
6. Add configuration options for AI service selection
7. Implement fallback mechanisms for service unavailability
Testing approach:
- Test integration with mocked AI services
- Verify context formatting and management
- Test streaming response handling
- Verify error handling and recovery
- Test with various research styles and queries

View File

@@ -1,83 +0,0 @@
# Task ID: 52
# Title: Implement Task Suggestion Command for CLI
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
Implement a new command 'suggest-task' that can be invoked from the CLI to generate intelligent task suggestions. The command should:
1. Collect a snapshot of all existing tasks including their titles, descriptions, statuses, and dependencies
2. Extract parent task subtask titles (not full objects) to provide context
3. Use this information to generate a contextually appropriate new task suggestion
4. Present the suggestion to the user in a clear format
5. Provide an interactive interface with options to:
- Accept the suggestion (creating a new task with the suggested details)
- Decline the suggestion (exiting without creating a task)
- Regenerate a new suggestion (requesting an alternative)
The 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.
The command should accept optional flags to customize the suggestion process, such as:
- `--parent=<task-id>` to suggest a task related to a specific parent task
- `--type=<task-type>` to suggest a specific type of task (feature, bugfix, refactor, etc.)
- `--context=<additional-context>` to provide additional information for the suggestion
# Test Strategy:
Testing should verify both the functionality and user experience of the suggest-task command:
1. Unit tests:
- Test the task collection mechanism to ensure it correctly gathers existing task data
- Test the context extraction logic to verify it properly isolates relevant subtask titles
- Test the suggestion generation with mocked AI responses
- Test the command's parsing of various flag combinations
2. Integration tests:
- Test the end-to-end flow with a mock project structure
- Verify the command correctly interacts with the AI service
- Test the task creation process when a suggestion is accepted
3. User interaction tests:
- Test the accept/decline/regenerate interface works correctly
- Verify appropriate feedback is displayed to the user
- Test handling of unexpected user inputs
4. Edge cases:
- Test behavior when run in an empty project with no existing tasks
- Test with malformed task data
- Test with API timeouts or failures
- Test with extremely large numbers of existing tasks
Manually verify the command produces contextually appropriate suggestions that align with the project's current state and needs.
# Subtasks:
## 1. Design data collection mechanism for existing tasks [pending]
### Dependencies: None
### Description: Create a module to collect and format existing task data from the system for AI processing
### 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.
## 2. Implement AI integration for task suggestions [pending]
### Dependencies: 52.1
### Description: Develop the core functionality to generate task suggestions using AI based on existing tasks
### 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.
## 3. Build interactive CLI interface for suggestions [pending]
### Dependencies: 52.2
### Description: Create the command-line interface for requesting and displaying task suggestions
### 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.
## 4. Implement suggestion selection and task creation [pending]
### Dependencies: 52.3
### Description: Allow users to interactively select suggestions to convert into actual tasks
### 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.
## 5. Add configuration options and flag handling [pending]
### Dependencies: 52.3, 52.4
### Description: Implement various configuration options and command flags for customizing suggestion behavior
### 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.

View File

@@ -1,91 +0,0 @@
# Task ID: 53
# Title: Implement Subtask Suggestion Feature for Parent Tasks
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
Develop a new command `suggest-subtask <task-id>` that generates intelligent subtask suggestions for a specified parent task. The implementation should:
1. Accept a parent task ID as input and validate it exists
2. Gather a snapshot of all existing tasks in the system (titles only, with their statuses and dependencies)
3. Retrieve the full details of the specified parent task
4. Use this context to generate a relevant subtask suggestion that would logically help complete the parent task
5. Present the suggestion to the user in the CLI with options to:
- Accept (a): Add the subtask to the system under the parent task
- Decline (d): Reject the suggestion without adding anything
- Regenerate (r): Generate a new alternative subtask suggestion
- Edit (e): Accept but allow editing the title/description before adding
The suggestion algorithm should consider:
- The parent task's description and requirements
- Current progress (% complete) of the parent task
- Existing subtasks already created for this parent
- Similar patterns from other tasks in the system
- Logical next steps based on software development best practices
When a subtask is accepted, it should be properly linked to the parent task and assigned appropriate default values for priority and status.
# Test Strategy:
Testing should verify both the functionality and the quality of suggestions:
1. Unit tests:
- Test command parsing and validation of task IDs
- Test snapshot creation of existing tasks
- Test the suggestion generation with mocked data
- Test the user interaction flow with simulated inputs
2. Integration tests:
- Create a test parent task and verify subtask suggestions are contextually relevant
- Test the accept/decline/regenerate workflow end-to-end
- Verify proper linking of accepted subtasks to parent tasks
- Test with various types of parent tasks (frontend, backend, documentation, etc.)
3. Quality assessment:
- Create a benchmark set of 10 diverse parent tasks
- Generate 3 subtask suggestions for each and have team members rate relevance on 1-5 scale
- Ensure average relevance score exceeds 3.5/5
- Verify suggestions don't duplicate existing subtasks
4. Edge cases:
- Test with a parent task that has no description
- Test with a parent task that already has many subtasks
- Test with a newly created system with minimal task history
# Subtasks:
## 1. Implement parent task validation [pending]
### Dependencies: None
### Description: Create validation logic to ensure subtasks are being added to valid parent tasks
### 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.
## 2. Build context gathering mechanism [pending]
### Dependencies: 53.1
### Description: Develop a system to collect relevant context from parent task and existing subtasks
### 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.
## 3. Develop AI suggestion logic for subtasks [pending]
### Dependencies: 53.2
### Description: Create the core AI integration to generate relevant subtask suggestions
### 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.
## 4. Create interactive CLI interface [pending]
### Dependencies: 53.3
### Description: Build a user-friendly command-line interface for the subtask suggestion feature
### 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.
## 5. Implement subtask linking functionality [pending]
### Dependencies: 53.4
### Description: Create system to properly link suggested subtasks to their parent task
### 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.
## 6. Perform comprehensive testing [pending]
### Dependencies: 53.5
### Description: Test the subtask suggestion feature across various scenarios
### 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.

View File

@@ -1,43 +0,0 @@
# Task ID: 54
# Title: Add Research Flag to Add-Task Command
# Status: done
# Dependencies: None
# Priority: medium
# 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.
# 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:
1. Update the command parser to recognize the new --research flag
2. When the flag is present, extract the task title/description as the research topic
3. Call the Perplexity research functionality with this topic
4. Display research results to the user
5. Allow the user to refine their task based on the research (modify title, description, etc.)
6. Continue with normal task creation flow after research is complete
7. Ensure the research results can be optionally attached to the task as reference material
8. Add appropriate help text explaining this feature in the command help
The implementation should leverage the existing Perplexity research command from Task #51, ensuring code reuse where possible.
# Test Strategy:
Testing should verify both the functionality and usability of the new feature:
1. Unit tests:
- Verify the command parser correctly recognizes the --research flag
- Test that the research functionality is properly invoked with the correct topic
- Ensure task creation proceeds correctly after research is complete
2. Integration tests:
- Test the complete flow from command invocation to task creation with research
- Verify research results are properly attached to the task when requested
- Test error handling when research API is unavailable
3. Manual testing:
- Run the command with --research flag and verify the user experience
- Test with various task topics to ensure research is relevant
- Verify the help documentation correctly explains the feature
- Test the command without the flag to ensure backward compatibility
4. Edge cases:
- Test with very short/vague task descriptions
- Test with complex technical topics
- Test cancellation of task creation during the research phase

View File

@@ -1,82 +0,0 @@
# Task ID: 55
# Title: Implement Positional Arguments Support for CLI Commands
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Upgrade CLI commands to support positional arguments alongside the existing flag-based syntax, allowing for more intuitive command usage.
# 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:
1. Update the argument parsing logic to detect when arguments are provided without flag prefixes (--)
2. Map positional arguments to their corresponding parameters based on their order
3. For each command in commands.js, define a consistent positional argument order (e.g., for set-status: first arg = id, second arg = status)
4. Maintain backward compatibility with the existing flag-based syntax
5. Handle edge cases such as:
- Commands with optional parameters
- Commands with multiple parameters
- Commands that accept arrays or complex data types
6. Update the help text for each command to show both usage patterns
7. Modify the cursor rules to work with both input styles
8. Ensure error messages are clear when positional arguments are provided incorrectly
Example implementations:
- `task-master set-status 25 done` should be equivalent to `task-master set-status --id=25 --status=done`
- `task-master add-task "New task name" "Task description"` should be equivalent to `task-master add-task --name="New task name" --description="Task description"`
The code should prioritize maintaining the existing functionality while adding this new capability.
# Test Strategy:
Testing should verify both the new positional argument functionality and continued support for flag-based syntax:
1. Unit tests:
- Create tests for each command that verify it works with both positional and flag-based arguments
- Test edge cases like missing arguments, extra arguments, and mixed usage (some positional, some flags)
- Verify help text correctly displays both usage patterns
2. Integration tests:
- Test the full CLI with various commands using both syntax styles
- Verify that output is identical regardless of which syntax is used
- Test commands with different numbers of arguments
3. Manual testing:
- Run through a comprehensive set of real-world usage scenarios with both syntax styles
- Verify cursor behavior works correctly with both input methods
- Check that error messages are helpful when incorrect positional arguments are provided
4. Documentation verification:
- Ensure README and help text accurately reflect the new dual syntax support
- Verify examples in documentation show both styles where appropriate
All tests should pass with 100% of commands supporting both argument styles without any regression in existing functionality.
# Subtasks:
## 1. Analyze current CLI argument parsing structure [pending]
### Dependencies: None
### Description: Review the existing CLI argument parsing code to understand how arguments are currently processed and identify integration points for positional arguments.
### 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.
## 2. Design positional argument specification format [pending]
### Dependencies: 55.1
### Description: Create a specification for how positional arguments will be defined in command definitions, including their order, required/optional status, and type validation.
### 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.
## 3. Implement core positional argument parsing logic [pending]
### Dependencies: 55.1, 55.2
### Description: Modify the argument parser to recognize and process positional arguments according to the specification, while maintaining compatibility with existing named arguments.
### 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.
## 4. Handle edge cases and error conditions [pending]
### Dependencies: 55.3
### Description: Implement robust handling for edge cases such as too many/few arguments, type mismatches, and ambiguous situations between positional and named arguments.
### 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.
## 5. Update documentation and create usage examples [pending]
### Dependencies: 55.2, 55.3, 55.4
### Description: Update CLI documentation to explain positional argument support and provide clear examples showing how to use positional arguments with different commands.
### 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.

View File

@@ -1,32 +0,0 @@
# Task ID: 56
# Title: Refactor Task-Master Files into Node Module Structure
# Status: done
# Dependencies: None
# Priority: medium
# Description: Restructure the task-master files by moving them from the project root into a proper node module structure to improve organization and maintainability.
# 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:
1. Create a dedicated directory structure within node_modules or as a local package
2. Update all import/require paths throughout the codebase to reference the new module location
3. Reorganize the files into a logical structure (lib/, utils/, commands/, etc.)
4. Ensure the module has a proper package.json with dependencies and exports
5. Update any build processes, scripts, or configuration files to reflect the new structure
6. Maintain backward compatibility where possible to minimize disruption
7. Document the new structure and any changes to usage patterns
This 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.
# Test Strategy:
Testing for this refactoring should be comprehensive to ensure nothing breaks during the restructuring:
1. Create a complete inventory of existing functionality through automated tests before starting
2. Implement unit tests for each module to verify they function correctly in the new structure
3. Create integration tests that verify the interactions between modules work as expected
4. Test all CLI commands to ensure they continue to function with the new module structure
5. Verify that all import/require statements resolve correctly
6. Test on different environments (development, staging) to ensure compatibility
7. Perform regression testing on all features that depend on task-master functionality
8. Create a rollback plan and test it to ensure we can revert changes if critical issues arise
9. Conduct performance testing to ensure the refactoring doesn't introduce overhead
10. Have multiple developers test the changes on their local environments before merging

View File

@@ -1,105 +0,0 @@
# Task ID: 57
# Title: Enhance Task-Master CLI User Experience and Interface
# Status: pending
# Dependencies: None
# Priority: medium
# 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.
# Details:
The current Task-Master CLI interface is functional but lacks polish and produces excessive log output. This task involves several key improvements:
1. Log Management:
- Implement log levels (ERROR, WARN, INFO, DEBUG, TRACE)
- Only show INFO and above by default
- Add a --verbose flag to show all logs
- Create a dedicated log file for detailed logs
2. Visual Enhancements:
- Add a clean, branded header when the tool starts
- Implement color-coding for different types of messages (success in green, errors in red, etc.)
- Use spinners or progress indicators for operations that take time
- Add clear visual separation between command input and output
3. Interactive Elements:
- Add loading animations for longer operations
- Implement interactive prompts for complex inputs instead of requiring all parameters upfront
- Add confirmation dialogs for destructive operations
4. Output Formatting:
- Format task listings in tables with consistent spacing
- Implement a compact mode and a detailed mode for viewing tasks
- Add visual indicators for task status (icons or colors)
5. Help and Documentation:
- Enhance help text with examples and clearer descriptions
- Add contextual hints for common next steps after commands
Use 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.
# Test Strategy:
Testing should verify both functionality and user experience improvements:
1. Automated Tests:
- Create unit tests for log level filtering functionality
- Test that all commands still function correctly with the new UI
- Verify that non-interactive mode works in CI environments
- Test that verbose and quiet modes function as expected
2. User Experience Testing:
- Create a test script that runs through common user flows
- Capture before/after screenshots for visual comparison
- Measure and compare the number of lines output for common operations
3. Usability Testing:
- Have 3-5 team members perform specific tasks using the new interface
- Collect feedback on clarity, ease of use, and visual appeal
- Identify any confusion points or areas for improvement
4. Edge Case Testing:
- Test in terminals with different color schemes and sizes
- Verify functionality in environments without color support
- Test with very large task lists to ensure formatting remains clean
Acceptance Criteria:
- Log output is reduced by at least 50% in normal operation
- All commands provide clear visual feedback about their progress and completion
- Help text is comprehensive and includes examples
- Interface is visually consistent across all commands
- Tool remains fully functional in non-interactive environments
# Subtasks:
## 1. Implement Configurable Log Levels [pending]
### Dependencies: None
### Description: Create a logging system with different verbosity levels that users can configure
### 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.
## 2. Design Terminal Color Scheme and Visual Elements [pending]
### Dependencies: None
### Description: Create a consistent and accessible color scheme for the CLI interface
### 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.
## 3. Implement Progress Indicators and Loading Animations [pending]
### Dependencies: 57.2
### Description: Add visual feedback for long-running operations
### 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.
## 4. Develop Interactive Selection Menus [pending]
### Dependencies: 57.2
### Description: Create interactive menus for task selection and configuration
### 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.
## 5. Design Tabular and Structured Output Formats [pending]
### Dependencies: 57.2
### Description: Improve the formatting of task lists and detailed information
### 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.
## 6. Create Help System and Interactive Documentation [pending]
### Dependencies: 57.2, 57.4, 57.5
### Description: Develop an in-CLI help system with examples and contextual assistance
### 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.

View File

@@ -1,63 +0,0 @@
# Task ID: 58
# Title: Implement Elegant Package Update Mechanism for Task-Master
# Status: done
# Dependencies: None
# Priority: medium
# Description: Create a robust update mechanism that handles package updates gracefully, ensuring all necessary files are updated when the global package is upgraded.
# Details:
Develop a comprehensive update system with these components:
1. **Update Detection**: When task-master runs, check if the current version matches the installed version. If not, notify the user an update is available.
2. **Update Command**: Implement a dedicated `task-master update` command that:
- Updates the global package (`npm -g task-master-ai@latest`)
- Automatically runs necessary initialization steps
- Preserves user configurations while updating system files
3. **Smart File Management**:
- Create a manifest of core files with checksums
- During updates, compare existing files with the manifest
- Only overwrite files that have changed in the update
- Preserve user-modified files with an option to merge changes
4. **Configuration Versioning**:
- Add version tracking to configuration files
- Implement migration paths for configuration changes between versions
- Provide backward compatibility for older configurations
5. **Update Notifications**:
- Add a non-intrusive notification when updates are available
- Include a changelog summary of what's new
This system should work seamlessly with the existing `task-master init` command but provide a more automated and user-friendly update experience.
# Test Strategy:
Test the update mechanism with these specific scenarios:
1. **Version Detection Test**:
- Install an older version, then verify the system correctly detects when a newer version is available
- Test with minor and major version changes
2. **Update Command Test**:
- Verify `task-master update` successfully updates the global package
- Confirm all necessary files are updated correctly
- Test with and without user-modified files present
3. **File Preservation Test**:
- Modify configuration files, then update
- Verify user changes are preserved while system files are updated
- Test with conflicts between user changes and system updates
4. **Rollback Test**:
- Implement and test a rollback mechanism if updates fail
- Verify system returns to previous working state
5. **Integration Test**:
- Create a test project with the current version
- Run through the update process
- Verify all functionality continues to work after update
6. **Edge Case Tests**:
- Test updating with insufficient permissions
- Test updating with network interruptions
- Test updating from very old versions to latest

View File

@@ -1,68 +0,0 @@
# Task ID: 59
# Title: Remove Manual Package.json Modifications and Implement Automatic Dependency Management
# Status: done
# Dependencies: None
# Priority: medium
# 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.
# Details:
Currently, the application is attempting to manually modify users' package.json files, which is not the recommended approach for npm packages. Instead:
1. Review all code that directly manipulates package.json files in users' projects
2. Remove these manual modifications
3. Properly define all dependencies in the package.json of task-master-ai itself
4. Ensure all peer dependencies are correctly specified
5. For any scripts that need to be available to users, use proper npm bin linking or npx commands
6. Update the installation process to leverage npm's built-in dependency management
7. If configuration is needed in users' projects, implement a proper initialization command that creates config files rather than modifying package.json
8. Document the new approach in the README and any other relevant documentation
This change will make the package more reliable, follow npm best practices, and prevent potential conflicts or errors when modifying users' project files.
# Test Strategy:
1. Create a fresh test project directory
2. Install the updated task-master-ai package using npm install task-master-ai
3. Verify that no code attempts to modify the test project's package.json
4. Confirm all dependencies are properly installed in node_modules
5. Test all commands to ensure they work without the previous manual package.json modifications
6. Try installing in projects with various existing configurations to ensure no conflicts occur
7. Test the uninstall process to verify it cleanly removes the package without leaving unwanted modifications
8. Verify the package works in different npm environments (npm 6, 7, 8) and with different Node.js versions
9. Create an integration test that simulates a real user workflow from installation through usage
# Subtasks:
## 1. Conduct Code Audit for Dependency Management [done]
### Dependencies: None
### Description: Review the current codebase to identify all areas where dependencies are manually managed, modified, or referenced outside of npm best practices.
### Details:
Focus on scripts, configuration files, and any custom logic related to dependency installation or versioning.
## 2. Remove Manual Dependency Modifications [done]
### Dependencies: 59.1
### Description: Eliminate any custom scripts or manual steps that alter dependencies outside of npm's standard workflow.
### Details:
Refactor or delete code that manually installs, updates, or modifies dependencies, ensuring all dependency management is handled via npm.
## 3. Update npm Dependencies [done]
### Dependencies: 59.2
### Description: Update all project dependencies using npm, ensuring versions are current and compatible, and resolve any conflicts.
### Details:
Run npm update, audit for vulnerabilities, and adjust package.json and package-lock.json as needed.
## 4. Update Initialization and Installation Commands [done]
### Dependencies: 59.3
### Description: Revise project setup scripts and documentation to reflect the new npm-based dependency management approach.
### Details:
Ensure that all initialization commands (e.g., npm install) are up-to-date and remove references to deprecated manual steps.
## 5. Update Documentation [done]
### Dependencies: 59.4
### Description: Revise project documentation to describe the new dependency management process and provide clear setup instructions.
### Details:
Update README, onboarding guides, and any developer documentation to align with npm best practices.
## 6. Perform Regression Testing [done]
### Dependencies: 59.5
### Description: Run comprehensive tests to ensure that the refactor has not introduced any regressions or broken existing functionality.
### Details:
Execute automated and manual tests, focusing on areas affected by dependency management changes.

View File

@@ -1,117 +0,0 @@
# Task ID: 60
# Title: Implement Mentor System with Round-Table Discussion Feature
# Status: pending
# Dependencies: None
# Priority: medium
# 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:
1. **Mentor Management**:
- Create a `mentors.json` file to store mentor data including name, personality, expertise, and other relevant attributes
- Implement `add-mentor` command that accepts a name and prompt describing the mentor's characteristics
- Implement `remove-mentor` command to delete mentors from the system
- Implement `list-mentors` command to display all configured mentors and their details
- Set a recommended maximum of 5 mentors with appropriate warnings
2. **Round-Table Discussion**:
- Create a `round-table` command with the following parameters:
- `--prompt`: Optional text prompt to guide the discussion
- `--id`: Optional task/subtask ID(s) to provide context (support comma-separated values)
- `--turns`: Number of discussion rounds (each mentor speaks once per turn)
- `--output`: Optional flag to export results to a file
- Implement an interactive CLI experience using inquirer for the round-table
- Generate a simulated discussion where each mentor speaks in turn based on their personality
- After all turns complete, generate insights, recommendations, and a summary
- Display results in the CLI
- When `--output` is specified, create a `round-table.txt` file containing:
- Initial prompt
- Target task ID(s)
- Full round-table discussion transcript
- Recommendations and insights section
3. **Integration with Task System**:
- Enhance `update`, `update-task`, and `update-subtask` commands to accept a round-table.txt file
- Use the round-table output as input for updating tasks or subtasks
- Allow appending round-table insights to subtasks
4. **LLM Integration**:
- Configure the system to effectively simulate different personalities using LLM
- Ensure mentors maintain consistent personalities across different round-tables
- Implement proper context handling to ensure relevant task information is included
Ensure all commands have proper help text and error handling for cases like no mentors configured, invalid task IDs, etc.
# Test Strategy:
1. **Unit Tests**:
- Test mentor data structure creation and validation
- Test mentor addition with various input formats
- Test mentor removal functionality
- Test listing of mentors with different configurations
- Test round-table parameter parsing and validation
2. **Integration Tests**:
- Test the complete flow of adding mentors and running a round-table
- Test round-table with different numbers of turns
- Test round-table with task context vs. custom prompt
- Test output file generation and format
- Test using round-table output to update tasks and subtasks
3. **Edge Cases**:
- Test behavior when no mentors are configured but round-table is called
- Test with invalid task IDs in the --id parameter
- Test with extremely long discussions (many turns)
- Test with mentors that have similar personalities
- Test removing a mentor that doesn't exist
- Test adding more than the recommended 5 mentors
4. **Manual Testing Scenarios**:
- Create mentors with distinct personalities (e.g., Vitalik Buterin, Steve Jobs, etc.)
- Run a round-table on a complex task and verify the insights are helpful
- Verify the personality simulation is consistent and believable
- Test the round-table output file readability and usefulness
- Verify that using round-table output to update tasks produces meaningful improvements
# Subtasks:
## 1. Design Mentor System Architecture [pending]
### Dependencies: None
### Description: Create a comprehensive architecture for the mentor system, defining data models, relationships, and interaction patterns.
### 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.
## 2. Implement Mentor Profile Management [pending]
### Dependencies: 60.1
### Description: Develop the functionality for creating, editing, and managing mentor profiles in the system.
### 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.
## 3. Develop Round-Table Discussion Framework [pending]
### Dependencies: 60.1
### Description: Create the core framework for hosting and managing round-table discussions between mentors and users.
### 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.
## 4. Implement LLM Integration for AI Mentors [pending]
### Dependencies: 60.3
### Description: Integrate LLM capabilities to simulate AI mentors that can participate in round-table discussions.
### 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.
## 5. Build Discussion Output Formatter [pending]
### Dependencies: 60.3, 60.4
### Description: Create a system to format and present round-table discussion outputs in a structured, readable format.
### 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.
## 6. Integrate Mentor System with Task Management [pending]
### Dependencies: 60.2, 60.3
### Description: Connect the mentor system with the existing task management functionality to enable task-specific mentoring.
### 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.
## 7. Test and Optimize Round-Table Discussions [pending]
### Dependencies: 60.4, 60.5, 60.6
### Description: Conduct comprehensive testing of the round-table discussion feature and optimize for performance and user experience.
### 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.

File diff suppressed because it is too large Load Diff

View File

@@ -1,90 +0,0 @@
# Task ID: 62
# Title: Add --simple Flag to Update Commands for Direct Text Input
# Status: pending
# Dependencies: None
# Priority: medium
# 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:
1. Update the command parsers for both update-task and update-subtask to recognize the --simple flag
2. Modify the update logic to check for this flag and conditionally skip AI processing
3. When the flag is present, format the user's input text with a timestamp in the same format as AI-processed updates
4. Ensure the update is properly saved to the task or subtask's history
5. Update the help documentation to include information about this new flag
6. The timestamp format should match the existing format used for AI-generated updates
7. The simple update should be visually distinguishable from AI updates in the display (consider adding a 'manual update' indicator)
8. Maintain all existing functionality when the flag is not used
# Test Strategy:
Testing should verify both the functionality and user experience of the new feature:
1. Unit tests:
- Test that the command parser correctly recognizes the --simple flag
- Verify that AI processing is bypassed when the flag is present
- Ensure timestamps are correctly formatted and added
2. Integration tests:
- Update a task with --simple flag and verify the exact text is saved
- Update a subtask with --simple flag and verify the exact text is saved
- Compare the output format with AI-processed updates to ensure consistency
3. User experience tests:
- Verify help documentation correctly explains the new flag
- Test with various input lengths to ensure proper formatting
- Ensure the update appears correctly when viewing task history
4. Edge cases:
- Test with empty input text
- Test with very long input text
- Test with special characters and formatting in the input
# Subtasks:
## 1. Update command parsers to recognize --simple flag [pending]
### Dependencies: None
### Description: Modify the command parsers for both update-task and update-subtask commands to recognize and process the new --simple flag option.
### 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.
## 2. Implement conditional logic to bypass AI processing [pending]
### Dependencies: 62.1
### Description: Modify the update logic to check for the --simple flag and conditionally skip the AI processing pipeline when the flag is present.
### 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.
## 3. Format user input with timestamp for simple updates [pending]
### Dependencies: 62.2
### 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.
### 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.
## 4. Add visual indicator for manual updates [pending]
### Dependencies: 62.3
### Description: Make simple updates visually distinguishable from AI-processed updates by adding a 'manual update' indicator or other visual differentiation.
### 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.
## 5. Implement storage of simple updates in history [pending]
### Dependencies: 62.3, 62.4
### 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.
### 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.
## 6. Update help documentation for the new flag [pending]
### Dependencies: 62.1
### Description: Update the help documentation for both update-task and update-subtask commands to include information about the new --simple flag.
### 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.
## 7. Implement integration tests for the simple update feature [pending]
### Dependencies: 62.1, 62.2, 62.3, 62.4, 62.5
### 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.
### 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.
## 8. Perform final validation and documentation [pending]
### Dependencies: 62.1, 62.2, 62.3, 62.4, 62.5, 62.6, 62.7
### Description: Conduct final validation of the feature across all use cases and update the user documentation to include the new functionality.
### 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.

View File

@@ -1,138 +0,0 @@
# Task ID: 63
# Title: Add pnpm Support for the Taskmaster Package
# Status: done
# Dependencies: None
# Priority: medium
# 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.
# Details:
This task involves:
1. Update the installation documentation to include pnpm installation commands (e.g., `pnpm add taskmaster`).
2. Ensure all package scripts are compatible with pnpm's execution model:
- Review and modify package.json scripts if necessary
- Test script execution with pnpm syntax (`pnpm run <script>`)
- Address any pnpm-specific path or execution differences
- Confirm that scripts responsible for showing a website or prompt during install behave identically with pnpm and npm
3. Create a pnpm-lock.yaml file by installing dependencies with pnpm.
4. Test the application's installation and operation when installed via pnpm:
- Global installation (`pnpm add -g taskmaster`)
- Local project installation
- Verify CLI commands work correctly when installed with pnpm
- Verify binaries `task-master` and `task-master-mcp` are properly linked
- Ensure the `init` command (scripts/init.js) correctly creates directory structure and copies templates as described
5. Update CI/CD pipelines to include testing with pnpm:
- Add a pnpm test matrix to GitHub Actions workflows
- Ensure tests pass when dependencies are installed with pnpm
6. Handle any pnpm-specific dependency resolution issues:
- Address potential hoisting differences between npm and pnpm
- Test with pnpm's strict mode to ensure compatibility
- Verify proper handling of 'module' package type
7. Document any pnpm-specific considerations or commands in the README and documentation.
8. Verify that the `scripts/init.js` file works correctly with pnpm:
- Ensure it properly creates `.cursor/rules`, `scripts`, and `tasks` directories
- Verify template copying (`.env.example`, `.gitignore`, rule files, `dev.js`)
- Confirm `package.json` merging works correctly
- Test MCP config setup (`.cursor/mcp.json`)
9. Ensure core logic in `scripts/modules/` works correctly when installed via pnpm.
This implementation should maintain full feature parity and identical user experience regardless of which package manager is used to install Taskmaster.
# Test Strategy:
1. Manual Testing:
- Install Taskmaster globally using pnpm: `pnpm add -g taskmaster`
- Install Taskmaster locally in a test project: `pnpm add taskmaster`
- Verify all CLI commands function correctly with both installation methods
- Test all major features to ensure they work identically to npm installations
- Verify binaries `task-master` and `task-master-mcp` are properly linked and executable
- Test the `init` command to ensure it correctly sets up the directory structure and files as defined in scripts/init.js
2. Automated Testing:
- Create a dedicated test workflow in GitHub Actions that uses pnpm
- Run the full test suite using pnpm to install dependencies
- Verify all tests pass with the same results as npm
3. Documentation Testing:
- Review all documentation to ensure pnpm commands are correctly documented
- Verify installation instructions work as written
- Test any pnpm-specific instructions or notes
4. Compatibility Testing:
- Test on different operating systems (Windows, macOS, Linux)
- Verify compatibility with different pnpm versions (latest stable and LTS)
- Test in environments with multiple package managers installed
- Verify proper handling of 'module' package type
5. Edge Case Testing:
- Test installation in a project that uses pnpm workspaces
- Verify behavior when upgrading from an npm installation to pnpm
- Test with pnpm's various flags and modes (--frozen-lockfile, --strict-peer-dependencies)
6. Performance Comparison:
- Measure and document any performance differences between package managers
- Compare installation times and disk space usage
7. Structure Testing:
- Verify that the core logic in `scripts/modules/` is accessible and functions correctly
- Confirm that the `init` command properly creates all required directories and files as per scripts/init.js
- Test package.json merging functionality
- Verify MCP config setup
Success 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:
## 1. Update Documentation for pnpm Support [done]
### Dependencies: None
### 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.
### 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.
## 2. Ensure Package Scripts Compatibility with pnpm [done]
### Dependencies: 63.1
### 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.
### 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.
## 3. Generate and Validate pnpm Lockfile [done]
### Dependencies: 63.2
### 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.
### 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.
## 4. Test Taskmaster Installation and Operation with pnpm [done]
### Dependencies: 63.3
### 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.
### 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.
## 5. Integrate pnpm into CI/CD Pipeline [done]
### Dependencies: 63.4
### 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.
### 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.
## 6. Verify Installation UI/Website Consistency [done]
### Dependencies: 63.4
### 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.
### 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.
## 7. Test init.js Script with pnpm [done]
### Dependencies: 63.4
### 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.
### 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.
## 8. Verify Binary Links with pnpm [done]
### Dependencies: 63.4
### 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.
### 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.

View File

@@ -1,202 +0,0 @@
# Task ID: 64
# Title: Add Yarn Support for Taskmaster Installation
# Status: done
# Dependencies: None
# Priority: medium
# 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.
If 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.
# 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:
1. Update package.json to ensure compatibility with Yarn installation methods, considering the 'module' package type and binary definitions
2. Verify all scripts and dependencies work correctly with Yarn
3. Add Yarn-specific configuration files (e.g., .yarnrc.yml if needed)
4. Update installation documentation to include Yarn installation instructions
5. Ensure all post-install scripts work correctly with Yarn
6. Verify that all CLI commands function properly when installed via Yarn
7. Ensure binaries `task-master` and `task-master-mcp` are properly linked
8. Test the `scripts/init.js` file with Yarn to verify it correctly:
- Creates directory structure (`.cursor/rules`, `scripts`, `tasks`)
- Copies templates (`.env.example`, `.gitignore`, rule files, `dev.js`)
- Manages `package.json` merging
- Sets up MCP config (`.cursor/mcp.json`)
9. Handle any Yarn-specific package resolution or hoisting issues
10. Test compatibility with different Yarn versions (classic and berry/v2+)
11. Ensure proper lockfile generation and management
12. Update any package manager detection logic in the codebase to recognize Yarn installations
13. Verify that core logic in `scripts/modules/` works correctly when installed via Yarn
14. 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.
The implementation should maintain feature parity and identical user experience regardless of which package manager (npm, pnpm, or Yarn) is used to install Taskmaster.
# Test Strategy:
Testing should verify complete Yarn support through the following steps:
1. Fresh installation tests:
- Install Taskmaster using `yarn add taskmaster` (global and local installations)
- Verify installation completes without errors
- Check that binaries `task-master` and `task-master-mcp` are properly linked
- Test the `init` command to ensure it correctly sets up the directory structure and files as defined in scripts/init.js
2. Functionality tests:
- Run all Taskmaster commands on a Yarn-installed version
- Verify all features work identically to npm installations
- Test with both Yarn v1 (classic) and Yarn v2+ (berry)
- Verify proper handling of 'module' package type
3. Update/uninstall tests:
- Test updating the package using Yarn commands
- Verify clean uninstallation using Yarn
4. CI integration:
- Add Yarn installation tests to CI pipeline
- Test on different operating systems (Windows, macOS, Linux)
5. Documentation verification:
- Ensure all documentation accurately reflects Yarn installation methods
- Verify any Yarn-specific commands or configurations are properly documented
6. Edge cases:
- Test installation in monorepo setups using Yarn workspaces
- Verify compatibility with other Yarn-specific features (plug'n'play, zero-installs)
7. Structure Testing:
- Verify that the core logic in `scripts/modules/` is accessible and functions correctly
- Confirm that the `init` command properly creates all required directories and files as per scripts/init.js
- Test package.json merging functionality
- Verify MCP config setup
8. Website/Account Setup Testing:
- 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.
- Document any website-specific steps that users need to complete during installation.
All tests should pass with the same results as when using npm, with identical user experience throughout the installation and usage process.
# Subtasks:
## 1. Update package.json for Yarn Compatibility [done]
### Dependencies: None
### 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.
### 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.
## 2. Add Yarn-Specific Configuration Files [done]
### Dependencies: 64.1
### 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.
### 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.
## 3. Test and Fix Yarn Compatibility for Scripts and CLI [done]
### Dependencies: 64.2
### 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.
### 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.
## 4. Update Documentation for Yarn Installation and Usage [done]
### Dependencies: 64.3
### 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.
### 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.
## 5. Implement and Test Package Manager Detection Logic [done]
### Dependencies: 64.4
### 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.
### 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.
## 6. Verify Installation UI/Website Consistency [done]
### Dependencies: 64.3
### 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.
### 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.
## 7. Test init.js Script with Yarn [done]
### Dependencies: 64.3
### 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.
### 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.
## 8. Verify Binary Links with Yarn [done]
### Dependencies: 64.3
### 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.
### 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.
## 9. Test Website Account Setup with Yarn [done]
### Dependencies: 64.6
### 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.
### 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.
<info added on 2025-04-25T08:45:48.709Z>
Since the request is vague, I'll provide helpful implementation details for testing website account setup with Yarn:
For 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.
</info added on 2025-04-25T08:45:48.709Z>
<info added on 2025-04-25T08:46:08.651Z>
- 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.
- 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].
- 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.
- 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.
- 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].
- For documentation, provide annotated screenshots or screen recordings of the account setup process, highlighting any Yarn-specific prompts, warnings, or differences encountered.
- 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.
</info added on 2025-04-25T08:46:08.651Z>
<info added on 2025-04-25T17:04:12.550Z>
For 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.
To be specific:
- You don't need to create a Yarn account
- Yarn is simply the tool used to install Taskmaster (`yarn add taskmaster` instead of `npm install taskmaster`)
- 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
- If Taskmaster includes a web dashboard or requires users to create accounts within the Taskmaster system, those features should be tested
If 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.
</info added on 2025-04-25T17:04:12.550Z>
<info added on 2025-04-25T17:19:03.256Z>
When testing website account setup with Yarn after the codebase refactor, pay special attention to:
- Verify that any environment-specific configuration files (like `.env` or config JSON files) are properly loaded when the application is installed via Yarn
- Test the session management implementation to ensure user sessions persist correctly across page refreshes and browser restarts
- Check that any database migrations or schema updates required for account setup execute properly when installed via Yarn
- Validate that client-side form validation logic works consistently with server-side validation
- Ensure that any WebSocket connections for real-time features initialize correctly after the refactor
- Test account deletion and data export functionality to verify GDPR compliance remains intact
- Document any changes to the authentication flow that resulted from the refactor and confirm they work identically with Yarn installation
</info added on 2025-04-25T17:19:03.256Z>
<info added on 2025-04-25T17:22:05.951Z>
When testing website account setup with Yarn after the logging fix, implement these additional verification steps:
1. Verify that all account-related actions are properly logged with the correct log levels (debug, info, warn, error) according to the updated logging framework
2. Test the error handling paths specifically - force authentication failures and verify the logs contain sufficient diagnostic information
3. Check that sensitive user information is properly redacted in logs according to privacy requirements
4. Confirm that log rotation and persistence work correctly when high volumes of authentication attempts occur
5. Validate that any custom logging middleware correctly captures HTTP request/response data for account operations
6. Test that log aggregation tools (if used) can properly parse and display the account setup logs in their expected format
7. Verify that performance metrics for account setup flows are correctly captured in logs for monitoring purposes
8. Document any Yarn-specific environment variables that affect the logging configuration for the website component
</info added on 2025-04-25T17:22:05.951Z>
<info added on 2025-04-25T17:22:46.293Z>
When testing website account setup with Yarn, consider implementing a positive user experience validation:
1. Measure and document time-to-completion for the account setup process to ensure it meets usability standards
2. Create a satisfaction survey for test users to rate the account setup experience on a 1-5 scale
3. Implement A/B testing for different account setup flows to identify the most user-friendly approach
4. Add delightful micro-interactions or success animations that make the setup process feel rewarding
5. Test the "welcome" or "onboarding" experience that follows successful account creation
6. Ensure helpful tooltips and contextual help are displayed at appropriate moments during setup
7. Verify that error messages are friendly, clear, and provide actionable guidance rather than technical jargon
8. Test the account recovery flow to ensure users have a smooth experience if they forget credentials
</info added on 2025-04-25T17:22:46.293Z>

View File

@@ -1,49 +0,0 @@
# Task ID: 65
# Title: Add Bun Support for Taskmaster Installation
# Status: done
# Dependencies: None
# Priority: medium
# 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.
# Test Strategy:
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.
# Subtasks:
## 1. Research Bun compatibility requirements [done]
### Dependencies: None
### Description: Investigate Bun's JavaScript runtime environment and identify key differences from Node.js that may affect Taskmaster's installation and operation.
### 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.
## 2. Update installation scripts for Bun compatibility [done]
### Dependencies: 65.1
### Description: Modify the existing installation scripts to detect and support Bun as a runtime environment.
### 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.
## 3. Create Bun-specific installation path [done]
### Dependencies: 65.2
### Description: Implement a dedicated installation flow for Bun users that optimizes for Bun's capabilities.
### 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.
## 4. Test Taskmaster installation with Bun [done]
### Dependencies: 65.3
### Description: Perform comprehensive testing of the installation process using Bun across different operating systems.
### 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.
## 5. Test Taskmaster operation with Bun [done]
### Dependencies: 65.4
### Description: Ensure all Taskmaster functionality works correctly when running under Bun.
### 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.
## 6. Update documentation for Bun support [done]
### Dependencies: 65.4, 65.5
### Description: Update all relevant documentation to include information about installing and running Taskmaster with Bun.
### 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.

View File

@@ -1,61 +0,0 @@
# Task ID: 66
# Title: Support Status Filtering in Show Command for Subtasks
# Status: done
# Dependencies: None
# Priority: medium
# 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:
1. 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').
2. Modify the show command handler in the appropriate module (likely in scripts/modules/) to:
- Parse and validate the status parameter
- Filter the subtasks collection based on the provided status before displaying results
- Handle invalid status values gracefully with appropriate error messages
- Support standard status values (e.g., 'not-started', 'in-progress', 'completed', 'blocked')
- Consider supporting multiple status values (comma-separated or multiple flags)
3. Update the help documentation to include information about the new status filtering option.
4. Ensure backward compatibility - the show command should function as before when no status parameter is provided.
5. Consider adding a '--status-list' option to display all available status values for reference.
6. Update any relevant unit tests to cover the new functionality.
7. If the application uses a database or persistent storage, ensure the filtering happens at the query level for performance when possible.
8. Maintain consistent formatting and styling of output regardless of filtering.
# Test Strategy:
Testing for this feature should include:
1. Unit tests:
- Test parsing of the status parameter in various formats (--status=value, -s value)
- Test filtering logic with different status values
- Test error handling for invalid status values
- Test backward compatibility (no status parameter)
- Test edge cases (empty status, case sensitivity, etc.)
2. Integration tests:
- Verify that the command correctly filters subtasks when a valid status is provided
- Verify that all subtasks are shown when no status filter is applied
- Test with a project containing subtasks of various statuses
3. Manual testing:
- Create a test project with multiple subtasks having different statuses
- Run the show command with different status filters and verify results
- Test with both long-form (--status) and short-form (-s) parameters
- Verify help documentation correctly explains the new parameter
4. Edge case testing:
- Test with non-existent status values
- Test with empty project (no subtasks)
- Test with a project where all subtasks have the same status
5. Documentation verification:
- Ensure the README or help documentation is updated to include the new parameter
- Verify examples in documentation work as expected
All tests should pass before considering this task complete.

View File

@@ -1,106 +0,0 @@
# Task ID: 67
# Title: Add CLI JSON output and Cursor keybindings integration
# Status: pending
# Dependencies: None
# Priority: high
# Description: Enhance Taskmaster CLI with JSON output option and add a new command to install pre-configured Cursor keybindings
# 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
# Test Strategy:
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:
## 1. Implement Core JSON Output Logic for `next` and `show` Commands [pending]
### Dependencies: None
### 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.
### Details:
1. Update the CLI argument parser to add the `--json` boolean flag to both commands
2. Create a `formatAsJson` utility function in `src/utils/output.js` that takes a data object and returns a properly formatted JSON string
3. In the command handler functions (`src/commands/next.js` and `src/commands/show.js`), add a conditional check for the `--json` flag
4. If the flag is set, call the `formatAsJson` function with the raw data object and print the result
5. If the flag is not set, continue with the existing human-readable formatting logic
6. Ensure proper error handling for JSON serialization failures
7. Update the command help text in both files to document the new flag
## 2. Extend JSON Output to All Relevant Commands and Ensure Schema Consistency [pending]
### Dependencies: 67.1
### 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.
### Details:
1. Create a JSON schema definition file at `src/schemas/task.json` to define the standard structure for task objects
2. Modify the following command files to support the `--json` flag:
- `src/commands/list.js`
- `src/commands/status.js`
- `src/commands/search.js`
- `src/commands/summary.js`
3. Refactor the `formatAsJson` utility to handle different data types (single task, task array, status object, etc.)
4. Add a `validateJsonSchema` function in `src/utils/validation.js` to ensure output conforms to defined schemas
5. Update each command's help text documentation to include the `--json` flag description
6. Implement consistent error handling for JSON output (using a standard error object format)
7. For list-type commands, ensure array outputs are properly formatted as JSON arrays
## 3. Create `install-keybindings` Command Structure and OS Detection [pending]
### Dependencies: None
### 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.
### Details:
1. Create a new command file at `src/commands/install-keybindings.js`
2. Register the command in the main CLI entry point (`src/index.js`)
3. Implement OS detection using `os.platform()` in Node.js
4. Define the following path constants in `src/config/paths.js`:
- Windows: `%APPDATA%\Cursor\User\keybindings.json`
- macOS: `~/Library/Application Support/Cursor/User/keybindings.json`
- Linux: `~/.config/Cursor/User/keybindings.json`
5. Create a `getCursorKeybindingsPath()` function that returns the appropriate path based on detected OS
6. Add path override capability via a `--path` command line option
7. Implement proper error handling for unsupported operating systems
8. Add detailed help text explaining the command's purpose and options
## 4. Implement Keybinding File Handling and Backup Logic [pending]
### Dependencies: 67.3
### 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.
### Details:
1. Create a `KeybindingsManager` class in `src/utils/keybindings.js` with the following methods:
- `checkFileExists(path)`: Verify if the keybindings file exists
- `createBackup(path)`: Copy existing file to `keybindings.json.bak`
- `readKeybindings(path)`: Read and parse the JSON file
- `writeKeybindings(path, data)`: Serialize and write data to the file
- `createEmptyFile(path)`: Create a new file with `[]` content
2. In the command handler, use these methods to:
- Check if the target file exists
- Create a backup if it does (with timestamp in filename)
- Read existing keybindings or create an empty file
- Parse the JSON content with proper error handling
3. Add a `--no-backup` flag to skip backup creation
4. Implement verbose logging with a `--verbose` flag
5. Handle all potential file system errors (permissions, disk space, etc.)
6. Add a `--dry-run` option that shows what would be done without making changes
## 5. Add Taskmaster Keybindings, Prevent Duplicates, and Support Customization [pending]
### Dependencies: 67.4
### 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.
### Details:
1. Define default Taskmaster keybindings in `src/config/default-keybindings.js` as an array of objects with:
- `key`: Default key combination (e.g., `"ctrl+alt+n"`)
- `command`: Cursor command ID (e.g., `"taskmaster.nextTask"`)
- `when`: Context when keybinding is active (e.g., `"editorTextFocus"`)
- `args`: Any command arguments as an object
- `description`: Human-readable description of what the keybinding does
2. Implement the following keybindings:
- Next task to clipboard: `ctrl+alt+n`
- Update task status: `ctrl+alt+u`
- Open agent chat with task context: `ctrl+alt+a`
- Show task details: `ctrl+alt+d`
3. Add command-line options to customize each keybinding:
- `--next-key="ctrl+alt+n"`
- `--update-key="ctrl+alt+u"`
- `--agent-key="ctrl+alt+a"`
- `--details-key="ctrl+alt+d"`
4. Implement a `mergeKeybindings(existing, new)` function that:
- Checks for duplicates based on command ID
- Checks for key combination conflicts
- Warns about conflicts but allows override with `--force` flag
- Preserves existing non-Taskmaster keybindings
5. Add a `--reset` flag to remove all existing Taskmaster keybindings before adding new ones
6. Add a `--list` option to display currently installed Taskmaster keybindings
7. Implement an `--uninstall` option to remove all Taskmaster keybindings

View File

@@ -1,25 +0,0 @@
# Task ID: 68
# Title: Ability to create tasks without parsing PRD
# Status: done
# Dependencies: None
# Priority: medium
# 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:
# Test Strategy:
# Subtasks:
## 1. Design task creation form without PRD [done]
### Dependencies: None
### Description: Create a user interface form that allows users to manually input task details without requiring a PRD document
### 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.
## 2. Implement task saving functionality [done]
### Dependencies: 68.1
### Description: Develop the backend functionality to save manually created tasks to the database
### 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.

Some files were not shown because too many files have changed in this diff Show More