Compare commits

..

112 Commits

Author SHA1 Message Date
Eyal Toledano
16e6326010 fix(config): adds missing import + task management for api key design 2025-06-05 14:20:25 -04:00
Eyal Toledano
a9c1b6bbcf fix(config-manager): Add silent mode check and improve test mocking for ensureConfigFileExists 2025-06-05 13:33:20 -04:00
Eyal Toledano
f12fc476d3 fix(init): Ensure hosted mode option available by creating .taskmasterconfig early
- Added ensureConfigFileExists() to create default config if missing
- Call early in init flows before gateway check - Preserve email from initializeUser()
- Add comprehensive tests
2025-06-05 13:30:14 -04:00
Eyal Toledano
31178e2f43 chore: adjust .taskmasterconfig defaults 2025-06-04 19:04:17 -04:00
Eyal Toledano
3fa3be4e1b chore: fix user email, telemetryEnabled by default 2025-06-04 19:03:47 -04:00
Eyal Toledano
685365270d feat: integrate Supabase authenticated users
- Updated init.js, ai-services-unified.js, user-management.js, telemetry-submission.js, and .taskmasterconfig to support Supabase authentication flow and authenticated gateway calls
2025-06-04 18:53:28 -04:00
Eyal Toledano
58aa0992f6 feat(error-handling): Implement comprehensive gateway error handling with user-friendly messages
- Add comprehensive gateway error handler with friendly user messages
- Handle subscription status errors (inactive BYOK, subscription required)
- Handle authentication errors (invalid API keys, missing tokens)
- Handle rate limiting with retry suggestions
- Handle model availability and validation errors
- Handle network connectivity issues
- Provide actionable solutions for each error type
- Prevent duplicate error messages by returning early after showing friendly error
- Fix telemetry tests to use correct environment variable names (TASKMASTER_API_KEY)
- Fix config manager getUserId function to properly save default userId to file
- All tests now passing (34 test suites, 360 tests)
2025-06-02 12:34:47 -04:00
Eyal Toledano
2819be51d3 feat: Implement TaskMaster AI Gateway integration with enhanced UX
- Fix Zod schema conversion, update headers, add premium telemetry display, improve user auth flow, and standardize email fields

Functionally complete on this end, mostly polish around user experience and need to add in profile, upgrade/downgrade, etc.

But the AI commands are working off the gateway.
2025-06-01 19:37:12 -04:00
Eyal Toledano
9b87dd23de fix(gateway/auth): Implement proper auth/init flow with automatic background userId generation
- Fix getUserId() to use placeholder that triggers auth/init if the auth/init endpoint is down for whatever reason
- Add silent auth/init attempt in AI services
- Improve hosted mode error handling
- Remove fake userId/email generation from init.js
2025-05-31 19:47:18 -04:00
Eyal Toledano
769275b3bc fix(config): Fix config structure and tests after refactoring
- Fixed getUserId() to always return value, never null (sets default '1234567890')
- Updated all test files to match new config.account structure
- Fixed config-manager.test.js default config expectations
- Updated telemetry-submission.test.js and ai-services-unified.test.js mocks
- Added getTelemetryEnabled export to all config-manager mocks
- All 44 tests now passing
2025-05-30 19:40:38 -04:00
Eyal Toledano
4e9d58a1b0 feat(config): Restructure .taskmasterconfig and enhance gateway integration
Config Structure Changes and Gateway Integration

## Configuration Structure Changes
- Restructured .taskmasterconfig to use 'account' section for user settings
- Moved userId, userEmail, mode, telemetryEnabled from global to account section
- API keys remain isolated in .env file (not accessible to AI)
- Enhanced getUserId() to always return value, never null (sets default '1234567890')

## Gateway Integration Enhancements
- Updated registerUserWithGateway() to accept both email and userId parameters
- Enhanced /auth/init endpoint integration for existing user validation
- API key updates automatically written to .env during registration process
- Improved user identification and validation flow

## Code Updates for New Structure
- Fixed config-manager.js getter functions for account section access
- Updated user-management.js to use config.account.userId/mode
- Modified telemetry-submission.js to read from account section
- Added getTelemetryEnabled() function with proper account section access
- Enhanced telemetry configuration reading with new structure

## Comprehensive Test Updates
- Updated integration tests (init-config.test.js) for new config structure
- Fixed unit tests (config-manager.test.js) with updated default config
- Updated telemetry tests (telemetry-submission.test.js) for account structure
- Added missing getTelemetryEnabled mock to ai-services-unified.test.js
- Fixed all test expectations to use config.account.* instead of config.global.*
- Removed references to deprecated config.subscription object

## Configuration Access Consistency
- Standardized configuration access patterns across entire codebase
- Clean separation: user settings in account, API keys in .env, models/global in respective sections
- All tests passing with new configuration structure
- Maintained backward compatibility during transition

Changes support enhanced telemetry system with proper user management and gateway integration while maintaining security through API key isolation.
2025-05-30 18:53:16 -04:00
Eyal Toledano
e573db3b3b feat(task-90): Complete telemetry integration with init flow improvements - Task 90.3: AI Services Integration COMPLETED with automatic submission after AI usage logging and graceful error handling - Init Flow Enhancements: restructured to prioritize gateway selection with beautiful UI for BYOK vs Hosted modes - Telemetry Improvements: modified submission to send FULL data to gateway while maintaining security filtering for users - All 344 tests passing, telemetry integration ready for production 2025-05-30 16:35:40 -04:00
Eyal Toledano
75b7b93fa4 feat(task-90): Complete telemetry integration with /auth/init + fix Roo test brittleness
- Updated telemetry submission to use /auth/init endpoint instead of /api/v1/users
- Hardcoded gateway endpoint to http://localhost:4444/api/v1/telemetry for all users
- Removed unnecessary service API key complexity - simplified authentication
- Enhanced init.js with hosted gateway setup option and user registration
- Added configureTelemetrySettings() to update .taskmasterconfig with credentials
- Fixed brittle Roo integration tests that required exact string matching
- Updated tests to use flexible regex patterns supporting any quote style
- All test suites now green: 332 tests passed, 11 skipped, 0 failed
- All 11 telemetry tests passing with live gateway integration verified
- Ready for ai-services-unified.js integration in subtask 90.3
2025-05-28 22:38:18 -04:00
Eyal Toledano
6ec3a10083 feat(task-90): Complete subtask 90.2 with gateway integration and init.js enhancements
- Hardcoded gateway endpoint to http://localhost:4444/api/v1/telemetry
- Updated credential handling to use config-based approach (not env vars)
- Added registerUserWithGateway() function for user registration/lookup
- Enhanced init.js with hosted gateway setup option and configureTelemetrySettings()
- Updated all 10 tests to reflect new architecture - all passing
- Security features maintained: sensitive data filtering, Bearer token auth
- Ready for ai-services-unified.js integration in subtask 90.3
2025-05-28 21:05:25 -04:00
Eyal Toledano
8ad31ac5eb feat(task-90): Complete subtask 90.2 with secure telemetry submission service - Implemented telemetry submission with Zod validation, retry logic, graceful error handling, and user opt-out support - Used correct Bearer token authentication with X-User-Email header - Successfully tested with live gateway endpoint, all 6 tests passing - Verified security: sensitive data filtered before submission 2025-05-28 15:12:31 -04:00
Eyal Toledano
2773e347f9 feat(task-90): Complete subtask 90.2
- Implement secure telemetry submission service
- Created scripts/modules/telemetry-submission.js with submitTelemetryData function
- Implemented secure filtering: removes commandArgs and fullOutput before remote submission
- Added comprehensive validation using Zod schema for telemetry data integrity
- Implemented exponential backoff retry logic (3 attempts max) with smart retry decisions
- Added graceful error handling that never blocks execution
- Respects user opt-out preferences via config.telemetryEnabled
- Configured for localhost testing endpoint (http://localhost:4444/api/v1/telemetry) for now
- Added comprehensive test coverage with 6/6 passing tests covering all scenarios
- Includes submitTelemetryDataAsync for fire-and-forget submissions
2025-05-28 14:51:42 -04:00
Eyal Toledano
bfc39dd377 feat(task-90): Complete subtask 90.1
- Implement secure telemetry capture with filtering - Enhanced ai-services-unified.js to capture commandArgs and fullOutput in telemetry - Added filterSensitiveTelemetryData() function to prevent sensitive data exposure - Updated processMCPResponseData() to filter telemetry before sending to MCP clients - Verified CLI displayAiUsageSummary() only shows safe fields - Added comprehensive test coverage with 4 passing tests - Resolved critical security issue: API keys and sensitive data now filtered from responses
2025-05-28 14:26:24 -04:00
Eyal Toledano
9e6c190af3 fix(move-task): Fix duplicate task creation when moving subtask to standalone task 2025-05-28 14:05:30 -04:00
Eyal Toledano
ab64437ad2 chore: task management 2025-05-28 11:16:54 -04:00
Eyal Toledano
cb95a07771 chore: task management 2025-05-28 11:16:09 -04:00
Eyal Toledano
c096f3fe9d Merge branch 'v017-adds' into gateway 2025-05-28 11:13:26 -04:00
Eyal Toledano
b6a3b8d385 chore: task management - moves 87,88,89 to 90,91,92 2025-05-28 10:38:33 -04:00
Eyal Toledano
78397fe0be chore: formatting 2025-05-28 10:25:39 -04:00
Eyal Toledano
f9b89dc25c 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
2025-05-28 10:25:15 -04:00
Eyal Toledano
ca69e1294f Merge branch 'next' of github.com:eyaltoledano/claude-task-master into v017-adds 2025-05-28 10:08:14 -04:00
Eyal Toledano
ce09d9cdc3 chore: task mgmt 2025-05-28 09:56:08 -04:00
Ralph Khreish
669b744ced Feat/add nvmrc (#612)
* feat: Add .nvmrc and align engines to Node 20

* chore: set nvm to 22, engines to 18

* chore: format

* chore: add changeset

---------

Co-authored-by: Amir Golan <amirgolan@Amirs-MacBook-Pro.local>
2025-05-28 15:02:15 +02:00
Nathan Marley
f058543888 Replace prettier with biome (#531) 2025-05-28 14:47:16 +02:00
Eyal Toledano
b5c2cf47b0 chore: task management 2025-05-28 00:29:43 -04:00
Ralph Khreish
acd5c1ea3d chore: add contributing.md (#611) 2025-05-28 00:59:14 +02:00
github-actions[bot]
682b54e103 docs: Auto-update and format models.md 2025-05-27 22:42:42 +00:00
Ralph Khreish
6a8a68e1a3 Feat/add.azure.and.other.providers (#607)
* fix: claude-4 not having the right max_tokens

* feat: add bedrock support

* chore: fix package-lock.json

* fix: rename baseUrl to baseURL

* feat: add azure support

* fix: final touches of azure integration

* feat: add google vertex provider

* chore: fix tests and refactor task-manager.test.js

* chore: move task 92 to 94
2025-05-28 00:42:31 +02:00
Ralph Khreish
80735f9e60 feat(config): Implement TASK_MASTER_PROJECT_ROOT support for project root resolution (#604)
* feat(config): Implement TASK_MASTER_PROJECT_ROOT support for project root resolution

- Added support for the TASK_MASTER_PROJECT_ROOT environment variable in MCP configuration, establishing a clear precedence order for project root resolution.
- Updated utility functions to prioritize the environment variable, followed by args.projectRoot and session-based resolution.
- Enhanced error handling and logging for project root determination.
- Introduced new tasks for comprehensive testing and documentation updates related to the new configuration options.

* chore: fix CI issues
2025-05-28 00:32:34 +02:00
Eyal Toledano
ac36e2497e chore: task management and removes mistakenly staged changes 2025-05-27 12:43:59 -04:00
Eyal Toledano
1d4b80fe6f chore: task management 2025-05-27 12:41:08 -04:00
github-actions[bot]
48732d5423 docs: Auto-update and format models.md 2025-05-25 22:13:23 -04:00
Eyal Toledano
2d520de269 fix(add-task): removes stdout in add-task which will crash MCP server (#593)
* fix(add-task): fixes an isse in which stdout leaks out of add-task causing the mcp server to crash if used.

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-05-25 22:13:23 -04:00
Eyal Toledano
023f51c579 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.
2025-05-25 20:16:48 -04:00
Eyal Toledano
1e020023ed 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.
2025-05-25 19:39:23 -04:00
Eyal Toledano
325f5a2aa3 chore: formatting 2025-05-25 18:58:42 -04:00
Eyal Toledano
de46bfd84b chore: removes task004 chat that had like 11k lines lol. 2025-05-25 18:50:59 -04:00
Eyal Toledano
cc26c36366 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
2025-05-25 18:48:39 -04:00
Eyal Toledano
15ad34928d 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
2025-05-25 18:03:43 -04:00
Eyal Toledano
f74d639110 fix(move): adjusts logic to prevent an issue when moving from parent to subtask if the target parent has no subtasks. 2025-05-25 17:49:32 -04:00
Eyal Toledano
de58e9ede5 feat(fuzzy): improves fuzzy search to introspect into subtasks as well. might still need improvement. 2025-05-25 17:33:00 -04:00
Eyal Toledano
947541e4ee 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
2025-05-25 17:19:28 -04:00
Eyal Toledano
275cd55da7 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 2025-05-25 03:51:51 -04:00
Eyal Toledano
67ac212973 chore: task management 2025-05-25 01:26:14 -04:00
Eyal Toledano
235371ff47 chore: task management and small bug fix. 2025-05-25 01:03:58 -04:00
celgost
b60e1cf835 revamping readme (#522) 2025-05-24 17:21:15 +02:00
Ralph Khreish
d1e45ff50e Merge pull request #589 from eyaltoledano/changeset-release/main
Version Packages
2025-05-24 16:25:26 +02:00
github-actions[bot]
1513858da4 Version Packages 2025-05-24 14:07:53 +00:00
Ralph Khreish
59dcf4bd64 Release 0.15.0
Release 0.15.0
2025-05-24 16:07:24 +02:00
github-actions[bot]
a09ba021c5 chore: rc version bump 2025-05-24 00:44:47 +00:00
Eyal Toledano
e906166141 Merge pull request #567 from eyaltoledano/parse-prd-research
v0.15 improvements & new features
2025-05-23 20:42:41 -04:00
Eyal Toledano
231e569e84 Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7 2025-05-23 20:33:45 -04:00
Eyal Toledano
09add37423 feat(models): Add comprehensive Ollama model validation and interactive setup - Add 'Custom Ollama model' option to interactive setup (--setup) - Implement live validation against local Ollama instance via /api/tags - Support configurable Ollama endpoints from .taskmasterconfig - Add robust error handling for server connectivity and model existence - Enhance user experience with clear validation feedback - Support both MCP server and CLI interfaces 2025-05-23 20:20:39 -04:00
Eyal Toledano
91fc779714 chore: adjusts changesets and an import. 2025-05-23 17:41:25 -04:00
Eyal Toledano
8c69c0aafd Task management, research, improvements for 24, 41 and 51 2025-05-23 17:30:25 -04:00
Eyal Toledano
43ad75c7fa chore: formatting 2025-05-23 14:44:53 -04:00
Eyal Toledano
a59dd037cf chore: changeset for Claude Code rules. depends on us adding it as an init option from the other PR. 2025-05-23 13:23:26 -04:00
Eyal Toledano
3293c7858b feat: adds AGENTS.md to the assets/ folder so we can add it into the project if the user selects Claude Code as the IDE of choice in the init sequence (to be done in another PR) 2025-05-23 13:17:45 -04:00
Eyal Toledano
b371808524 fix(models): Adjusts the Claude 4 models and introduces the llms-install.md file to enable AI agents to install the Taskmaster MCP server programmatically. 2025-05-23 12:59:14 -04:00
Shrey Paharia
86d8f00af8 Add next task to set status for mcp server (#558) 2025-05-22 11:09:36 +02:00
Eyal Toledano
0c55ce0165 chore: linting and prettier 2025-05-22 04:17:06 -04:00
Eyal Toledano
5a91941913 removes changeset for set/mark which i didnt add in the end 2025-05-22 04:15:10 -04:00
Eyal Toledano
04af16de27 feat(move-tasks): Implement move command for tasks and subtasks
Adds a new CLI command and MCP tool to reorganize tasks and subtasks within the hierarchy. Features include:
- Moving tasks between different positions in the task list
- Converting tasks to subtasks and vice versa
- Moving subtasks between parents
- Moving multiple tasks at once with comma-separated IDs
- Creating placeholder tasks when moving to new IDs
- Validation to prevent accidental data loss

This is particularly useful for resolving merge conflicts when multiple team members create tasks on different branches.
2025-05-22 04:14:22 -04:00
Eyal Toledano
edf0f23005 update changesets 2025-05-22 03:03:25 -04:00
Eyal Toledano
e0e1155260 fix(parse-prd): Fix parameter naming inconsistency in CLI parse-prd command 2025-05-22 02:59:32 -04:00
Eyal Toledano
70f4054f26 feat(parse-prd): Add research flag to parse-prd command for enhanced PRD analysis. Significantly improves parse PRD system prompt when used with research. 2025-05-22 02:57:51 -04:00
Eyal Toledano
34c769bcd0 feat(analyze): add task ID filtering to analyze-complexity command
Enhance analyze-complexity to support analyzing specific tasks by ID or range:
- Add --id option for comma-separated task IDs
- Add --from/--to options for analyzing tasks within a range
- Implement intelligent merging with existing reports
- Update CLI, MCP tools, and direct functions for consistent support
- Add changeset documenting the feature
2025-05-22 01:49:41 -04:00
Eyal Toledano
34df2c8bbd feat: automatically create tasks.json when missing (Task #68)
This commit implements automatic tasks.json file creation when it doesn't exist:

- When tasks.json is missing or invalid, create a new one with { tasks: [] }
- Allows adding tasks immediately after initializing a project without parsing a PRD
- Replaces error with informative feedback about file creation
- Enables smoother workflow for new projects or directories

This change improves user experience by removing the requirement to parse a PRD
before adding the first task to a newly initialized project. Closes #494
2025-05-22 01:18:27 -04:00
Eyal Toledano
5e9bc28abe feat(add-task): enhance dependency detection with semantic search
This commit significantly improves the  functionality by implementing
fuzzy semantic search to find contextually relevant dependencies:

- Add Fuse.js for powerful fuzzy search capability with weighted multi-field matching
- Implement score-based relevance ranking with high/medium relevance tiers
- Enhance context generation to include detailed information about similar tasks
- Fix context shadowing issue that prevented detailed task information from
  reaching the AI model
- Add informative CLI output showing semantic search results and dependency patterns
- Improve formatting of dependency information in prompts with task titles

The result is that newly created tasks are automatically placed within the correct
dependency structure without manual intervention, with the AI having much better
context about which tasks are most relevant to the new one being created.

This significantly improves the user experience by reducing the need to manually
update task dependencies after creation, all without increasing token usage or costs.
2025-05-22 01:09:40 -04:00
Eyal Toledano
d2e64318e2 fix(ai-services): add logic for API key checking in fallback sequence 2025-05-21 22:49:25 -04:00
Eyal Toledano
4c835264ac task management 2025-05-21 21:23:39 -04:00
github-actions[bot]
c882f89a8c Version Packages 2025-05-20 18:40:38 +02:00
Ralph Khreish
20e1b72a17 Merge pull request #549 from eyaltoledano/changeset-release/main
Version Packages
2025-05-20 00:34:13 +02:00
github-actions[bot]
db631f43a5 Version Packages 2025-05-19 22:31:08 +00:00
Ralph Khreish
3b9402f1f8 Merge Release 0.14.0 #529
Release 0.14.0
2025-05-20 00:30:46 +02:00
Ralph Khreish
c8c0fc2a57 fix: improve ollama object to telemetry structure (#546) 2025-05-19 23:05:45 +02:00
HR
60b8e97a1c fix: roomodes typo (#544) 2025-05-19 17:00:06 +02:00
github-actions[bot]
3a6d6dd671 chore: rc version bump 2025-05-18 08:08:54 +00:00
Ralph Khreish
f4a83ec047 feat: add ollama support (#536) 2025-05-18 10:07:31 +02:00
Eyal Toledano
0699f64299 Merge pull request #442 from eyaltoledano/telemetry
feat(telemetry): Implement AI usage telemetry pattern and apply to ad…
2025-05-17 22:34:01 -04:00
Eyal Toledano
60b8f5faa3 fix(expand-task): Ensure advanced parsing logic works and trimmed AI response properly if any jsonToParse modifications need to be made on initial parse of response. 2025-05-17 22:26:37 -04:00
Eyal Toledano
cd6e42249e fix(parse-prd): simplifies append and force variable names across the chain to avoid confusion. parse-prd append tested on MCP and the fix is good to go. Also adjusts e2e test to properly capture costs. 2025-05-17 20:10:53 -04:00
Eyal Toledano
fcd80623b6 linting 2025-05-17 18:43:15 -04:00
Eyal Toledano
026815353f fix(ai): Correctly imports generateText in openai.js, adds specific cause and reason for OpenRouter failures in the openrouter.js catch, performs complexity analysis on all tm tasks, adds new tasks to further improve the maxTokens to take input and output maximum into account. Adjusts default fallback max tokens so 3.5 does not fail. 2025-05-17 18:42:57 -04:00
Eyal Toledano
8a3b611fc2 fix(telemetry): renames _aggregateTelemetry to aggregateTelemetry to avoid confusion about it being a private function (it's not) 2025-05-17 17:48:45 -04:00
Eyal Toledano
6ba42b53dc fix: dupe export 2025-05-16 18:17:33 -04:00
Eyal Toledano
3e304232ab Solves merge conflicts with origin/next. 2025-05-16 18:15:11 -04:00
Eyal Toledano
70fa5b0031 fix(config): adjusts getUserId to optionally create/fill in the (currently hardcoded) userId to the telemetry object if it is not found. This prevents the telemetry call from landing as null for users who may have a taskmasterconfig but no userId in the globals. 2025-05-16 17:41:48 -04:00
github-actions[bot]
314c0de8c4 chore: rc version bump 2025-05-16 21:37:00 +00:00
Ralph Khreish
58b417a8ce Add complexity score to task (#528)
* feat: added complexity score handling to list tasks

* feat: added handling for complexity score in find task by id

* test: remove console dir

* chore: add changeset

* format: fixed formatting issues

* ref: reorder imports

* feat: updated handling for findTaskById to take complexityReport as input

* test: fix findTaskById complexity report testcases

* fix: added handling for complexity report path

* chore: add changeset

* fix: moved complexity report handling to list tasks rather than list tasks direct

* fix: add complexity handling to next task in list command

* fix: added handling for show cli

* fix: fixed next cli command handling

* fix: fixed handling for complexity report path in mcp

* feat: added handling to get-task

* feat: added handling for next-task in mcp

* feat: add handling for report path override

* chore: remove unecessary changeset

* ref: remove unecessary comments

* feat: update list and find next task

* fix: fixed running tests

* fix: fixed findTaskById

* fix: fixed findTaskById and tests

* fix: fixed addComplexityToTask util

* fix: fixed mcp server project root input

* chore: cleanup

---------

Co-authored-by: Shrey Paharia <shreypaharia@gmail.com>
2025-05-16 23:24:25 +02:00
Ralph Khreish
bc19bc7927 Merge remote-tracking branch 'origin/next' into telemetry 2025-05-16 18:16:58 +02:00
Eyal Toledano
da636f6681 fix(e2e): further improves the end to end script to take into account the changes made for each AI provider as it now responds with an obejct not just the result straight up. 2025-05-14 19:04:47 -04:00
Eyal Toledano
ca5ec03cd8 fix(ai,tasks): Enhance AI provider robustness and task processing
This commit introduces several improvements to AI interactions and
task management functionalities:

- AI Provider Enhancements (for Telemetry & Robustness):
    - :
        - Added a check in  to ensure
          is a string, throwing an error if not. This prevents downstream
           errors (e.g., in ).
    - , , :
        - Standardized return structures for their respective
          and  functions to consistently include /
          and  fields. This aligns them with other providers (like
          Anthropic, Google, Perplexity) for consistent telemetry data
          collection, as part of implementing subtask 77.14 and similar work.

- Task Expansion ():
    - Updated  to be more explicit
      about using an empty array  for empty  to
      better guide AI output.
    - Implemented a pre-emptive cleanup step in
      to replace malformed  with
      before JSON parsing. This improves resilience to AI output quirks,
      particularly observed with Perplexity.

- Adjusts issue in commands.js where successfulRemovals would be undefined. It's properly invoked from the result variable now.

- Updates supported models for Gemini
These changes address issues observed during E2E tests, enhance the
reliability of AI-driven task analysis and expansion, and promote
consistent telemetry data across multiple AI providers.
2025-05-14 19:04:03 -04:00
Eyal Toledano
79a41543d5 fix(ai): Align Perplexity provider with standard telemetry response structure
This commit updates the Perplexity AI provider () to ensure its functions return data in a structure consistent with other providers and the expectations of the unified AI service layer ().

Specifically:
-  now returns an object  instead of only the text string.
-  now returns an object  instead of only the result object.

These changes ensure that  can correctly extract both the primary AI-generated content and the token usage data for telemetry purposes when Perplexity models are used. This resolves issues encountered during E2E testing where complexity analysis (which can use Perplexity for its research role) failed due to unexpected response formats.

The  function was already compliant.
2025-05-14 11:46:35 -04:00
Eyal Toledano
9f4bac8d6a fix(ai): Improve AI object response handling in parse-prd
This commit updates  to more robustly handle responses from .

Previously, the module strictly expected the AI-generated object to be nested under . This change ensures that it now first checks if  itself contains the expected task data object, and then falls back to checking .

This enhancement increases compatibility with varying AI provider response structures, similar to the improvements recently made in .
2025-05-13 13:21:51 -04:00
Eyal Toledano
e53d5e1577 feat(ai): Enhance Google provider telemetry and AI object response handling
This commit introduces two key improvements:

1.  **Google Provider Telemetry:**
    - Updated  to include token usage data (, ) in the responses from  and .
    - This aligns the Google provider with others for consistent AI usage telemetry.

2.  **Robust AI Object Response Handling:**
    - Modified  to more flexibly handle responses from .
    - The add-task module now check for the AI-generated object in both  and , improving compatibility with different AI provider response structures (e.g., Gemini).

These changes enhance the reliability of AI interactions, particularly with the Google provider, and ensure accurate telemetry collection.
2025-05-13 12:13:35 -04:00
Eyal Toledano
59230c4d91 chore: task management and formatting. 2025-05-09 14:12:21 -04:00
Eyal Toledano
04b6a3cb21 feat(telemetry): Integrate AI usage telemetry into analyze-complexity
This commit applies the standard telemetry pattern to the analyze-task-complexity command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/analyze-task-complexity.js):
    -   The call to generateTextService now includes commandName: 'analyze-complexity' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for parsing the complexity report JSON.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { report: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/analyze-task-complexity.js):
    -   The call to the core analyzeTaskComplexity function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 19:34:00 -04:00
Eyal Toledano
37178ff1b9 feat(telemetry): Integrate AI usage telemetry into update-subtask
This commit applies the standard telemetry pattern to the update-subtask command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/update-subtask-by-id.js):
    -   The call to generateTextService now includes commandName: 'update-subtask' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for the appended content.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { updatedSubtask: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/update-subtask-by-id.js):
    -   The call to the core updateSubtaskById function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 19:04:25 -04:00
Eyal Toledano
bbc8b9cc1f feat(telemetry): Integrate AI usage telemetry into update-tasks
This commit applies the standard telemetry pattern to the update-tasks command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/update-tasks.js):
    -   The call to generateTextService now includes commandName: 'update-tasks' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for parsing the updated task JSON.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { success: true, updatedTasks: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/update-tasks.js):
    -   The call to the core updateTasks function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 18:51:29 -04:00
Eyal Toledano
c955431753 feat(telemetry): Integrate AI usage telemetry into update-tasks
This commit applies the standard telemetry pattern to the  command and its corresponding MCP tool.

Key Changes:

1.  **Core Logic ():**
    -   The call to  now includes  and .
    -   The full response  is captured.
    -    (the AI-generated text) is used for parsing the updated task JSON.
    -   If running in CLI mode (),  is called with the .
    -   The function now returns .

2.  **Direct Function ():**
    -   The call to the core  function now passes the necessary context for telemetry (, ).
    -   The successful response object now correctly extracts  and includes it in the  field returned to the MCP client.
2025-05-08 18:37:41 -04:00
Eyal Toledano
21c3cb8cda feat(telemetry): Integrate telemetry for expand-all, aggregate results
This commit implements AI usage telemetry for the `expand-all-tasks` command/tool and refactors its CLI output for clarity and consistency.

Key Changes:

1.  **Telemetry Integration for `expand-all-tasks` (Subtask 77.8):**\n    -   The `expandAllTasks` core logic (`scripts/modules/task-manager/expand-all-tasks.js`) now calls the `expandTask` function for each eligible task and collects the individual `telemetryData` returned.\n    -   A new helper function `_aggregateTelemetry` (in `utils.js`) is used to sum up token counts and costs from all individual expansions into a single `telemetryData` object for the entire `expand-all` operation.\n    -   The `expandAllTasksDirect` wrapper (`mcp-server/src/core/direct-functions/expand-all-tasks.js`) now receives and passes this aggregated `telemetryData` in the MCP response.\n    -   For CLI usage, `displayAiUsageSummary` is called once with the aggregated telemetry.

2.  **Improved CLI Output for `expand-all`:**\n    -   The `expandAllTasks` core function now handles displaying a final "Expansion Summary" box (showing Attempted, Expanded, Skipped, Failed counts) directly after the aggregated telemetry summary.\n    -   This consolidates all summary output within the core function for better flow and removes redundant logging from the command action in `scripts/modules/commands.js`.\n    -   The summary box border is green for success and red if any expansions failed.

3.  **Code Refinements:**\n    -   Ensured `chalk` and `boxen` are imported in `expand-all-tasks.js` for the new summary box.\n    -   Minor adjustments to logging messages for clarity.
2025-05-08 18:22:00 -04:00
Eyal Toledano
ab84afd036 feat(telemetry): Integrate usage telemetry for expand-task, fix return types
This commit integrates AI usage telemetry for the `expand-task` command/tool and resolves issues related to incorrect return type handling and logging.

Key Changes:

1.  **Telemetry Integration for `expand-task` (Subtask 77.7):**\n    -   Applied the standard telemetry pattern to the `expandTask` core logic (`scripts/modules/task-manager/expand-task.js`) and the `expandTaskDirect` wrapper (`mcp-server/src/core/direct-functions/expand-task.js`).\n    -   AI service calls now pass `commandName` and `outputType`.\n    -   Core function returns `{ task, telemetryData }`.\n    -   Direct function correctly extracts `task` and passes `telemetryData` in the MCP response `data` field.\n    -   Telemetry summary is now displayed in the CLI output for the `expand` command.

2.  **Fix AI Service Return Type Handling (`ai-services-unified.js`):**\n    -   Corrected the `_unifiedServiceRunner` function to properly handle the return objects from provider-specific functions (`generateText`, `generateObject`).\n    -   It now correctly extracts `providerResponse.text` or `providerResponse.object` into the `mainResult` field based on `serviceType`, resolving the "text.trim is not a function" error encountered during `expand-task`.

3.  **Log Cleanup:**\n    -   Removed various redundant or excessive `console.log` statements across multiple files (as indicated by recent changes) to reduce noise and improve clarity, particularly for MCP interactions.
2025-05-08 16:02:23 -04:00
Eyal Toledano
f89d2aacc0 feat(telemetry): Integrate AI usage telemetry into parse-prd
Implements AI usage telemetry capture and propagation for the  command and MCP tool, following the established telemetry pattern.

Key changes:

-   **Core ():**
    -   Modified the  call to include  and .
    -   Updated to receive  from .
    -   Adjusted to return an object .
    -   Added a call to  to show telemetry data in the CLI output when not in MCP mode.

-   **Direct Function ():**
    -   Updated the call to the core  function to pass , , and .
    -   Modified to correctly handle the new return structure from the core function.
    -   Ensures  received from the core function is included in the  field of the successful MCP response.

-   **MCP Tool ():**
    -   No changes required; existing  correctly passes through the  object containing .

-   **CLI Command ():**
    -   The  command's action now relies on the core  function to handle CLI success messages and telemetry display.

This ensures that AI usage for the  functionality is tracked and can be displayed or logged as appropriate for both CLI and MCP interactions.
2025-05-07 14:22:42 -04:00
Eyal Toledano
0288311965 fix(parse-prd): resolves issue preventing --append flag from properly working in the CLI context. Adds changeset. 2025-05-07 14:17:41 -04:00
Eyal Toledano
8ae772086d fix(next): adjusts CLI output for next when the result is a subtask. previously incorrect suggested creating subtasks for the subtask. 2025-05-07 14:07:50 -04:00
Eyal Toledano
2b3ae8bf89 tests: adjusts the tests to properly pass. 2025-05-07 13:54:01 -04:00
Eyal Toledano
245c3cb398 feat(telemetry): Implement AI usage telemetry pattern and apply to add-task
This commit introduces a standardized pattern for capturing and propagating AI usage telemetry (cost, tokens, model used) across the Task Master stack and applies it to the 'add-task' functionality.

Key changes include:

- **Telemetry Pattern Definition:**
  - Added  defining the integration pattern for core logic, direct functions, MCP tools, and CLI commands.
  - Updated related rules (, ,
 Usage: mcp [OPTIONS] COMMAND [ARGS]...

 MCP development tools

╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --help          Show this message and exit.                                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Commands ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ version   Show the MCP version.                                                                                                            │
│ dev       Run a MCP server with the MCP Inspector.                                                                                         │
│ run       Run a MCP server.                                                                                                                │
│ install   Install a MCP server in the Claude desktop app.                                                                                  │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯, , ) to reference the new telemetry rule.

- **Core Telemetry Implementation ():**
  - Refactored the unified AI service to generate and return a  object alongside the main AI result.
  - Fixed an MCP server startup crash by removing redundant local loading of  and instead using the  imported from  for cost calculations.
  - Added  to the  object.

- ** Integration:**
  - Modified  (core) to receive  from the AI service, return it, and call the new UI display function for CLI output.
  - Updated  to receive  from the core function and include it in the  payload of its response.
  - Ensured  (MCP tool) correctly passes the  through via .
  - Updated  to correctly pass context (, ) to the core  function and rely on it for CLI telemetry display.

- **UI Enhancement:**
  - Added  function to  to show telemetry details in the CLI.

- **Project Management:**
  - Added subtasks 77.6 through 77.12 to track the rollout of this telemetry pattern to other AI-powered commands (, , , , , , ).

This establishes the foundation for tracking AI usage across the application.
2025-05-07 13:41:25 -04:00
204 changed files with 47441 additions and 13605 deletions

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Resolve all issues related to MCP

View File

@@ -0,0 +1,44 @@
---
'task-master-ai': minor
---
Add comprehensive AI-powered research command with intelligent context gathering and interactive follow-ups.
The new `research` command provides AI-powered research capabilities that automatically gather relevant project context to answer your questions. The command intelligently selects context from multiple sources and supports interactive follow-up questions in CLI mode.
**Key Features:**
- **Intelligent Task Discovery**: Automatically finds relevant tasks and subtasks using fuzzy search based on your query keywords, supplementing any explicitly provided task IDs
- **Multi-Source Context**: Gathers context from tasks, files, project structure, and custom text to provide comprehensive answers
- **Interactive Follow-ups**: CLI users can ask follow-up questions that build on the conversation history while allowing fresh context discovery for each question
- **Flexible Detail Levels**: Choose from low (concise), medium (balanced), or high (comprehensive) response detail levels
- **Token Transparency**: Displays detailed token breakdown showing context size, sources, and estimated costs
- **Enhanced Display**: Syntax-highlighted code blocks and structured output with clear visual separation
**Usage Examples:**
```bash
# Basic research with auto-discovered context
task-master research "How should I implement user authentication?"
# Research with specific task context
task-master research "What's the best approach for this?" --id=15,23.2
# Research with file context and project tree
task-master research "How does the current auth system work?" --files=src/auth.js,config/auth.json --tree
# Research with custom context and low detail
task-master research "Quick implementation steps?" --context="Using JWT tokens" --detail=low
```
**Context Sources:**
- **Tasks**: Automatically discovers relevant tasks/subtasks via fuzzy search, plus any explicitly specified via `--id`
- **Files**: Include specific files via `--files` for code-aware responses
- **Project Tree**: Add `--tree` to include project structure overview
- **Custom Context**: Provide additional context via `--context` for domain-specific information
**Interactive Features (CLI only):**
- Follow-up questions that maintain conversation history
- Fresh fuzzy search for each follow-up to discover newly relevant tasks
- Cumulative context building across the conversation
- Clean visual separation between exchanges
The research command integrates with the existing AI service layer and supports all configured AI providers. MCP integration provides the same functionality for programmatic access without interactive features.

View File

@@ -0,0 +1,13 @@
---
'task-master-ai': patch
---
Fix critical bugs in task move functionality:
- **Fixed moving tasks to become subtasks of empty parents**: When moving a task to become a subtask of a parent that had no existing subtasks (e.g., task 89 → task 98.1), the operation would fail with validation errors.
- **Fixed moving subtasks between parents**: Subtasks can now be properly moved between different parent tasks, including to parents that previously had no subtasks.
- **Improved comma-separated batch moves**: Multiple tasks can now be moved simultaneously using comma-separated IDs (e.g., "88,90" → "92,93") with proper error handling and atomic operations.
These fixes enables proper task hierarchy reorganization for corner cases that were previously broken.

View File

@@ -1,9 +0,0 @@
---
'task-master-ai': patch
---
Fix CLI --force flag for parse-prd command
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
- Fixes #477

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': minor
---
.taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Add AWS bedrock support

View File

@@ -0,0 +1,13 @@
---
'task-master-ai': minor
---
# Add Google Vertex AI Provider Integration
- Implemented `VertexAIProvider` class extending BaseAIProvider
- Added authentication and configuration handling for Vertex AI
- Updated configuration manager with Vertex-specific getters
- Modified AI services unified system to integrate the provider
- Added documentation for Vertex AI setup and configuration
- Updated environment variable examples for Vertex AI support
- Implemented specialized error handling for Vertex-specific issues

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Add support for Azure

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Task Master no longer tells you to update when you're already up to date

View File

@@ -0,0 +1,17 @@
---
'task-master-ai': minor
---
Add comprehensive `research` MCP tool for AI-powered research queries
- **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.

View File

@@ -0,0 +1,5 @@
---
"task-master-ai": minor
---
Increased minimum required node version to > 18 (was > 14)

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Renamed baseUrl to baseURL

View File

@@ -1,12 +0,0 @@
{
"mode": "exit",
"tag": "rc",
"initialVersions": {
"task-master-ai": "0.13.2"
},
"changesets": [
"beige-doodles-type",
"red-oranges-attend",
"red-suns-wash"
]
}

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Add src directory to exports

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fix max_tokens error when trying to use claude-sonnet-4 and claude-opus-4

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Fix the error handling of task status settings

View File

@@ -0,0 +1,7 @@
---
'task-master-ai': minor
---
Add TASK_MASTER_PROJECT_ROOT env variable supported in mcp.json and .env for project root resolution
- Some users were having issues where the MCP wasn't able to detect the location of their project root, you can now set the `TASK_MASTER_PROJECT_ROOT` environment variable to the root of your project.

View File

@@ -1,7 +0,0 @@
---
'task-master-ai': patch
---
Remove caching layer from MCP direct functions for task listing, next task, and complexity report
- Fixes issues users where having where they were getting stale data

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Fix for issue #409 LOG_LEVEL Pydantic validation error

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': minor
---
Display task complexity scores in task lists, next task, and task details views.

View File

@@ -1,7 +0,0 @@
---
'task-master-ai': patch
---
Fix initial .env.example to work out of the box
- Closes #419

View File

@@ -0,0 +1,19 @@
---
'task-master-ai': minor
---
Enhanced get-task/show command to support comma-separated task IDs for efficient batch operations
**New Features:**
- **Multiple Task Retrieval**: Pass comma-separated IDs to get/show multiple tasks at once (e.g., `task-master show 1,3,5` or MCP `get_task` with `id: "1,3,5"`)
- **Smart Display Logic**: Single ID shows detailed view, multiple IDs show compact summary table with interactive options
- **Batch Action Menu**: Interactive menu for multiple tasks with copy-paste ready commands for common operations (mark as done/in-progress, expand all, view dependencies, etc.)
- **MCP Array Response**: MCP tool returns structured array of task objects for efficient AI agent context gathering
**Benefits:**
- **Faster Context Gathering**: AI agents can collect multiple tasks/subtasks in one call instead of iterating
- **Improved Workflow**: Interactive batch operations reduce repetitive command execution
- **Better UX**: Responsive layout adapts to terminal width, maintains consistency with existing UI patterns
- **API Efficiency**: RESTful array responses in MCP format enable more sophisticated integrations
This enhancement maintains full backward compatibility while significantly improving efficiency for both human users and AI agents working with multiple tasks.

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Fix default fallback model and maxTokens in Taskmaster initialization

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fix add-task MCP command causing an error

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Fix bug when updating tasks on the MCP server (#412)

View File

@@ -1,11 +0,0 @@
---
'task-master-ai': patch
---
Fix duplicate output on CLI help screen
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
- Ensures a clean, branded help experience with no repeated content.
- Fixes #339

View File

@@ -1,8 +1,29 @@
{
"mcpServers": {
"task-master-ai": {
"task-master-ai-tm": {
"command": "node",
"args": ["./mcp-server/server.js"],
"args": [
"./mcp-server/server.js"
],
"env": {
"ANTHROPIC_API_KEY": "ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "PERPLEXITY_API_KEY_HERE",
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
"XAI_API_KEY": "XAI_API_KEY_HERE",
"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"
}
},
"task-master-ai": {
"command": "npx",
"args": [
"-y",
"--package=task-master-ai",
"task-master-ai"
],
"env": {
"ANTHROPIC_API_KEY": "ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "PERPLEXITY_API_KEY_HERE",
@@ -15,5 +36,9 @@
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
}
}
},
"env": {
"TASKMASTER_TELEMETRY_API_KEY": "339a81c9-5b9c-4d60-92d8-cba2ee2a8cc3",
"TASKMASTER_TELEMETRY_USER_EMAIL": "user_1748640077834@taskmaster.dev"
}
}

View File

@@ -50,6 +50,7 @@ This rule guides AI assistants on how to view, configure, and interact with the
- **Key Locations** (See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) - Configuration Management):
- **MCP/Cursor:** Set keys in the `env` section of `.cursor/mcp.json`.
- **CLI:** Set keys in a `.env` file in the project root.
- As the AI agent, you do not have access to read the .env -- but do not attempt to recreate it!
- **Provider List & Keys:**
- **`anthropic`**: Requires `ANTHROPIC_API_KEY`.
- **`google`**: Requires `GOOGLE_API_KEY`.

View File

@@ -1,6 +1,7 @@
---
description: Guidelines for interacting with the unified AI service layer.
globs: scripts/modules/ai-services-unified.js, scripts/modules/task-manager/*.js, scripts/modules/commands.js
alwaysApply: false
---
# AI Services Layer Guidelines
@@ -25,6 +26,7 @@ This document outlines the architecture and usage patterns for interacting with
* Implements **retry logic** for specific API errors (`_attemptProviderCallWithRetries`).
* Resolves API keys automatically via `_resolveApiKey` (using `resolveEnvVariable`).
* Maps requests to the correct provider implementation (in `src/ai-providers/`) via `PROVIDER_FUNCTIONS`.
* Returns a structured object containing the primary AI result (`mainResult`) and telemetry data (`telemetryData`). See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for details on how this telemetry data is propagated and handled.
* **Provider Implementations (`src/ai-providers/*.js`):**
* Contain provider-specific wrappers around Vercel AI SDK functions (`generateText`, `generateObject`).
@@ -90,7 +92,7 @@ This document outlines the architecture and usage patterns for interacting with
* ✅ **DO**: Centralize **all** LLM calls through `generateTextService` or `generateObjectService`.
* ✅ **DO**: Determine the appropriate `role` (`main`, `research`, `fallback`) in your core logic and pass it to the service.
* ✅ **DO**: Pass the `session` object (received in the `context` parameter, especially from direct function wrappers) to the service call when in MCP context.
* ✅ **DO**: Ensure API keys are correctly configured in `.env` (for CLI) or `.cursor/mcp.json` (for MCP).
* ✅ **DO**: Ensure API keys are correctly configured in `.env` (for CLI) or `.cursor/mcp.json` (for MCP). FYI: As the AI agent, you do not have access to read the .env -- so do not attempt to recreate it!
* ✅ **DO**: Ensure `.taskmasterconfig` exists and has valid provider/model IDs for the roles you intend to use (manage via `task-master models --setup`).
* ✅ **DO**: Use `generateTextService` and implement robust manual JSON parsing (with Zod validation *after* parsing) when structured output is needed, as `generateObjectService` has shown unreliability with some providers/schemas.
* ❌ **DON'T**: Import or call anything from the old `ai-services.js`, `ai-client-factory.js`, or `ai-client-utils.js` files.

View File

@@ -39,11 +39,12 @@ alwaysApply: false
- **Responsibilities** (See also: [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc)):
- Exports `generateTextService`, `generateObjectService`.
- Handles provider/model selection based on `role` and `.taskmasterconfig`.
- Resolves API keys (from `.env` or `session.env`).
- Resolves API keys (from `.env` or `session.env`). As the AI agent, you do not have access to read the .env -- but do not attempt to recreate it!
- Implements fallback and retry logic.
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
- Telemetry data generated by the AI service layer is propagated upwards through core logic, direct functions, and MCP tools. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the detailed integration pattern.
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
- **[`src/ai-providers/*.js`](mdc:src/ai-providers): Provider-Specific Implementations**
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.
- **Responsibilities**: Interact directly with Vercel AI SDK adapters.
@@ -62,7 +63,7 @@ alwaysApply: false
- API Key Resolution (`resolveEnvVariable`).
- Silent Mode Control (`enableSilentMode`, `disableSilentMode`).
- **[`mcp-server/`](mdc:mcp-server/): MCP Server Integration**
- **[`mcp-server/`](mdc:mcp-server): MCP Server Integration**
- **Purpose**: Provides MCP interface using FastMCP.
- **Responsibilities** (See also: [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)):
- Registers tools (`mcp-server/src/tools/*.js`). Tool `execute` methods **should be wrapped** with the `withNormalizedProjectRoot` HOF (from `tools/utils.js`) to ensure consistent path handling.

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

@@ -49,6 +49,7 @@ Task Master offers two primary ways to interact:
- 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
## Task Complexity Analysis
@@ -154,6 +155,25 @@ Taskmaster configuration is managed through two main mechanisms:
- Task files are automatically regenerated after dependency changes
- Dependencies are visualized with status indicators in task listings and files
## Task Reorganization
- Use `move_task` / `task-master move --from=<id> --to=<id>` to move tasks or subtasks within the hierarchy
- This command supports several use cases:
- Moving a standalone task to become a subtask (e.g., `--from=5 --to=7`)
- Moving a subtask to become a standalone task (e.g., `--from=5.2 --to=7`)
- Moving a subtask to a different parent (e.g., `--from=5.2 --to=7.3`)
- Reordering subtasks within the same parent (e.g., `--from=5.2 --to=5.4`)
- Moving a task to a new, non-existent ID position (e.g., `--from=5 --to=25`)
- Moving multiple tasks at once using comma-separated IDs (e.g., `--from=10,11,12 --to=16,17,18`)
- The system includes validation to prevent data loss:
- Allows moving to non-existent IDs by creating placeholder tasks
- Prevents moving to existing task IDs that have content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- The system maintains proper parent-child relationships and dependency integrity
- Task files are automatically regenerated after the move operation
- This provides greater flexibility in organizing and refining your task structure as project understanding evolves
- This is especially useful when dealing with potential merge conflicts arising from teams creating tasks on separate branches. Solve these conflicts very easily by moving your tasks and keeping theirs.
## Iterative Subtask Implementation
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:

View File

@@ -0,0 +1,367 @@
---
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
```
## **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]
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
# 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
# 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
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**
```bash
# If multiple people work on overlapping tasks:
# 1. Use Task Master's move functionality to reorganize
task-master move --from=5 --to=25 # Move conflicting task
# 2. Update task dependencies
task-master add-dependency --id=6 --depends-on=5
# 3. Coordinate through PR comments and task updates
```
### **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..."
```
---
**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

@@ -3,7 +3,6 @@ description: Glossary of other Cursor rules
globs: **/*
alwaysApply: true
---
# Glossary of Task Master Cursor Rules
This file provides a quick reference to the purpose of each rule file located in the `.cursor/rules` directory.
@@ -23,4 +22,5 @@ This file provides a quick reference to the purpose of each rule file located in
- **[`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.
- **[`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc)**: Guidelines for integrating AI usage telemetry across Task Master.

View File

@@ -522,3 +522,8 @@ Follow these steps to add MCP support for an existing Task Master command (see [
// Add more functions as implemented
};
```
## Telemetry Integration
- Direct functions calling core logic that involves AI should receive and pass through `telemetryData` within their successful `data` payload. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the standard pattern.
- MCP tools use `handleApiResult`, which ensures the `data` object (potentially including `telemetryData`) from the direct function is correctly included in the final response.

View File

@@ -3,7 +3,6 @@ description: Guidelines for integrating new features into the Task Master CLI
globs: scripts/modules/*.js
alwaysApply: false
---
# Task Master Feature Integration Guidelines
## Feature Placement Decision Process
@@ -25,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
@@ -196,6 +200,8 @@ The standard pattern for adding a feature follows this workflow:
- ✅ **DO**: If an MCP tool fails with vague errors (e.g., JSON parsing issues like `Unexpected token ... is not valid JSON`), **try running the equivalent CLI command directly in the terminal** (e.g., `task-master expand --all`). CLI output often provides much more specific error messages (like missing function definitions or stack traces from the core logic) that pinpoint the root cause.
- ❌ **DON'T**: Rely solely on MCP logs if the error is unclear; use the CLI as a complementary debugging tool for core logic issues.
- **Telemetry Integration**: Ensure AI calls correctly handle and propagate `telemetryData` as described in [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc).
```javascript
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
/**

View File

@@ -112,9 +112,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master show [id] [options]`
* **Description:** `Display detailed information for a specific Taskmaster task or subtask by its 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', or subtask, e.g., '15.2', you want to view.` (CLI: `[id]. Supports comma-separated list of tasks to get multiple tasks at once.` positional or `-i, --id <id>`)
* `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.
* **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.
---
@@ -269,11 +270,36 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `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.
### 17. Move Task (`move_task`)
* **MCP Tool:** `move_task`
* **CLI Command:** `task-master move [options]`
* **Description:** `Move a task or subtask to a new position within the task hierarchy.`
* **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>`)
* `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
* Moving a subtask to become a standalone task
* Moving a subtask to a different parent
* Reordering subtasks within the same parent
* Moving a task to a new, non-existent ID (automatically creates placeholders)
* Moving multiple tasks at once with comma-separated IDs
* **Validation Features:**
* Allows moving tasks to non-existent destination IDs (creates placeholder tasks)
* Prevents moving to existing task IDs that already have content (to avoid overwriting)
* Validates that source tasks exist before attempting to move them
* Maintains proper parent-child relationships
* **Example CLI:** `task-master move --from=5.2 --to=7.3` to move subtask 5.2 to become subtask 7.3.
* **Example Multi-Move:** `task-master move --from=10,11,12 --to=16,17,18` to move multiple tasks to new positions.
* **Common Use:** Resolving merge conflicts in tasks.json when multiple team members create tasks on different branches.
---
## Dependency Management
### 17. Add Dependency (`add_dependency`)
### 18. Add Dependency (`add_dependency`)
* **MCP Tool:** `add_dependency`
* **CLI Command:** `task-master add-dependency [options]`
@@ -284,7 +310,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `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.
### 18. Remove Dependency (`remove_dependency`)
### 19. Remove Dependency (`remove_dependency`)
* **MCP Tool:** `remove_dependency`
* **CLI Command:** `task-master remove-dependency [options]`
@@ -295,7 +321,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `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.
### 19. Validate Dependencies (`validate_dependencies`)
### 20. Validate Dependencies (`validate_dependencies`)
* **MCP Tool:** `validate_dependencies`
* **CLI Command:** `task-master validate-dependencies [options]`
@@ -304,7 +330,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `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.
### 20. Fix Dependencies (`fix_dependencies`)
### 21. Fix Dependencies (`fix_dependencies`)
* **MCP Tool:** `fix_dependencies`
* **CLI Command:** `task-master fix-dependencies [options]`
@@ -317,7 +343,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
## Analysis & Reporting
### 21. Analyze Project Complexity (`analyze_project_complexity`)
### 22. Analyze Project Complexity (`analyze_project_complexity`)
* **MCP Tool:** `analyze_project_complexity`
* **CLI Command:** `task-master analyze-complexity [options]`
@@ -330,7 +356,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **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.
### 22. View Complexity Report (`complexity_report`)
### 23. View Complexity Report (`complexity_report`)
* **MCP Tool:** `complexity_report`
* **CLI Command:** `task-master complexity-report [options]`
@@ -341,9 +367,46 @@ This document provides a detailed reference for interacting with Taskmaster, cov
---
## 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 for 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>`)
* `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.
---
## File Management
### 23. Generate Task Files (`generate`)
### 24. Generate Task Files (`generate`)
* **MCP Tool:** `generate`
* **CLI Command:** `task-master generate [options]`

View File

@@ -0,0 +1,408 @@
---
description:
globs:
alwaysApply: true
---
# Test Workflow & Development Process
## **Test-Driven Development (TDD) Integration**
### **Core TDD Cycle with Jest**
```bash
# 1. Start development with watch mode
npm run test:watch
# 2. Write failing test first
# Create test file: src/utils/newFeature.test.ts
# Write test that describes expected behavior
# 3. Implement minimum code to make test pass
# 4. Refactor while keeping tests green
# 5. Add edge cases and error scenarios
```
### **TDD Workflow Per Subtask**
```bash
# When starting a new subtask:
task-master set-status --id=4.1 --status=in-progress
# Begin TDD cycle:
npm run test:watch # Keep running during development
# Document TDD progress in subtask:
task-master update-subtask --id=4.1 --prompt="TDD Progress:
- Written 3 failing tests for core functionality
- Implemented basic feature, tests now passing
- Adding edge case tests for error handling"
# Complete subtask with test summary:
task-master update-subtask --id=4.1 --prompt="Implementation complete:
- Feature implemented with 8 unit tests
- Coverage: 95% statements, 88% branches
- All tests passing, TDD cycle complete"
```
## **Testing Commands & Usage**
### **Development Commands**
```bash
# Primary development command - use during coding
npm run test:watch # Watch mode with Jest
npm run test:watch -- --testNamePattern="auth" # Watch specific tests
# Targeted testing during development
npm run test:unit # Run only unit tests
npm run test:unit -- --coverage # Unit tests with coverage
# Integration testing when APIs are ready
npm run test:integration # Run integration tests
npm run test:integration -- --detectOpenHandles # Debug hanging tests
# End-to-end testing for workflows
npm run test:e2e # Run E2E tests
npm run test:e2e -- --timeout=30000 # Extended timeout for E2E
```
### **Quality Assurance Commands**
```bash
# Full test suite with coverage (before commits)
npm run test:coverage # Complete coverage analysis
# All tests (CI/CD pipeline)
npm test # Run all test projects
# Specific test file execution
npm test -- auth.test.ts # Run specific test file
npm test -- --testNamePattern="should handle errors" # Run specific tests
```
## **Test Implementation Patterns**
### **Unit Test Development**
```typescript
// ✅ DO: Follow established patterns from auth.test.ts
describe('FeatureName', () => {
beforeEach(() => {
jest.clearAllMocks();
// Setup mocks with proper typing
});
describe('functionName', () => {
it('should handle normal case', () => {
// Test implementation with specific assertions
});
it('should throw error for invalid input', async () => {
// Error scenario testing
await expect(functionName(invalidInput))
.rejects.toThrow('Specific error message');
});
});
});
```
### **Integration Test Development**
```typescript
// ✅ DO: Use supertest for API endpoint testing
import request from 'supertest';
import { app } from '../../src/app';
describe('POST /api/auth/register', () => {
beforeEach(async () => {
await integrationTestUtils.cleanupTestData();
});
it('should register user successfully', async () => {
const userData = createTestUser();
const response = await request(app)
.post('/api/auth/register')
.send(userData)
.expect(201);
expect(response.body).toMatchObject({
id: expect.any(String),
email: userData.email
});
// Verify database state
const user = await prisma.user.findUnique({
where: { email: userData.email }
});
expect(user).toBeTruthy();
});
});
```
### **E2E Test Development**
```typescript
// ✅ DO: Test complete user workflows
describe('User Authentication Flow', () => {
it('should complete registration → login → protected access', async () => {
// Step 1: Register
const userData = createTestUser();
await request(app)
.post('/api/auth/register')
.send(userData)
.expect(201);
// Step 2: Login
const loginResponse = await request(app)
.post('/api/auth/login')
.send({ email: userData.email, password: userData.password })
.expect(200);
const { token } = loginResponse.body;
// Step 3: Access protected resource
await request(app)
.get('/api/profile')
.set('Authorization', `Bearer ${token}`)
.expect(200);
}, 30000); // Extended timeout for E2E
});
```
## **Mocking & Test Utilities**
### **Established Mocking Patterns**
```typescript
// ✅ DO: Use established bcrypt mocking pattern
jest.mock('bcrypt');
import bcrypt from 'bcrypt';
const mockHash = bcrypt.hash as jest.MockedFunction<typeof bcrypt.hash>;
const mockCompare = bcrypt.compare as jest.MockedFunction<typeof bcrypt.compare>;
// ✅ DO: Use Prisma mocking for unit tests
jest.mock('@prisma/client', () => ({
PrismaClient: jest.fn().mockImplementation(() => ({
user: {
create: jest.fn(),
findUnique: jest.fn(),
},
$connect: jest.fn(),
$disconnect: jest.fn(),
})),
}));
```
### **Test Fixtures Usage**
```typescript
// ✅ DO: Use centralized test fixtures
import { createTestUser, adminUser, invalidUser } from '../fixtures/users';
describe('User Service', () => {
it('should handle admin user creation', async () => {
const userData = createTestUser(adminUser);
// Test implementation
});
it('should reject invalid user data', async () => {
const userData = createTestUser(invalidUser);
// Error testing
});
});
```
## **Coverage Standards & Monitoring**
### **Coverage Thresholds**
- **Global Standards**: 80% lines/functions, 70% branches
- **Critical Code**: 90% utils, 85% middleware
- **New Features**: Must meet or exceed global thresholds
- **Legacy Code**: Gradual improvement with each change
### **Coverage Reporting & Analysis**
```bash
# Generate coverage reports
npm run test:coverage
# View detailed HTML report
open coverage/lcov-report/index.html
# Coverage files generated:
# - coverage/lcov-report/index.html # Detailed HTML report
# - coverage/lcov.info # LCOV format for IDE integration
# - coverage/coverage-final.json # JSON format for tooling
```
### **Coverage Quality Checks**
```typescript
// ✅ DO: Test all code paths
describe('validateInput', () => {
it('should return true for valid input', () => {
expect(validateInput('valid')).toBe(true);
});
it('should return false for various invalid inputs', () => {
expect(validateInput('')).toBe(false); // Empty string
expect(validateInput(null)).toBe(false); // Null value
expect(validateInput(undefined)).toBe(false); // Undefined
});
it('should throw for unexpected input types', () => {
expect(() => validateInput(123)).toThrow('Invalid input type');
});
});
```
## **Testing During Development Phases**
### **Feature Development Phase**
```bash
# 1. Start feature development
task-master set-status --id=X.Y --status=in-progress
# 2. Begin TDD cycle
npm run test:watch
# 3. Document test progress in subtask
task-master update-subtask --id=X.Y --prompt="Test development:
- Created test file with 5 failing tests
- Implemented core functionality
- Tests passing, adding error scenarios"
# 4. Verify coverage before completion
npm run test:coverage
# 5. Update subtask with final test status
task-master update-subtask --id=X.Y --prompt="Testing complete:
- 12 unit tests with full coverage
- All edge cases and error scenarios covered
- Ready for integration testing"
```
### **Integration Testing Phase**
```bash
# After API endpoints are implemented
npm run test:integration
# Update integration test templates
# Replace placeholder tests with real endpoint calls
# Document integration test results
task-master update-subtask --id=X.Y --prompt="Integration tests:
- Updated auth endpoint tests
- Database integration verified
- All HTTP status codes and responses tested"
```
### **Pre-Commit Testing Phase**
```bash
# Before committing code
npm run test:coverage # Verify all tests pass with coverage
npm run test:unit # Quick unit test verification
npm run test:integration # Integration test verification (if applicable)
# Commit pattern for test updates
git add tests/ src/**/*.test.ts
git commit -m "test(task-X): Add comprehensive tests for Feature Y
- Unit tests with 95% coverage (exceeds 90% threshold)
- Integration tests for API endpoints
- Test fixtures for data generation
- Proper mocking patterns established
Task X: Feature Y - Testing complete"
```
## **Error Handling & Debugging**
### **Test Debugging Techniques**
```typescript
// ✅ DO: Use test utilities for debugging
import { testUtils } from '../setup';
it('should debug complex operation', () => {
testUtils.withConsole(() => {
// Console output visible only for this test
console.log('Debug info:', complexData);
service.complexOperation();
});
});
// ✅ DO: Use proper async debugging
it('should handle async operations', async () => {
const promise = service.asyncOperation();
// Test intermediate state
expect(service.isProcessing()).toBe(true);
const result = await promise;
expect(result).toBe('expected');
expect(service.isProcessing()).toBe(false);
});
```
### **Common Test Issues & Solutions**
```bash
# Hanging tests (common with database connections)
npm run test:integration -- --detectOpenHandles
# Memory leaks in tests
npm run test:unit -- --logHeapUsage
# Slow tests identification
npm run test:coverage -- --verbose
# Mock not working properly
# Check: mock is declared before imports
# Check: jest.clearAllMocks() in beforeEach
# Check: TypeScript typing is correct
```
## **Continuous Integration Integration**
### **CI/CD Pipeline Testing**
```yaml
# Example GitHub Actions integration
- name: Run tests
run: |
npm ci
npm run test:coverage
- name: Upload coverage reports
uses: codecov/codecov-action@v3
with:
file: ./coverage/lcov.info
```
### **Pre-commit Hooks**
```bash
# Setup pre-commit testing (recommended)
# In package.json scripts:
"pre-commit": "npm run test:unit && npm run test:integration"
# Husky integration example:
npx husky add .husky/pre-commit "npm run test:unit"
```
## **Test Maintenance & Evolution**
### **Adding Tests for New Features**
1. **Create test file** alongside source code or in `tests/unit/`
2. **Follow established patterns** from `src/utils/auth.test.ts`
3. **Use existing fixtures** from `tests/fixtures/`
4. **Apply proper mocking** patterns for dependencies
5. **Meet coverage thresholds** for the module
### **Updating Integration/E2E Tests**
1. **Update templates** in `tests/integration/` when APIs change
2. **Modify E2E workflows** in `tests/e2e/` for new user journeys
3. **Update test fixtures** for new data requirements
4. **Maintain database cleanup** utilities
### **Test Performance Optimization**
- **Parallel execution**: Jest runs tests in parallel by default
- **Test isolation**: Use proper setup/teardown for independence
- **Mock optimization**: Mock heavy dependencies appropriately
- **Database efficiency**: Use transaction rollbacks where possible
---
**Key References:**
- [Testing Standards](mdc:.cursor/rules/tests.mdc)
- [Git Workflow](mdc:.cursor/rules/git_workflow.mdc)
- [Development Workflow](mdc:.cursor/rules/dev_workflow.mdc)
- [Jest Configuration](mdc:jest.config.js)
- [Auth Test Example](mdc:src/utils/auth.test.ts)

228
.cursor/rules/telemetry.mdc Normal file
View File

@@ -0,0 +1,228 @@
---
description: Guidelines for integrating AI usage telemetry across Task Master.
globs: scripts/modules/**/*.js,mcp-server/src/**/*.js
alwaysApply: true
---
# AI Usage Telemetry Integration
This document outlines the standard pattern for capturing, propagating, and handling AI usage telemetry data (cost, tokens, model, etc.) across the Task Master stack. This ensures consistent telemetry for both CLI and MCP interactions.
## Overview
Telemetry data is generated within the unified AI service layer ([`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)) and then passed upwards through the calling functions.
- **Data Source**: [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js) (specifically its `generateTextService`, `generateObjectService`, etc.) returns an object like `{ mainResult: AI_CALL_OUTPUT, telemetryData: TELEMETRY_OBJECT }`.
- **`telemetryData` Object Structure**:
```json
{
"timestamp": "ISO_STRING_DATE",
"userId": "USER_ID_FROM_CONFIG",
"commandName": "invoking_command_or_tool_name",
"modelUsed": "ai_model_id",
"providerName": "ai_provider_name",
"inputTokens": NUMBER,
"outputTokens": NUMBER,
"totalTokens": NUMBER,
"totalCost": NUMBER, // e.g., 0.012414
"currency": "USD" // e.g., "USD"
}
```
## Integration Pattern by Layer
The key principle is that each layer receives telemetry data from the layer below it (if applicable) and passes it to the layer above it, or handles it for display in the case of the CLI.
### 1. Core Logic Functions (e.g., in `scripts/modules/task-manager/`)
Functions in this layer that invoke AI services are responsible for handling the `telemetryData` they receive from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
- **Actions**:
1. Call the appropriate AI service function (e.g., `generateObjectService`).
- Pass `commandName` (e.g., `add-task`, `expand-task`) and `outputType` (e.g., `cli` or `mcp`) in the `params` object to the AI service. The `outputType` can be derived from context (e.g., presence of `mcpLog`).
2. The AI service returns an object, e.g., `aiServiceResponse = { mainResult: {/*AI output*/}, telemetryData: {/*telemetry data*/} }`.
3. Extract `aiServiceResponse.mainResult` for the core processing.
4. **Must return an object that includes `aiServiceResponse.telemetryData`**.
Example: `return { operationSpecificData: /*...*/, telemetryData: aiServiceResponse.telemetryData };`
- **CLI Output Handling (If Applicable)**:
- If the core function also handles CLI output (e.g., it has an `outputFormat` parameter that can be `'text'` or `'cli'`):
1. Check if `outputFormat === 'text'` (or `'cli'`).
2. If so, and if `aiServiceResponse.telemetryData` is available, call `displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli')` from [`scripts/modules/ui.js`](mdc:scripts/modules/ui.js).
- This ensures telemetry is displayed directly to CLI users after the main command output.
- **Example Snippet (Core Logic in `scripts/modules/task-manager/someAiAction.js`)**:
```javascript
import { generateObjectService } from '../ai-services-unified.js';
import { displayAiUsageSummary } from '../ui.js';
async function performAiRelatedAction(params, context, outputFormat = 'text') {
const { commandNameFromContext, /* other context vars */ } = context;
let aiServiceResponse = null;
try {
aiServiceResponse = await generateObjectService({
// ... other parameters for AI service ...
commandName: commandNameFromContext || 'default-action-name',
outputType: context.mcpLog ? 'mcp' : 'cli' // Derive outputType
});
const usefulAiOutput = aiServiceResponse.mainResult.object;
// ... do work with usefulAiOutput ...
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
return {
actionData: /* results of processing */,
telemetryData: aiServiceResponse.telemetryData
};
} catch (error) {
// ... handle error ...
throw error;
}
}
```
### 2. Direct Function Wrappers (in `mcp-server/src/core/direct-functions/`)
These functions adapt core logic for the MCP server, ensuring structured responses.
- **Actions**:
1. Call the corresponding core logic function.
- Pass necessary context (e.g., `session`, `mcpLog`, `projectRoot`).
- Provide the `commandName` (typically derived from the MCP tool name) and `outputType: 'mcp'` in the context object passed to the core function.
- If the core function supports an `outputFormat` parameter, pass `'json'` to suppress CLI-specific UI.
2. The core logic function returns an object (e.g., `coreResult = { actionData: ..., telemetryData: ... }`).
3. Include `coreResult.telemetryData` as a field within the `data` object of the successful response returned by the direct function.
- **Example Snippet (Direct Function `someAiActionDirect.js`)**:
```javascript
import { performAiRelatedAction } from '../../../../scripts/modules/task-manager/someAiAction.js'; // Core function
import { createLogWrapper } from '../../tools/utils.js'; // MCP Log wrapper
export async function someAiActionDirect(args, log, context = {}) {
const { session } = context;
// ... prepare arguments for core function from args, including args.projectRoot ...
try {
const coreResult = await performAiRelatedAction(
{ /* parameters for core function */ },
{ // Context for core function
session,
mcpLog: createLogWrapper(log),
projectRoot: args.projectRoot,
commandNameFromContext: 'mcp_tool_some_ai_action', // Example command name
outputType: 'mcp'
},
'json' // Request 'json' output format from core function
);
return {
success: true,
data: {
operationSpecificData: coreResult.actionData,
telemetryData: coreResult.telemetryData // Pass telemetry through
}
};
} catch (error) {
// ... error handling, return { success: false, error: ... } ...
}
}
```
### 3. MCP Tools (in `mcp-server/src/tools/`)
These are the exposed endpoints for MCP clients.
- **Actions**:
1. Call the corresponding direct function wrapper.
2. The direct function returns an object structured like `{ success: true, data: { operationSpecificData: ..., telemetryData: ... } }` (or an error object).
3. Pass this entire result object to `handleApiResult(result, log)` from [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
4. `handleApiResult` ensures that the `data` field from the direct function's response (which correctly includes `telemetryData`) is part of the final MCP response.
- **Example Snippet (MCP Tool `some_ai_action.js`)**:
```javascript
import { someAiActionDirect } from '../core/task-master-core.js';
import { handleApiResult, withNormalizedProjectRoot } from './utils.js';
// ... zod for parameters ...
export function registerSomeAiActionTool(server) {
server.addTool({
name: "some_ai_action",
// ... description, parameters ...
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
const resultFromDirectFunction = await someAiActionDirect(
{ /* args including projectRoot */ },
log,
{ session }
);
return handleApiResult(resultFromDirectFunction, log); // This passes the nested telemetryData through
} catch (error) {
// ... error handling ...
}
})
});
}
```
### 4. CLI Commands (`scripts/modules/commands.js`)
These define the command-line interface.
- **Actions**:
1. Call the appropriate core logic function.
2. Pass `outputFormat: 'text'` (or ensure the core function defaults to text-based output for CLI).
3. The core logic function (as per Section 1) is responsible for calling `displayAiUsageSummary` if telemetry data is available and it's in CLI mode.
4. The command action itself **should not** call `displayAiUsageSummary` if the core logic function already handles this. This avoids duplicate display.
- **Example Snippet (CLI Command in `commands.js`)**:
```javascript
// In scripts/modules/commands.js
import { performAiRelatedAction } from './task-manager/someAiAction.js'; // Core function
programInstance
.command('some-cli-ai-action')
// ... .option() ...
.action(async (options) => {
try {
const projectRoot = findProjectRoot() || '.'; // Example root finding
// ... prepare parameters for core function from command options ...
await performAiRelatedAction(
{ /* parameters for core function */ },
{ // Context for core function
projectRoot,
commandNameFromContext: 'some-cli-ai-action',
outputType: 'cli'
},
'text' // Explicitly request text output format for CLI
);
// Core function handles displayAiUsageSummary internally for 'text' outputFormat
} catch (error) {
// ... error handling ...
}
});
```
## Summary Flow
The telemetry data flows as follows:
1. **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)**: Generates `telemetryData` and returns `{ mainResult, telemetryData }`.
2. **Core Logic Function**:
* Receives `{ mainResult, telemetryData }`.
* Uses `mainResult`.
* If CLI (`outputFormat: 'text'`), calls `displayAiUsageSummary(telemetryData)`.
* Returns `{ operationSpecificData, telemetryData }`.
3. **Direct Function Wrapper**:
* Receives `{ operationSpecificData, telemetryData }` from core logic.
* Returns `{ success: true, data: { operationSpecificData, telemetryData } }`.
4. **MCP Tool**:
* Receives direct function response.
* `handleApiResult` ensures the final MCP response to the client is `{ success: true, data: { operationSpecificData, telemetryData } }`.
5. **CLI Command**:
* Calls core logic with `outputFormat: 'text'`. Display is handled by core logic.
This pattern ensures telemetry is captured and appropriately handled/exposed across all interaction modes.

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

@@ -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,56 @@ 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.

View File

@@ -7,3 +7,9 @@ MISTRAL_API_KEY=YOUR_MISTRAL_KEY_HERE
OPENROUTER_API_KEY=YOUR_OPENROUTER_KEY_HERE
XAI_API_KEY=YOUR_XAI_KEY_HERE
AZURE_OPENAI_API_KEY=YOUR_AZURE_KEY_HERE
# Google Vertex AI Configuration
VERTEX_PROJECT_ID=your-gcp-project-id
VERTEX_LOCATION=us-central1
# Optional: Path to service account credentials JSON file (alternative to API key)
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json

40
.github/workflows/update-models-md.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: Update models.md from supported-models.json
on:
push:
branches:
- main
- next
paths:
- 'scripts/modules/supported-models.json'
- 'docs/scripts/models-json-to-markdown.js'
jobs:
update_markdown:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Run transformation script
run: node docs/scripts/models-json-to-markdown.js
- name: Format Markdown with Prettier
run: npx prettier --write docs/models.md
- name: Stage docs/models.md
run: git add docs/models.md
- name: Commit & Push docs/models.md
uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref_name }}
message: 'docs: Auto-update and format models.md'
author_name: 'github-actions[bot]'
author_email: 'github-actions[bot]@users.noreply.github.com'

33
.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
@@ -64,3 +77,17 @@ dev-debug.log
# NPMRC
.npmrc
# Added by Claude Task Master
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# OS specific
# Task files
tasks.json
tasks/

1
.nvmrc Normal file
View File

@@ -0,0 +1 @@
22

View File

@@ -1,7 +0,0 @@
# Ignore artifacts:
build
coverage
.changeset
tasks
package-lock.json
tests/fixture/*.json

View File

@@ -1,11 +0,0 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": true,
"semi": true,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "lf"
}

View File

@@ -2,8 +2,8 @@
"models": {
"main": {
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 100000,
"modelId": "claude-sonnet-4-20250514",
"maxTokens": 64000,
"temperature": 0.2
},
"research": {
@@ -14,8 +14,8 @@
},
"fallback": {
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 120000,
"modelId": "claude-3-5-sonnet-20241022",
"maxTokens": 64000,
"temperature": 0.2
}
},
@@ -25,7 +25,13 @@
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Taskmaster",
"ollamaBaseUrl": "http://localhost:11434/api",
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
"ollamaBaseURL": "http://localhost:11434/api",
"azureBaseURL": "https://your-endpoint.azure.com/"
},
"account": {
"userId": "1234567890",
"email": "",
"mode": "byok",
"telemetryEnabled": true
}
}

View File

@@ -1,5 +1,299 @@
# task-master-ai
## 0.15.0
### Minor Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
- **Robust Error Handling**:
- Detects when Ollama server is not running and provides clear error messages
- Validates model existence and lists available alternatives when model not found
- Graceful fallback behavior for connection issues
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
- Added Mistral models: Devstral Small, Mistral Nemo
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
- Updated Gemini model to latest 2.5 Flash preview version
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
- Research current technologies and best practices relevant to the project
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
- Include specific library recommendations with version numbers
- Provide more detailed implementation guidance based on industry standards
- Create more accurate dependency relationships between tasks
This results in higher quality, more actionable tasks with minimal additional effort.
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
Status: DONE
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
**Usage:**
- CLI command: `task-master move --from=<id> --to=<id>`
- MCP tool: `move_task` with parameters:
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
- `to`: ID of destination (e.g., "7" or "7.3")
- `file` (optional): Custom path to tasks.json
**Example scenarios:**
- Move task to become subtask: `--from="5" --to="7"`
- Move subtask to standalone task: `--from="5.2" --to="7"`
- Move subtask to different parent: `--from="5.2" --to="7.3"`
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
**Multiple Task Support:**
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
**Validation Features:**
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- Ensures proper parent-child relationships are maintained
### Patch Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
## 0.15.0-rc.0
### Minor Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
- **Robust Error Handling**:
- Detects when Ollama server is not running and provides clear error messages
- Validates model existence and lists available alternatives when model not found
- Graceful fallback behavior for connection issues
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
- Added Mistral models: Devstral Small, Mistral Nemo
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
- Updated Gemini model to latest 2.5 Flash preview version
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
- Research current technologies and best practices relevant to the project
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
- Include specific library recommendations with version numbers
- Provide more detailed implementation guidance based on industry standards
- Create more accurate dependency relationships between tasks
This results in higher quality, more actionable tasks with minimal additional effort.
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
Status: DONE
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
**Usage:**
- CLI command: `task-master move --from=<id> --to=<id>`
- MCP tool: `move_task` with parameters:
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
- `to`: ID of destination (e.g., "7" or "7.3")
- `file` (optional): Custom path to tasks.json
**Example scenarios:**
- Move task to become subtask: `--from="5" --to="7"`
- Move subtask to standalone task: `--from="5.2" --to="7"`
- Move subtask to different parent: `--from="5.2" --to="7.3"`
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
**Multiple Task Support:**
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
**Validation Features:**
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- Ensures proper parent-child relationships are maintained
### Patch Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
## 0.14.0
### Minor Changes
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
- You can now add it by running `task-master models --setup` and selecting it.
- Ollama is a local model provider, so no API key is required.
- Ollama models are available at `http://localhost:11434/api` by default.
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
### Patch Changes
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Resolve all issues related to MCP
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
- Fixes #477
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add src directory to exports
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
- Fixes issues users where having where they were getting stale data
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
- Closes #419
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
- Ensures a clean, branded help experience with no repeated content.
- Fixes #339
## 0.14.0-rc.1
### Minor Changes
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
- You can now add it by running `task-master models --setup` and selecting it.
- Ollama is a local model provider, so no API key is required.
- Ollama models are available at `http://localhost:11434/api` by default.
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
### Patch Changes
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
## 0.14.0-rc.0
### Minor Changes
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
### Patch Changes
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
- Fixes #477
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
- Fixes issues users where having where they were getting stale data
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
- Closes #419
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
- Ensures a clean, branded help experience with no repeated content.
- Fixes #339
## 0.13.1
### Patch Changes

335
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,335 @@
# Contributing to Task Master
Thank you for your interest in contributing to Task Master! We're excited to work with you and appreciate your help in making this project better. 🚀
## 🤝 Our Collaborative Approach
We're a **PR-friendly team** that values collaboration:
-**We review PRs quickly** - Usually within hours, not days
-**We're super reactive** - Expect fast feedback and engagement
-**We sometimes take over PRs** - If your contribution is valuable but needs cleanup, we might jump in to help finish it
-**We're open to all contributions** - From bug fixes to major features
**We don't mind AI-generated code**, but we do expect you to:
-**Review and understand** what the AI generated
-**Test the code thoroughly** before submitting
-**Ensure it's well-written** and follows our patterns
-**Don't submit "AI slop"** - untested, unreviewed AI output
> **Why this matters**: We spend significant time reviewing PRs. Help us help you by submitting quality contributions that save everyone time!
## 🚀 Quick Start for Contributors
### 1. Fork and Clone
```bash
git clone https://github.com/YOUR_USERNAME/claude-task-master.git
cd claude-task-master
npm install
```
### 2. Create a Feature Branch
**Important**: Always target the `next` branch, not `main`:
```bash
git checkout next
git pull origin next
git checkout -b feature/your-feature-name
```
### 3. Make Your Changes
Follow our development guidelines below.
### 4. Test Everything Yourself
**Before submitting your PR**, ensure:
```bash
# Run all tests
npm test
# Check formatting
npm run format-check
# Fix formatting if needed
npm run format
```
### 5. Create a Changeset
**Required for most changes**:
```bash
npm run changeset
```
See the [Changeset Guidelines](#changeset-guidelines) below for details.
### 6. Submit Your PR
- Target the `next` branch
- Write a clear description
- Reference any related issues
## 📋 Development Guidelines
### Branch Strategy
- **`main`**: Production-ready code
- **`next`**: Development branch - **target this for PRs**
- **Feature branches**: `feature/description` or `fix/description`
### Code Quality Standards
1. **Write tests** for new functionality
2. **Follow existing patterns** in the codebase
3. **Add JSDoc comments** for functions
4. **Keep functions focused** and single-purpose
### Testing Requirements
Your PR **must pass all CI checks**:
-**Unit tests**: `npm test`
-**Format check**: `npm run format-check`
**Test your changes locally first** - this saves review time and shows you care about quality.
## 📦 Changeset Guidelines
We use [Changesets](https://github.com/changesets/changesets) to manage versioning and generate changelogs.
### When to Create a Changeset
**Always create a changeset for**:
- ✅ New features
- ✅ Bug fixes
- ✅ Breaking changes
- ✅ Performance improvements
- ✅ User-facing documentation updates
- ✅ Dependency updates that affect functionality
**Skip changesets for**:
- ❌ Internal documentation only
- ❌ Test-only changes
- ❌ Code formatting/linting
- ❌ Development tooling that doesn't affect users
### How to Create a Changeset
1. **After making your changes**:
```bash
npm run changeset
```
2. **Choose the bump type**:
- **Major**: Breaking changes
- **Minor**: New features
- **Patch**: Bug fixes, docs, performance improvements
3. **Write a clear summary**:
```
Add support for custom AI models in MCP configuration
```
4. **Commit the changeset file** with your changes:
```bash
git add .changeset/*.md
git commit -m "feat: add custom AI model support"
```
### Changeset vs Git Commit Messages
- **Changeset summary**: User-facing, goes in CHANGELOG.md
- **Git commit**: Developer-facing, explains the technical change
Example:
```bash
# Changeset summary (user-facing)
"Add support for custom Ollama models"
# Git commit message (developer-facing)
"feat(models): implement custom Ollama model validation
- Add model validation for custom Ollama endpoints
- Update configuration schema to support custom models
- Add tests for new validation logic"
```
## 🔧 Development Setup
### Prerequisites
- Node.js 14+
- npm or yarn
### Environment Setup
1. **Copy environment template**:
```bash
cp .env.example .env
```
2. **Add your API keys** (for testing AI features):
```bash
ANTHROPIC_API_KEY=your_key_here
OPENAI_API_KEY=your_key_here
# Add others as needed
```
### Running Tests
```bash
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run with coverage
npm run test:coverage
# Run E2E tests
npm run test:e2e
```
### Code Formatting
We use Prettier for consistent formatting:
```bash
# Check formatting
npm run format-check
# Fix formatting
npm run format
```
## 📝 PR Guidelines
### Before Submitting
- [ ] **Target the `next` branch**
- [ ] **Test everything locally**
- [ ] **Run the full test suite**
- [ ] **Check code formatting**
- [ ] **Create a changeset** (if needed)
- [ ] **Re-read your changes** - ensure they're clean and well-thought-out
### PR Description Template
```markdown
## Description
Brief description of what this PR does.
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
- [ ] I have tested this locally
- [ ] All existing tests pass
- [ ] I have added tests for new functionality
## Changeset
- [ ] I have created a changeset (or this change doesn't need one)
## Additional Notes
Any additional context or notes for reviewers.
```
### What We Look For
✅ **Good PRs**:
- Clear, focused changes
- Comprehensive testing
- Good commit messages
- Proper changeset (when needed)
- Self-reviewed code
❌ **Avoid**:
- Massive PRs that change everything
- Untested code
- Formatting issues
- Missing changesets for user-facing changes
- AI-generated code that wasn't reviewed
## 🏗️ Project Structure
```
claude-task-master/
├── bin/ # CLI executables
├── mcp-server/ # MCP server implementation
├── scripts/ # Core task management logic
├── src/ # Shared utilities and providers and well refactored code (we are slowly moving everything here)
├── tests/ # Test files
├── docs/ # Documentation
└── .cursor/ # Cursor IDE rules and configuration
└── assets/ # Assets like rules and configuration for all IDEs
```
### Key Areas for Contribution
- **CLI Commands**: `scripts/modules/commands.js`
- **MCP Tools**: `mcp-server/src/tools/`
- **Core Logic**: `scripts/modules/task-manager/`
- **AI Providers**: `src/ai-providers/`
- **Tests**: `tests/`
## 🐛 Reporting Issues
### Bug Reports
Include:
- Task Master version
- Node.js version
- Operating system
- Steps to reproduce
- Expected vs actual behavior
- Error messages/logs
### Feature Requests
Include:
- Clear description of the feature
- Use case/motivation
- Proposed implementation (if you have ideas)
- Willingness to contribute
## 💬 Getting Help
- **Discord**: [Join our community](https://discord.gg/taskmasterai)
- **Issues**: [GitHub Issues](https://github.com/eyaltoledano/claude-task-master/issues)
- **Discussions**: [GitHub Discussions](https://github.com/eyaltoledano/claude-task-master/discussions)
## 📄 License
By contributing, you agree that your contributions will be licensed under the same license as the project (MIT with Commons Clause).
---
**Thank you for contributing to Task Master!** 🎉
Your contributions help make AI-driven development more accessible and efficient for everyone.

115
README.md
View File

@@ -11,20 +11,67 @@ A task management system for AI-driven development with Claude, designed to work
## Requirements
Taskmaster utilizes AI across several commands, and those require a separate API key. You can use a variety of models from different AI providers provided you add your API keys. For example, if you want to use Claude 3.7, you'll need an Anthropic API key.
You can define 3 types of models to be used: the main model, the research model, and the fallback model (in case either the main or research fail). Whatever model you use, its provider API key must be present in either mcp.json or .env.
At least one (1) of the following is required:
- Anthropic API key (Claude API)
- OpenAI SDK (for Perplexity API integration, optional)
- OpenAI API key
- Google Gemini API key
- Perplexity API key (for research model)
- xAI API Key (for research or main model)
- OpenRouter API Key (for research or main model)
Using the research model is optional but highly recommended. You will need at least ONE API key. Adding all API keys enables you to seamlessly switch between model providers at will.
## Quick Start
### Option 1 | MCP (Recommended):
### Option 1: MCP (Recommended)
MCP (Model Control Protocol) provides the easiest way to get started with Task Master directly in your editor.
MCP (Model Control Protocol) lets you run Task Master directly from your editor.
1. **Add the MCP config to your editor** (Cursor recommended, but it works with other text editors):
#### 1. Add your MCP config at the following path depending on your editor
```json
| Editor | Scope | Linux/macOS Path | Windows Path | Key |
| ------------ | ------- | ------------------------------------- | ------------------------------------------------- | ------------ |
| **Cursor** | Global | `~/.cursor/mcp.json` | `%USERPROFILE%\.cursor\mcp.json` | `mcpServers` |
| | Project | `<project_folder>/.cursor/mcp.json` | `<project_folder>\.cursor\mcp.json` | `mcpServers` |
| **Windsurf** | Global | `~/.codeium/windsurf/mcp_config.json` | `%USERPROFILE%\.codeium\windsurf\mcp_config.json` | `mcpServers` |
| **VSCode** | Project | `<project_folder>/.vscode/mcp.json` | `<project_folder>\.vscode\mcp.json` | `servers` |
##### Cursor & Windsurf (`mcpServers`)
```jsonc
{
"mcpServers": {
"taskmaster-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
"OPENAI_API_KEY": "YOUR_OPENAI_KEY_HERE",
"GOOGLE_API_KEY": "YOUR_GOOGLE_KEY_HERE",
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE",
"OLLAMA_API_KEY": "YOUR_OLLAMA_API_KEY_HERE"
}
}
}
}
```
> 🔑 Replace `YOUR_…_KEY_HERE` with your real API keys. You can remove keys you don't use.
##### VSCode (`servers` + `type`)
```jsonc
{
"servers": {
"taskmaster-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
@@ -37,29 +84,59 @@ MCP (Model Control Protocol) provides the easiest way to get started with Task M
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE"
}
},
"type": "stdio"
}
}
}
```
2. **Enable the MCP** in your editor
> 🔑 Replace `YOUR_…_KEY_HERE` with your real API keys. You can remove keys you don't use.
3. **Prompt the AI** to initialize Task Master:
#### 2. (Cursor-only) Enable Taskmaster MCP
```
Can you please initialize taskmaster-ai into my project?
```
Open Cursor Settings (Ctrl+Shift+J) ➡ Click on MCP tab on the left ➡ Enable task-master-ai with the toggle
4. **Use common commands** directly through your AI assistant:
#### 3. (Optional) Configure the models you want to use
In your editors AI chat pane, say:
```txt
Can you parse my PRD at scripts/prd.txt?
What's the next task I should work on?
Can you help me implement task 3?
Can you help me expand task 4?
Change the main, research and fallback models to <model_name>, <model_name> and <model_name> respectively.
```
[Table of available models](docs/models.md)
#### 4. Initialize Task Master
In your editors AI chat pane, say:
```txt
Initialize taskmaster-ai in my project
```
#### 5. Make sure you have a PRD in `<project_folder>/scripts/prd.txt`
An example of a PRD is located into `<project_folder>/scripts/example_prd.txt`.
**Always start with a detailed PRD.**
The more detailed your PRD, the better the generated tasks will be.
#### 6. Common Commands
Use your AI assistant to:
- Parse requirements: `Can you parse my PRD at scripts/prd.txt?`
- Plan next step: `Whats the next task I should work on?`
- Implement a task: `Can you help me implement task 3?`
- View multiple tasks: `Can you show me tasks 1, 3, and 5?`
- Expand a task: `Can you help me expand task 4?`
- **Research fresh information**: `Research the latest best practices for implementing JWT authentication with Node.js`
- **Research with context**: `Research React Query v5 migration strategies for our current API implementation in src/api.js`
[More examples on how to use Task Master in chat](docs/examples.md)
### Option 2: Using Command Line
#### Installation
@@ -99,6 +176,12 @@ task-master list
# Show the next task to work on
task-master next
# Show specific task(s) - supports comma-separated IDs
task-master show 1,3,5
# Research fresh information with project context
task-master research "What are the latest best practices for JWT authentication?"
# Generate task files
task-master generate
```

View File

@@ -1,31 +0,0 @@
{
"models": {
"main": {
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 120000,
"temperature": 0.2
},
"research": {
"provider": "perplexity",
"modelId": "sonar-pro",
"maxTokens": 8700,
"temperature": 0.1
},
"fallback": {
"provider": "anthropic",
"modelId": "claude-3-5-sonnet-20240620",
"maxTokens": 8192,
"temperature": 0.1
}
},
"global": {
"logLevel": "info",
"debug": false,
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Taskmaster",
"ollamaBaseUrl": "http://localhost:11434/api",
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
}
}

413
assets/AGENTS.md Normal file
View File

@@ -0,0 +1,413 @@
# Task Master AI - Claude Code Integration Guide
## Essential Commands
### Core Workflow Commands
```bash
# Project Setup
task-master init # Initialize Task Master in current project
task-master parse-prd scripts/prd.txt # Generate tasks from PRD document
task-master models --setup # Configure AI models interactively
# Daily Development Workflow
task-master list # Show all tasks with status
task-master next # Get next available task to work on
task-master show <id> # View detailed task information (e.g., task-master show 1.2)
task-master set-status --id=<id> --status=done # Mark task complete
# Task Management
task-master add-task --prompt="description" --research # Add new task with AI assistance
task-master expand --id=<id> --research --force # Break task into subtasks
task-master update-task --id=<id> --prompt="changes" # Update specific task
task-master update --from=<id> --prompt="changes" # Update multiple tasks from ID onwards
task-master update-subtask --id=<id> --prompt="notes" # Add implementation notes to subtask
# Analysis & Planning
task-master analyze-complexity --research # Analyze task complexity
task-master complexity-report # View complexity analysis
task-master expand --all --research # Expand all eligible tasks
# Dependencies & Organization
task-master add-dependency --id=<id> --depends-on=<id> # Add task dependency
task-master move --from=<id> --to=<id> # Reorganize task hierarchy
task-master validate-dependencies # Check for dependency issues
task-master generate # Update task markdown files (usually auto-called)
```
## Key Files & Project Structure
### Core Files
- `tasks/tasks.json` - Main task data file (auto-managed)
- `.taskmasterconfig` - AI model configuration (use `task-master models` to modify)
- `scripts/prd.txt` - Product Requirements Document for parsing
- `tasks/*.txt` - Individual task files (auto-generated from tasks.json)
- `.env` - API keys for CLI usage
### Claude Code Integration Files
- `CLAUDE.md` - Auto-loaded context for Claude Code (this file)
- `.claude/settings.json` - Claude Code tool allowlist and preferences
- `.claude/commands/` - Custom slash commands for repeated workflows
- `.mcp.json` - MCP server configuration (project-specific)
### Directory Structure
```
project/
├── tasks/
│ ├── tasks.json # Main task database
│ ├── task-1.md # Individual task files
│ └── task-2.md
├── scripts/
│ ├── prd.txt # Product requirements
│ └── task-complexity-report.json
├── .claude/
│ ├── settings.json # Claude Code configuration
│ └── commands/ # Custom slash commands
├── .taskmasterconfig # AI models & settings
├── .env # API keys
├── .mcp.json # MCP configuration
└── CLAUDE.md # This file - auto-loaded by Claude Code
```
## MCP Integration
Task Master provides an MCP server that Claude Code can connect to. Configure in `.mcp.json`:
```json
{
"mcpServers": {
"task-master-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "your_key_here",
"PERPLEXITY_API_KEY": "your_key_here",
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
"XAI_API_KEY": "XAI_API_KEY_HERE",
"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"
}
}
}
}
```
### Essential MCP Tools
```javascript
help; // = shows available taskmaster commands
// Project setup
initialize_project; // = task-master init
parse_prd; // = task-master parse-prd
// Daily workflow
get_tasks; // = task-master list
next_task; // = task-master next
get_task; // = task-master show <id>
set_task_status; // = task-master set-status
// Task management
add_task; // = task-master add-task
expand_task; // = task-master expand
update_task; // = task-master update-task
update_subtask; // = task-master update-subtask
update; // = task-master update
// Analysis
analyze_project_complexity; // = task-master analyze-complexity
complexity_report; // = task-master complexity-report
```
## Claude Code Workflow Integration
### Standard Development Workflow
#### 1. Project Initialization
```bash
# Initialize Task Master
task-master init
# Create or obtain PRD, then parse it
task-master parse-prd scripts/prd.txt
# Analyze complexity and expand tasks
task-master analyze-complexity --research
task-master expand --all --research
```
If tasks already exist, another PRD can be parsed (with new information only!) using parse-prd with --append flag. This will add the generated tasks to the existing list of tasks..
#### 2. Daily Development Loop
```bash
# Start each session
task-master next # Find next available task
task-master show <id> # Review task details
# During implementation, check in code context into the tasks and subtasks
task-master update-subtask --id=<id> --prompt="implementation notes..."
# Complete tasks
task-master set-status --id=<id> --status=done
```
#### 3. Multi-Claude Workflows
For complex projects, use multiple Claude Code sessions:
```bash
# Terminal 1: Main implementation
cd project && claude
# Terminal 2: Testing and validation
cd project-test-worktree && claude
# Terminal 3: Documentation updates
cd project-docs-worktree && claude
```
### Custom Slash Commands
Create `.claude/commands/taskmaster-next.md`:
```markdown
Find the next available Task Master task and show its details.
Steps:
1. Run `task-master next` to get the next task
2. If a task is available, run `task-master show <id>` for full details
3. Provide a summary of what needs to be implemented
4. Suggest the first implementation step
```
Create `.claude/commands/taskmaster-complete.md`:
```markdown
Complete a Task Master task: $ARGUMENTS
Steps:
1. Review the current task with `task-master show $ARGUMENTS`
2. Verify all implementation is complete
3. Run any tests related to this task
4. Mark as complete: `task-master set-status --id=$ARGUMENTS --status=done`
5. Show the next available task with `task-master next`
```
## Tool Allowlist Recommendations
Add to `.claude/settings.json`:
```json
{
"allowedTools": [
"Edit",
"Bash(task-master *)",
"Bash(git commit:*)",
"Bash(git add:*)",
"Bash(npm run *)",
"mcp__task_master_ai__*"
]
}
```
## Configuration & Setup
### API Keys Required
At least **one** of these API keys must be configured:
- `ANTHROPIC_API_KEY` (Claude models) - **Recommended**
- `PERPLEXITY_API_KEY` (Research features) - **Highly recommended**
- `OPENAI_API_KEY` (GPT models)
- `GOOGLE_API_KEY` (Gemini models)
- `MISTRAL_API_KEY` (Mistral models)
- `OPENROUTER_API_KEY` (Multiple models)
- `XAI_API_KEY` (Grok models)
An API key is required for any provider used across any of the 3 roles defined in the `models` command.
### Model Configuration
```bash
# Interactive setup (recommended)
task-master models --setup
# Set specific models
task-master models --set-main claude-3-5-sonnet-20241022
task-master models --set-research perplexity-llama-3.1-sonar-large-128k-online
task-master models --set-fallback gpt-4o-mini
```
## Task Structure & IDs
### Task ID Format
- Main tasks: `1`, `2`, `3`, etc.
- Subtasks: `1.1`, `1.2`, `2.1`, etc.
- Sub-subtasks: `1.1.1`, `1.1.2`, etc.
### Task Status Values
- `pending` - Ready to work on
- `in-progress` - Currently being worked on
- `done` - Completed and verified
- `deferred` - Postponed
- `cancelled` - No longer needed
- `blocked` - Waiting on external factors
### Task Fields
```json
{
"id": "1.2",
"title": "Implement user authentication",
"description": "Set up JWT-based auth system",
"status": "pending",
"priority": "high",
"dependencies": ["1.1"],
"details": "Use bcrypt for hashing, JWT for tokens...",
"testStrategy": "Unit tests for auth functions, integration tests for login flow",
"subtasks": []
}
```
## Claude Code Best Practices with Task Master
### Context Management
- Use `/clear` between different tasks to maintain focus
- This CLAUDE.md file is automatically loaded for context
- Use `task-master show <id>` to pull specific task context when needed
### Iterative Implementation
1. `task-master show <subtask-id>` - Understand requirements
2. Explore codebase and plan implementation
3. `task-master update-subtask --id=<id> --prompt="detailed plan"` - Log plan
4. `task-master set-status --id=<id> --status=in-progress` - Start work
5. Implement code following logged plan
6. `task-master update-subtask --id=<id> --prompt="what worked/didn't work"` - Log progress
7. `task-master set-status --id=<id> --status=done` - Complete task
### Complex Workflows with Checklists
For large migrations or multi-step processes:
1. Create a markdown PRD file describing the new changes: `touch task-migration-checklist.md` (prds can be .txt or .md)
2. Use Taskmaster to parse the new prd with `task-master parse-prd --append` (also available in MCP)
3. Use Taskmaster to expand the newly generated tasks into subtasks. Consdier using `analyze-complexity` with the correct --to and --from IDs (the new ids) to identify the ideal subtask amounts for each task. Then expand them.
4. Work through items systematically, checking them off as completed
5. Use `task-master update-subtask` to log progress on each task/subtask and/or updating/researching them before/during implementation if getting stuck
### Git Integration
Task Master works well with `gh` CLI:
```bash
# Create PR for completed task
gh pr create --title "Complete task 1.2: User authentication" --body "Implements JWT auth system as specified in task 1.2"
# Reference task in commits
git commit -m "feat: implement JWT auth (task 1.2)"
```
### Parallel Development with Git Worktrees
```bash
# Create worktrees for parallel task development
git worktree add ../project-auth feature/auth-system
git worktree add ../project-api feature/api-refactor
# Run Claude Code in each worktree
cd ../project-auth && claude # Terminal 1: Auth work
cd ../project-api && claude # Terminal 2: API work
```
## Troubleshooting
### AI Commands Failing
```bash
# Check API keys are configured
cat .env # For CLI usage
# Verify model configuration
task-master models
# Test with different model
task-master models --set-fallback gpt-4o-mini
```
### MCP Connection Issues
- Check `.mcp.json` configuration
- Verify Node.js installation
- Use `--mcp-debug` flag when starting Claude Code
- Use CLI as fallback if MCP unavailable
### Task File Sync Issues
```bash
# Regenerate task files from tasks.json
task-master generate
# Fix dependency issues
task-master fix-dependencies
```
DO NOT RE-INITIALIZE. That will not do anything beyond re-adding the same Taskmaster core files.
## Important Notes
### AI-Powered Operations
These commands make AI calls and may take up to a minute:
- `parse_prd` / `task-master parse-prd`
- `analyze_project_complexity` / `task-master analyze-complexity`
- `expand_task` / `task-master expand`
- `expand_all` / `task-master expand --all`
- `add_task` / `task-master add-task`
- `update` / `task-master update`
- `update_task` / `task-master update-task`
- `update_subtask` / `task-master update-subtask`
### File Management
- Never manually edit `tasks.json` - use commands instead
- Never manually edit `.taskmasterconfig` - use `task-master models`
- Task markdown files in `tasks/` are auto-generated
- Run `task-master generate` after manual changes to tasks.json
### Claude Code Session Management
- Use `/clear` frequently to maintain focused context
- Create custom slash commands for repeated Task Master workflows
- Configure tool allowlist to streamline permissions
- Use headless mode for automation: `claude -p "task-master next"`
### Multi-Task Updates
- Use `update --from=<id>` to update multiple future tasks
- Use `update-task --id=<id>` for single task updates
- Use `update-subtask --id=<id>` for implementation logging
### Research Mode
- Add `--research` flag for research-based AI enhancement
- Requires a research model API key like Perplexity (`PERPLEXITY_API_KEY`) in environment
- Provides more informed task creation and updates
- Recommended for complex technical tasks
---
_This guide ensures Claude Code has immediate access to Task Master's essential functionality for agentic development workflows._

View File

@@ -6,3 +6,4 @@ GOOGLE_API_KEY="your_google_api_key_here" # Optional, for Google Gem
MISTRAL_API_KEY="your_mistral_key_here" # Optional, for Mistral AI models.
XAI_API_KEY="YOUR_XAI_KEY_HERE" # Optional, for xAI AI models.
AZURE_OPENAI_API_KEY="your_azure_key_here" # Optional, for Azure OpenAI models (requires endpoint in .taskmasterconfig).
OLLAMA_API_KEY="your_ollama_api_key_here" # Optional: For remote Ollama servers that require authentication.

View File

@@ -39,7 +39,7 @@
{
"slug": "debug",
"name": "Debug",
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mdode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
"customInstructions": "Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.",
"groups": [
"read",

47
biome.json Normal file
View File

@@ -0,0 +1,47 @@
{
"files": {
"ignore": [
"build",
"coverage",
".changeset",
"tasks",
"package-lock.json",
"tests/fixture/*.json"
]
},
"formatter": {
"bracketSpacing": true,
"enabled": true,
"indentStyle": "tab",
"lineWidth": 80
},
"javascript": {
"formatter": {
"arrowParentheses": "always",
"quoteStyle": "single",
"trailingCommas": "none"
}
},
"linter": {
"rules": {
"complexity": {
"noForEach": "off",
"useOptionalChain": "off"
},
"correctness": {
"noConstantCondition": "off",
"noUnreachable": "off"
},
"suspicious": {
"noDuplicateTestHooks": "off",
"noPrototypeBuiltins": "off"
},
"style": {
"noUselessElse": "off",
"useNodejsImportProtocol": "off",
"useNumberNamespace": "off",
"noParameterAssign": "off"
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,368 @@
We want to refine how Task Master handles AI model token limits to be more precise, by:
1. Distinguishing between `maxInputTokens` and `maxOutputTokens` in the configuration.
2. Dynamically adjusting the `maxOutputTokens` for an API call based on the actual prompt length to stay within the model's total context window (or respecting separate input/output limits if the API and model support that).
3. Ensuring that `ai-services-unified.js` uses these more granular limits.
This is a good improvement for both cost control and preventing errors.
Here's a plan:
**Phase 1: Configuration and Core Logic Updates**
1. **Update `.taskmasterconfig` Structure:**
- I'll modify the `models` section in your `.taskmasterconfig`. For each role (`main`, `research`, `fallback`), `maxTokens` will be replaced with `maxInputTokens` and `maxOutputTokens`.
- We'll need to decide on reasonable default values for these new fields. We can look at the current `maxTokens` and the model's known limits to make an initial guess.
2. **Update `MODEL_MAP` in `ai-services-unified.js`:**
- This array already stores cost data. We need to ensure it also stores the _absolute_ maximum input and output tokens for each model listed (e.g., `model_max_input_tokens`, `model_max_output_tokens`). If these fields are not present, they will need to be added. The values in `.taskmasterconfig` will then represent user-defined operational limits, which should ideally be validated against these absolute maximums.
3. **Update `config-manager.js`:**
- Getter functions like `getParametersForRole` will be updated to fetch `maxInputTokens` and `maxOutputTokens` instead of the singular `maxTokens`.
- New getters might be needed if we want to access the model's absolute limits directly from `MODEL_MAP` via `config-manager.js`.
4. **Update `ai-services-unified.js` (`_unifiedServiceRunner`):**
- **Token Counting:** This is a crucial step. Before an API call, we need to estimate the token count of the combined `systemPrompt` and `userPrompt`.
- The Vercel AI SDK or the individual provider SDKs might offer utilities for this. For example, some SDKs expose a `tokenizer` or a way to count tokens for a given string.
- If a direct utility isn't available through the Vercel SDK for the specific provider, we might need to use a library like `tiktoken` for OpenAI/Anthropic models or investigate provider-specific tokenization. This could be complex as tokenization varies between models.
- For now, let's assume we can get a reasonable estimate.
- **Dynamic Output Token Calculation & Validation:**
- Retrieve `configured_max_input_tokens` and `configured_max_output_tokens` from `config-manager.js` for the current role.
- Retrieve `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
- Let `prompt_tokens = countTokens(systemPrompt + userPrompt)`.
- **Input Validation:** If `prompt_tokens > configured_max_input_tokens` OR `prompt_tokens > model_absolute_max_input_tokens`, throw an error. (We might also consider auto-truncation strategies in the future, but an error is safer to start).
- **Output Calculation:** The `max_tokens` parameter sent to the API (which typically refers to the _max number of tokens to generate_) should be `configured_max_output_tokens`. We also need to ensure this doesn't violate the model's absolute output limit.
- Some models have a _total_ context window (input + output). If this is the case for a model, the `max_tokens` parameter for the API call might need to be `min(configured_max_output_tokens, model_absolute_total_tokens - prompt_tokens)`. However, many modern APIs handle separate input and output limits, simplifying this. We'll aim to pass `configured_max_output_tokens` as the API's `max_tokens` parameter, assuming the input validation has passed.
- **API Call Parameter:** Update the `callParams` to use the correctly determined `max_tokens` for generation (which will be our `configured_max_output_tokens`).
**Phase 2: Error Handling and Refinements**
1. **Enhanced Error Handling:** Provide clear error messages if prompt tokens exceed input limits, or if API calls fail due to token issues despite our calculations.
2. **Validation:** Add validation (perhaps in `config-manager.js` or when `task-master models --setup` is run) to ensure `configured_max_input_tokens` and `configured_max_output_tokens` in `.taskmasterconfig` do not exceed the `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
Let's start by inspecting `scripts/modules/config-manager.js` to see how parameters and `MODEL_MAP` are currently handled. This will inform the changes needed for `.taskmasterconfig` and `ai-services-unified.js`.
I will now read `scripts/modules/config-manager.js`.
Okay, I've reviewed `scripts/modules/config-manager.js`. Here's what I've gathered and how it impacts the plan:
- **`MODEL_MAP` Source:** `MODEL_MAP` is loaded from `supported-models.json`. This is excellent, as it means we can update the model capabilities (including new token limits) in a structured JSON file.
- **Configuration Loading:** `_loadAndValidateConfig` handles loading `.taskmasterconfig` and merging it with `DEFAULTS`.
- **Getters:** There are specific getters for `maxTokens` for each role (e.g., `getMainMaxTokens`). We will need to update these.
- **`getParametersForRole`:** This function already exists and is a good candidate for returning the new `maxInputTokens` and `maxOutputTokens`.
Here's the refined plan:
**Phase 1: Configuration and Data Structures**
1. **Update `supported-models.json`:**
- For each model entry in `supported-models.json`, we need to add `maxInputTokens` and `maxOutputTokens` fields. These should reflect the _absolute maximums_ for that specific model.
- Example entry change:
```json
// Before
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"context_window": 200000, // This might be total context
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"maxInputTokens": 190000, // Example
"maxOutputTokens": 8192, // Example, often smaller for generation
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
```
- I will need to find the official input/output token limits for the models currently in your `MODEL_MAP`. If you have this information handy, it would speed things up. Otherwise, I can make educated guesses or search for them.
2. **Update `.taskmasterconfig` (Defaults and User File):**
- In `scripts/modules/config-manager.js`, modify the `DEFAULTS` object. For each role (`main`, `research`, `fallback`), replace `maxTokens` with:
- `maxInputTokens`: A sensible default (e.g., a large portion of the model's capability, but user-configurable).
- `maxOutputTokens`: A sensible default for generation (e.g., 4096 or 8192).
- You will then need to manually update your existing `.taskmasterconfig` file to reflect this new structure. I can provide the snippet for you to paste.
3. **Update `config-manager.js`:**
- Modify `getParametersForRole(role, explicitRoot = null)`:
- It currently fetches `maxTokens` and `temperature`.
- Update it to fetch `maxInputTokens`, `maxOutputTokens`, and `temperature` from the loaded config for the given role.
- Remove the role-specific `getMaxTokens` functions (e.g., `getMainMaxTokens`, `getResearchMaxTokens`, `getFallbackMaxTokens`). The `getParametersForRole` will be the central way to get these.
- (Optional, for later validation) Consider adding a new function `getModelCapabilities(providerName, modelId)` that reads from `MODEL_MAP` to return the absolute `maxInputTokens` and `maxOutputTokens` for a given model. This would be useful for validating the user's settings in `.taskmasterconfig`.
**Phase 2: Core Logic in `ai-services-unified.js`**
1. **Token Counting (`_unifiedServiceRunner`):**
- This is the most complex part. We need a reliable way to count tokens for the prompts.
- **Strategy 1 (Ideal):** Leverage Vercel AI SDK. The SDK might provide a way to get a tokenizer for the active model or a utility function. We'll need to investigate its capabilities.
- **Strategy 2 (Fallback):** Use a library like `tiktoken` for models compatible with OpenAI's tokenization (many are, including some Anthropic models). For other models, we might need provider-specific tokenizers or make estimations (less ideal).
- **Initial Approach:** Let's try to find a Vercel AI SDK utility first. If not, we'll start with `tiktoken` as a common case and acknowledge that other models might need specific handling later.
- The function `_unifiedServiceRunner` will call this token counting utility:
```javascript
// Placeholder for token counting
function countTokens(text, modelId /* or providerName */) {
// ... implementation using SDK or library ...
// This is a simplification; actual tokenization is model-specific.
// For now, a rough estimate might be (text.length / 4) as a placeholder
// if a proper tokenizer isn't immediately available.
if (!text) return 0;
return Math.ceil(text.length / 3.5); // Very rough general estimate
}
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
```
2. **Dynamic Output Token Calculation & Validation (`_unifiedServiceRunner`):**
- Fetch parameters using the updated `getParametersForRole` from `config-manager.js`:
```javascript
const roleParams = getParametersForRole(
currentRole,
effectiveProjectRoot
);
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
```
- Fetch model's absolute limits from `MODEL_MAP` (we'll need a helper in `config-manager.js` or do it directly in `ai-services-unified.js` for now):
```javascript
// Simplified; ideally use a robust getter from config-manager
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
(m) => m.id === modelId
);
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
const modelAbsoluteMaxOutput =
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
```
- **Input Validation:**
```javascript
if (promptTokens > roleParams.maxInputTokens) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
);
}
if (promptTokens > modelAbsoluteMaxInput) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
);
}
```
- **API Call Parameter (`max_tokens` for generation):**
The `max_tokens` parameter passed to the provider's API call should be `roleParams.maxOutputTokens`. We must also ensure this doesn't exceed the model's absolute output capability.
```javascript
const apiMaxOutputTokens = Math.min(
roleParams.maxOutputTokens,
modelAbsoluteMaxOutput
);
const callParams = {
apiKey,
modelId,
// Use apiMaxOutputTokens for the actual API call
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
temperature: roleParams.temperature,
messages,
baseUrl,
...(serviceType === 'generateObject' && { schema, objectName }),
...restApiParams
};
```
3. **Update `logAiUsage`:**
- The cost calculation in `logAiUsage` seems correct as it already uses `inputCost` and `outputCost` per 1M tokens. This part should remain compatible.
**Next Steps:**
1. **Modify `supported-models.json`:** I need the content of this file to propose the new `maxInputTokens` and `maxOutputTokens` fields. Please provide it.
2. **Decide on Tokenizer Strategy:** What are your thoughts on the token counting? Are you aware of any utilities within Vercel AI SDK for this, or should we plan to integrate `tiktoken` initially?
Once I have the content of `supported-models.json`, I can draft the changes for it and then proceed to `config-manager.js` and `.taskmasterconfig`.
```json
// Before
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"context_window": 200000, // This might be total context
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"maxInputTokens": 190000, // Example
"maxOutputTokens": 8192, // Example, often smaller for generation
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
```
```javascript
// Placeholder for token counting
function countTokens(text, modelId /* or providerName */) {
// ... implementation using SDK or library ...
// This is a simplification; actual tokenization is model-specific.
// For now, a rough estimate might be (text.length / 4) as a placeholder
// if a proper tokenizer isn't immediately available.
if (!text) return 0;
return Math.ceil(text.length / 3.5); // Very rough general estimate
}
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
```
```javascript
const roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
```
```javascript
// Simplified; ideally use a robust getter from config-manager
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
(m) => m.id === modelId
);
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
const modelAbsoluteMaxOutput =
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
```
```javascript
if (promptTokens > roleParams.maxInputTokens) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
);
}
if (promptTokens > modelAbsoluteMaxInput) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
);
}
```
```javascript
const apiMaxOutputTokens = Math.min(
roleParams.maxOutputTokens,
modelAbsoluteMaxOutput
);
const callParams = {
apiKey,
modelId,
// Use apiMaxOutputTokens for the actual API call
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
temperature: roleParams.temperature,
messages,
baseUrl,
...(serviceType === 'generateObject' && { schema, objectName }),
...restApiParams
};
```
Okay, I have the contents of `supported-models.json`.
It seems many models have a `max_tokens` field, which I assume is the _total context window_. Some don't have it, and for others (like OpenAI `gpt-4o`), the listed `max_tokens` (16384) is known to be its _output_ token limit when using the Chat Completions API, while the context window is much larger (128k). This highlights the complexity: `max_tokens` in `supported-models.json` is used inconsistently.
**Revised Plan for `supported-models.json` and Token Definitions:**
To bring clarity, we'll introduce two new fields and ensure their meaning is consistent:
- `contextWindowTokens`: The total number of tokens the model can process (input + output). This would replace the current ambiguous `max_tokens`.
- `maxOutputTokens`: The maximum number of tokens the model can _generate_ in a single response. This is often smaller than the total context window, especially for larger models.
If a model _only_ specifies a total context window, we'll have to make a reasonable assumption for `maxOutputTokens` (e.g., 4096 or 8192, or a fraction of the total context window). If it only specifies an output token limit (like some OpenAI models in certain API modes), we'll need to find its total context window.
**Updated `supported-models.json` Structure (Example):**
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```
I will proceed to generate the updated `supported-models.json` content. This will be a significant change. I will make my best effort to find the correct `contextWindowTokens` and `maxOutputTokens` for each model. If official numbers are ambiguous or not readily available, I'll use sensible defaults and add a comment.
**Regarding Tokenizer Strategy:**
- **Vercel AI SDK:** The `ai` package (Vercel AI SDK) itself is a lightweight wrapper. Tokenization is usually handled by the underlying provider-specific SDKs (e.g., `@anthropic-ai/sdk`, `openai`). The Vercel SDK doesn't provide a universal tokenizer.
- **Provider SDKs:**
- `@anthropic-ai/sdk`: Does not expose a public tokenizer directly. Anthropic recommends counting based on their guidelines (roughly 3.5 chars/token for English).
- `openai` (for Node.js): The `gpt-3-encoder` or `tiktoken` libraries are commonly used. `tiktoken` is more current.
- **`tiktoken`:** This is a good general-purpose library for OpenAI models and those that use compatible tokenization (many models fine-tuned from Llama, etc., might be close). It supports various encodings.
- **Recommendation:**
1. Start by integrating `tiktoken`. We can select the encoding based on the provider or even specific model if needed (e.g., `cl100k_base` for gpt-4, gpt-3.5-turbo, DALL-E models).
2. For providers where `tiktoken` is not accurate (e.g., Google's Gemini, Perplexity if they have proprietary tokenizers), we might have to rely on character-based estimations (e.g., `length / N`) as a rougher guide or investigate if their specific SDKs offer token counting.
3. The Vercel AI SDK's `experimental_streamObject` and other functions _might_ internally handle some aspects of token counting for request preparation, but we need explicit counting for our logic _before_ the call.
For now, let's assume we'll add a `countTokens` utility that uses `tiktoken` for OpenAI and Anthropic (as Anthropic's guidance is character-based but `cl100k_base` is often a decent proxy for their tokenization for rough estimates, though not perfect), and a character-based fallback for others.
I will now generate the proposed changes for `scripts/modules/supported-models.json`. This will be a large diff.
After this, we'll move to:
1. Updating `.taskmasterconfig` defaults in `config-manager.js` and providing you the snippet for your user file.
2. Updating `config-manager.js` getters.
3. Implementing the logic in `ai-services-unified.js`.
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```

View File

@@ -9,7 +9,7 @@ Welcome to the Task Master documentation. Use the links below to navigate to the
## Reference
- [Command Reference](command-reference.md) - Complete list of all available commands
- [Command Reference](command-reference.md) - Complete list of all available commands (including research and multi-task viewing)
- [Task Structure](task-structure.md) - Understanding the task format and features
## Examples & Licensing

View File

@@ -43,10 +43,28 @@ task-master show <id>
# or
task-master show --id=<id>
# View multiple tasks with comma-separated IDs
task-master show 1,3,5
task-master show 44,55
# View a specific subtask (e.g., subtask 2 of task 1)
task-master show 1.2
# Mix parent tasks and subtasks
task-master show 44,44.1,55,55.2
```
**Multiple Task Display:**
- **Single ID**: Shows detailed task view with full implementation details
- **Multiple IDs**: Shows compact summary table with interactive action menu
- **Action Menu**: Provides copy-paste ready commands for batch operations:
- Mark all as in-progress/done
- Show next available task
- Expand all tasks (generate subtasks)
- View dependency relationships
- Generate task files
## Update Tasks
```bash
@@ -187,6 +205,32 @@ task-master validate-dependencies
task-master fix-dependencies
```
## Move Tasks
```bash
# Move a task or subtask to a new position
task-master move --from=<id> --to=<id>
# Examples:
# Move task to become a subtask
task-master move --from=5 --to=7
# Move subtask to become a standalone task
task-master move --from=5.2 --to=7
# Move subtask to a different parent
task-master move --from=5.2 --to=7.3
# Reorder subtasks within the same parent
task-master move --from=5.2 --to=5.4
# Move a task to a new ID position (creates placeholder if doesn't exist)
task-master move --from=5 --to=25
# Move multiple tasks at once (must have the same number of IDs)
task-master move --from=10,11,12 --to=16,17,18
```
## Add a New Task
```bash
@@ -236,3 +280,42 @@ task-master models --setup
```
Configuration is stored in `.taskmasterconfig` in your project root. API keys are still managed via `.env` or MCP configuration. Use `task-master models` without flags to see available built-in models. Use `--setup` for a guided experience.
## Research Fresh Information
```bash
# Perform AI-powered research with fresh, up-to-date information
task-master research "What are the latest best practices for JWT authentication in Node.js?"
# Research with specific task context
task-master research "How to implement OAuth 2.0?" --id=15,16
# Research with file context for code-aware suggestions
task-master research "How can I optimize this API implementation?" --files=src/api.js,src/auth.js
# Research with custom context and project tree
task-master research "Best practices for error handling" --context="We're using Express.js" --tree
# Research with different detail levels
task-master research "React Query v5 migration guide" --detail=high
# Save research results to a file
task-master research "Database optimization techniques" --save=research/db-optimization.md
```
**The research command is a powerful tool that provides:**
- **Fresh information beyond AI knowledge cutoffs**
- **Project-aware context** from your tasks and files
- **Automatic task discovery** using fuzzy search
- **Multiple detail levels** (low, medium, high)
- **Token counting and cost tracking**
- **Interactive follow-up questions**
**Use research frequently to:**
- Get current best practices before implementing features
- Research new technologies and libraries
- Find solutions to complex problems
- Validate your implementation approaches
- Stay updated with latest security recommendations

View File

@@ -16,14 +16,14 @@ Taskmaster uses two primary methods for configuration:
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 64000,
"temperature": 0.2,
"baseUrl": "https://api.anthropic.com/v1"
"baseURL": "https://api.anthropic.com/v1"
},
"research": {
"provider": "perplexity",
"modelId": "sonar-pro",
"maxTokens": 8700,
"temperature": 0.1,
"baseUrl": "https://api.perplexity.ai/v1"
"baseURL": "https://api.perplexity.ai/v1"
},
"fallback": {
"provider": "anthropic",
@@ -38,8 +38,10 @@ Taskmaster uses two primary methods for configuration:
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Your Project Name",
"ollamaBaseUrl": "http://localhost:11434/api",
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
"ollamaBaseURL": "http://localhost:11434/api",
"azureBaseURL": "https://your-endpoint.azure.com/",
"vertexProjectId": "your-gcp-project-id",
"vertexLocation": "us-central1"
}
}
```
@@ -53,15 +55,18 @@ Taskmaster uses two primary methods for configuration:
- `ANTHROPIC_API_KEY`: Your Anthropic API key.
- `PERPLEXITY_API_KEY`: Your Perplexity API key.
- `OPENAI_API_KEY`: Your OpenAI API key.
- `GOOGLE_API_KEY`: Your Google API key.
- `GOOGLE_API_KEY`: Your Google API key (also used for Vertex AI provider).
- `MISTRAL_API_KEY`: Your Mistral API key.
- `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key (also requires `AZURE_OPENAI_ENDPOINT`).
- `OPENROUTER_API_KEY`: Your OpenRouter API key.
- `XAI_API_KEY`: Your X-AI API key.
- **Optional Endpoint Overrides:**
- **Per-role `baseUrl` in `.taskmasterconfig`:** You can add a `baseUrl` property to any model role (`main`, `research`, `fallback`) to override the default API endpoint for that provider. If omitted, the provider's standard endpoint is used.
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key (can also be set as `baseUrl` for the Azure model role).
- **Per-role `baseURL` in `.taskmasterconfig`:** You can add a `baseURL` property to any model role (`main`, `research`, `fallback`) to override the default API endpoint for that provider. If omitted, the provider's standard endpoint is used.
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key (can also be set as `baseURL` for the Azure model role).
- `OLLAMA_BASE_URL`: Override the default Ollama API URL (Default: `http://localhost:11434/api`).
- `VERTEX_PROJECT_ID`: Your Google Cloud project ID for Vertex AI. Required when using the 'vertex' provider.
- `VERTEX_LOCATION`: Google Cloud region for Vertex AI (e.g., 'us-central1'). Default is 'us-central1'.
- `GOOGLE_APPLICATION_CREDENTIALS`: Path to service account credentials JSON file for Google Cloud auth (alternative to API key for Vertex AI).
**Important:** Settings like model ID selections (`main`, `research`, `fallback`), `maxTokens`, `temperature`, `logLevel`, `defaultSubtasks`, `defaultPriority`, and `projectName` are **managed in `.taskmasterconfig`**, not environment variables.
@@ -78,6 +83,11 @@ PERPLEXITY_API_KEY=pplx-your-key-here
# Optional Endpoint Overrides
# AZURE_OPENAI_ENDPOINT=https://your-azure-endpoint.openai.azure.com/
# OLLAMA_BASE_URL=http://custom-ollama-host:11434/api
# Google Vertex AI Configuration (Required if using 'vertex' provider)
# VERTEX_PROJECT_ID=your-gcp-project-id
# VERTEX_LOCATION=us-central1
# GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json
```
## Troubleshooting
@@ -102,3 +112,45 @@ git clone https://github.com/eyaltoledano/claude-task-master.git
cd claude-task-master
node scripts/init.js
```
## Provider-Specific Configuration
### Google Vertex AI Configuration
Google Vertex AI is Google Cloud's enterprise AI platform and requires specific configuration:
1. **Prerequisites**:
- A Google Cloud account with Vertex AI API enabled
- Either a Google API key with Vertex AI permissions OR a service account with appropriate roles
- A Google Cloud project ID
2. **Authentication Options**:
- **API Key**: Set the `GOOGLE_API_KEY` environment variable
- **Service Account**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to your service account JSON file
3. **Required Configuration**:
- Set `VERTEX_PROJECT_ID` to your Google Cloud project ID
- Set `VERTEX_LOCATION` to your preferred Google Cloud region (default: us-central1)
4. **Example Setup**:
```bash
# In .env file
GOOGLE_API_KEY=AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXX
VERTEX_PROJECT_ID=my-gcp-project-123
VERTEX_LOCATION=us-central1
```
Or using service account:
```bash
# In .env file
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
VERTEX_PROJECT_ID=my-gcp-project-123
VERTEX_LOCATION=us-central1
```
5. **In .taskmasterconfig**:
```json
"global": {
"vertexProjectId": "my-gcp-project-123",
"vertexLocation": "us-central1"
}
```

View File

@@ -21,6 +21,20 @@ What's the next task I should work on? Please consider dependencies and prioriti
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
```
## Viewing multiple tasks
```
Can you show me tasks 1, 3, and 5 so I can understand their relationship?
```
```
I need to see the status of tasks 44, 55, and their subtasks. Can you show me those?
```
```
Show me tasks 10, 12, and 15 and give me some batch actions I can perform on them.
```
## Managing subtasks
```
@@ -30,7 +44,7 @@ I need to regenerate the subtasks for task 3 with a different approach. Can you
## Handling changes
```
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
I've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
```
## Completing work
@@ -40,6 +54,34 @@ I've finished implementing the authentication system described in task 2. All te
Please mark it as complete and tell me what I should work on next.
```
## Reorganizing tasks
```
I think subtask 5.2 would fit better as part of task 7. Can you move it there?
```
(Agent runs: `task-master move --from=5.2 --to=7.3`)
```
Task 8 should actually be a subtask of task 4. Can you reorganize this?
```
(Agent runs: `task-master move --from=8 --to=4.1`)
```
I just merged the main branch and there's a conflict in tasks.json. My teammates created tasks 10-15 on their branch while I created tasks 10-12 on my branch. Can you help me resolve this by moving my tasks?
```
(Agent runs:
```bash
task-master move --from=10 --to=16
task-master move --from=11 --to=17
task-master move --from=12 --to=18
```
)
## Analyzing complexity
```
@@ -81,3 +123,56 @@ Please add a new task to implement user profile image uploads using Cloudinary,
```
(Agent runs: `task-master add-task --prompt="Implement user profile image uploads using Cloudinary" --research`)
## Research-Driven Development
### Getting Fresh Information
```
Research the latest best practices for implementing JWT authentication in Node.js applications.
```
(Agent runs: `task-master research "Latest best practices for JWT authentication in Node.js"`)
### Research with Project Context
```
I'm working on task 15 which involves API optimization. Can you research current best practices for our specific implementation?
```
(Agent runs: `task-master research "API optimization best practices" --id=15 --files=src/api.js`)
### Research Before Implementation
```
Before I implement task 8 (React Query integration), can you research the latest React Query v5 patterns and any breaking changes?
```
(Agent runs: `task-master research "React Query v5 patterns and breaking changes" --id=8`)
### Research and Update Pattern
```
Research the latest security recommendations for Express.js applications and update our authentication task with the findings.
```
(Agent runs:
1. `task-master research "Latest Express.js security recommendations" --id=12`
2. `task-master update-subtask --id=12.3 --prompt="Updated with latest security findings: [research results]"`)
### Research for Debugging
```
I'm having issues with our WebSocket implementation in task 20. Can you research common WebSocket problems and solutions?
```
(Agent runs: `task-master research "Common WebSocket implementation problems and solutions" --id=20 --files=src/websocket.js`)
### Research Technology Comparisons
```
We need to choose between Redis and Memcached for caching. Can you research the current recommendations for our use case?
```
(Agent runs: `task-master research "Redis vs Memcached 2024 comparison for session caching" --tree`)

125
docs/models.md Normal file
View File

@@ -0,0 +1,125 @@
# Available Models as of May 27, 2025
## Main Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | ---------------------------------------------- | --------- | ---------- | ----------- |
| anthropic | claude-sonnet-4-20250514 | 0.727 | 3 | 15 |
| anthropic | claude-opus-4-20250514 | 0.725 | 15 | 75 |
| anthropic | claude-3-7-sonnet-20250219 | 0.623 | 3 | 15 |
| anthropic | claude-3-5-sonnet-20241022 | 0.49 | 3 | 15 |
| openai | gpt-4o | 0.332 | 2.5 | 10 |
| openai | o1 | 0.489 | 15 | 60 |
| openai | o3 | 0.5 | 10 | 40 |
| openai | o3-mini | 0.493 | 1.1 | 4.4 |
| openai | o4-mini | 0.45 | 1.1 | 4.4 |
| openai | o1-mini | 0.4 | 1.1 | 4.4 |
| openai | o1-pro | — | 150 | 600 |
| openai | gpt-4-5-preview | 0.38 | 75 | 150 |
| openai | gpt-4-1-mini | — | 0.4 | 1.6 |
| openai | gpt-4-1-nano | — | 0.1 | 0.4 |
| openai | gpt-4o-mini | 0.3 | 0.15 | 0.6 |
| google | gemini-2.5-pro-preview-05-06 | 0.638 | — | — |
| google | gemini-2.5-pro-preview-03-25 | 0.638 | — | — |
| google | gemini-2.5-flash-preview-04-17 | — | — | — |
| google | gemini-2.0-flash | 0.754 | 0.15 | 0.6 |
| google | gemini-2.0-flash-lite | — | — | — |
| perplexity | sonar-reasoning-pro | 0.211 | 2 | 8 |
| perplexity | sonar-reasoning | 0.211 | 1 | 5 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
| ollama | devstral:latest | — | 0 | 0 |
| ollama | qwen3:latest | — | 0 | 0 |
| ollama | qwen3:14b | — | 0 | 0 |
| ollama | qwen3:32b | — | 0 | 0 |
| ollama | mistral-small3.1:latest | — | 0 | 0 |
| ollama | llama3.3:latest | — | 0 | 0 |
| ollama | phi4:latest | — | 0 | 0 |
| openrouter | google/gemini-2.5-flash-preview-05-20 | — | 0.15 | 0.6 |
| openrouter | google/gemini-2.5-flash-preview-05-20:thinking | — | 0.15 | 3.5 |
| openrouter | google/gemini-2.5-pro-exp-03-25 | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324:free | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324 | — | 0.27 | 1.1 |
| openrouter | openai/gpt-4.1 | — | 2 | 8 |
| openrouter | openai/gpt-4.1-mini | — | 0.4 | 1.6 |
| openrouter | openai/gpt-4.1-nano | — | 0.1 | 0.4 |
| openrouter | openai/o3 | — | 10 | 40 |
| openrouter | openai/codex-mini | — | 1.5 | 6 |
| openrouter | openai/gpt-4o-mini | — | 0.15 | 0.6 |
| openrouter | openai/o4-mini | 0.45 | 1.1 | 4.4 |
| openrouter | openai/o4-mini-high | — | 1.1 | 4.4 |
| openrouter | openai/o1-pro | — | 150 | 600 |
| openrouter | meta-llama/llama-3.3-70b-instruct | — | 120 | 600 |
| openrouter | meta-llama/llama-4-maverick | — | 0.18 | 0.6 |
| openrouter | meta-llama/llama-4-scout | — | 0.08 | 0.3 |
| openrouter | qwen/qwen-max | — | 1.6 | 6.4 |
| openrouter | qwen/qwen-turbo | — | 0.05 | 0.2 |
| openrouter | qwen/qwen3-235b-a22b | — | 0.14 | 2 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct:free | — | 0 | 0 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct | — | 0.1 | 0.3 |
| openrouter | mistralai/devstral-small | — | 0.1 | 0.3 |
| openrouter | mistralai/mistral-nemo | — | 0.03 | 0.07 |
| openrouter | thudm/glm-4-32b:free | — | 0 | 0 |
## Research Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | -------------------------- | --------- | ---------- | ----------- |
| openai | gpt-4o-search-preview | 0.33 | 2.5 | 10 |
| openai | gpt-4o-mini-search-preview | 0.3 | 0.15 | 0.6 |
| perplexity | sonar-pro | — | 3 | 15 |
| perplexity | sonar | — | 1 | 1 |
| perplexity | deep-research | 0.211 | 2 | 8 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
## Fallback Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | ---------------------------------------------- | --------- | ---------- | ----------- |
| anthropic | claude-sonnet-4-20250514 | 0.727 | 3 | 15 |
| anthropic | claude-opus-4-20250514 | 0.725 | 15 | 75 |
| anthropic | claude-3-7-sonnet-20250219 | 0.623 | 3 | 15 |
| anthropic | claude-3-5-sonnet-20241022 | 0.49 | 3 | 15 |
| openai | gpt-4o | 0.332 | 2.5 | 10 |
| openai | o3 | 0.5 | 10 | 40 |
| openai | o4-mini | 0.45 | 1.1 | 4.4 |
| google | gemini-2.5-pro-preview-05-06 | 0.638 | — | — |
| google | gemini-2.5-pro-preview-03-25 | 0.638 | — | — |
| google | gemini-2.5-flash-preview-04-17 | — | — | — |
| google | gemini-2.0-flash | 0.754 | 0.15 | 0.6 |
| google | gemini-2.0-flash-lite | — | — | — |
| perplexity | sonar-reasoning-pro | 0.211 | 2 | 8 |
| perplexity | sonar-reasoning | 0.211 | 1 | 5 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
| ollama | devstral:latest | — | 0 | 0 |
| ollama | qwen3:latest | — | 0 | 0 |
| ollama | qwen3:14b | — | 0 | 0 |
| ollama | qwen3:32b | — | 0 | 0 |
| ollama | mistral-small3.1:latest | — | 0 | 0 |
| ollama | llama3.3:latest | — | 0 | 0 |
| ollama | phi4:latest | — | 0 | 0 |
| openrouter | google/gemini-2.5-flash-preview-05-20 | — | 0.15 | 0.6 |
| openrouter | google/gemini-2.5-flash-preview-05-20:thinking | — | 0.15 | 3.5 |
| openrouter | google/gemini-2.5-pro-exp-03-25 | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324:free | — | 0 | 0 |
| openrouter | openai/gpt-4.1 | — | 2 | 8 |
| openrouter | openai/gpt-4.1-mini | — | 0.4 | 1.6 |
| openrouter | openai/gpt-4.1-nano | — | 0.1 | 0.4 |
| openrouter | openai/o3 | — | 10 | 40 |
| openrouter | openai/codex-mini | — | 1.5 | 6 |
| openrouter | openai/gpt-4o-mini | — | 0.15 | 0.6 |
| openrouter | openai/o4-mini | 0.45 | 1.1 | 4.4 |
| openrouter | openai/o4-mini-high | — | 1.1 | 4.4 |
| openrouter | openai/o1-pro | — | 150 | 600 |
| openrouter | meta-llama/llama-3.3-70b-instruct | — | 120 | 600 |
| openrouter | meta-llama/llama-4-maverick | — | 0.18 | 0.6 |
| openrouter | meta-llama/llama-4-scout | — | 0.08 | 0.3 |
| openrouter | qwen/qwen-max | — | 1.6 | 6.4 |
| openrouter | qwen/qwen-turbo | — | 0.05 | 0.2 |
| openrouter | qwen/qwen3-235b-a22b | — | 0.14 | 2 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct:free | — | 0 | 0 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct | — | 0.1 | 0.3 |
| openrouter | mistralai/mistral-nemo | — | 0.03 | 0.07 |
| openrouter | thudm/glm-4-32b:free | — | 0 | 0 |

View File

@@ -0,0 +1,131 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const supportedModelsPath = path.join(
__dirname,
'..',
'modules',
'supported-models.json'
);
const outputMarkdownPath = path.join(
__dirname,
'..',
'..',
'docs',
'models.md'
);
function formatCost(cost) {
if (cost === null || cost === undefined) {
return '—';
}
return cost;
}
function formatSweScore(score) {
if (score === null || score === undefined || score === 0) {
return '—';
}
return score.toString();
}
function generateMarkdownTable(title, models) {
if (!models || models.length === 0) {
return `## ${title}\n\nNo models in this category.\n\n`;
}
let table = `## ${title}\n\n`;
table += '| Provider | Model Name | SWE Score | Input Cost | Output Cost |\n';
table += '|---|---|---|---|---|\n';
models.forEach((model) => {
table += `| ${model.provider} | ${model.modelName} | ${formatSweScore(model.sweScore)} | ${formatCost(model.inputCost)} | ${formatCost(model.outputCost)} |\n`;
});
table += '\n';
return table;
}
function main() {
try {
const correctSupportedModelsPath = path.join(
__dirname,
'..',
'..',
'scripts',
'modules',
'supported-models.json'
);
const correctOutputMarkdownPath = path.join(__dirname, '..', 'models.md');
const supportedModelsContent = fs.readFileSync(
correctSupportedModelsPath,
'utf8'
);
const supportedModels = JSON.parse(supportedModelsContent);
const mainModels = [];
const researchModels = [];
const fallbackModels = [];
for (const provider in supportedModels) {
if (Object.hasOwnProperty.call(supportedModels, provider)) {
const models = supportedModels[provider];
models.forEach((model) => {
const modelEntry = {
provider: provider,
modelName: model.id,
sweScore: model.swe_score,
inputCost: model.cost_per_1m_tokens
? model.cost_per_1m_tokens.input
: null,
outputCost: model.cost_per_1m_tokens
? model.cost_per_1m_tokens.output
: null
};
if (model.allowed_roles.includes('main')) {
mainModels.push(modelEntry);
}
if (model.allowed_roles.includes('research')) {
researchModels.push(modelEntry);
}
if (model.allowed_roles.includes('fallback')) {
fallbackModels.push(modelEntry);
}
});
}
}
const date = new Date();
const monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
const formattedDate = `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
let markdownContent = `# Available Models as of ${formattedDate}\n\n`;
markdownContent += generateMarkdownTable('Main Models', mainModels);
markdownContent += generateMarkdownTable('Research Models', researchModels);
markdownContent += generateMarkdownTable('Fallback Models', fallbackModels);
fs.writeFileSync(correctOutputMarkdownPath, markdownContent, 'utf8');
console.log(`Successfully updated ${correctOutputMarkdownPath}`);
} catch (error) {
console.error('Error transforming models.json to models.md:', error);
process.exit(1);
}
}
main();

View File

@@ -198,10 +198,15 @@ Ask the agent to list available tasks:
What tasks are available to work on next?
```
```
Can you show me tasks 1, 3, and 5 to understand their current status?
```
The agent will:
- Run `task-master list` to see all tasks
- Run `task-master next` to determine the next task to work on
- Run `task-master show 1,3,5` to display multiple tasks with interactive options
- Analyze dependencies to determine which tasks are ready to be worked on
- Prioritize tasks based on priority level and ID order
- Suggest the next task(s) to implement
@@ -221,6 +226,21 @@ You can ask:
Let's implement task 3. What does it involve?
```
### 2.1. Viewing Multiple Tasks
For efficient context gathering and batch operations:
```
Show me tasks 5, 7, and 9 so I can plan my implementation approach.
```
The agent will:
- Run `task-master show 5,7,9` to display a compact summary table
- Show task status, priority, and progress indicators
- Provide an interactive action menu with batch operations
- Allow you to perform group actions like marking multiple tasks as in-progress
### 3. Task Verification
Before marking a task as complete, verify it according to:
@@ -268,7 +288,61 @@ task-master update --from=4 --prompt="Update to use MongoDB, researching best pr
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
### 6. Breaking Down Complex Tasks
### 6. Reorganizing Tasks
If you need to reorganize your task structure:
```
I think subtask 5.2 would fit better as part of task 7 instead. Can you move it there?
```
The agent will execute:
```bash
task-master move --from=5.2 --to=7.3
```
You can reorganize tasks in various ways:
- Moving a standalone task to become a subtask: `--from=5 --to=7`
- Moving a subtask to become a standalone task: `--from=5.2 --to=7`
- Moving a subtask to a different parent: `--from=5.2 --to=7.3`
- Reordering subtasks within the same parent: `--from=5.2 --to=5.4`
- Moving a task to a new ID position: `--from=5 --to=25` (even if task 25 doesn't exist yet)
- Moving multiple tasks at once: `--from=10,11,12 --to=16,17,18` (must have same number of IDs, Taskmaster will look through each position)
When moving tasks to new IDs:
- The system automatically creates placeholder tasks for non-existent destination IDs
- This prevents accidental data loss during reorganization
- Any tasks that depend on moved tasks will have their dependencies updated
- When moving a parent task, all its subtasks are automatically moved with it and renumbered
This is particularly useful as your project understanding evolves and you need to refine your task structure.
### 7. Resolving Merge Conflicts with Tasks
When working with a team, you might encounter merge conflicts in your tasks.json file if multiple team members create tasks on different branches. The move command makes resolving these conflicts straightforward:
```
I just merged the main branch and there's a conflict with tasks.json. My teammates created tasks 10-15 while I created tasks 10-12 on my branch. Can you help me resolve this?
```
The agent will help you:
1. Keep your teammates' tasks (10-15)
2. Move your tasks to new positions to avoid conflicts:
```bash
# Move your tasks to new positions (e.g., 16-18)
task-master move --from=10 --to=16
task-master move --from=11 --to=17
task-master move --from=12 --to=18
```
This approach preserves everyone's work while maintaining a clean task structure, making it much easier to handle task conflicts than trying to manually merge JSON files.
### 8. Breaking Down Complex Tasks
For complex tasks that need more granularity:
@@ -369,3 +443,55 @@ Can you analyze the complexity of our tasks to help me understand which ones nee
```
Can you show me the complexity report in a more readable format?
```
### Research-Driven Development
Task Master includes a powerful research tool that provides fresh, up-to-date information beyond the AI's knowledge cutoff. This is particularly valuable for:
#### Getting Current Best Practices
```
Before implementing task 5 (authentication), research the latest JWT security recommendations.
```
The agent will execute:
```bash
task-master research "Latest JWT security recommendations 2024" --id=5
```
#### Research with Project Context
```
Research React Query v5 migration strategies for our current API implementation.
```
The agent will execute:
```bash
task-master research "React Query v5 migration strategies" --files=src/api.js,src/hooks.js
```
#### Research and Update Pattern
A powerful workflow is to research first, then update tasks with findings:
```
Research the latest Node.js performance optimization techniques and update task 12 with the findings.
```
The agent will:
1. Run research: `task-master research "Node.js performance optimization 2024" --id=12`
2. Update the task: `task-master update-subtask --id=12.2 --prompt="Updated with latest performance findings: [research results]"`
#### When to Use Research
- **Before implementing any new technology**
- **When encountering security-related tasks**
- **For performance optimization tasks**
- **When debugging complex issues**
- **Before making architectural decisions**
- **When updating dependencies**
The research tool automatically includes relevant project context and provides fresh information that can significantly improve implementation quality.

View File

@@ -1,6 +1,6 @@
export default {
// Use Node.js environment for testing
testEnvironment: 'node',
testEnvironment: "node",
// Automatically clear mock calls between every test
clearMocks: true,
@@ -9,27 +9,27 @@ export default {
collectCoverage: false,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
coverageDirectory: "coverage",
// A list of paths to directories that Jest should use to search for files in
roots: ['<rootDir>/tests'],
roots: ["<rootDir>/tests"],
// The glob patterns Jest uses to detect test files
testMatch: ['**/__tests__/**/*.js', '**/?(*.)+(spec|test).js'],
testMatch: ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
// Transform files
transform: {},
// Disable transformations for node_modules
transformIgnorePatterns: ['/node_modules/'],
transformIgnorePatterns: ["/node_modules/"],
// Set moduleNameMapper for absolute paths
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1'
"^@/(.*)$": "<rootDir>/$1",
},
// Setup module aliases
moduleDirectories: ['node_modules', '<rootDir>'],
moduleDirectories: ["node_modules", "<rootDir>"],
// Configure test coverage thresholds
coverageThreshold: {
@@ -37,16 +37,16 @@ export default {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
statements: 80,
},
},
// Generate coverage report in these formats
coverageReporters: ['text', 'lcov'],
coverageReporters: ["text", "lcov"],
// Verbose output
verbose: true,
// Setup file
setupFilesAfterEnv: ['<rootDir>/tests/setup.js']
setupFilesAfterEnv: ["<rootDir>/tests/setup.js"],
};

131
llms-install.md Normal file
View File

@@ -0,0 +1,131 @@
``# Taskmaster AI Installation Guide
This guide helps AI assistants install and configure Taskmaster for users in their development projects.
## What is Taskmaster?
Taskmaster is an AI-driven task management system designed for development workflows. It helps break down projects into manageable tasks, track dependencies, and maintain development momentum through structured, AI-enhanced planning.
## Installation Steps
### Step 1: Add MCP Configuration
Add the following configuration to the user's MCP settings file (`.cursor/mcp.json` for Cursor, or equivalent for other editors):
```json
{
"mcpServers": {
"taskmaster-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "user_will_add_their_key_here",
"PERPLEXITY_API_KEY": "user_will_add_their_key_here",
"OPENAI_API_KEY": "user_will_add_their_key_here",
"GOOGLE_API_KEY": "user_will_add_their_key_here",
"MISTRAL_API_KEY": "user_will_add_their_key_here",
"OPENROUTER_API_KEY": "user_will_add_their_key_here",
"XAI_API_KEY": "user_will_add_their_key_here"
}
}
}
}
```
### Step 2: API Key Requirements
Inform the user they need **at least one** API key from the following providers:
- **Anthropic** (for Claude models) - Recommended
- **OpenAI** (for GPT models)
- **Google** (for Gemini models)
- **Perplexity** (for research features) - Highly recommended
- **Mistral** (for Mistral models)
- **OpenRouter** (access to multiple models)
- **xAI** (for Grok models)
The user will be able to define 3 separate roles (can be the same provider or separate providers) for main AI operations, research operations (research providers/models only), and a fallback model in case of errors.
### Step 3: Initialize Project
Once the MCP server is configured and API keys are added, initialize Taskmaster in the user's project:
> Can you initialize Task Master in my project?
This will run the `initialize_project` tool to set up the basic file structure.
### Step 4: Create Initial Tasks
Users have two options for creating initial tasks:
**Option A: Parse a PRD (Recommended)**
If they have a Product Requirements Document:
> Can you parse my PRD file at [path/to/prd.txt] to generate initial tasks?
If the user does not have a PRD, the AI agent can help them create one and store it in scripts/prd.txt for parsing.
**Option B: Start from scratch**
> Can you help me add my first task: [describe the task]
## Common Usage Patterns
### Daily Workflow
> What's the next task I should work on?
> Can you show me the details for task [ID]?
> Can you mark task [ID] as done?
### Task Management
> Can you break down task [ID] into subtasks?
> Can you add a new task: [description]
> Can you analyze the complexity of my tasks?
### Project Organization
> Can you show me all my pending tasks?
> Can you move task [ID] to become a subtask of [parent ID]?
> Can you update task [ID] with this new information: [details]
## Verification Steps
After installation, verify everything is working:
1. **Check MCP Connection**: The AI should be able to access Task Master tools
2. **Test Basic Commands**: Try `get_tasks` to list current tasks
3. **Verify API Keys**: Ensure AI-powered commands work (like `add_task`)
Note: An API key fallback exists that allows the MCP server to read API keys from `.env` instead of the MCP JSON config. It is recommended to have keys in both places in case the MCP server is unable to read keys from its environment for whatever reason.
When adding keys to `.env` only, the `models` tool will explain that the keys are not OK for MCP. Despite this, the fallback should kick in and the API keys will be read from the `.env` file.
## Troubleshooting
**If MCP server doesn't start:**
- Verify the JSON configuration is valid
- Check that Node.js is installed
- Ensure API keys are properly formatted
**If AI commands fail:**
- Verify at least one API key is configured
- Check API key permissions and quotas
- Try using a different model via the `models` tool
## CLI Fallback
Taskmaster is also available via CLI commands, by installing with `npm install task-master-ai@latest` in a terminal. Running `task-master help` will show all available commands, which offer a 1:1 experience with the MCP server. As the AI agent, you should refer to the system prompts and rules provided to you to identify Taskmaster-specific rules that help you understand how and when to use it.
## Next Steps
Once installed, users can:
- Create new tasks with `add-task` or parse a PRD (scripts/prd.txt) into tasks with `parse-prd`
- Set up model preferences with `models` tool
- Expand tasks into subtasks with `expand-all` and `expand-task`
- Explore advanced features like research mode and complexity analysis
For detailed documentation, refer to the Task Master docs directory.``

View File

@@ -94,6 +94,7 @@ export async function addTaskDirect(args, log, context = {}) {
let manualTaskData = null;
let newTaskId;
let telemetryData;
if (isManualCreation) {
// Create manual task data object
@@ -109,7 +110,7 @@ export async function addTaskDirect(args, log, context = {}) {
);
// Call the addTask function with manual task data
newTaskId = await addTask(
const result = await addTask(
tasksPath,
null, // prompt is null for manual creation
taskDependencies,
@@ -117,13 +118,17 @@ export async function addTaskDirect(args, log, context = {}) {
{
session,
mcpLog,
projectRoot
projectRoot,
commandName: 'add-task',
outputType: 'mcp'
},
'json', // outputFormat
manualTaskData, // Pass the manual task data
false, // research flag is false for manual creation
projectRoot // Pass projectRoot
);
newTaskId = result.newTaskId;
telemetryData = result.telemetryData;
} else {
// AI-driven task creation
log.info(
@@ -131,7 +136,7 @@ export async function addTaskDirect(args, log, context = {}) {
);
// Call the addTask function, passing the research flag
newTaskId = await addTask(
const result = await addTask(
tasksPath,
prompt, // Use the prompt for AI creation
taskDependencies,
@@ -139,12 +144,16 @@ export async function addTaskDirect(args, log, context = {}) {
{
session,
mcpLog,
projectRoot
projectRoot,
commandName: 'add-task',
outputType: 'mcp'
},
'json', // outputFormat
null, // manualTaskData is null for AI creation
research // Pass the research flag
);
newTaskId = result.newTaskId;
telemetryData = result.telemetryData;
}
// Restore normal logging
@@ -154,7 +163,8 @@ export async function addTaskDirect(args, log, context = {}) {
success: true,
data: {
taskId: newTaskId,
message: `Successfully added new task #${newTaskId}`
message: `Successfully added new task #${newTaskId}`,
telemetryData: telemetryData
}
};
} catch (error) {

View File

@@ -18,6 +18,9 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
* @param {string} args.outputPath - Explicit absolute path to save the report.
* @param {string|number} [args.threshold] - Minimum complexity score to recommend expansion (1-10)
* @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis
* @param {string} [args.ids] - Comma-separated list of task IDs to analyze
* @param {number} [args.from] - Starting task ID in a range to analyze
* @param {number} [args.to] - Ending task ID in a range to analyze
* @param {string} [args.projectRoot] - Project root path.
* @param {Object} log - Logger object
* @param {Object} [context={}] - Context object containing session data
@@ -26,7 +29,16 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
*/
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
const { session } = context;
const { tasksJsonPath, outputPath, threshold, research, projectRoot } = args;
const {
tasksJsonPath,
outputPath,
threshold,
research,
projectRoot,
ids,
from,
to
} = args;
const logWrapper = createLogWrapper(log);
@@ -58,6 +70,14 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
log.info(`Analyzing task complexity from: ${tasksPath}`);
log.info(`Output report will be saved to: ${resolvedOutputPath}`);
if (ids) {
log.info(`Analyzing specific task IDs: ${ids}`);
} else if (from || to) {
const fromStr = from !== undefined ? from : 'first';
const toStr = to !== undefined ? to : 'last';
log.info(`Analyzing tasks in range: ${fromStr} to ${toStr}`);
}
if (research) {
log.info('Using research role for complexity analysis');
}
@@ -68,7 +88,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
output: outputPath,
threshold: threshold,
research: research === true, // Ensure boolean
projectRoot: projectRoot // Pass projectRoot here
projectRoot: projectRoot, // Pass projectRoot here
id: ids, // Pass the ids parameter to the core function as 'id'
from: from, // Pass from parameter
to: to // Pass to parameter
};
// --- End Initial Checks ---
@@ -79,17 +102,19 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
}
let report;
let coreResult;
try {
// --- Call Core Function (Pass context separately) ---
// Pass coreOptions as the first argument
// Pass context object { session, mcpLog } as the second argument
report = await analyzeTaskComplexity(
coreOptions, // Pass options object
{ session, mcpLog: logWrapper } // Pass context object
// Removed the explicit 'json' format argument, assuming context handling is sufficient
// If issues persist, we might need to add an explicit format param to analyzeTaskComplexity
);
coreResult = await analyzeTaskComplexity(coreOptions, {
session,
mcpLog: logWrapper,
commandName: 'analyze-complexity',
outputType: 'mcp'
});
report = coreResult.report;
} catch (error) {
log.error(
`Error in analyzeTaskComplexity core function: ${error.message}`
@@ -125,8 +150,11 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
};
}
// Added a check to ensure report is defined before accessing its properties
if (!report || typeof report !== 'object') {
if (
!coreResult ||
!coreResult.report ||
typeof coreResult.report !== 'object'
) {
log.error(
'Core analysis function returned an invalid or undefined response.'
);
@@ -141,8 +169,8 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
try {
// Ensure complexityAnalysis exists and is an array
const analysisArray = Array.isArray(report.complexityAnalysis)
? report.complexityAnalysis
const analysisArray = Array.isArray(coreResult.report.complexityAnalysis)
? coreResult.report.complexityAnalysis
: [];
// Count tasks by complexity (remains the same)
@@ -159,15 +187,16 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
return {
success: true,
data: {
message: `Task complexity analysis complete. Report saved to ${outputPath}`, // Use outputPath from args
reportPath: outputPath, // Use outputPath from args
message: `Task complexity analysis complete. Report saved to ${outputPath}`,
reportPath: outputPath,
reportSummary: {
taskCount: analysisArray.length,
highComplexityTasks,
mediumComplexityTasks,
lowComplexityTasks
},
fullReport: report // Now includes the full report
fullReport: coreResult.report,
telemetryData: coreResult.telemetryData
}
};
} catch (parseError) {

View File

@@ -63,12 +63,18 @@ export async function expandAllTasksDirect(args, log, context = {}) {
{ session, mcpLog, projectRoot }
);
// Core function now returns a summary object
// Core function now returns a summary object including the *aggregated* telemetryData
return {
success: true,
data: {
message: `Expand all operation completed. Expanded: ${result.expandedCount}, Failed: ${result.failedCount}, Skipped: ${result.skippedCount}`,
details: result // Include the full result details
details: {
expandedCount: result.expandedCount,
failedCount: result.failedCount,
skippedCount: result.skippedCount,
tasksToExpand: result.tasksToExpand
},
telemetryData: result.telemetryData // Pass the aggregated object
}
};
} catch (error) {

View File

@@ -193,13 +193,19 @@ export async function expandTaskDirect(args, log, context = {}) {
if (!wasSilent) enableSilentMode();
// Call the core expandTask function with the wrapped logger and projectRoot
const updatedTaskResult = await expandTask(
const coreResult = await expandTask(
tasksPath,
taskId,
numSubtasks,
useResearch,
additionalContext,
{ mcpLog, session, projectRoot },
{
mcpLog,
session,
projectRoot,
commandName: 'expand-task',
outputType: 'mcp'
},
forceFlag
);
@@ -215,16 +221,17 @@ export async function expandTaskDirect(args, log, context = {}) {
? updatedTask.subtasks.length - subtasksCountBefore
: 0;
// Return the result
// Return the result, including telemetryData
log.info(
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
);
return {
success: true,
data: {
task: updatedTask,
task: coreResult.task,
subtasksAdded,
hasExistingSubtasks
hasExistingSubtasks,
telemetryData: coreResult.telemetryData
},
fromCache: false
};

View File

@@ -0,0 +1,101 @@
/**
* Direct function wrapper for moveTask
*/
import { moveTask } from '../../../../scripts/modules/task-manager.js';
import { findTasksJsonPath } from '../utils/path-utils.js';
import {
enableSilentMode,
disableSilentMode
} from '../../../../scripts/modules/utils.js';
/**
* Move a task or subtask to a new position
* @param {Object} args - Function arguments
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file
* @param {string} args.sourceId - ID of the task/subtask to move (e.g., '5' or '5.2' or '5,6,7')
* @param {string} args.destinationId - ID of the destination (e.g., '7' or '7.3' or '7,8,9')
* @param {string} args.file - Alternative path to the tasks.json file
* @param {string} args.projectRoot - Project root directory
* @param {boolean} args.generateFiles - Whether to regenerate task files after moving (default: true)
* @param {Object} log - Logger object
* @returns {Promise<{success: boolean, data?: Object, error?: Object}>}
*/
export async function moveTaskDirect(args, log, context = {}) {
const { session } = context;
// Validate required parameters
if (!args.sourceId) {
return {
success: false,
error: {
message: 'Source ID is required',
code: 'MISSING_SOURCE_ID'
}
};
}
if (!args.destinationId) {
return {
success: false,
error: {
message: 'Destination ID is required',
code: 'MISSING_DESTINATION_ID'
}
};
}
try {
// Find tasks.json path if not provided
let tasksPath = args.tasksJsonPath || args.file;
if (!tasksPath) {
if (!args.projectRoot) {
return {
success: false,
error: {
message:
'Project root is required if tasksJsonPath is not provided',
code: 'MISSING_PROJECT_ROOT'
}
};
}
tasksPath = findTasksJsonPath(args, log);
}
// Enable silent mode to prevent console output during MCP operation
enableSilentMode();
// Call the core moveTask function with file generation control
const generateFiles = args.generateFiles !== false; // Default to true
const result = await moveTask(
tasksPath,
args.sourceId,
args.destinationId,
generateFiles
);
// Restore console output
disableSilentMode();
return {
success: true,
data: {
...result,
message: `Successfully moved task/subtask ${args.sourceId} to ${args.destinationId}`
}
};
} catch (error) {
// Restore console output in case of error
disableSilentMode();
log.error(`Failed to move task: ${error.message}`);
return {
success: false,
error: {
message: error.message,
code: 'MOVE_TASK_ERROR'
}
};
}
}

View File

@@ -31,6 +31,7 @@ export async function parsePRDDirect(args, log, context = {}) {
numTasks: numTasksArg,
force,
append,
research,
projectRoot
} = args;
@@ -105,19 +106,23 @@ export async function parsePRDDirect(args, log, context = {}) {
}
}
const useForce = force === true;
const useAppend = append === true;
if (useAppend) {
if (append) {
logWrapper.info('Append mode enabled.');
if (useForce) {
if (force) {
logWrapper.warn(
'Both --force and --append flags were provided. --force takes precedence; append mode will be ignored.'
);
}
}
if (research) {
logWrapper.info(
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${useForce}, Append: ${useAppend}, ProjectRoot: ${projectRoot}`
'Research mode enabled. Using Perplexity AI for enhanced PRD analysis.'
);
}
logWrapper.info(
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, Research: ${research}, ProjectRoot: ${projectRoot}`
);
const wasSilent = isSilentMode();
@@ -131,21 +136,29 @@ export async function parsePRDDirect(args, log, context = {}) {
inputPath,
outputPath,
numTasks,
{ session, mcpLog: logWrapper, projectRoot, useForce, useAppend },
{
session,
mcpLog: logWrapper,
projectRoot,
force,
append,
research,
commandName: 'parse-prd',
outputType: 'mcp'
},
'json'
);
// parsePRD returns { success: true, tasks: processedTasks } on success
if (result && result.success && Array.isArray(result.tasks)) {
logWrapper.success(
`Successfully parsed PRD. Generated ${result.tasks.length} tasks.`
);
// Adjust check for the new return structure
if (result && result.success) {
const successMsg = `Successfully parsed PRD and generated tasks in ${result.tasksPath}`;
logWrapper.success(successMsg);
return {
success: true,
data: {
message: `Successfully parsed PRD and generated ${result.tasks.length} tasks.`,
outputPath: outputPath,
taskCount: result.tasks.length
message: successMsg,
outputPath: result.tasksPath,
telemetryData: result.telemetryData
}
};
} else {

View File

@@ -0,0 +1,159 @@
/**
* research.js
* Direct function implementation for AI-powered research queries
*/
import { performResearch } from '../../../../scripts/modules/task-manager.js';
import {
enableSilentMode,
disableSilentMode
} from '../../../../scripts/modules/utils.js';
import { createLogWrapper } from '../../tools/utils.js';
/**
* Direct function wrapper for performing AI-powered research with project context.
*
* @param {Object} args - Command arguments
* @param {string} args.query - Research query/prompt (required)
* @param {string} [args.taskIds] - Comma-separated list of task/subtask IDs for context
* @param {string} [args.filePaths] - Comma-separated list of file paths for context
* @param {string} [args.customContext] - Additional custom context text
* @param {boolean} [args.includeProjectTree=false] - Include project file tree in context
* @param {string} [args.detailLevel='medium'] - Detail level: 'low', 'medium', 'high'
* @param {string} [args.projectRoot] - Project root path
* @param {Object} log - Logger object
* @param {Object} context - Additional context (session)
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
*/
export async function researchDirect(args, log, context = {}) {
// Destructure expected args
const {
query,
taskIds,
filePaths,
customContext,
includeProjectTree = false,
detailLevel = 'medium',
projectRoot
} = args;
const { session } = context; // Destructure session from context
// Enable silent mode to prevent console logs from interfering with JSON response
enableSilentMode();
// Create logger wrapper using the utility
const mcpLog = createLogWrapper(log);
try {
// Check required parameters
if (!query || typeof query !== 'string' || query.trim().length === 0) {
log.error('Missing or invalid required parameter: query');
disableSilentMode();
return {
success: false,
error: {
code: 'MISSING_PARAMETER',
message:
'The query parameter is required and must be a non-empty string'
}
};
}
// Parse comma-separated task IDs if provided
const parsedTaskIds = taskIds
? taskIds
.split(',')
.map((id) => id.trim())
.filter((id) => id.length > 0)
: [];
// Parse comma-separated file paths if provided
const parsedFilePaths = filePaths
? filePaths
.split(',')
.map((path) => path.trim())
.filter((path) => path.length > 0)
: [];
// Validate detail level
const validDetailLevels = ['low', 'medium', 'high'];
if (!validDetailLevels.includes(detailLevel)) {
log.error(`Invalid detail level: ${detailLevel}`);
disableSilentMode();
return {
success: false,
error: {
code: 'INVALID_PARAMETER',
message: `Detail level must be one of: ${validDetailLevels.join(', ')}`
}
};
}
log.info(
`Performing research query: "${query.substring(0, 100)}${query.length > 100 ? '...' : ''}", ` +
`taskIds: [${parsedTaskIds.join(', ')}], ` +
`filePaths: [${parsedFilePaths.join(', ')}], ` +
`detailLevel: ${detailLevel}, ` +
`includeProjectTree: ${includeProjectTree}, ` +
`projectRoot: ${projectRoot}`
);
// Prepare options for the research function
const researchOptions = {
taskIds: parsedTaskIds,
filePaths: parsedFilePaths,
customContext: customContext || '',
includeProjectTree,
detailLevel,
projectRoot
};
// Prepare context for the research function
const researchContext = {
session,
mcpLog,
commandName: 'research',
outputType: 'mcp'
};
// Call the performResearch function
const result = await performResearch(
query.trim(),
researchOptions,
researchContext,
'json', // outputFormat - use 'json' to suppress CLI UI
false // allowFollowUp - disable for MCP calls
);
// Restore normal logging
disableSilentMode();
return {
success: true,
data: {
query: result.query,
result: result.result,
contextSize: result.contextSize,
contextTokens: result.contextTokens,
tokenBreakdown: result.tokenBreakdown,
systemPromptTokens: result.systemPromptTokens,
userPromptTokens: result.userPromptTokens,
totalInputTokens: result.totalInputTokens,
detailLevel: result.detailLevel,
telemetryData: result.telemetryData
}
};
} catch (error) {
// Make sure to restore normal logging even if there's an error
disableSilentMode();
log.error(`Error in researchDirect: ${error.message}`);
return {
success: false,
error: {
code: error.code || 'RESEARCH_ERROR',
message: error.message
}
};
}
}

View File

@@ -9,7 +9,7 @@ import {
disableSilentMode,
isSilentMode
} from '../../../../scripts/modules/utils.js';
import { nextTaskDirect } from './next-task.js';
/**
* Direct function wrapper for setTaskStatus with error handling.
*
@@ -19,7 +19,7 @@ import {
*/
export async function setTaskStatusDirect(args, log) {
// Destructure expected args, including the resolved tasksJsonPath
const { tasksJsonPath, id, status } = args;
const { tasksJsonPath, id, status, complexityReportPath } = args;
try {
log.info(`Setting task status with args: ${JSON.stringify(args)}`);
@@ -85,6 +85,39 @@ export async function setTaskStatusDirect(args, log) {
},
fromCache: false // This operation always modifies state and should never be cached
};
// If the task was completed, attempt to fetch the next task
if (result.data.status === 'done') {
try {
log.info(`Attempting to fetch next task for task ${taskId}`);
const nextResult = await nextTaskDirect(
{
tasksJsonPath: tasksJsonPath,
reportPath: complexityReportPath
},
log
);
if (nextResult.success) {
log.info(
`Successfully retrieved next task: ${nextResult.data.nextTask}`
);
result.data = {
...result.data,
nextTask: nextResult.data.nextTask,
isNextSubtask: nextResult.data.isSubtask,
nextSteps: nextResult.data.nextSteps
};
} else {
log.warn(
`Failed to retrieve next task: ${nextResult.error?.message || 'Unknown error'}`
);
}
} catch (nextErr) {
log.error(`Error retrieving next task: ${nextErr.message}`);
}
}
return result;
} catch (error) {
log.error(`Error setting task status: ${error.message}`);

View File

@@ -66,9 +66,27 @@ export async function showTaskDirect(args, log) {
const complexityReport = readComplexityReport(reportPath);
// Parse comma-separated IDs
const taskIds = id
.split(',')
.map((taskId) => taskId.trim())
.filter((taskId) => taskId.length > 0);
if (taskIds.length === 0) {
return {
success: false,
error: {
code: 'INVALID_TASK_ID',
message: 'No valid task IDs provided'
}
};
}
// Handle single task ID (existing behavior)
if (taskIds.length === 1) {
const { task, originalSubtaskCount } = findTaskById(
tasksData.tasks,
id,
taskIds[0],
complexityReport,
status
);
@@ -78,12 +96,12 @@ export async function showTaskDirect(args, log) {
success: false,
error: {
code: 'TASK_NOT_FOUND',
message: `Task or subtask with ID ${id} not found`
message: `Task or subtask with ID ${taskIds[0]} not found`
}
};
}
log.info(`Successfully retrieved task ${id}.`);
log.info(`Successfully retrieved task ${taskIds[0]}.`);
const returnData = { ...task };
if (originalSubtaskCount !== null) {
@@ -92,6 +110,47 @@ export async function showTaskDirect(args, log) {
}
return { success: true, data: returnData };
}
// Handle multiple task IDs
const foundTasks = [];
const notFoundIds = [];
taskIds.forEach((taskId) => {
const { task, originalSubtaskCount } = findTaskById(
tasksData.tasks,
taskId,
complexityReport,
status
);
if (task) {
const taskData = { ...task };
if (originalSubtaskCount !== null) {
taskData._originalSubtaskCount = originalSubtaskCount;
taskData._subtaskFilter = status;
}
foundTasks.push(taskData);
} else {
notFoundIds.push(taskId);
}
});
log.info(
`Successfully retrieved ${foundTasks.length} of ${taskIds.length} requested tasks.`
);
// Return multiple tasks with metadata
return {
success: true,
data: {
tasks: foundTasks,
requestedIds: taskIds,
foundCount: foundTasks.length,
notFoundIds: notFoundIds,
isMultiple: true
}
};
} catch (error) {
log.error(`Error showing task ${id}: ${error.message}`);
return {

View File

@@ -108,18 +108,24 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
try {
// Execute core updateSubtaskById function
const updatedSubtask = await updateSubtaskById(
const coreResult = await updateSubtaskById(
tasksPath,
subtaskIdStr,
prompt,
useResearch,
{ mcpLog: logWrapper, session, projectRoot },
{
mcpLog: logWrapper,
session,
projectRoot,
commandName: 'update-subtask',
outputType: 'mcp'
},
'json'
);
if (updatedSubtask === null) {
if (!coreResult || coreResult.updatedSubtask === null) {
const message = `Subtask ${id} or its parent task not found.`;
logWrapper.error(message); // Log as error since it couldn't be found
logWrapper.error(message);
return {
success: false,
error: { code: 'SUBTASK_NOT_FOUND', message: message },
@@ -136,9 +142,10 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
message: `Successfully updated subtask with ID ${subtaskIdStr}`,
subtaskId: subtaskIdStr,
parentId: subtaskIdStr.split('.')[0],
subtask: updatedSubtask,
subtask: coreResult.updatedSubtask,
tasksPath,
useResearch
useResearch,
telemetryData: coreResult.telemetryData
},
fromCache: false
};

View File

@@ -110,7 +110,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
try {
// Execute core updateTaskById function with proper parameters
const updatedTask = await updateTaskById(
const coreResult = await updateTaskById(
tasksPath,
taskId,
prompt,
@@ -118,19 +118,26 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
{
mcpLog: logWrapper,
session,
projectRoot
projectRoot,
commandName: 'update-task',
outputType: 'mcp'
},
'json'
);
// Check if the core function indicated the task wasn't updated (e.g., status was 'done')
if (updatedTask === null) {
// Check if the core function returned null or an object without success
if (!coreResult || coreResult.updatedTask === null) {
// Core function logs the reason, just return success with info
const message = `Task ${taskId} was not updated (likely already completed).`;
logWrapper.info(message);
return {
success: true,
data: { message: message, taskId: taskId, updated: false },
data: {
message: message,
taskId: taskId,
updated: false,
telemetryData: coreResult?.telemetryData
},
fromCache: false
};
}
@@ -146,7 +153,8 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
tasksPath: tasksPath,
useResearch: useResearch,
updated: true,
updatedTask: updatedTask
updatedTask: coreResult.updatedTask,
telemetryData: coreResult.telemetryData
},
fromCache: false
};

View File

@@ -85,7 +85,6 @@ export async function updateTasksDirect(args, log, context = {}) {
'json'
);
// updateTasks returns { success: true, updatedTasks: [...] } on success
if (result && result.success && Array.isArray(result.updatedTasks)) {
logWrapper.success(
`Successfully updated ${result.updatedTasks.length} tasks.`
@@ -95,7 +94,8 @@ export async function updateTasksDirect(args, log, context = {}) {
data: {
message: `Successfully updated ${result.updatedTasks.length} tasks.`,
tasksFile,
updatedCount: result.updatedTasks.length
updatedCount: result.updatedTasks.length,
telemetryData: result.telemetryData
}
};
} else {

View File

@@ -30,6 +30,8 @@ import { addDependencyDirect } from './direct-functions/add-dependency.js';
import { removeTaskDirect } from './direct-functions/remove-task.js';
import { initializeProjectDirect } from './direct-functions/initialize-project.js';
import { modelsDirect } from './direct-functions/models.js';
import { moveTaskDirect } from './direct-functions/move-task.js';
import { researchDirect } from './direct-functions/research.js';
// Re-export utility functions
export { findTasksJsonPath } from './utils/path-utils.js';
@@ -60,7 +62,9 @@ export const directFunctions = new Map([
['addDependencyDirect', addDependencyDirect],
['removeTaskDirect', removeTaskDirect],
['initializeProjectDirect', initializeProjectDirect],
['modelsDirect', modelsDirect]
['modelsDirect', modelsDirect],
['moveTaskDirect', moveTaskDirect],
['researchDirect', researchDirect]
]);
// Re-export all direct function implementations
@@ -89,5 +93,7 @@ export {
addDependencyDirect,
removeTaskDirect,
initializeProjectDirect,
modelsDirect
modelsDirect,
moveTaskDirect,
researchDirect
};

View File

@@ -49,6 +49,24 @@ export function registerAnalyzeProjectComplexityTool(server) {
.describe(
'Path to the tasks file relative to project root (default: tasks/tasks.json).'
),
ids: z
.string()
.optional()
.describe(
'Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").'
),
from: z.coerce
.number()
.int()
.positive()
.optional()
.describe('Starting task ID in a range to analyze.'),
to: z.coerce
.number()
.int()
.positive()
.optional()
.describe('Ending task ID in a range to analyze.'),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
@@ -107,7 +125,10 @@ export function registerAnalyzeProjectComplexityTool(server) {
outputPath: outputPath,
threshold: args.threshold,
research: args.research,
projectRoot: args.projectRoot
projectRoot: args.projectRoot,
ids: args.ids,
from: args.from,
to: args.to
},
log,
{ session }

View File

@@ -44,7 +44,11 @@ export function registerShowTaskTool(server) {
name: 'get_task',
description: 'Get detailed information about a specific task',
parameters: z.object({
id: z.string().describe('Task ID to get'),
id: z
.string()
.describe(
'Task ID(s) to get (can be comma-separated for multiple tasks)'
),
status: z
.string()
.optional()
@@ -66,7 +70,7 @@ export function registerShowTaskTool(server) {
'Absolute path to the project root directory (Optional, usually from session)'
)
}),
execute: withNormalizedProjectRoot(async (args, { log }) => {
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
const { id, file, status, projectRoot } = args;
try {
@@ -110,7 +114,8 @@ export function registerShowTaskTool(server) {
status: status,
projectRoot: projectRoot
},
log
log,
{ session }
);
if (result.success) {

View File

@@ -28,6 +28,8 @@ import { registerAddDependencyTool } from './add-dependency.js';
import { registerRemoveTaskTool } from './remove-task.js';
import { registerInitializeProjectTool } from './initialize-project.js';
import { registerModelsTool } from './models.js';
import { registerMoveTaskTool } from './move-task.js';
import { registerResearchTool } from './research.js';
/**
* Register all Task Master tools with the MCP server
@@ -61,6 +63,7 @@ export function registerTaskMasterTools(server) {
registerRemoveTaskTool(server);
registerRemoveSubtaskTool(server);
registerClearSubtasksTool(server);
registerMoveTaskTool(server);
// Group 5: Task Analysis & Expansion
registerAnalyzeProjectComplexityTool(server);
@@ -72,6 +75,9 @@ export function registerTaskMasterTools(server) {
registerRemoveDependencyTool(server);
registerValidateDependenciesTool(server);
registerFixDependenciesTool(server);
// Group 7: AI-Powered Features
registerResearchTool(server);
} catch (error) {
logger.error(`Error registering Task Master tools: ${error.message}`);
throw error;

View File

@@ -0,0 +1,66 @@
/**
* tools/move-task.js
* Tool for moving tasks or subtasks to a new position
*/
import { z } from 'zod';
import {
handleApiResult,
createErrorResponse,
withNormalizedProjectRoot
} from './utils.js';
import { moveTaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js';
/**
* Register the moveTask tool with the MCP server
* @param {Object} server - FastMCP server instance
*/
export function registerMoveTaskTool(server) {
server.addTool({
name: 'move_task',
description: 'Move a task or subtask to a new position',
parameters: z.object({
from: z
.string()
.describe(
'ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")'
),
to: z
.string()
.describe(
'ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated'
),
file: z.string().optional().describe('Custom path to tasks.json file'),
projectRoot: z
.string()
.optional()
.describe(
'Root directory of the project (typically derived from session)'
)
}),
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
// Let the core logic handle comma-separated IDs and validation
const result = await moveTaskDirect(
{
sourceId: args.from,
destinationId: args.to,
file: args.file,
projectRoot: args.projectRoot,
generateFiles: true // Always generate files for MCP operations
},
log,
{ session }
);
return handleApiResult(result, log);
} catch (error) {
return createErrorResponse(
`Failed to move task: ${error.message}`,
'MOVE_TASK_ERROR'
);
}
})
});
}

View File

@@ -49,6 +49,13 @@ export function registerParsePRDTool(server) {
.optional()
.default(false)
.describe('Append generated tasks to existing file.'),
research: z
.boolean()
.optional()
.default(false)
.describe(
'Use the research model for research-backed task generation, providing more comprehensive, accurate and up-to-date task details.'
),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
@@ -68,6 +75,7 @@ export function registerParsePRDTool(server) {
numTasks: args.numTasks,
force: args.force,
append: args.append,
research: args.research,
projectRoot: args.projectRoot
},
log,

View File

@@ -0,0 +1,82 @@
/**
* tools/research.js
* Tool to perform AI-powered research queries with project context
*/
import { z } from 'zod';
import {
createErrorResponse,
handleApiResult,
withNormalizedProjectRoot
} from './utils.js';
import { researchDirect } from '../core/task-master-core.js';
/**
* Register the research tool with the MCP server
* @param {Object} server - FastMCP server instance
*/
export function registerResearchTool(server) {
server.addTool({
name: 'research',
description: 'Perform AI-powered research queries with project context',
parameters: z.object({
query: z.string().describe('Research query/prompt (required)'),
taskIds: z
.string()
.optional()
.describe(
'Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17")'
),
filePaths: z
.string()
.optional()
.describe(
'Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md")'
),
customContext: z
.string()
.optional()
.describe('Additional custom context text to include in the research'),
includeProjectTree: z
.boolean()
.optional()
.describe(
'Include project file tree structure in context (default: false)'
),
detailLevel: z
.enum(['low', 'medium', 'high'])
.optional()
.describe('Detail level for the research response (default: medium)'),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
}),
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
log.info(
`Starting research with query: "${args.query.substring(0, 100)}${args.query.length > 100 ? '...' : ''}"`
);
// Call the direct function
const result = await researchDirect(
{
query: args.query,
taskIds: args.taskIds,
filePaths: args.filePaths,
customContext: args.customContext,
includeProjectTree: args.includeProjectTree || false,
detailLevel: args.detailLevel || 'medium',
projectRoot: args.projectRoot
},
log,
{ session }
);
return handleApiResult(result, log);
} catch (error) {
log.error(`Error in research tool: ${error.message}`);
return createErrorResponse(error.message);
}
})
});
}

View File

@@ -9,8 +9,14 @@ import {
createErrorResponse,
withNormalizedProjectRoot
} from './utils.js';
import { setTaskStatusDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js';
import {
setTaskStatusDirect,
nextTaskDirect
} from '../core/task-master-core.js';
import {
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
import { TASK_STATUS_OPTIONS } from '../../../src/constants/task-status.js';
/**
@@ -33,6 +39,12 @@ export function registerSetTaskStatusTool(server) {
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
),
file: z.string().optional().describe('Absolute path to the tasks file'),
complexityReport: z
.string()
.optional()
.describe(
'Path to the complexity report file (relative to project root or absolute)'
),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
@@ -55,11 +67,23 @@ export function registerSetTaskStatusTool(server) {
);
}
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
args.projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await setTaskStatusDirect(
{
tasksJsonPath: tasksJsonPath,
id: args.id,
status: args.status
status: args.status,
complexityReportPath
},
log
);

View File

@@ -3,16 +3,16 @@
* Utility functions for Task Master CLI integration
*/
import { spawnSync } from 'child_process';
import path from 'path';
import fs from 'fs';
import { contextManager } from '../core/context-manager.js'; // Import the singleton
import { spawnSync } from "child_process";
import path from "path";
import fs from "fs";
import { contextManager } from "../core/context-manager.js"; // Import the singleton
// Import path utilities to ensure consistent path resolution
import {
lastFoundProjectRoot,
PROJECT_MARKERS
} from '../core/utils/path-utils.js';
PROJECT_MARKERS,
} from "../core/utils/path-utils.js";
/**
* Get normalized project root path
@@ -22,7 +22,7 @@ import {
*/
function getProjectRoot(projectRootRaw, log) {
// PRECEDENCE ORDER:
// 1. Environment variable override
// 1. Environment variable override (TASK_MASTER_PROJECT_ROOT)
// 2. Explicitly provided projectRoot in args
// 3. Previously found/cached project root
// 4. Current directory if it has project markers
@@ -77,7 +77,7 @@ function getProjectRoot(projectRootRaw, log) {
`No task-master project detected in current directory. Using ${currentDir} as project root.`
);
log.warn(
'Consider using --project-root to specify the correct project location or set TASK_MASTER_PROJECT_ROOT environment variable.'
"Consider using --project-root to specify the correct project location or set TASK_MASTER_PROJECT_ROOT environment variable."
);
return currentDir;
}
@@ -103,7 +103,7 @@ function getProjectRootFromSession(session, log) {
rootsRootsType: typeof session?.roots?.roots,
isRootsRootsArray: Array.isArray(session?.roots?.roots),
rootsRootsLength: session?.roots?.roots?.length,
firstRootsRoot: session?.roots?.roots?.[0]
firstRootsRoot: session?.roots?.roots?.[0],
})}`
);
@@ -126,16 +126,16 @@ function getProjectRootFromSession(session, log) {
if (rawRootPath) {
// Decode URI and strip file:// protocol
decodedPath = rawRootPath.startsWith('file://')
decodedPath = rawRootPath.startsWith("file://")
? decodeURIComponent(rawRootPath.slice(7))
: rawRootPath; // Assume non-file URI is already decoded? Or decode anyway? Let's decode.
if (!rawRootPath.startsWith('file://')) {
if (!rawRootPath.startsWith("file://")) {
decodedPath = decodeURIComponent(rawRootPath); // Decode even if no file://
}
// Handle potential Windows drive prefix after stripping protocol (e.g., /C:/...)
if (
decodedPath.startsWith('/') &&
decodedPath.startsWith("/") &&
/[A-Za-z]:/.test(decodedPath.substring(1, 3))
) {
decodedPath = decodedPath.substring(1); // Remove leading slash if it's like /C:/...
@@ -144,7 +144,7 @@ function getProjectRootFromSession(session, log) {
log.info(`Decoded path: ${decodedPath}`);
// Normalize slashes and resolve
const normalizedSlashes = decodedPath.replace(/\\/g, '/');
const normalizedSlashes = decodedPath.replace(/\\/g, "/");
finalPath = path.resolve(normalizedSlashes); // Resolve to absolute path for current OS
log.info(`Normalized and resolved session path: ${finalPath}`);
@@ -152,22 +152,22 @@ function getProjectRootFromSession(session, log) {
}
// Fallback Logic (remains the same)
log.warn('No project root URI found in session. Attempting fallbacks...');
log.warn("No project root URI found in session. Attempting fallbacks...");
const cwd = process.cwd();
// Fallback 1: Use server path deduction (Cursor IDE)
const serverPath = process.argv[1];
if (serverPath && serverPath.includes('mcp-server')) {
const mcpServerIndex = serverPath.indexOf('mcp-server');
if (serverPath && serverPath.includes("mcp-server")) {
const mcpServerIndex = serverPath.indexOf("mcp-server");
if (mcpServerIndex !== -1) {
const projectRoot = path.dirname(
serverPath.substring(0, mcpServerIndex)
); // Go up one level
if (
fs.existsSync(path.join(projectRoot, '.cursor')) ||
fs.existsSync(path.join(projectRoot, 'mcp-server')) ||
fs.existsSync(path.join(projectRoot, 'package.json'))
fs.existsSync(path.join(projectRoot, ".cursor")) ||
fs.existsSync(path.join(projectRoot, "mcp-server")) ||
fs.existsSync(path.join(projectRoot, "package.json"))
) {
log.info(
`Using project root derived from server path: ${projectRoot}`
@@ -202,7 +202,7 @@ function getProjectRootFromSession(session, log) {
function handleApiResult(
result,
log,
errorPrefix = 'API error',
errorPrefix = "API error",
processFunction = processMCPResponseData
) {
if (!result.success) {
@@ -223,7 +223,7 @@ function handleApiResult(
// Create the response payload including the fromCache flag
const responsePayload = {
fromCache: result.fromCache, // Get the flag from the original 'result'
data: processedData // Nest the processed data under a 'data' key
data: processedData, // Nest the processed data under a 'data' key
};
// Pass this combined payload to createContentResponse
@@ -261,10 +261,10 @@ function executeTaskMasterCommand(
// Common options for spawn
const spawnOptions = {
encoding: 'utf8',
encoding: "utf8",
cwd: cwd,
// Merge process.env with customEnv, giving precedence to customEnv
env: { ...process.env, ...(customEnv || {}) }
env: { ...process.env, ...(customEnv || {}) },
};
// Log the environment being passed (optional, for debugging)
@@ -272,13 +272,13 @@ function executeTaskMasterCommand(
// Execute the command using the global task-master CLI or local script
// Try the global CLI first
let result = spawnSync('task-master', fullArgs, spawnOptions);
let result = spawnSync("task-master", fullArgs, spawnOptions);
// If global CLI is not available, try fallback to the local script
if (result.error && result.error.code === 'ENOENT') {
log.info('Global task-master not found, falling back to local script');
if (result.error && result.error.code === "ENOENT") {
log.info("Global task-master not found, falling back to local script");
// Pass the same spawnOptions (including env) to the fallback
result = spawnSync('node', ['scripts/dev.js', ...fullArgs], spawnOptions);
result = spawnSync("node", ["scripts/dev.js", ...fullArgs], spawnOptions);
}
if (result.error) {
@@ -291,7 +291,7 @@ function executeTaskMasterCommand(
? result.stderr.trim()
: result.stdout
? result.stdout.trim()
: 'Unknown error';
: "Unknown error";
throw new Error(
`Command failed with exit code ${result.status}: ${errorOutput}`
);
@@ -300,13 +300,13 @@ function executeTaskMasterCommand(
return {
success: true,
stdout: result.stdout,
stderr: result.stderr
stderr: result.stderr,
};
} catch (error) {
log.error(`Error executing task-master command: ${error.message}`);
return {
success: false,
error: error.message
error: error.message,
};
}
}
@@ -332,7 +332,7 @@ async function getCachedOrExecute({ cacheKey, actionFn, log }) {
// Return the cached data in the same structure as a fresh result
return {
...cachedResult, // Spread the cached result to maintain its structure
fromCache: true // Just add the fromCache flag
fromCache: true, // Just add the fromCache flag
};
}
@@ -360,20 +360,38 @@ async function getCachedOrExecute({ cacheKey, actionFn, log }) {
// Return the fresh result, indicating it wasn't from cache
return {
...result,
fromCache: false
fromCache: false,
};
}
/**
* Filters sensitive fields from telemetry data before sending to users.
* Removes commandArgs and fullOutput which may contain API keys and sensitive data.
* @param {Object} telemetryData - The telemetry data object to filter.
* @returns {Object} - Filtered telemetry data safe for user exposure.
*/
function filterSensitiveTelemetryData(telemetryData) {
if (!telemetryData || typeof telemetryData !== "object") {
return telemetryData;
}
// Create a copy and remove sensitive fields
const { commandArgs, fullOutput, ...safeTelemetryData } = telemetryData;
return safeTelemetryData;
}
/**
* Recursively removes specified fields from task objects, whether single or in an array.
* Handles common data structures returned by task commands.
* Also filters sensitive telemetry data if present.
* @param {Object|Array} taskOrData - A single task object or a data object containing a 'tasks' array.
* @param {string[]} fieldsToRemove - An array of field names to remove.
* @returns {Object|Array} - The processed data with specified fields removed.
*/
function processMCPResponseData(
taskOrData,
fieldsToRemove = ['details', 'testStrategy']
fieldsToRemove = ["details", "testStrategy"]
) {
if (!taskOrData) {
return taskOrData;
@@ -381,7 +399,7 @@ function processMCPResponseData(
// Helper function to process a single task object
const processSingleTask = (task) => {
if (typeof task !== 'object' || task === null) {
if (typeof task !== "object" || task === null) {
return task;
}
@@ -392,6 +410,13 @@ function processMCPResponseData(
delete processedTask[field];
});
// Filter telemetry data if present
if (processedTask.telemetryData) {
processedTask.telemetryData = filterSensitiveTelemetryData(
processedTask.telemetryData
);
}
// Recursively process subtasks if they exist and are an array
if (processedTask.subtasks && Array.isArray(processedTask.subtasks)) {
// Use processArrayOfTasks to handle the subtasks array
@@ -406,33 +431,41 @@ function processMCPResponseData(
return tasks.map(processSingleTask);
};
// Handle top-level telemetry data filtering for any response structure
let processedData = { ...taskOrData };
if (processedData.telemetryData) {
processedData.telemetryData = filterSensitiveTelemetryData(
processedData.telemetryData
);
}
// Check if the input is a data structure containing a 'tasks' array (like from listTasks)
if (
typeof taskOrData === 'object' &&
taskOrData !== null &&
Array.isArray(taskOrData.tasks)
typeof processedData === "object" &&
processedData !== null &&
Array.isArray(processedData.tasks)
) {
return {
...taskOrData, // Keep other potential fields like 'stats', 'filter'
tasks: processArrayOfTasks(taskOrData.tasks)
...processedData, // Keep other potential fields like 'stats', 'filter'
tasks: processArrayOfTasks(processedData.tasks),
};
}
// Check if the input is likely a single task object (add more checks if needed)
else if (
typeof taskOrData === 'object' &&
taskOrData !== null &&
'id' in taskOrData &&
'title' in taskOrData
typeof processedData === "object" &&
processedData !== null &&
"id" in processedData &&
"title" in processedData
) {
return processSingleTask(taskOrData);
return processSingleTask(processedData);
}
// Check if the input is an array of tasks directly (less common but possible)
else if (Array.isArray(taskOrData)) {
return processArrayOfTasks(taskOrData);
else if (Array.isArray(processedData)) {
return processArrayOfTasks(processedData);
}
// If it doesn't match known task structures, return it as is
return taskOrData;
// If it doesn't match known task structures, return the processed data (with filtered telemetry)
return processedData;
}
/**
@@ -445,15 +478,15 @@ function createContentResponse(content) {
return {
content: [
{
type: 'text',
type: "text",
text:
typeof content === 'object'
typeof content === "object"
? // Format JSON nicely with indentation
JSON.stringify(content, null, 2)
: // Keep other content types as-is
String(content)
}
]
String(content),
},
],
};
}
@@ -466,11 +499,11 @@ function createErrorResponse(errorMessage) {
return {
content: [
{
type: 'text',
text: `Error: ${errorMessage}`
}
type: "text",
text: `Error: ${errorMessage}`,
},
],
isError: true
isError: true,
};
}
@@ -489,7 +522,7 @@ function createLogWrapper(log) {
debug: (message, ...args) =>
log.debug ? log.debug(message, ...args) : null,
// Map success to info as a common fallback
success: (message, ...args) => log.info(message, ...args)
success: (message, ...args) => log.info(message, ...args),
};
}
@@ -520,23 +553,23 @@ function normalizeProjectRoot(rawPath, log) {
}
// 2. Strip file:// prefix (handle 2 or 3 slashes)
if (pathString.startsWith('file:///')) {
if (pathString.startsWith("file:///")) {
pathString = pathString.slice(7); // Slice 7 for file:///, may leave leading / on Windows
} else if (pathString.startsWith('file://')) {
} else if (pathString.startsWith("file://")) {
pathString = pathString.slice(7); // Slice 7 for file://
}
// 3. Handle potential Windows leading slash after stripping prefix (e.g., /C:/...)
// This checks if it starts with / followed by a drive letter C: D: etc.
if (
pathString.startsWith('/') &&
pathString.startsWith("/") &&
/[A-Za-z]:/.test(pathString.substring(1, 3))
) {
pathString = pathString.substring(1); // Remove the leading slash
}
// 4. Normalize backslashes to forward slashes
pathString = pathString.replace(/\\/g, '/');
pathString = pathString.replace(/\\/g, "/");
// 5. Resolve to absolute path using server's OS convention
const resolvedPath = path.resolve(pathString);
@@ -578,6 +611,7 @@ function getRawProjectRootFromSession(session, log) {
/**
* Higher-order function to wrap MCP tool execute methods.
* Ensures args.projectRoot is present and normalized before execution.
* Uses TASK_MASTER_PROJECT_ROOT environment variable with proper precedence.
* @param {Function} executeFn - The original async execute(args, context) function.
* @returns {Function} The wrapped async execute function.
*/
@@ -585,34 +619,55 @@ function withNormalizedProjectRoot(executeFn) {
return async (args, context) => {
const { log, session } = context;
let normalizedRoot = null;
let rootSource = 'unknown';
let rootSource = "unknown";
try {
// Determine raw root: prioritize args, then session
let rawRoot = args.projectRoot;
if (!rawRoot) {
rawRoot = getRawProjectRootFromSession(session, log);
rootSource = 'session';
} else {
rootSource = 'args';
}
// PRECEDENCE ORDER:
// 1. TASK_MASTER_PROJECT_ROOT environment variable (from process.env or session)
// 2. args.projectRoot (explicitly provided)
// 3. Session-based project root resolution
// 4. Current directory fallback
if (!rawRoot) {
log.error('Could not determine project root from args or session.');
return createErrorResponse(
'Could not determine project root. Please provide projectRoot argument or ensure session contains root info.'
);
// 1. Check for TASK_MASTER_PROJECT_ROOT environment variable first
if (process.env.TASK_MASTER_PROJECT_ROOT) {
const envRoot = process.env.TASK_MASTER_PROJECT_ROOT;
normalizedRoot = path.isAbsolute(envRoot)
? envRoot
: path.resolve(process.cwd(), envRoot);
rootSource = "TASK_MASTER_PROJECT_ROOT environment variable";
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// Also check session environment variables for TASK_MASTER_PROJECT_ROOT
else if (session?.env?.TASK_MASTER_PROJECT_ROOT) {
const envRoot = session.env.TASK_MASTER_PROJECT_ROOT;
normalizedRoot = path.isAbsolute(envRoot)
? envRoot
: path.resolve(process.cwd(), envRoot);
rootSource = "TASK_MASTER_PROJECT_ROOT session environment variable";
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// 2. If no environment variable, try args.projectRoot
else if (args.projectRoot) {
normalizedRoot = normalizeProjectRoot(args.projectRoot, log);
rootSource = "args.projectRoot";
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// 3. If no args.projectRoot, try session-based resolution
else {
const sessionRoot = getProjectRootFromSession(session, log);
if (sessionRoot) {
normalizedRoot = sessionRoot; // getProjectRootFromSession already normalizes
rootSource = "session";
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
}
// Normalize the determined raw root
normalizedRoot = normalizeProjectRoot(rawRoot, log);
if (!normalizedRoot) {
log.error(
`Failed to normalize project root obtained from ${rootSource}: ${rawRoot}`
"Could not determine project root from environment, args, or session."
);
return createErrorResponse(
`Invalid project root provided or derived from ${rootSource}: ${rawRoot}`
"Could not determine project root. Please provide projectRoot argument or ensure TASK_MASTER_PROJECT_ROOT environment variable is set."
);
}
@@ -648,5 +703,6 @@ export {
createLogWrapper,
normalizeProjectRoot,
getRawProjectRootFromSession,
withNormalizedProjectRoot
withNormalizedProjectRoot,
filterSensitiveTelemetryData,
};

2427
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "task-master-ai",
"version": "0.13.2",
"version": "0.15.0",
"description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
"main": "index.js",
"type": "module",
@@ -21,8 +21,8 @@
"release": "changeset publish",
"inspector": "npx @modelcontextprotocol/inspector node mcp-server/server.js",
"mcp-server": "node mcp-server/server.js",
"format-check": "prettier --check .",
"format": "prettier --write ."
"format-check": "biome format .",
"format": "biome format . --write"
},
"keywords": [
"claude",
@@ -39,39 +39,47 @@
"author": "Eyal Toledano",
"license": "MIT WITH Commons-Clause",
"dependencies": {
"@ai-sdk/amazon-bedrock": "^2.2.9",
"@ai-sdk/anthropic": "^1.2.10",
"@ai-sdk/azure": "^1.3.17",
"@ai-sdk/google": "^1.2.13",
"@ai-sdk/google-vertex": "^2.2.23",
"@ai-sdk/mistral": "^1.2.7",
"@ai-sdk/openai": "^1.3.20",
"@ai-sdk/perplexity": "^1.1.7",
"@ai-sdk/xai": "^1.2.15",
"@anthropic-ai/sdk": "^0.39.0",
"@aws-sdk/credential-providers": "^3.817.0",
"@openrouter/ai-sdk-provider": "^0.4.5",
"ai": "^4.3.10",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-highlight": "^2.1.11",
"cli-table3": "^0.6.5",
"commander": "^11.1.0",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.21.2",
"fastmcp": "^1.20.5",
"figlet": "^1.8.0",
"fuse.js": "^7.0.0",
"fuse.js": "^7.1.0",
"gpt-tokens": "^1.3.14",
"gradient-string": "^3.0.0",
"helmet": "^8.1.0",
"inquirer": "^12.5.0",
"jsonwebtoken": "^9.0.2",
"lru-cache": "^10.2.0",
"ollama-ai-provider": "^1.2.0",
"open": "^10.1.2",
"openai": "^4.89.0",
"ora": "^8.2.0",
"task-master-ai": "^0.15.0",
"uuid": "^11.1.0",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-table3": "^0.6.5",
"zod": "^3.23.8"
"zod": "^3.23.8",
"zod-to-json-schema": "^3.24.5"
},
"engines": {
"node": ">=14.0.0"
"node": ">=18.0.0"
},
"repository": {
"type": "git",
@@ -92,10 +100,11 @@
"src/**"
],
"overrides": {
"node-fetch": "^3.3.2",
"node-fetch": "^2.6.12",
"whatwg-url": "^11.0.0"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.28.1",
"@types/jest": "^29.5.14",
@@ -104,7 +113,6 @@
"jest": "^29.7.0",
"jest-environment-node": "^29.7.0",
"mock-fs": "^5.5.0",
"node-fetch": "^3.3.2",
"prettier": "^3.5.3",
"react": "^18.3.1",
"supertest": "^7.1.0",

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,13 @@
import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import { fileURLToPath } from 'url';
import { log, resolveEnvVariable, findProjectRoot } from './utils.js';
import fs from "fs";
import path from "path";
import chalk from "chalk";
import { fileURLToPath } from "url";
import {
log,
findProjectRoot,
resolveEnvVariable,
isSilentMode,
} from "./utils.js";
// Calculate __dirname in ESM
const __filename = fileURLToPath(import.meta.url);
@@ -12,14 +17,14 @@ const __dirname = path.dirname(__filename);
let MODEL_MAP;
try {
const supportedModelsRaw = fs.readFileSync(
path.join(__dirname, 'supported-models.json'),
'utf-8'
path.join(__dirname, "supported-models.json"),
"utf-8"
);
MODEL_MAP = JSON.parse(supportedModelsRaw);
} catch (error) {
console.error(
chalk.red(
'FATAL ERROR: Could not load supported-models.json. Please ensure the file exists and is valid JSON.'
"FATAL ERROR: Could not load supported-models.json. Please ensure the file exists and is valid JSON."
),
error
);
@@ -27,42 +32,49 @@ try {
process.exit(1); // Exit if models can't be loaded
}
const CONFIG_FILE_NAME = '.taskmasterconfig';
const CONFIG_FILE_NAME = ".taskmasterconfig";
// Define valid providers dynamically from the loaded MODEL_MAP
const VALID_PROVIDERS = Object.keys(MODEL_MAP || {});
// Default configuration values (used if .taskmasterconfig is missing or incomplete)
const DEFAULTS = {
// Default configuration structure (updated)
const defaultConfig = {
global: {
logLevel: "info",
debug: false,
defaultSubtasks: 5,
defaultPriority: "medium",
projectName: "Taskmaster",
ollamaBaseURL: "http://localhost:11434/api",
azureBaseURL: "https://your-endpoint.azure.com/",
},
models: {
main: {
provider: 'anthropic',
modelId: 'claude-3-7-sonnet-20250219',
provider: "anthropic",
modelId: "claude-3-7-sonnet-20250219",
maxTokens: 64000,
temperature: 0.2
temperature: 0.2,
},
research: {
provider: 'perplexity',
modelId: 'sonar-pro',
provider: "perplexity",
modelId: "sonar-pro",
maxTokens: 8700,
temperature: 0.1
temperature: 0.1,
},
fallback: {
// No default fallback provider/model initially
provider: 'anthropic',
modelId: 'claude-3-5-sonnet',
provider: "anthropic",
modelId: "claude-3-5-sonnet",
maxTokens: 64000, // Default parameters if fallback IS configured
temperature: 0.2
}
temperature: 0.2,
},
},
account: {
userId: "1234567890", // Placeholder that triggers auth/init
email: "",
mode: "byok",
telemetryEnabled: true,
},
global: {
logLevel: 'info',
debug: false,
defaultSubtasks: 5,
defaultPriority: 'medium',
projectName: 'Task Master',
ollamaBaseUrl: 'http://localhost:11434/api'
}
};
// --- Internal Config Loading ---
@@ -73,16 +85,16 @@ let loadedConfigRoot = null; // Track which root loaded the config
class ConfigurationError extends Error {
constructor(message) {
super(message);
this.name = 'ConfigurationError';
this.name = "ConfigurationError";
}
}
function _loadAndValidateConfig(explicitRoot = null) {
const defaults = DEFAULTS; // Use the defined defaults
const defaults = defaultConfig; // Use the defined defaults
let rootToUse = explicitRoot;
let configSource = explicitRoot
? `explicit root (${explicitRoot})`
: 'defaults (no root provided yet)';
: "defaults (no root provided yet)";
// ---> If no explicit root, TRY to find it <---
if (!rootToUse) {
@@ -104,7 +116,7 @@ function _loadAndValidateConfig(explicitRoot = null) {
if (fs.existsSync(configPath)) {
configExists = true;
try {
const rawData = fs.readFileSync(configPath, 'utf-8');
const rawData = fs.readFileSync(configPath, "utf-8");
const parsedConfig = JSON.parse(rawData);
// Deep merge parsed config onto defaults
@@ -113,15 +125,16 @@ function _loadAndValidateConfig(explicitRoot = null) {
main: { ...defaults.models.main, ...parsedConfig?.models?.main },
research: {
...defaults.models.research,
...parsedConfig?.models?.research
...parsedConfig?.models?.research,
},
fallback:
parsedConfig?.models?.fallback?.provider &&
parsedConfig?.models?.fallback?.modelId
? { ...defaults.models.fallback, ...parsedConfig.models.fallback }
: { ...defaults.models.fallback }
: { ...defaults.models.fallback },
},
global: { ...defaults.global, ...parsedConfig?.global }
global: { ...defaults.global, ...parsedConfig?.global },
account: { ...defaults.account, ...parsedConfig?.account },
};
configSource = `file (${configPath})`; // Update source info
@@ -256,68 +269,68 @@ function getModelConfigForRole(role, explicitRoot = null) {
const roleConfig = config?.models?.[role];
if (!roleConfig) {
log(
'warn',
"warn",
`No model configuration found for role: ${role}. Returning default.`
);
return DEFAULTS.models[role] || {};
return defaultConfig.models[role] || {};
}
return roleConfig;
}
function getMainProvider(explicitRoot = null) {
return getModelConfigForRole('main', explicitRoot).provider;
return getModelConfigForRole("main", explicitRoot).provider;
}
function getMainModelId(explicitRoot = null) {
return getModelConfigForRole('main', explicitRoot).modelId;
return getModelConfigForRole("main", explicitRoot).modelId;
}
function getMainMaxTokens(explicitRoot = null) {
// Directly return value from config (which includes defaults)
return getModelConfigForRole('main', explicitRoot).maxTokens;
return getModelConfigForRole("main", explicitRoot).maxTokens;
}
function getMainTemperature(explicitRoot = null) {
// Directly return value from config
return getModelConfigForRole('main', explicitRoot).temperature;
return getModelConfigForRole("main", explicitRoot).temperature;
}
function getResearchProvider(explicitRoot = null) {
return getModelConfigForRole('research', explicitRoot).provider;
return getModelConfigForRole("research", explicitRoot).provider;
}
function getResearchModelId(explicitRoot = null) {
return getModelConfigForRole('research', explicitRoot).modelId;
return getModelConfigForRole("research", explicitRoot).modelId;
}
function getResearchMaxTokens(explicitRoot = null) {
// Directly return value from config
return getModelConfigForRole('research', explicitRoot).maxTokens;
return getModelConfigForRole("research", explicitRoot).maxTokens;
}
function getResearchTemperature(explicitRoot = null) {
// Directly return value from config
return getModelConfigForRole('research', explicitRoot).temperature;
return getModelConfigForRole("research", explicitRoot).temperature;
}
function getFallbackProvider(explicitRoot = null) {
// Directly return value from config (will be undefined if not set)
return getModelConfigForRole('fallback', explicitRoot).provider;
return getModelConfigForRole("fallback", explicitRoot).provider;
}
function getFallbackModelId(explicitRoot = null) {
// Directly return value from config
return getModelConfigForRole('fallback', explicitRoot).modelId;
return getModelConfigForRole("fallback", explicitRoot).modelId;
}
function getFallbackMaxTokens(explicitRoot = null) {
// Directly return value from config
return getModelConfigForRole('fallback', explicitRoot).maxTokens;
return getModelConfigForRole("fallback", explicitRoot).maxTokens;
}
function getFallbackTemperature(explicitRoot = null) {
// Directly return value from config
return getModelConfigForRole('fallback', explicitRoot).temperature;
return getModelConfigForRole("fallback", explicitRoot).temperature;
}
// --- Global Settings Getters ---
@@ -325,7 +338,7 @@ function getFallbackTemperature(explicitRoot = null) {
function getGlobalConfig(explicitRoot = null) {
const config = getConfig(explicitRoot);
// Ensure global defaults are applied if global section is missing
return { ...DEFAULTS.global, ...(config?.global || {}) };
return { ...defaultConfig.global, ...(config?.global || {}) };
}
function getLogLevel(explicitRoot = null) {
@@ -342,13 +355,13 @@ function getDefaultSubtasks(explicitRoot = null) {
// Directly return value from config, ensure integer
const val = getGlobalConfig(explicitRoot).defaultSubtasks;
const parsedVal = parseInt(val, 10);
return isNaN(parsedVal) ? DEFAULTS.global.defaultSubtasks : parsedVal;
return isNaN(parsedVal) ? defaultConfig.global.defaultSubtasks : parsedVal;
}
function getDefaultNumTasks(explicitRoot = null) {
const val = getGlobalConfig(explicitRoot).defaultNumTasks;
const parsedVal = parseInt(val, 10);
return isNaN(parsedVal) ? DEFAULTS.global.defaultNumTasks : parsedVal;
return isNaN(parsedVal) ? defaultConfig.global.defaultNumTasks : parsedVal;
}
function getDefaultPriority(explicitRoot = null) {
@@ -361,9 +374,34 @@ function getProjectName(explicitRoot = null) {
return getGlobalConfig(explicitRoot).projectName;
}
function getOllamaBaseUrl(explicitRoot = null) {
function getOllamaBaseURL(explicitRoot = null) {
// Directly return value from config
return getGlobalConfig(explicitRoot).ollamaBaseUrl;
return getGlobalConfig(explicitRoot).ollamaBaseURL;
}
function getAzureBaseURL(explicitRoot = null) {
// Directly return value from config
return getGlobalConfig(explicitRoot).azureBaseURL;
}
/**
* Gets the Google Cloud project ID for Vertex AI from configuration
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string|null} The project ID or null if not configured
*/
function getVertexProjectId(explicitRoot = null) {
// Return value from config
return getGlobalConfig(explicitRoot).vertexProjectId;
}
/**
* Gets the Google Cloud location for Vertex AI from configuration
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string} The location or default value of "us-central1"
*/
function getVertexLocation(explicitRoot = null) {
// Return value from config or default
return getGlobalConfig(explicitRoot).vertexLocation || "us-central1";
}
/**
@@ -391,31 +429,31 @@ function getParametersForRole(role, explicitRoot = null) {
// Check if a model-specific max_tokens is defined and valid
if (
modelDefinition &&
typeof modelDefinition.max_tokens === 'number' &&
typeof modelDefinition.max_tokens === "number" &&
modelDefinition.max_tokens > 0
) {
const modelSpecificMaxTokens = modelDefinition.max_tokens;
// Use the minimum of the role default and the model specific limit
effectiveMaxTokens = Math.min(roleMaxTokens, modelSpecificMaxTokens);
log(
'debug',
"debug",
`Applying model-specific max_tokens (${modelSpecificMaxTokens}) for ${modelId}. Effective limit: ${effectiveMaxTokens}`
);
} else {
log(
'debug',
"debug",
`No valid model-specific max_tokens override found for ${modelId}. Using role default: ${roleMaxTokens}`
);
}
} else {
log(
'debug',
"debug",
`No model definitions found for provider ${providerName} in MODEL_MAP. Using role default maxTokens: ${roleMaxTokens}`
);
}
} catch (lookupError) {
log(
'warn',
"warn",
`Error looking up model-specific max_tokens for ${modelId}: ${lookupError.message}. Using role default: ${roleMaxTokens}`
);
// Fallback to role default on error
@@ -424,7 +462,7 @@ function getParametersForRole(role, explicitRoot = null) {
return {
maxTokens: effectiveMaxTokens,
temperature: roleTemperature
temperature: roleTemperature,
};
}
@@ -438,25 +476,26 @@ function getParametersForRole(role, explicitRoot = null) {
*/
function isApiKeySet(providerName, session = null, projectRoot = null) {
// Define the expected environment variable name for each provider
if (providerName?.toLowerCase() === 'ollama') {
if (providerName?.toLowerCase() === "ollama") {
return true; // Indicate key status is effectively "OK"
}
const keyMap = {
openai: 'OPENAI_API_KEY',
anthropic: 'ANTHROPIC_API_KEY',
google: 'GOOGLE_API_KEY',
perplexity: 'PERPLEXITY_API_KEY',
mistral: 'MISTRAL_API_KEY',
azure: 'AZURE_OPENAI_API_KEY',
openrouter: 'OPENROUTER_API_KEY',
xai: 'XAI_API_KEY'
openai: "OPENAI_API_KEY",
anthropic: "ANTHROPIC_API_KEY",
google: "GOOGLE_API_KEY",
perplexity: "PERPLEXITY_API_KEY",
mistral: "MISTRAL_API_KEY",
azure: "AZURE_OPENAI_API_KEY",
openrouter: "OPENROUTER_API_KEY",
xai: "XAI_API_KEY",
vertex: "GOOGLE_API_KEY", // Vertex uses the same key as Google
// Add other providers as needed
};
const providerKey = providerName?.toLowerCase();
if (!providerKey || !keyMap[providerKey]) {
log('warn', `Unknown provider name: ${providerName} in isApiKeySet check.`);
log("warn", `Unknown provider name: ${providerName} in isApiKeySet check.`);
return false;
}
@@ -466,9 +505,9 @@ function isApiKeySet(providerName, session = null, projectRoot = null) {
// Check if the key exists, is not empty, and is not a placeholder
return (
apiKeyValue &&
apiKeyValue.trim() !== '' &&
apiKeyValue.trim() !== "" &&
!/YOUR_.*_API_KEY_HERE/.test(apiKeyValue) && // General placeholder check
!apiKeyValue.includes('KEY_HERE')
!apiKeyValue.includes("KEY_HERE")
); // Another common placeholder pattern
}
@@ -483,11 +522,11 @@ function getMcpApiKeyStatus(providerName, projectRoot = null) {
const rootDir = projectRoot || findProjectRoot(); // Use existing root finding
if (!rootDir) {
console.warn(
chalk.yellow('Warning: Could not find project root to check mcp.json.')
chalk.yellow("Warning: Could not find project root to check mcp.json.")
);
return false; // Cannot check without root
}
const mcpConfigPath = path.join(rootDir, '.cursor', 'mcp.json');
const mcpConfigPath = path.join(rootDir, ".cursor", "mcp.json");
if (!fs.existsSync(mcpConfigPath)) {
// console.warn(chalk.yellow('Warning: .cursor/mcp.json not found.'));
@@ -495,10 +534,10 @@ function getMcpApiKeyStatus(providerName, projectRoot = null) {
}
try {
const mcpConfigRaw = fs.readFileSync(mcpConfigPath, 'utf-8');
const mcpConfigRaw = fs.readFileSync(mcpConfigPath, "utf-8");
const mcpConfig = JSON.parse(mcpConfigRaw);
const mcpEnv = mcpConfig?.mcpServers?.['taskmaster-ai']?.env;
const mcpEnv = mcpConfig?.mcpServers?.["taskmaster-ai"]?.env;
if (!mcpEnv) {
// console.warn(chalk.yellow('Warning: Could not find taskmaster-ai env in mcp.json.'));
return false; // Structure missing
@@ -508,39 +547,43 @@ function getMcpApiKeyStatus(providerName, projectRoot = null) {
let placeholderValue = null;
switch (providerName) {
case 'anthropic':
case "anthropic":
apiKeyToCheck = mcpEnv.ANTHROPIC_API_KEY;
placeholderValue = 'YOUR_ANTHROPIC_API_KEY_HERE';
placeholderValue = "YOUR_ANTHROPIC_API_KEY_HERE";
break;
case 'openai':
case "openai":
apiKeyToCheck = mcpEnv.OPENAI_API_KEY;
placeholderValue = 'YOUR_OPENAI_API_KEY_HERE'; // Assuming placeholder matches OPENAI
placeholderValue = "YOUR_OPENAI_API_KEY_HERE"; // Assuming placeholder matches OPENAI
break;
case 'openrouter':
case "openrouter":
apiKeyToCheck = mcpEnv.OPENROUTER_API_KEY;
placeholderValue = 'YOUR_OPENROUTER_API_KEY_HERE';
placeholderValue = "YOUR_OPENROUTER_API_KEY_HERE";
break;
case 'google':
case "google":
apiKeyToCheck = mcpEnv.GOOGLE_API_KEY;
placeholderValue = 'YOUR_GOOGLE_API_KEY_HERE';
placeholderValue = "YOUR_GOOGLE_API_KEY_HERE";
break;
case 'perplexity':
case "perplexity":
apiKeyToCheck = mcpEnv.PERPLEXITY_API_KEY;
placeholderValue = 'YOUR_PERPLEXITY_API_KEY_HERE';
placeholderValue = "YOUR_PERPLEXITY_API_KEY_HERE";
break;
case 'xai':
case "xai":
apiKeyToCheck = mcpEnv.XAI_API_KEY;
placeholderValue = 'YOUR_XAI_API_KEY_HERE';
placeholderValue = "YOUR_XAI_API_KEY_HERE";
break;
case 'ollama':
case "ollama":
return true; // No key needed
case 'mistral':
case "mistral":
apiKeyToCheck = mcpEnv.MISTRAL_API_KEY;
placeholderValue = 'YOUR_MISTRAL_API_KEY_HERE';
placeholderValue = "YOUR_MISTRAL_API_KEY_HERE";
break;
case 'azure':
case "azure":
apiKeyToCheck = mcpEnv.AZURE_OPENAI_API_KEY;
placeholderValue = 'YOUR_AZURE_OPENAI_API_KEY_HERE';
placeholderValue = "YOUR_AZURE_OPENAI_API_KEY_HERE";
break;
case "vertex":
apiKeyToCheck = mcpEnv.GOOGLE_API_KEY; // Vertex uses Google API key
placeholderValue = "YOUR_GOOGLE_API_KEY_HERE";
break;
default:
return false; // Unknown provider
@@ -568,20 +611,20 @@ function getAvailableModels() {
const modelId = modelObj.id;
const sweScore = modelObj.swe_score;
const cost = modelObj.cost_per_1m_tokens;
const allowedRoles = modelObj.allowed_roles || ['main', 'fallback'];
const allowedRoles = modelObj.allowed_roles || ["main", "fallback"];
const nameParts = modelId
.split('-')
.split("-")
.map((p) => p.charAt(0).toUpperCase() + p.slice(1));
// Handle specific known names better if needed
let name = nameParts.join(' ');
if (modelId === 'claude-3.5-sonnet-20240620')
name = 'Claude 3.5 Sonnet';
if (modelId === 'claude-3-7-sonnet-20250219')
name = 'Claude 3.7 Sonnet';
if (modelId === 'gpt-4o') name = 'GPT-4o';
if (modelId === 'gpt-4-turbo') name = 'GPT-4 Turbo';
if (modelId === 'sonar-pro') name = 'Perplexity Sonar Pro';
if (modelId === 'sonar-mini') name = 'Perplexity Sonar Mini';
let name = nameParts.join(" ");
if (modelId === "claude-3.5-sonnet-20240620")
name = "Claude 3.5 Sonnet";
if (modelId === "claude-3-7-sonnet-20250219")
name = "Claude 3.7 Sonnet";
if (modelId === "gpt-4o") name = "GPT-4o";
if (modelId === "gpt-4-turbo") name = "GPT-4 Turbo";
if (modelId === "sonar-pro") name = "Perplexity Sonar Pro";
if (modelId === "sonar-mini") name = "Perplexity Sonar Mini";
available.push({
id: modelId,
@@ -589,7 +632,7 @@ function getAvailableModels() {
provider: provider,
swe_score: sweScore,
cost_per_1m_tokens: cost,
allowed_roles: allowedRoles
allowed_roles: allowedRoles,
});
});
} else {
@@ -597,7 +640,7 @@ function getAvailableModels() {
available.push({
id: `[${provider}-any]`,
name: `Any (${provider})`,
provider: provider
provider: provider,
});
}
}
@@ -619,7 +662,7 @@ function writeConfig(config, explicitRoot = null) {
if (!foundRoot) {
console.error(
chalk.red(
'Error: Could not determine project root. Configuration not saved.'
"Error: Could not determine project root. Configuration not saved."
)
);
return false;
@@ -669,6 +712,74 @@ function isConfigFilePresent(explicitRoot = null) {
return fs.existsSync(configPath);
}
/**
* Gets the user ID from the configuration.
* Returns a placeholder that triggers auth/init if no real userId exists.
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string|null} The user ID or placeholder, or null if auth unavailable.
*/
function getUserId(explicitRoot = null) {
const config = getConfig(explicitRoot);
// Ensure account section exists
if (!config.account) {
config.account = { ...defaultConfig.account };
}
// Check if the userId exists in the actual file (not merged config)
let needsToSaveUserId = false;
// Load the raw config to check if userId is actually in the file
try {
let rootPath = explicitRoot;
if (explicitRoot === null || explicitRoot === undefined) {
const foundRoot = findProjectRoot();
if (!foundRoot) {
// If no project root, can't check file, assume userId needs to be saved
needsToSaveUserId = true;
} else {
rootPath = foundRoot;
}
}
if (rootPath && !needsToSaveUserId) {
const configPath = path.join(rootPath, CONFIG_FILE_NAME);
if (fs.existsSync(configPath)) {
const rawConfig = JSON.parse(fs.readFileSync(configPath, "utf8"));
// Check if userId is missing from the actual file
needsToSaveUserId = !rawConfig.account?.userId;
} else {
// Config file doesn't exist, need to save
needsToSaveUserId = true;
}
}
} catch (error) {
// If there's any error reading the file, assume we need to save
needsToSaveUserId = true;
}
// If userId exists and is not the placeholder, return it
if (config.account.userId && config.account.userId !== "1234567890") {
return config.account.userId;
}
// If userId is missing from the actual file, set the placeholder and save it
if (needsToSaveUserId) {
config.account.userId = "1234567890";
const success = writeConfig(config, explicitRoot);
if (!success) {
console.warn("Warning: Failed to save default userId to config file");
}
// Force reload the cached config to reflect the change
loadedConfig = null;
loadedConfigRoot = null;
}
// Return the placeholder
// This signals to other code that auth/init needs to be attempted
return "1234567890";
}
/**
* Gets a list of all provider names defined in the MODEL_MAP.
* @returns {string[]} An array of provider names.
@@ -679,25 +790,96 @@ function getAllProviders() {
function getBaseUrlForRole(role, explicitRoot = null) {
const roleConfig = getModelConfigForRole(role, explicitRoot);
return roleConfig && typeof roleConfig.baseUrl === 'string'
? roleConfig.baseUrl
return roleConfig && typeof roleConfig.baseURL === "string"
? roleConfig.baseURL
: undefined;
}
// Get telemetryEnabled from account section
function getTelemetryEnabled(explicitRoot = null) {
const config = getConfig(explicitRoot);
return config.account?.telemetryEnabled ?? false;
}
// Update getUserEmail to use account
function getUserEmail(explicitRoot = null) {
const config = getConfig(explicitRoot);
return config.account?.email || "";
}
// Update getMode function to use account
function getMode(explicitRoot = null) {
const config = getConfig(explicitRoot);
return config.account?.mode || "byok";
}
/**
* Ensures that the .taskmasterconfig file exists, creating it with defaults if it doesn't.
* This is called early in initialization to prevent chicken-and-egg problems.
* @param {string|null} explicitRoot - Optional explicit path to the project root
* @returns {boolean} True if file exists or was created successfully, false otherwise
*/
function ensureConfigFileExists(explicitRoot = null) {
// ---> Determine root path reliably (following existing pattern) <---
let rootPath = explicitRoot;
if (explicitRoot === null || explicitRoot === undefined) {
// Logic matching _loadAndValidateConfig and other functions
const foundRoot = findProjectRoot(); // *** Explicitly call findProjectRoot ***
if (!foundRoot) {
console.warn(
chalk.yellow(
"Warning: Could not determine project root for config file creation."
)
);
return false;
}
rootPath = foundRoot;
}
// ---> End determine root path logic <---
const configPath = path.join(rootPath, CONFIG_FILE_NAME);
// If file already exists, we're good
if (fs.existsSync(configPath)) {
return true;
}
try {
// Create the default config file (following writeConfig pattern)
fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2));
// Only log if not in silent mode
if (!isSilentMode()) {
console.log(chalk.blue(` Created default .taskmasterconfig file`));
}
// Clear any cached config to ensure fresh load
loadedConfig = null;
loadedConfigRoot = null;
return true;
} catch (error) {
console.error(
chalk.red(
`Error creating default .taskmasterconfig file: ${error.message}`
)
);
return false;
}
}
export {
// Core config access
getConfig,
writeConfig,
ConfigurationError, // Export custom error type
isConfigFilePresent, // Add the new function export
ConfigurationError,
isConfigFilePresent,
// Validation
validateProvider,
validateProviderModelCombination,
VALID_PROVIDERS,
MODEL_MAP,
getAvailableModels,
// Role-specific getters (No env var overrides)
getMainProvider,
getMainModelId,
@@ -712,7 +894,6 @@ export {
getFallbackMaxTokens,
getFallbackTemperature,
getBaseUrlForRole,
// Global setting getters (No env var overrides)
getLogLevel,
getDebugFlag,
@@ -720,13 +901,21 @@ export {
getDefaultSubtasks,
getDefaultPriority,
getProjectName,
getOllamaBaseUrl,
getOllamaBaseURL,
getAzureBaseURL,
getParametersForRole,
getUserId,
// API Key Checkers (still relevant)
isApiKeySet,
getMcpApiKeyStatus,
// ADD: Function to get all provider names
getAllProviders
getAllProviders,
getVertexProjectId,
getVertexLocation,
// New getters
getTelemetryEnabled,
getUserEmail,
getMode,
// New function
ensureConfigFileExists,
};

View File

@@ -1,5 +1,19 @@
{
"anthropic": [
{
"id": "claude-sonnet-4-20250514",
"swe_score": 0.727,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 64000
},
{
"id": "claude-opus-4-20250514",
"swe_score": 0.725,
"cost_per_1m_tokens": { "input": 15.0, "output": 75.0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 32000
},
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
@@ -99,34 +113,39 @@
],
"google": [
{
"id": "gemini-2.5-pro-exp-03-25",
"id": "gemini-2.5-pro-preview-05-06",
"swe_score": 0.638,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"]
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
},
{
"id": "gemini-2.5-pro-preview-03-25",
"swe_score": 0.638,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
},
{
"id": "gemini-2.5-flash-preview-04-17",
"swe_score": 0,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"]
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
},
{
"id": "gemini-2.0-flash",
"swe_score": 0.754,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"]
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
},
{
"id": "gemini-2.0-flash-thinking-experimental",
"swe_score": 0.754,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "gemini-2.0-pro",
"id": "gemini-2.0-flash-lite",
"swe_score": 0,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"]
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
}
],
"perplexity": [
@@ -186,43 +205,43 @@
],
"ollama": [
{
"id": "gemma3:27b",
"id": "devstral:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "gemma3:12b",
"id": "qwen3:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "qwq",
"id": "qwen3:14b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "deepseek-r1",
"id": "qwen3:32b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "mistral-small3.1",
"id": "mistral-small3.1:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "llama3.3",
"id": "llama3.3:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "phi4",
"id": "phi4:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
@@ -230,9 +249,16 @@
],
"openrouter": [
{
"id": "google/gemini-2.0-flash-001",
"id": "google/gemini-2.5-flash-preview-05-20",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048576
},
{
"id": "google/gemini-2.5-flash-preview-05-20:thinking",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048576
},
@@ -258,40 +284,25 @@
"max_tokens": 64000
},
{
"id": "deepseek/deepseek-r1:free",
"id": "openai/gpt-4.1",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"cost_per_1m_tokens": { "input": 2, "output": 8 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 163840
"max_tokens": 1000000
},
{
"id": "microsoft/mai-ds-r1:free",
"id": "openai/gpt-4.1-mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"cost_per_1m_tokens": { "input": 0.4, "output": 1.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 163840
"max_tokens": 1000000
},
{
"id": "google/gemini-2.5-pro-preview-03-25",
"id": "openai/gpt-4.1-nano",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 1.25, "output": 10 },
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 65535
},
{
"id": "google/gemini-2.5-flash-preview",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main"],
"max_tokens": 65535
},
{
"id": "google/gemini-2.5-flash-preview:thinking",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
"allowed_roles": ["main"],
"max_tokens": 65535
"max_tokens": 1000000
},
{
"id": "openai/o3",
@@ -300,6 +311,20 @@
"allowed_roles": ["main", "fallback"],
"max_tokens": 200000
},
{
"id": "openai/codex-mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 1.5, "output": 6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{
"id": "openai/gpt-4o-mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{
"id": "openai/o4-mini",
"swe_score": 0.45,
@@ -329,46 +354,18 @@
"max_tokens": 1048576
},
{
"id": "google/gemma-3-12b-it:free",
"id": "meta-llama/llama-4-maverick",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"cost_per_1m_tokens": { "input": 0.18, "output": 0.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
"max_tokens": 1000000
},
{
"id": "google/gemma-3-12b-it",
"id": "meta-llama/llama-4-scout",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 50, "output": 100 },
"cost_per_1m_tokens": { "input": 0.08, "output": 0.3 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
},
{
"id": "google/gemma-3-27b-it:free",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 96000
},
{
"id": "google/gemma-3-27b-it",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 100, "output": 200 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
},
{
"id": "qwen/qwq-32b:free",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 40000
},
{
"id": "qwen/qwq-32b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 150, "output": 200 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
"max_tokens": 1000000
},
{
"id": "qwen/qwen-max",
@@ -384,6 +381,13 @@
"allowed_roles": ["main", "fallback"],
"max_tokens": 1000000
},
{
"id": "qwen/qwen3-235b-a22b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.14, "output": 2 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 24000
},
{
"id": "mistralai/mistral-small-3.1-24b-instruct:free",
"swe_score": 0,
@@ -398,6 +402,20 @@
"allowed_roles": ["main", "fallback"],
"max_tokens": 128000
},
{
"id": "mistralai/devstral-small",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.1, "output": 0.3 },
"allowed_roles": ["main"],
"max_tokens": 110000
},
{
"id": "mistralai/mistral-nemo",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.03, "output": 0.07 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{
"id": "thudm/glm-4-32b:free",
"swe_score": 0,

View File

@@ -23,6 +23,8 @@ import updateSubtaskById from './task-manager/update-subtask-by-id.js';
import removeTask from './task-manager/remove-task.js';
import taskExists from './task-manager/task-exists.js';
import isTaskDependentOn from './task-manager/is-task-dependent.js';
import moveTask from './task-manager/move-task.js';
import { performResearch } from './task-manager/research.js';
import { readComplexityReport } from './utils.js';
// Export task manager functions
export {
@@ -46,5 +48,7 @@ export {
findTaskById,
taskExists,
isTaskDependentOn,
moveTask,
performResearch,
readComplexityReport
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,15 @@
import chalk from 'chalk';
import boxen from 'boxen';
import readline from 'readline';
import fs from 'fs';
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
import {
startLoadingIndicator,
stopLoadingIndicator,
displayAiUsageSummary
} from '../ui.js';
import { generateTextService } from '../ai-services-unified.js';
@@ -47,6 +52,9 @@ Do not include any explanatory text, markdown formatting, or code block markers
* @param {string|number} [options.threshold] - Complexity threshold
* @param {boolean} [options.research] - Use research role
* @param {string} [options.projectRoot] - Project root path (for MCP/env fallback).
* @param {string} [options.id] - Comma-separated list of task IDs to analyze specifically
* @param {number} [options.from] - Starting task ID in a range to analyze
* @param {number} [options.to] - Ending task ID in a range to analyze
* @param {Object} [options._filteredTasksData] - Pre-filtered task data (internal use)
* @param {number} [options._originalTaskCount] - Original task count (internal use)
* @param {Object} context - Context object, potentially containing session and mcpLog
@@ -61,6 +69,15 @@ async function analyzeTaskComplexity(options, context = {}) {
const thresholdScore = parseFloat(options.threshold || '5');
const useResearch = options.research || false;
const projectRoot = options.projectRoot;
// New parameters for task ID filtering
const specificIds = options.id
? options.id
.split(',')
.map((id) => parseInt(id.trim(), 10))
.filter((id) => !isNaN(id))
: null;
const fromId = options.from !== undefined ? parseInt(options.from, 10) : null;
const toId = options.to !== undefined ? parseInt(options.to, 10) : null;
const outputFormat = mcpLog ? 'json' : 'text';
@@ -84,13 +101,14 @@ async function analyzeTaskComplexity(options, context = {}) {
reportLog(`Reading tasks from ${tasksPath}...`, 'info');
let tasksData;
let originalTaskCount = 0;
let originalData = null;
if (options._filteredTasksData) {
tasksData = options._filteredTasksData;
originalTaskCount = options._originalTaskCount || tasksData.tasks.length;
if (!options._originalTaskCount) {
try {
const originalData = readJSON(tasksPath);
originalData = readJSON(tasksPath);
if (originalData && originalData.tasks) {
originalTaskCount = originalData.tasks.length;
}
@@ -99,22 +117,80 @@ async function analyzeTaskComplexity(options, context = {}) {
}
}
} else {
tasksData = readJSON(tasksPath);
originalData = readJSON(tasksPath);
if (
!tasksData ||
!tasksData.tasks ||
!Array.isArray(tasksData.tasks) ||
tasksData.tasks.length === 0
!originalData ||
!originalData.tasks ||
!Array.isArray(originalData.tasks) ||
originalData.tasks.length === 0
) {
throw new Error('No tasks found in the tasks file');
}
originalTaskCount = tasksData.tasks.length;
originalTaskCount = originalData.tasks.length;
// Filter tasks based on active status
const activeStatuses = ['pending', 'blocked', 'in-progress'];
const filteredTasks = tasksData.tasks.filter((task) =>
let filteredTasks = originalData.tasks.filter((task) =>
activeStatuses.includes(task.status?.toLowerCase() || 'pending')
);
// Apply ID filtering if specified
if (specificIds && specificIds.length > 0) {
reportLog(
`Filtering tasks by specific IDs: ${specificIds.join(', ')}`,
'info'
);
filteredTasks = filteredTasks.filter((task) =>
specificIds.includes(task.id)
);
if (outputFormat === 'text') {
if (filteredTasks.length === 0 && specificIds.length > 0) {
console.log(
chalk.yellow(
`Warning: No active tasks found with IDs: ${specificIds.join(', ')}`
)
);
} else if (filteredTasks.length < specificIds.length) {
const foundIds = filteredTasks.map((t) => t.id);
const missingIds = specificIds.filter(
(id) => !foundIds.includes(id)
);
console.log(
chalk.yellow(
`Warning: Some requested task IDs were not found or are not active: ${missingIds.join(', ')}`
)
);
}
}
}
// Apply range filtering if specified
else if (fromId !== null || toId !== null) {
const effectiveFromId = fromId !== null ? fromId : 1;
const effectiveToId =
toId !== null
? toId
: Math.max(...originalData.tasks.map((t) => t.id));
reportLog(
`Filtering tasks by ID range: ${effectiveFromId} to ${effectiveToId}`,
'info'
);
filteredTasks = filteredTasks.filter(
(task) => task.id >= effectiveFromId && task.id <= effectiveToId
);
if (outputFormat === 'text' && filteredTasks.length === 0) {
console.log(
chalk.yellow(
`Warning: No active tasks found in range: ${effectiveFromId}-${effectiveToId}`
)
);
}
}
tasksData = {
...tasksData,
...originalData,
tasks: filteredTasks,
_originalTaskCount: originalTaskCount
};
@@ -125,7 +201,18 @@ async function analyzeTaskComplexity(options, context = {}) {
`Found ${originalTaskCount} total tasks in the task file.`,
'info'
);
if (skippedCount > 0) {
// Updated messaging to reflect filtering logic
if (specificIds || fromId !== null || toId !== null) {
const filterMsg = specificIds
? `Analyzing ${tasksData.tasks.length} tasks with specific IDs: ${specificIds.join(', ')}`
: `Analyzing ${tasksData.tasks.length} tasks in range: ${fromId || 1} to ${toId || 'end'}`;
reportLog(filterMsg, 'info');
if (outputFormat === 'text') {
console.log(chalk.blue(filterMsg));
}
} else if (skippedCount > 0) {
const skipMessage = `Skipping ${skippedCount} tasks marked as done/cancelled/deferred. Analyzing ${tasksData.tasks.length} active tasks.`;
reportLog(skipMessage, 'info');
if (outputFormat === 'text') {
@@ -133,7 +220,59 @@ async function analyzeTaskComplexity(options, context = {}) {
}
}
// Check for existing report before doing analysis
let existingReport = null;
let existingAnalysisMap = new Map(); // For quick lookups by task ID
try {
if (fs.existsSync(outputPath)) {
existingReport = readJSON(outputPath);
reportLog(`Found existing complexity report at ${outputPath}`, 'info');
if (
existingReport &&
existingReport.complexityAnalysis &&
Array.isArray(existingReport.complexityAnalysis)
) {
// Create lookup map of existing analysis entries
existingReport.complexityAnalysis.forEach((item) => {
existingAnalysisMap.set(item.taskId, item);
});
reportLog(
`Existing report contains ${existingReport.complexityAnalysis.length} task analyses`,
'info'
);
}
}
} catch (readError) {
reportLog(
`Warning: Could not read existing report: ${readError.message}`,
'warn'
);
existingReport = null;
existingAnalysisMap.clear();
}
if (tasksData.tasks.length === 0) {
// If using ID filtering but no matching tasks, return existing report or empty
if (existingReport && (specificIds || fromId !== null || toId !== null)) {
reportLog(
`No matching tasks found for analysis. Keeping existing report.`,
'info'
);
if (outputFormat === 'text') {
console.log(
chalk.yellow(
`No matching tasks found for analysis. Keeping existing report.`
)
);
}
return {
report: existingReport,
telemetryData: null
};
}
// Otherwise create empty report
const emptyReport = {
meta: {
generatedAt: new Date().toISOString(),
@@ -142,9 +281,9 @@ async function analyzeTaskComplexity(options, context = {}) {
projectName: getProjectName(session),
usedResearch: useResearch
},
complexityAnalysis: []
complexityAnalysis: existingReport?.complexityAnalysis || []
};
reportLog(`Writing empty complexity report to ${outputPath}...`, 'info');
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
writeJSON(outputPath, emptyReport);
reportLog(
`Task complexity analysis complete. Report written to ${outputPath}`,
@@ -192,39 +331,40 @@ async function analyzeTaskComplexity(options, context = {}) {
)
);
}
return emptyReport;
return {
report: emptyReport,
telemetryData: null
};
}
// Continue with regular analysis path
const prompt = generateInternalComplexityAnalysisPrompt(tasksData);
// System prompt remains simple for text generation
const systemPrompt =
'You are an expert software architect and project manager analyzing task complexity. Respond only with the requested valid JSON array.';
let loadingIndicator = null;
if (outputFormat === 'text') {
loadingIndicator = startLoadingIndicator('Calling AI service...');
loadingIndicator = startLoadingIndicator(
`${useResearch ? 'Researching' : 'Analyzing'} the complexity of your tasks with AI...\n`
);
}
let fullResponse = ''; // To store the raw text response
let aiServiceResponse = null;
let complexityAnalysis = null;
try {
const role = useResearch ? 'research' : 'main';
reportLog(`Using AI service with role: ${role}`, 'info');
fullResponse = await generateTextService({
aiServiceResponse = await generateTextService({
prompt,
systemPrompt,
role,
session,
projectRoot
projectRoot,
commandName: 'analyze-complexity',
outputType: mcpLog ? 'mcp' : 'cli'
});
reportLog(
'Successfully received text response via AI service',
'success'
);
// --- Stop Loading Indicator (Unchanged) ---
if (loadingIndicator) {
stopLoadingIndicator(loadingIndicator);
loadingIndicator = null;
@@ -236,26 +376,18 @@ async function analyzeTaskComplexity(options, context = {}) {
chalk.green('AI service call complete. Parsing response...')
);
}
// --- End Stop Loading Indicator ---
// --- Re-introduce Manual JSON Parsing & Cleanup ---
reportLog(`Parsing complexity analysis from text response...`, 'info');
let complexityAnalysis;
try {
let cleanedResponse = fullResponse;
// Basic trim first
let cleanedResponse = aiServiceResponse.mainResult;
cleanedResponse = cleanedResponse.trim();
// Remove potential markdown code block fences
const codeBlockMatch = cleanedResponse.match(
/```(?:json)?\s*([\s\S]*?)\s*```/
);
if (codeBlockMatch) {
cleanedResponse = codeBlockMatch[1].trim(); // Trim content inside block
reportLog('Extracted JSON from code block', 'info');
cleanedResponse = codeBlockMatch[1].trim();
} else {
// If no code block, ensure it starts with '[' and ends with ']'
// This is less robust but a common fallback
const firstBracket = cleanedResponse.indexOf('[');
const lastBracket = cleanedResponse.lastIndexOf(']');
if (firstBracket !== -1 && lastBracket > firstBracket) {
@@ -263,13 +395,11 @@ async function analyzeTaskComplexity(options, context = {}) {
firstBracket,
lastBracket + 1
);
reportLog('Extracted content between first [ and last ]', 'info');
} else {
reportLog(
'Warning: Response does not appear to be a JSON array.',
'warn'
);
// Keep going, maybe JSON.parse can handle it or will fail informatively
}
}
@@ -283,48 +413,23 @@ async function analyzeTaskComplexity(options, context = {}) {
);
}
try {
complexityAnalysis = JSON.parse(cleanedResponse);
} catch (jsonError) {
} catch (parseError) {
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
reportLog(
'Initial JSON parsing failed. Raw response might be malformed.',
'error'
);
reportLog(`Original JSON Error: ${jsonError.message}`, 'error');
if (outputFormat === 'text' && getDebugFlag(session)) {
console.log(chalk.red('--- Start Raw Malformed Response ---'));
console.log(chalk.gray(fullResponse));
console.log(chalk.red('--- End Raw Malformed Response ---'));
}
// Re-throw the specific JSON parsing error
throw new Error(
`Failed to parse JSON response: ${jsonError.message}`
);
}
// Ensure it's an array after parsing
if (!Array.isArray(complexityAnalysis)) {
throw new Error('Parsed response is not a valid JSON array.');
}
} catch (error) {
// Catch errors specifically from the parsing/cleanup block
if (loadingIndicator) stopLoadingIndicator(loadingIndicator); // Ensure indicator stops
reportLog(
`Error parsing complexity analysis JSON: ${error.message}`,
`Error parsing complexity analysis JSON: ${parseError.message}`,
'error'
);
if (outputFormat === 'text') {
console.error(
chalk.red(
`Error parsing complexity analysis JSON: ${error.message}`
`Error parsing complexity analysis JSON: ${parseError.message}`
)
);
}
throw error; // Re-throw parsing error
throw parseError;
}
// --- End Manual JSON Parsing & Cleanup ---
// --- Post-processing (Missing Task Check) - (Unchanged) ---
const taskIds = tasksData.tasks.map((t) => t.id);
const analysisTaskIds = complexityAnalysis.map((a) => a.taskId);
const missingTaskIds = taskIds.filter(
@@ -359,35 +464,64 @@ async function analyzeTaskComplexity(options, context = {}) {
}
}
}
// --- End Post-processing ---
// --- Report Creation & Writing (Unchanged) ---
const finalReport = {
// Merge with existing report
let finalComplexityAnalysis = [];
if (existingReport && Array.isArray(existingReport.complexityAnalysis)) {
// Create a map of task IDs that we just analyzed
const analyzedTaskIds = new Set(
complexityAnalysis.map((item) => item.taskId)
);
// Keep existing entries that weren't in this analysis run
const existingEntriesNotAnalyzed =
existingReport.complexityAnalysis.filter(
(item) => !analyzedTaskIds.has(item.taskId)
);
// Combine with new analysis
finalComplexityAnalysis = [
...existingEntriesNotAnalyzed,
...complexityAnalysis
];
reportLog(
`Merged ${complexityAnalysis.length} new analyses with ${existingEntriesNotAnalyzed.length} existing entries`,
'info'
);
} else {
// No existing report or invalid format, just use the new analysis
finalComplexityAnalysis = complexityAnalysis;
}
const report = {
meta: {
generatedAt: new Date().toISOString(),
tasksAnalyzed: tasksData.tasks.length,
totalTasks: originalTaskCount,
analysisCount: finalComplexityAnalysis.length,
thresholdScore: thresholdScore,
projectName: getProjectName(session),
usedResearch: useResearch
},
complexityAnalysis: complexityAnalysis
complexityAnalysis: finalComplexityAnalysis
};
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
writeJSON(outputPath, finalReport);
writeJSON(outputPath, report);
reportLog(
`Task complexity analysis complete. Report written to ${outputPath}`,
'success'
);
// --- End Report Creation & Writing ---
// --- Display CLI Summary (Unchanged) ---
if (outputFormat === 'text') {
console.log(
chalk.green(
`Task complexity analysis complete. Report written to ${outputPath}`
)
);
// Calculate statistics specifically for this analysis run
const highComplexity = complexityAnalysis.filter(
(t) => t.complexityScore >= 8
).length;
@@ -399,18 +533,25 @@ async function analyzeTaskComplexity(options, context = {}) {
).length;
const totalAnalyzed = complexityAnalysis.length;
console.log('\nComplexity Analysis Summary:');
console.log('\nCurrent Analysis Summary:');
console.log('----------------------------');
console.log(
`Active tasks sent for analysis: ${tasksData.tasks.length}`
);
console.log(`Tasks successfully analyzed: ${totalAnalyzed}`);
console.log(`Tasks analyzed in this run: ${totalAnalyzed}`);
console.log(`High complexity tasks: ${highComplexity}`);
console.log(`Medium complexity tasks: ${mediumComplexity}`);
console.log(`Low complexity tasks: ${lowComplexity}`);
if (existingReport) {
console.log('\nUpdated Report Summary:');
console.log('----------------------------');
console.log(
`Sum verification: ${highComplexity + mediumComplexity + lowComplexity} (should equal ${totalAnalyzed})`
`Total analyses in report: ${finalComplexityAnalysis.length}`
);
console.log(
`Analyses from previous runs: ${finalComplexityAnalysis.length - totalAnalyzed}`
);
console.log(`New/updated analyses: ${totalAnalyzed}`);
}
console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`);
console.log(
`\nSee ${outputPath} for the full report and expansion commands.`
@@ -435,23 +576,28 @@ async function analyzeTaskComplexity(options, context = {}) {
if (getDebugFlag(session)) {
console.debug(
chalk.gray(
`Final analysis object: ${JSON.stringify(finalReport, null, 2)}`
`Final analysis object: ${JSON.stringify(report, null, 2)}`
)
);
}
}
// --- End Display CLI Summary ---
return finalReport;
} catch (error) {
// Catches errors from generateTextService call
if (aiServiceResponse.telemetryData) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
}
return {
report: report,
telemetryData: aiServiceResponse?.telemetryData
};
} catch (aiError) {
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
reportLog(`Error during AI service call: ${error.message}`, 'error');
reportLog(`Error during AI service call: ${aiError.message}`, 'error');
if (outputFormat === 'text') {
console.error(
chalk.red(`Error during AI service call: ${error.message}`)
chalk.red(`Error during AI service call: ${aiError.message}`)
);
if (error.message.includes('API key')) {
if (aiError.message.includes('API key')) {
console.log(
chalk.yellow(
'\nPlease ensure your API keys are correctly configured in .env or ~/.taskmaster/.env'
@@ -462,10 +608,9 @@ async function analyzeTaskComplexity(options, context = {}) {
);
}
}
throw error; // Re-throw AI service error
throw aiError;
}
} catch (error) {
// Catches general errors (file read, etc.)
reportLog(`Error analyzing task complexity: ${error.message}`, 'error');
if (outputFormat === 'text') {
console.error(

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