Compare commits

..

1 Commits

Author SHA1 Message Date
Ralph Khreish
754b710076 fix: shebang issues
Closes #241 #211 #184 #193
2025-04-16 11:04:56 +02:00
319 changed files with 24021 additions and 53857 deletions

View File

@@ -0,0 +1,6 @@
---
'task-master-ai': patch
---
- Fixes shebang issue not allowing task-master to run on certain windows operating systems
- Resolves #241 #211 #184 #193

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Updates the parameter descriptions for update, update-task and update-subtask to ensure the MCP server correctly reaches for the right update command based on what is being updated -- all tasks, one task, or a subtask.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,18 +1,17 @@
{
"mcpServers": {
"task-master-ai": {
"taskmaster-ai": {
"command": "node",
"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"
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
"MODEL": "claude-3-7-sonnet-20250219",
"PERPLEXITY_MODEL": "sonar-pro",
"MAX_TOKENS": 64000,
"TEMPERATURE": 0.2,
"DEFAULT_SUBTASKS": 5,
"DEFAULT_PRIORITY": "medium"
}
}
}

View File

@@ -1,155 +0,0 @@
---
description: Guidelines for managing Task Master AI providers and models.
globs:
alwaysApply: false
---
# Task Master AI Provider Management
This rule guides AI assistants on how to view, configure, and interact with the different AI providers and models supported by Task Master. For internal implementation details of the service layer, see [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc).
- **Primary Interaction:**
- Use the `models` MCP tool or the `task-master models` CLI command to manage AI configurations. See [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc) for detailed command/tool usage.
- **Configuration Roles:**
- Task Master uses three roles for AI models:
- `main`: Primary model for general tasks (generation, updates).
- `research`: Model used when the `--research` flag or `research: true` parameter is used (typically models with web access or specialized knowledge).
- `fallback`: Model used if the primary (`main`) model fails.
- Each role is configured with a specific `provider:modelId` pair (e.g., `openai:gpt-4o`).
- **Viewing Configuration & Available Models:**
- To see the current model assignments for each role and list all models available for assignment:
- **MCP Tool:** `models` (call with no arguments or `listAvailableModels: true`)
- **CLI Command:** `task-master models`
- The output will show currently assigned models and a list of others, prefixed with their provider (e.g., `google:gemini-2.5-pro-exp-03-25`).
- **Setting Models for Roles:**
- To assign a model to a role:
- **MCP Tool:** `models` with `setMain`, `setResearch`, or `setFallback` parameters.
- **CLI Command:** `task-master models` with `--set-main`, `--set-research`, or `--set-fallback` flags.
- **Crucially:** When providing the model ID to *set*, **DO NOT include the `provider:` prefix**. Use only the model ID itself.
- ✅ **DO:** `models(setMain='gpt-4o')` or `task-master models --set-main=gpt-4o`
- ❌ **DON'T:** `models(setMain='openai:gpt-4o')` or `task-master models --set-main=openai:gpt-4o`
- The tool/command will automatically determine the provider based on the model ID.
- **Setting Custom Models (Ollama/OpenRouter):**
- To set a model ID not in the internal list for Ollama or OpenRouter:
- **MCP Tool:** Use `models` with `set<Role>` and **also** `ollama: true` or `openrouter: true`.
- Example: `models(setMain='my-custom-ollama-model', ollama=true)`
- Example: `models(setMain='some-openrouter-model', openrouter=true)`
- **CLI Command:** Use `task-master models` with `--set-<role>` and **also** `--ollama` or `--openrouter`.
- Example: `task-master models --set-main=my-custom-ollama-model --ollama`
- Example: `task-master models --set-main=some-openrouter-model --openrouter`
- **Interactive Setup:** Use `task-master models --setup` and select the `Ollama (Enter Custom ID)` or `OpenRouter (Enter Custom ID)` options.
- **OpenRouter Validation:** When setting a custom OpenRouter model, Taskmaster attempts to validate the ID against the live OpenRouter API.
- **Ollama:** No live validation occurs for custom Ollama models; ensure the model is available on your Ollama server.
- **Supported Providers & Required API Keys:**
- Task Master integrates with various providers via the Vercel AI SDK.
- **API keys are essential** for most providers and must be configured correctly.
- **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.
- **Provider List & Keys:**
- **`anthropic`**: Requires `ANTHROPIC_API_KEY`.
- **`google`**: Requires `GOOGLE_API_KEY`.
- **`openai`**: Requires `OPENAI_API_KEY`.
- **`perplexity`**: Requires `PERPLEXITY_API_KEY`.
- **`xai`**: Requires `XAI_API_KEY`.
- **`mistral`**: Requires `MISTRAL_API_KEY`.
- **`azure`**: Requires `AZURE_OPENAI_API_KEY` and `AZURE_OPENAI_ENDPOINT`.
- **`openrouter`**: Requires `OPENROUTER_API_KEY`.
- **`ollama`**: Might require `OLLAMA_API_KEY` (not currently supported) *and* `OLLAMA_BASE_URL` (default: `http://localhost:11434/api`). *Check specific setup.*
- **Troubleshooting:**
- If AI commands fail (especially in MCP context):
1. **Verify API Key:** Ensure the correct API key for the *selected provider* (check `models` output) exists in the appropriate location (`.cursor/mcp.json` env or `.env`).
2. **Check Model ID:** Ensure the model ID set for the role is valid (use `models` listAvailableModels/`task-master models`).
3. **Provider Status:** Check the status of the external AI provider's service.
4. **Restart MCP:** If changes were made to configuration or provider code, restart the MCP server.
## Adding a New AI Provider (Vercel AI SDK Method)
Follow these steps to integrate a new AI provider that has an official Vercel AI SDK adapter (`@ai-sdk/<provider>`):
1. **Install Dependency:**
- Install the provider-specific package:
```bash
npm install @ai-sdk/<provider-name>
```
2. **Create Provider Module:**
- Create a new file in `src/ai-providers/` named `<provider-name>.js`.
- Use existing modules (`openai.js`, `anthropic.js`, etc.) as a template.
- **Import:**
- Import the provider's `create<ProviderName>` function from `@ai-sdk/<provider-name>`.
- Import `generateText`, `streamText`, `generateObject` from the core `ai` package.
- Import the `log` utility from `../../scripts/modules/utils.js`.
- **Implement Core Functions:**
- `generate<ProviderName>Text(params)`:
- Accepts `params` (apiKey, modelId, messages, etc.).
- Instantiate the client: `const client = create<ProviderName>({ apiKey });`
- Call `generateText({ model: client(modelId), ... })`.
- Return `result.text`.
- Include basic validation and try/catch error handling.
- `stream<ProviderName>Text(params)`:
- Similar structure to `generateText`.
- Call `streamText({ model: client(modelId), ... })`.
- Return the full stream result object.
- Include basic validation and try/catch.
- `generate<ProviderName>Object(params)`:
- Similar structure.
- Call `generateObject({ model: client(modelId), schema, messages, ... })`.
- Return `result.object`.
- Include basic validation and try/catch.
- **Export Functions:** Export the three implemented functions (`generate<ProviderName>Text`, `stream<ProviderName>Text`, `generate<ProviderName>Object`).
3. **Integrate with Unified Service:**
- Open `scripts/modules/ai-services-unified.js`.
- **Import:** Add `import * as <providerName> from '../../src/ai-providers/<provider-name>.js';`
- **Map:** Add an entry to the `PROVIDER_FUNCTIONS` map:
```javascript
'<provider-name>': {
generateText: <providerName>.generate<ProviderName>Text,
streamText: <providerName>.stream<ProviderName>Text,
generateObject: <providerName>.generate<ProviderName>Object
},
```
4. **Update Configuration Management:**
- Open `scripts/modules/config-manager.js`.
- **`MODEL_MAP`:** Add the new `<provider-name>` key to the `MODEL_MAP` loaded from `supported-models.json` (or ensure the loading handles new providers dynamically if `supported-models.json` is updated first).
- **`VALID_PROVIDERS`:** Ensure the new `<provider-name>` is included in the `VALID_PROVIDERS` array (this should happen automatically if derived from `MODEL_MAP` keys).
- **API Key Handling:**
- Update the `keyMap` in `_resolveApiKey` and `isApiKeySet` with the correct environment variable name (e.g., `PROVIDER_API_KEY`).
- Update the `switch` statement in `getMcpApiKeyStatus` to check the corresponding key in `mcp.json` and its placeholder value.
- Add a case to the `switch` statement in `getMcpApiKeyStatus` for the new provider, including its placeholder string if applicable.
- **Ollama Exception:** If adding Ollama or another provider *not* requiring an API key, add a specific check at the beginning of `isApiKeySet` and `getMcpApiKeyStatus` to return `true` immediately for that provider.
5. **Update Supported Models List:**
- Edit `scripts/modules/supported-models.json`.
- Add a new key for the `<provider-name>`.
- Add an array of model objects under the provider key, each including:
- `id`: The specific model identifier (e.g., `claude-3-opus-20240229`).
- `name`: A user-friendly name (optional).
- `swe_score`, `cost_per_1m_tokens`: (Optional) Add performance/cost data if available.
- `allowed_roles`: An array of roles (`"main"`, `"research"`, `"fallback"`) the model is suitable for.
- `max_tokens`: (Optional but recommended) The maximum token limit for the model.
6. **Update Environment Examples:**
- Add the new `PROVIDER_API_KEY` to `.env.example`.
- Add the new `PROVIDER_API_KEY` with its placeholder (`YOUR_PROVIDER_API_KEY_HERE`) to the `env` section for `taskmaster-ai` in `.cursor/mcp.json.example` (if it exists) or update instructions.
7. **Add Unit Tests:**
- Create `tests/unit/ai-providers/<provider-name>.test.js`.
- Mock the `@ai-sdk/<provider-name>` module and the core `ai` module functions (`generateText`, `streamText`, `generateObject`).
- Write tests for each exported function (`generate<ProviderName>Text`, etc.) to verify:
- Correct client instantiation.
- Correct parameters passed to the mocked Vercel AI SDK functions.
- Correct handling of results.
- Error handling (missing API key, SDK errors).
8. **Documentation:**
- Update any relevant documentation (like `README.md` or other rules) mentioning supported providers or configuration.
*(Note: For providers **without** an official Vercel AI SDK adapter, the process would involve directly using the provider's own SDK or API within the `src/ai-providers/<provider-name>.js` module and manually constructing responses compatible with the unified service layer, which is significantly more complex.)*

View File

@@ -1,102 +0,0 @@
---
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
---
# AI Services Layer Guidelines
This document outlines the architecture and usage patterns for interacting with Large Language Models (LLMs) via Task Master's unified AI service layer (`ai-services-unified.js`). The goal is to centralize configuration, provider selection, API key management, fallback logic, and error handling.
**Core Components:**
* **Configuration (`.taskmasterconfig` & [`config-manager.js`](mdc:scripts/modules/config-manager.js)):**
* Defines the AI provider and model ID for different **roles** (`main`, `research`, `fallback`).
* Stores parameters like `maxTokens` and `temperature` per role.
* Managed via the `task-master models --setup` CLI command.
* [`config-manager.js`](mdc:scripts/modules/config-manager.js) provides **getters** (e.g., `getMainProvider()`, `getParametersForRole()`) to access these settings. Core logic should **only** use these getters for *non-AI related application logic* (e.g., `getDefaultSubtasks`). The unified service fetches necessary AI parameters internally based on the `role`.
* **API keys** are **NOT** stored here; they are resolved via `resolveEnvVariable` (in [`utils.js`](mdc:scripts/modules/utils.js)) from `.env` (for CLI) or the MCP `session.env` object (for MCP calls). See [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc).
* **Unified Service (`ai-services-unified.js`):**
* Exports primary interaction functions: `generateTextService`, `generateObjectService`. (Note: `streamTextService` exists but has known reliability issues with some providers/payloads).
* Contains the core `_unifiedServiceRunner` logic.
* Internally uses `config-manager.js` getters to determine the provider/model/parameters based on the requested `role`.
* Implements the **fallback sequence** (e.g., main -> fallback -> research) if the primary provider/model fails.
* Constructs the `messages` array required by the Vercel AI SDK.
* 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`).
**Usage Pattern (from Core Logic like `task-manager/*.js`):**
1. **Import Service:** Import `generateTextService` or `generateObjectService` from `../ai-services-unified.js`.
```javascript
// Preferred for most tasks (especially with complex JSON)
import { generateTextService } from '../ai-services-unified.js';
// Use if structured output is reliable for the specific use case
// import { generateObjectService } from '../ai-services-unified.js';
```
2. **Prepare Parameters:** Construct the parameters object for the service call.
* `role`: **Required.** `'main'`, `'research'`, or `'fallback'`. Determines the initial provider/model/parameters used by the unified service.
* `session`: **Required if called from MCP context.** Pass the `session` object received by the direct function wrapper. The unified service uses `session.env` to find API keys.
* `systemPrompt`: Your system instruction string.
* `prompt`: The user message string (can be long, include stringified data, etc.).
* (For `generateObjectService` only): `schema` (Zod schema), `objectName`.
3. **Call Service:** Use `await` to call the service function.
```javascript
// Example using generateTextService (most common)
try {
const resultText = await generateTextService({
role: useResearch ? 'research' : 'main', // Determine role based on logic
session: context.session, // Pass session from context object
systemPrompt: "You are...",
prompt: userMessageContent
});
// Process the raw text response (e.g., parse JSON, use directly)
// ...
} catch (error) {
// Handle errors thrown by the unified service (if all fallbacks/retries fail)
report('error', `Unified AI service call failed: ${error.message}`);
throw error;
}
// Example using generateObjectService (use cautiously)
try {
const resultObject = await generateObjectService({
role: 'main',
session: context.session,
schema: myZodSchema,
objectName: 'myDataObject',
systemPrompt: "You are...",
prompt: userMessageContent
});
// resultObject is already a validated JS object
// ...
} catch (error) {
report('error', `Unified AI service call failed: ${error.message}`);
throw error;
}
```
4. **Handle Results/Errors:** Process the returned text/object or handle errors thrown by the unified service layer.
**Key Implementation Rules & Gotchas:**
* ✅ **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 `.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.
* ❌ **DON'T**: Initialize AI clients (Anthropic, Perplexity, etc.) directly within core logic (`task-manager/`) or MCP direct functions.
* ❌ **DON'T**: Fetch AI-specific parameters (model ID, max tokens, temp) using `config-manager.js` getters *for the AI call*. Pass the `role` instead.
* ❌ **DON'T**: Implement fallback or retry logic outside `ai-services-unified.js`.
* ❌ **DON'T**: Handle API key resolution outside the service layer (it uses `utils.js` internally).
* ⚠️ **generateObjectService Caution**: Be aware of potential reliability issues with `generateObjectService` across different providers and complex schemas. Prefer `generateTextService` + manual parsing as a more robust alternative for structured data needs.

View File

@@ -3,6 +3,7 @@ description: Describes the high-level architecture of the Task Master CLI applic
globs: scripts/modules/*.js
alwaysApply: false
---
# Application Architecture Overview
- **Modular Structure**: The Task Master CLI is built using a modular architecture, with distinct modules responsible for different aspects of the application. This promotes separation of concerns, maintainability, and testability.
@@ -13,75 +14,161 @@ alwaysApply: false
- **Purpose**: Defines and registers all CLI commands using Commander.js.
- **Responsibilities** (See also: [`commands.mdc`](mdc:.cursor/rules/commands.mdc)):
- Parses command-line arguments and options.
- Invokes appropriate core logic functions from `scripts/modules/`.
- Handles user input/output for CLI.
- Implements CLI-specific validation.
- Invokes appropriate functions from other modules to execute commands (e.g., calls `initializeProject` from `init.js` for the `init` command).
- Handles user input and output related to command execution.
- Implements input validation and error handling for CLI commands.
- **Key Components**:
- `programInstance` (Commander.js `Command` instance): Manages command definitions.
- `registerCommands(programInstance)`: Function to register all application commands.
- Command action handlers: Functions executed when a specific command is invoked, delegating to core modules.
- **[`task-manager.js`](mdc:scripts/modules/task-manager.js) & `task-manager/` directory: Task Data & Core Logic**
- **Purpose**: Contains core functions for task data manipulation (CRUD), AI interactions, and related logic.
- **[`task-manager.js`](mdc:scripts/modules/task-manager.js): Task Data Management**
- **Purpose**: Manages task data, including loading, saving, creating, updating, deleting, and querying tasks.
- **Responsibilities**:
- Reading/writing `tasks.json`.
- Implementing functions for task CRUD, parsing PRDs, expanding tasks, updating status, etc.
- **Delegating AI interactions** to the `ai-services-unified.js` layer.
- Accessing non-AI configuration via `config-manager.js` getters.
- **Key Files**: Individual files within `scripts/modules/task-manager/` handle specific actions (e.g., `add-task.js`, `expand-task.js`).
- Reads and writes task data to `tasks.json` file.
- Implements functions for task CRUD operations (Create, Read, Update, Delete).
- Handles task parsing from PRD documents using AI.
- Manages task expansion and subtask generation.
- Updates task statuses and properties.
- Implements task listing and display logic.
- Performs task complexity analysis using AI.
- **Key Functions**:
- `readTasks(tasksPath)` / `writeTasks(tasksPath, tasksData)`: Load and save task data.
- `parsePRD(prdFilePath, outputPath, numTasks)`: Parses PRD document to create tasks.
- `expandTask(taskId, numSubtasks, useResearch, prompt, force)`: Expands a task into subtasks.
- `setTaskStatus(tasksPath, taskIdInput, newStatus)`: Updates task status.
- `listTasks(tasksPath, statusFilter, withSubtasks)`: Lists tasks with filtering and subtask display options.
- `analyzeComplexity(tasksPath, reportPath, useResearch, thresholdScore)`: Analyzes task complexity.
- **[`dependency-manager.js`](mdc:scripts/modules/dependency-manager.js): Dependency Management**
- **Purpose**: Manages task dependencies.
- **Responsibilities**: Add/remove/validate/fix dependencies.
- **Purpose**: Manages task dependencies, including adding, removing, validating, and fixing dependency relationships.
- **Responsibilities**:
- Adds and removes task dependencies.
- Validates dependency relationships to prevent circular dependencies and invalid references.
- Fixes invalid dependencies by removing non-existent or self-referential dependencies.
- Provides functions to check for circular dependencies.
- **Key Functions**:
- `addDependency(tasksPath, taskId, dependencyId)`: Adds a dependency between tasks.
- `removeDependency(tasksPath, taskId, dependencyId)`: Removes a dependency.
- `validateDependencies(tasksPath)`: Validates task dependencies.
- `fixDependencies(tasksPath)`: Fixes invalid task dependencies.
- `isCircularDependency(tasks, taskId, dependencyChain)`: Detects circular dependencies.
- **[`ui.js`](mdc:scripts/modules/ui.js): User Interface Components**
- **Purpose**: Handles CLI output formatting (tables, colors, boxes, spinners).
- **Responsibilities**: Displaying tasks, reports, progress, suggestions.
- **Purpose**: Handles all user interface elements, including displaying information, formatting output, and providing user feedback.
- **Responsibilities**:
- Displays task lists, task details, and command outputs in a formatted way.
- Uses `chalk` for colored output and `boxen` for boxed messages.
- Implements table display using `cli-table3`.
- Shows loading indicators using `ora`.
- Provides helper functions for status formatting, dependency display, and progress reporting.
- Suggests next actions to the user after command execution.
- **Key Functions**:
- `displayTaskList(tasks, statusFilter, withSubtasks)`: Displays a list of tasks in a table.
- `displayTaskDetails(task)`: Displays detailed information for a single task.
- `displayComplexityReport(reportPath)`: Displays the task complexity report.
- `startLoadingIndicator(message)` / `stopLoadingIndicator(indicator)`: Manages loading indicators.
- `getStatusWithColor(status)`: Returns status string with color formatting.
- `formatDependenciesWithStatus(dependencies, allTasks, inTable)`: Formats dependency list with status indicators.
- **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js): Unified AI Service Layer**
- **Purpose**: Centralized interface for all LLM interactions using Vercel AI SDK.
- **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`).
- 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.
- **[`ai-services.js`](mdc:scripts/modules/ai-services.js) (Conceptual): AI Integration**
- **Purpose**: Abstracts interactions with AI models (like Anthropic Claude and Perplexity AI) for various features. *Note: This module might be implicitly implemented within `task-manager.js` and `utils.js` or could be explicitly created for better organization as the project evolves.*
- **Responsibilities**:
- Handles API calls to AI services.
- Manages prompts and parameters for AI requests.
- Parses AI responses and extracts relevant information.
- Implements logic for task complexity analysis, task expansion, and PRD parsing using AI.
- **Potential Functions**:
- `getAIResponse(prompt, model, maxTokens, temperature)`: Generic function to interact with AI model.
- `analyzeTaskComplexityWithAI(taskDescription)`: Sends task description to AI for complexity analysis.
- `expandTaskWithAI(taskDescription, numSubtasks, researchContext)`: Generates subtasks using AI.
- `parsePRDWithAI(prdContent)`: Extracts tasks from PRD content using AI.
- **[`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.
- **[`config-manager.js`](mdc:scripts/modules/config-manager.js): Configuration Management**
- **Purpose**: Loads, validates, and provides access to configuration.
- **[`utils.js`](mdc:scripts/modules/utils.js): Utility Functions and Configuration**
- **Purpose**: Provides reusable utility functions and global configuration settings used across the **CLI application**.
- **Responsibilities** (See also: [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)):
- Reads and merges `.taskmasterconfig` with defaults.
- Provides getters (e.g., `getMainProvider`, `getLogLevel`, `getDefaultSubtasks`) for accessing settings.
- **Note**: Does **not** store or directly handle API keys (keys are in `.env` or MCP `session.env`).
- **[`utils.js`](mdc:scripts/modules/utils.js): Core Utility Functions**
- **Purpose**: Low-level, reusable CLI utilities.
- **Responsibilities** (See also: [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)):
- Logging (`log` function), File I/O (`readJSON`, `writeJSON`), String utils (`truncate`).
- Task utils (`findTaskById`), Dependency utils (`findCycles`).
- API Key Resolution (`resolveEnvVariable`).
- Silent Mode Control (`enableSilentMode`, `disableSilentMode`).
- Manages global configuration settings loaded from environment variables and defaults.
- Implements logging utility with different log levels and output formatting.
- Provides file system operation utilities (read/write JSON files).
- Includes string manipulation utilities (e.g., `truncate`, `sanitizePrompt`).
- Offers task-specific utility functions (e.g., `formatTaskId`, `findTaskById`, `taskExists`).
- Implements graph algorithms like cycle detection for dependency management.
- **Silent Mode Control**: Provides `enableSilentMode` and `disableSilentMode` functions to control log output.
- **Key Components**:
- `CONFIG`: Global configuration object.
- `log(level, ...args)`: Logging function.
- `readJSON(filepath)` / `writeJSON(filepath, data)`: File I/O utilities for JSON files.
- `truncate(text, maxLength)`: String truncation utility.
- `formatTaskId(id)` / `findTaskById(tasks, taskId)`: Task ID and search utilities.
- `findCycles(subtaskId, dependencyMap)`: Cycle detection algorithm.
- `enableSilentMode()` / `disableSilentMode()`: Control console logging output.
- **[`mcp-server/`](mdc:mcp-server/): MCP Server Integration**
- **Purpose**: Provides MCP interface using FastMCP.
- **Purpose**: Provides an MCP (Model Context Protocol) interface for Task Master, allowing integration with external tools like Cursor. Uses FastMCP framework.
- **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.
- The HOF provides a normalized `args.projectRoot` to the `execute` method.
- Tool `execute` methods call **direct function wrappers** (`mcp-server/src/core/direct-functions/*.js`), passing the normalized `projectRoot` and other args.
- Direct functions use path utilities (`mcp-server/src/core/utils/`) to resolve paths based on `projectRoot` from session.
- Direct functions implement silent mode, logger wrappers, and call core logic functions from `scripts/modules/`.
- Manages MCP caching and response formatting.
- Registers Task Master functionalities as tools consumable via MCP.
- Handles MCP requests via tool `execute` methods defined in `mcp-server/src/tools/*.js`.
- Tool `execute` methods call corresponding **direct function wrappers**.
- Tool `execute` methods use `getProjectRootFromSession` (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) to determine the project root from the client session and pass it to the direct function.
- **Direct function wrappers (`*Direct` functions in `mcp-server/src/core/direct-functions/*.js`) contain the main logic for handling MCP requests**, including path resolution, argument validation, caching, and calling core Task Master functions.
- Direct functions use `findTasksJsonPath` (from [`core/utils/path-utils.js`](mdc:mcp-server/src/core/utils/path-utils.js)) to locate `tasks.json` based on the provided `projectRoot`.
- **Silent Mode Implementation**: Direct functions use `enableSilentMode` and `disableSilentMode` to prevent logs from interfering with JSON responses.
- **Async Operations**: Uses `AsyncOperationManager` to handle long-running operations in the background.
- **Project Initialization**: Provides `initialize_project` command for setting up new projects from within integrated clients.
- Tool `execute` methods use `handleApiResult` from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js) to process the result from the direct function and format the final MCP response.
- Uses CLI execution via `executeTaskMasterCommand` as a fallback only when necessary.
- **Implements Robust Path Finding**: The utility [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js) (specifically `getProjectRootFromSession`) and [`core/utils/path-utils.js`](mdc:mcp-server/src/core/utils/path-utils.js) (specifically `findTasksJsonPath`) work together. The tool gets the root via session, passes it to the direct function, which uses `findTasksJsonPath` to locate the specific `tasks.json` file within that root.
- **Implements Caching**: Utilizes a caching layer (`ContextManager` with `lru-cache`). Caching logic is invoked *within* the direct function wrappers using the `getCachedOrExecute` utility for performance-sensitive read operations.
- Standardizes response formatting and data filtering using utilities in [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
- **Resource Management**: Provides access to static and dynamic resources.
- **Key Components**:
- `mcp-server/src/index.js`: Main server class definition with FastMCP initialization, resource registration, and server lifecycle management.
- `mcp-server/src/server.js`: Main server setup and initialization.
- `mcp-server/src/tools/`: Directory containing individual tool definitions. Each tool's `execute` method orchestrates the call to core logic and handles the response.
- `mcp-server/src/tools/utils.js`: Provides MCP-specific utilities like `handleApiResult`, `processMCPResponseData`, `getCachedOrExecute`, and **`getProjectRootFromSession`**.
- `mcp-server/src/core/utils/`: Directory containing utility functions specific to the MCP server, like **`path-utils.js` for resolving `tasks.json` within a given root** and **`async-manager.js` for handling background operations**.
- `mcp-server/src/core/direct-functions/`: Directory containing individual files for each **direct function wrapper (`*Direct`)**. These files contain the primary logic for MCP tool execution.
- `mcp-server/src/core/resources/`: Directory containing resource handlers for task templates, workflow definitions, and other static/dynamic data exposed to LLM clients.
- [`task-master-core.js`](mdc:mcp-server/src/core/task-master-core.js): Acts as an import/export hub, collecting and exporting direct functions from the `direct-functions` directory and MCP utility functions.
- **Naming Conventions**:
- **Files** use **kebab-case**: `list-tasks.js`, `set-task-status.js`, `parse-prd.js`
- **Direct Functions** use **camelCase** with `Direct` suffix: `listTasksDirect`, `setTaskStatusDirect`, `parsePRDDirect`
- **Tool Registration Functions** use **camelCase** with `Tool` suffix: `registerListTasksTool`, `registerSetTaskStatusTool`
- **MCP Tool Names** use **snake_case**: `list_tasks`, `set_task_status`, `parse_prd_document`
- **Resource Handlers** use **camelCase** with pattern URI: `@mcp.resource("tasks://templates/{template_id}")`
- **AsyncOperationManager**:
- **Purpose**: Manages background execution of long-running operations.
- **Location**: `mcp-server/src/core/utils/async-manager.js`
- **Key Features**:
- Operation tracking with unique IDs using UUID
- Status management (pending, running, completed, failed)
- Progress reporting forwarded from background tasks
- Operation history with automatic cleanup of completed operations
- Context preservation (log, session, reportProgress)
- Robust error handling for background tasks
- **Usage**: Used for CPU-intensive operations like task expansion and PRD parsing
- **[`init.js`](mdc:scripts/init.js): Project Initialization Logic**
- **Purpose**: Sets up new Task Master project structure.
- **Responsibilities**: Creates directories, copies templates, manages `package.json`, sets up `.cursor/mcp.json`.
- **Purpose**: Contains the core logic for setting up a new Task Master project structure.
- **Responsibilities**:
- Creates necessary directories (`.cursor/rules`, `scripts`, `tasks`).
- Copies template files (`.env.example`, `.gitignore`, rule files, `dev.js`, etc.).
- Creates or merges `package.json` with required dependencies and scripts.
- Sets up MCP configuration (`.cursor/mcp.json`).
- Optionally initializes a git repository and installs dependencies.
- Handles user prompts for project details *if* called without skip flags (`-y`).
- **Key Function**:
- `initializeProject(options)`: The main function exported and called by the `init` command's action handler in [`commands.js`](mdc:scripts/modules/commands.js). It receives parsed options directly.
- **Note**: This script is used as a module and no longer handles its own argument parsing or direct execution via a separate `bin` file.
- **Data Flow and Module Dependencies (Updated)**:
- **Data Flow and Module Dependencies**:
- **CLI**: `bin/task-master.js` -> `scripts/dev.js` (loads `.env`) -> `scripts/modules/commands.js` -> Core Logic (`scripts/modules/*`) -> Unified AI Service (`ai-services-unified.js`) -> Provider Adapters -> LLM API.
- **MCP**: External Tool -> `mcp-server/server.js` -> Tool (`mcp-server/src/tools/*`) -> Direct Function (`mcp-server/src/core/direct-functions/*`) -> Core Logic (`scripts/modules/*`) -> Unified AI Service (`ai-services-unified.js`) -> Provider Adapters -> LLM API.
- **Configuration**: Core logic needing non-AI settings calls `config-manager.js` getters (passing `session.env` via `explicitRoot` if from MCP). Unified AI Service internally calls `config-manager.js` getters (using `role`) for AI params and `utils.js` (`resolveEnvVariable` with `session.env`) for API keys.
- **Commands Initiate Actions**: User commands entered via the CLI (parsed by `commander` based on definitions in [`commands.js`](mdc:scripts/modules/commands.js)) are the entry points for most operations.
- **Command Handlers Delegate to Core Logic**: Action handlers within [`commands.js`](mdc:scripts/modules/commands.js) call functions in core modules like [`task-manager.js`](mdc:scripts/modules/task-manager.js), [`dependency-manager.js`](mdc:scripts/modules/dependency-manager.js), and [`init.js`](mdc:scripts/init.js) (for the `init` command) to perform the actual work.
- **UI for Presentation**: [`ui.js`](mdc:scripts/modules/ui.js) is used by command handlers and task/dependency managers to display information to the user. UI functions primarily consume data and format it for output, without modifying core application state.
- **Utilities for Common Tasks**: [`utils.js`](mdc:scripts/modules/utils.js) provides helper functions used by all other modules for configuration, logging, file operations, and common data manipulations.
- **AI Services Integration**: AI functionalities (complexity analysis, task expansion, PRD parsing) are invoked from [`task-manager.js`](mdc:scripts/modules/task-manager.js) and potentially [`commands.js`](mdc:scripts/modules/commands.js), likely using functions that would reside in a dedicated `ai-services.js` module or be integrated within `utils.js` or `task-manager.js`.
- **MCP Server Interaction**: External tools interact with the `mcp-server`. MCP Tool `execute` methods use `getProjectRootFromSession` to find the project root, then call direct function wrappers (in `mcp-server/src/core/direct-functions/`) passing the root in `args`. These wrappers handle path finding for `tasks.json` (using `path-utils.js`), validation, caching, call the core logic from `scripts/modules/` (passing logging context via the standard wrapper pattern detailed in mcp.mdc), and return a standardized result. The final MCP response is formatted by `mcp-server/src/tools/utils.js`. See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for details.
## Silent Mode Implementation Pattern in MCP Direct Functions
@@ -279,8 +366,19 @@ The `initialize_project` command provides a way to set up a new Task Master proj
- Configures project metadata (name, description, version)
- Handles shell alias creation if requested
- Works in both interactive and non-interactive modes
- Creates necessary directories and files for a new project
- Sets up `tasks.json` and initial task files
- Configures project metadata (name, description, version)
- Handles shell alias creation if requested
- Works in both interactive and non-interactive modes
## Async Operation Management
The AsyncOperationManager provides background task execution capabilities:
- **Location**: `mcp-server/src/core/utils/async-manager.js`
- **Key Components**:
- `asyncOperationManager` singleton instance
- `addOperation(operationFn, args, context)` method
- `getStatus(operationId)` method
- **Usage Flow**:
1. Client calls an MCP tool that may take time to complete
2. Tool uses AsyncOperationManager to run the operation in background
3. Tool returns immediate response with operation ID
4. Client polls `get_operation_status` tool with the ID
5. Once completed, client can access operation results

View File

@@ -34,8 +34,8 @@ While this document details the implementation of Task Master's **CLI commands**
- **Command Handler Organization**:
- ✅ DO: Keep action handlers concise and focused
- ✅ DO: Extract core functionality to appropriate modules
- ✅ DO: Have the action handler import and call the relevant functions from core modules, like `task-manager.js` or `init.js`, passing the parsed `options`.
- ✅ DO: Perform basic parameter validation, such as checking for required options, within the action handler or at the start of the called core function.
- ✅ DO: Have the action handler import and call the relevant function(s) from core modules (e.g., `task-manager.js`, `init.js`), passing the parsed `options`.
- ✅ DO: Perform basic parameter validation (e.g., checking for required options) within the action handler or at the start of the called core function.
- ❌ DON'T: Implement business logic in command handlers
## Best Practices for Removal/Delete Commands
@@ -44,7 +44,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
- **Confirmation Prompts**:
- ✅ **DO**: Include a confirmation prompt by default for destructive operations
- ✅ **DO**: Provide a `--yes` or `-y` flag to skip confirmation, useful for scripting or automation
- ✅ **DO**: Provide a `--yes` or `-y` flag to skip confirmation for scripting/automation
- ✅ **DO**: Show what will be deleted in the confirmation message
- ❌ **DON'T**: Perform destructive operations without user confirmation unless explicitly overridden
@@ -78,7 +78,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
- **File Path Handling**:
- ✅ **DO**: Use `path.join()` to construct file paths
- ✅ **DO**: Follow established naming conventions for tasks, like `task_001.txt`
- ✅ **DO**: Follow established naming conventions for tasks (e.g., `task_001.txt`)
- ✅ **DO**: Check if files exist before attempting to delete them
- ✅ **DO**: Handle file deletion errors gracefully
- ❌ **DON'T**: Construct paths with string concatenation
@@ -166,10 +166,10 @@ When implementing commands that delete or remove data (like `remove-task` or `re
- ✅ DO: Use descriptive, action-oriented names
- **Option Names**:
- ✅ DO: Use kebab-case for long-form option names, like `--output-format`
- ✅ DO: Provide single-letter shortcuts when appropriate, like `-f, --file`
- ✅ DO: Use kebab-case for long-form option names (`--output-format`)
- ✅ DO: Provide single-letter shortcuts when appropriate (`-f, --file`)
- ✅ DO: Use consistent option names across similar commands
- ❌ DON'T: Use different names for the same concept, such as `--file` in one command and `--path` in another
- ❌ DON'T: Use different names for the same concept (`--file` in one command, `--path` in another)
```javascript
// ✅ DO: Use consistent option naming
@@ -181,7 +181,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
.option('-p, --path <dir>', 'Output directory') // Should be --output
```
> **Note**: Although options are defined with kebab-case, like `--num-tasks`, Commander.js stores them internally as camelCase properties. Access them in code as `options.numTasks`, not `options['num-tasks']`.
> **Note**: Although options are defined with kebab-case (`--num-tasks`), Commander.js stores them internally as camelCase properties. Access them in code as `options.numTasks`, not `options['num-tasks']`.
- **Boolean Flag Conventions**:
- ✅ DO: Use positive flags with `--skip-` prefix for disabling behavior
@@ -210,7 +210,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
- **Required Parameters**:
- ✅ DO: Check that required parameters are provided
- ✅ DO: Provide clear error messages when parameters are missing
- ✅ DO: Use early returns with `process.exit(1)` for validation failures
- ✅ DO: Use early returns with process.exit(1) for validation failures
```javascript
// ✅ DO: Validate required parameters early
@@ -221,7 +221,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
```
- **Parameter Type Conversion**:
- ✅ DO: Convert string inputs to appropriate types, such as numbers or booleans
- ✅ DO: Convert string inputs to appropriate types (numbers, booleans)
- ✅ DO: Handle conversion errors gracefully
```javascript
@@ -254,7 +254,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
const taskId = parseInt(options.id, 10);
if (isNaN(taskId) || taskId <= 0) {
console.error(chalk.red(`Error: Invalid task ID: ${options.id}. Task ID must be a positive integer.`));
console.log(chalk.yellow("Usage example: task-master update-task --id='23' --prompt='Update with new information.\\nEnsure proper error handling.'"));
console.log(chalk.yellow('Usage example: task-master update-task --id=\'23\' --prompt=\'Update with new information.\nEnsure proper error handling.\''));
process.exit(1);
}
@@ -392,9 +392,9 @@ When implementing commands that delete or remove data (like `remove-task` or `re
process.on('uncaughtException', (err) => {
// Handle Commander-specific errors
if (err.code === 'commander.unknownOption') {
const option = err.message.match(/'([^']+)'/)?.[1]; // Safely extract option name
const option = err.message.match(/'([^']+)'/)?.[1];
console.error(chalk.red(`Error: Unknown option '${option}'`));
console.error(chalk.yellow("Run 'task-master <command> --help' to see available options"));
console.error(chalk.yellow(`Run 'task-master <command> --help' to see available options`));
process.exit(1);
}
@@ -464,9 +464,9 @@ When implementing commands that delete or remove data (like `remove-task` or `re
.option('-f, --file <path>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-p, --parent <id>', 'ID of the parent task (required)')
.option('-i, --task-id <id>', 'Existing task ID to convert to subtask')
.option('-t, --title <title>', 'Title for the new subtask, required if not converting')
.option('-d, --description <description>', 'Description for the new subtask, optional')
.option('--details <details>', 'Implementation details for the new subtask, optional')
.option('-t, --title <title>', 'Title for the new subtask (when not converting)')
.option('-d, --description <description>', 'Description for the new subtask (when not converting)')
.option('--details <details>', 'Implementation details for the new subtask (when not converting)')
.option('--dependencies <ids>', 'Comma-separated list of subtask IDs this subtask depends on')
.option('--status <status>', 'Initial status for the subtask', 'pending')
.option('--skip-generate', 'Skip regenerating task files')
@@ -489,8 +489,8 @@ When implementing commands that delete or remove data (like `remove-task` or `re
.command('remove-subtask')
.description('Remove a subtask from its parent task, optionally converting it to a standalone task')
.option('-f, --file <path>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-i, --id <id>', 'ID of the subtask to remove in format parentId.subtaskId, required')
.option('-c, --convert', 'Convert the subtask to a standalone task instead of deleting')
.option('-i, --id <id>', 'ID of the subtask to remove in format "parentId.subtaskId" (required)')
.option('-c, --convert', 'Convert the subtask to a standalone task')
.option('--skip-generate', 'Skip regenerating task files')
.action(async (options) => {
// Implementation with detailed error handling
@@ -513,8 +513,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
// ✅ DO: Implement version checking function
async function checkForUpdate() {
// Implementation details...
// Example return structure:
return { currentVersion, latestVersion, updateAvailable };
return { currentVersion, latestVersion, needsUpdate };
}
// ✅ DO: Implement semantic version comparison
@@ -554,7 +553,7 @@ When implementing commands that delete or remove data (like `remove-task` or `re
// After command execution, check if an update is available
const updateInfo = await updateCheckPromise;
if (updateInfo.updateAvailable) {
if (updateInfo.needsUpdate) {
displayUpgradeNotification(updateInfo.currentVersion, updateInfo.latestVersion);
}
} catch (error) {

View File

@@ -3,6 +3,7 @@ description: Guide for using Task Master to manage task-driven development workf
globs: **/*
alwaysApply: true
---
# Task Master Development Workflow
This guide outlines the typical process for using Task Master to manage software development projects.
@@ -28,55 +29,53 @@ Task Master offers two primary ways to interact:
## Standard Development Workflow Process
- Start new projects by running `initialize_project` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input='<prd-file.txt>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to generate initial tasks.json
- Start new projects by running `init` tool / `task-master init` or `parse_prd` / `task-master parse-prd --input='<prd-file.txt>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to generate initial tasks.json
- Begin coding sessions with `get_tasks` / `task-master list` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to see current tasks, status, and IDs
- Determine the next task to work on using `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Analyze task complexity with `analyze_project_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before breaking down tasks
- Analyze task complexity with `analyze_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before breaking down tasks
- Review complexity report using `complexity_report` / `task-master complexity-report` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Select tasks based on dependencies (all marked 'done'), priority level, and ID order
- Clarify tasks by checking task files in tasks/ directory or asking for user input
- View specific task details using `get_task` / `task-master show <id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to understand implementation requirements
- Break down complex tasks using `expand_task` / `task-master expand --id=<id> --force --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) with appropriate flags like `--force` (to replace existing subtasks) and `--research`.
- Break down complex tasks using `expand_task` / `task-master expand --id=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) with appropriate flags
- Clear existing subtasks if needed using `clear_subtasks` / `task-master clear-subtasks --id=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) before regenerating
- Implement code following task details, dependencies, and project standards
- Verify tasks according to test strategies before marking as complete (See [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
- Mark completed tasks with `set_task_status` / `task-master set-status --id=<id> --status=done` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Update dependent tasks when implementation differs from original plan using `update` / `task-master update --from=<id> --prompt="..."` or `update_task` / `task-master update-task --id=<id> --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Add new tasks discovered during implementation using `add_task` / `task-master add-task --prompt="..." --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Add new tasks discovered during implementation using `add_task` / `task-master add-task --prompt="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Add new subtasks as needed using `add_subtask` / `task-master add-subtask --parent=<id> --title="..."` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Append notes or details to subtasks using `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='Add implementation notes here...\nMore details...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
- Generate task files with `generate` / `task-master generate` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) after updating tasks.json
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
- Respect dependency chains and task priorities when selecting work
- Report progress regularly using `get_tasks` / `task-master list`
- Reorganize tasks as needed using `move_task` / `task-master move --from=<id> --to=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to change task hierarchy or ordering
## Task Complexity Analysis
- Run `analyze_project_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) for comprehensive analysis
- Run `analyze_complexity` / `task-master analyze-complexity --research` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) for comprehensive analysis
- Review complexity report via `complexity_report` / `task-master complexity-report` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) for a formatted, readable version.
- Focus on tasks with highest complexity scores (8-10) for detailed breakdown
- Use analysis results to determine appropriate subtask allocation
- Note that reports are automatically used by the `expand_task` tool/command
- Note that reports are automatically used by the `expand` tool/command
## Task Breakdown Process
- Use `expand_task` / `task-master expand --id=<id>`. It automatically uses the complexity report if found, otherwise generates default number of subtasks.
- Use `--num=<number>` to specify an explicit number of subtasks, overriding defaults or complexity report recommendations.
- Add `--research` flag to leverage Perplexity AI for research-backed expansion.
- Add `--force` flag to clear existing subtasks before generating new ones (default is to append).
- Use `--prompt="<context>"` to provide additional context when needed.
- Review and adjust generated subtasks as necessary.
- Use `expand_all` tool or `task-master expand --all` to expand multiple pending tasks at once, respecting flags like `--force` and `--research`.
- If subtasks need complete replacement (regardless of the `--force` flag on `expand`), clear them first with `clear_subtasks` / `task-master clear-subtasks --id=<id>`.
- For tasks with complexity analysis, use `expand_task` / `task-master expand --id=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc))
- Otherwise use `expand_task` / `task-master expand --id=<id> --num=<number>`
- Add `--research` flag to leverage Perplexity AI for research-backed expansion
- Use `--prompt="<context>"` to provide additional context when needed
- Review and adjust generated subtasks as necessary
- Use `--all` flag with `expand` or `expand_all` to expand multiple pending tasks at once
- If subtasks need regeneration, clear them first with `clear_subtasks` / `task-master clear-subtasks` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
## Implementation Drift Handling
- When implementation differs significantly from planned approach
- When future tasks need modification due to current implementation choices
- When new dependencies or requirements emerge
- Use `update` / `task-master update --from=<futureTaskId> --prompt='<explanation>\nUpdate context...' --research` to update multiple future tasks.
- Use `update_task` / `task-master update-task --id=<taskId> --prompt='<explanation>\nUpdate context...' --research` to update a single specific task.
- Use `update` / `task-master update --from=<futureTaskId> --prompt='<explanation>\nUpdate context...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to update multiple future tasks.
- Use `update_task` / `task-master update-task --id=<taskId> --prompt='<explanation>\nUpdate context...'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to update a single specific task.
## Task Status Management
@@ -98,32 +97,28 @@ Task Master offers two primary ways to interact:
- **details**: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
- **testStrategy**: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
- **subtasks**: List of smaller, more specific tasks (Example: `[{"id": 1, "title": "Configure OAuth", ...}]`)
- Refer to task structure details (previously linked to `tasks.mdc`).
- Refer to [`tasks.mdc`](mdc:.cursor/rules/tasks.mdc) for more details on the task data structure.
## Configuration Management (Updated)
## Environment Variables Configuration
Taskmaster configuration is managed through two main mechanisms:
1. **`.taskmaster/config.json` File (Primary):**
* Located in the project root directory.
* Stores most configuration settings: AI model selections (main, research, fallback), parameters (max tokens, temperature), logging level, default subtasks/priority, project name, etc.
* **Managed via `task-master models --setup` command.** Do not edit manually unless you know what you are doing.
* **View/Set specific models via `task-master models` command or `models` MCP tool.**
* Created automatically when you run `task-master models --setup` for the first time.
2. **Environment Variables (`.env` / `mcp.json`):**
* Used **only** for sensitive API keys and specific endpoint URLs.
* Place API keys (one per provider) in a `.env` file in the project root for CLI usage.
* For MCP/Cursor integration, configure these keys in the `env` section of `.cursor/mcp.json`.
* Available keys/variables: See `assets/env.example` or the Configuration section in the command reference (previously linked to `taskmaster.mdc`).
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `TASKMASTER_LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
**If AI commands FAIL in MCP** verify that the API key for the selected provider is present in the `env` section of `.cursor/mcp.json`.
**If AI commands FAIL in CLI** verify that the API key for the selected provider is present in the `.env` file in the root of the project.
- Task Master behavior is configured via environment variables:
- **ANTHROPIC_API_KEY** (Required): Your Anthropic API key for Claude.
- **MODEL**: Claude model to use (e.g., `claude-3-opus-20240229`).
- **MAX_TOKENS**: Maximum tokens for AI responses.
- **TEMPERATURE**: Temperature for AI model responses.
- **DEBUG**: Enable debug logging (`true`/`false`).
- **LOG_LEVEL**: Console output level (`debug`, `info`, `warn`, `error`).
- **DEFAULT_SUBTASKS**: Default number of subtasks for `expand`.
- **DEFAULT_PRIORITY**: Default priority for new tasks.
- **PROJECT_NAME**: Project name used in metadata.
- **PROJECT_VERSION**: Project version used in metadata.
- **PERPLEXITY_API_KEY**: API key for Perplexity AI (for `--research` flags).
- **PERPLEXITY_MODEL**: Perplexity model to use (e.g., `sonar-medium-online`).
- See [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc) for default values and examples.
## Determining the Next Task
- Run `next_task` / `task-master next` to show the next task to work on.
- Run `next_task` / `task-master next` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to show the next task to work on
- The command identifies tasks with all dependencies satisfied
- Tasks are prioritized by priority level, dependency count, and ID
- The command shows comprehensive task information including:
@@ -138,7 +133,7 @@ Taskmaster configuration is managed through two main mechanisms:
## Viewing Specific Task Details
- Run `get_task` / `task-master show <id>` to view a specific task.
- Run `get_task` / `task-master show <id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to view a specific task
- Use dot notation for subtasks: `task-master show 1.2` (shows subtask 2 of task 1)
- Displays comprehensive information similar to the next command, but for a specific task
- For parent tasks, shows all subtasks and their current status
@@ -148,32 +143,13 @@ Taskmaster configuration is managed through two main mechanisms:
## Managing Task Dependencies
- Use `add_dependency` / `task-master add-dependency --id=<id> --depends-on=<id>` to add a dependency.
- Use `remove_dependency` / `task-master remove-dependency --id=<id> --depends-on=<id>` to remove a dependency.
- Use `add_dependency` / `task-master add-dependency --id=<id> --depends-on=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to add a dependency
- Use `remove_dependency` / `task-master remove-dependency --id=<id> --depends-on=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to remove a dependency
- The system prevents circular dependencies and duplicate dependency entries
- Dependencies are checked for existence before being added or removed
- 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:
@@ -188,14 +164,14 @@ Once a task has been broken down into subtasks using `expand_task` or similar me
* Gather *all* relevant details from this exploration phase.
3. **Log the Plan:**
* Run `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='<detailed plan>'`.
* Run `update_subtask` / `task-master update-subtask --id=<subtaskId> --prompt='<detailed plan>'` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
* Provide the *complete and detailed* findings from the exploration phase in the prompt. Include file paths, line numbers, proposed diffs, reasoning, and any potential challenges identified. Do not omit details. The goal is to create a rich, timestamped log within the subtask's `details`.
4. **Verify the Plan:**
* Run `get_task` / `task-master show <subtaskId>` again to confirm that the detailed implementation plan has been successfully appended to the subtask's details.
5. **Begin Implementation:**
* Set the subtask status using `set_task_status` / `task-master set-status --id=<subtaskId> --status=in-progress`.
* Set the subtask status using `set_task_status` / `task-master set-status --id=<subtaskId> --status=in-progress` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)).
* Start coding based on the logged plan.
6. **Refine and Log Progress (Iteration 2+):**
@@ -213,7 +189,7 @@ Once a task has been broken down into subtasks using `expand_task` or similar me
7. **Review & Update Rules (Post-Implementation):**
* Once the implementation for the subtask is functionally complete, review all code changes and the relevant chat history.
* Identify any new or modified code patterns, conventions, or best practices established during the implementation.
* Create new or update existing rules following internal guidelines (previously linked to `cursor_rules.mdc` and `self_improve.mdc`).
* Create new or update existing Cursor rules in the `.cursor/rules/` directory to capture these patterns, following the guidelines in [`cursor_rules.mdc`](mdc:.cursor/rules/cursor_rules.mdc) and [`self_improve.mdc`](mdc:.cursor/rules/self_improve.mdc).
8. **Mark Task Complete:**
* After verifying the implementation and updating any necessary rules, mark the subtask as completed: `set_task_status` / `task-master set-status --id=<subtaskId> --status=done`.
@@ -222,10 +198,10 @@ Once a task has been broken down into subtasks using `expand_task` or similar me
* Stage the relevant code changes and any updated/new rule files (`git add .`).
* Craft a comprehensive Git commit message summarizing the work done for the subtask, including both code implementation and any rule adjustments.
* Execute the commit command directly in the terminal (e.g., `git commit -m 'feat(module): Implement feature X for subtask <subtaskId>\n\n- Details about changes...\n- Updated rule Y for pattern Z'`).
* Consider if a Changeset is needed according to internal versioning guidelines (previously linked to `changeset.mdc`). If so, run `npm run changeset`, stage the generated file, and amend the commit or create a new one.
* Consider if a Changeset is needed according to [`changeset.mdc`](mdc:.cursor/rules/changeset.mdc). If so, run `npm run changeset`, stage the generated file, and amend the commit or create a new one.
10. **Proceed to Next Subtask:**
* Identify the next subtask (e.g., using `next_task` / `task-master next`).
* Identify the next subtask in the dependency chain (e.g., using `next_task` / `task-master next`) and repeat this iterative process starting from step 1.
## Code Analysis & Refactoring Techniques

View File

@@ -3,6 +3,7 @@ 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.
@@ -22,5 +23,4 @@ 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

@@ -3,6 +3,7 @@ description: Guidelines for implementing and interacting with the Task Master MC
globs: mcp-server/src/**/*, scripts/modules/**/*
alwaysApply: false
---
# Task Master MCP Server Guidelines
This document outlines the architecture and implementation patterns for the Task Master Model Context Protocol (MCP) server, designed for integration with tools like Cursor.
@@ -89,54 +90,69 @@ When implementing a new direct function in `mcp-server/src/core/direct-functions
```
5. **Handling Logging Context (`mcpLog`)**:
- **Requirement**: Core functions (like those in `task-manager.js`) may accept an `options` object containing an optional `mcpLog` property. If provided, the core function expects this object to have methods like `mcpLog.info(...)`, `mcpLog.error(...)`.
- **Solution: The Logger Wrapper Pattern**: When calling a core function from a direct function, pass the `log` object provided by FastMCP *wrapped* in the standard `logWrapper` object. This ensures the core function receives a logger with the expected method structure.
- **Requirement**: Core functions that use the internal `report` helper function (common in `task-manager.js`, `dependency-manager.js`, etc.) expect the `options` object to potentially contain an `mcpLog` property. This `mcpLog` object **must** have callable methods for each log level (e.g., `mcpLog.info(...)`, `mcpLog.error(...)`).
- **Challenge**: The `log` object provided by FastMCP to the direct function's context, while functional, might not perfectly match this expected structure or could change in the future. Passing it directly can lead to runtime errors like `mcpLog[level] is not a function`.
- **Solution: The Logger Wrapper Pattern**: To reliably bridge the FastMCP `log` object and the core function's `mcpLog` expectation, use a simple wrapper object within the direct function:
```javascript
// Standard logWrapper pattern within a Direct Function
const logWrapper = {
info: (message, ...args) => log.info(message, ...args),
warn: (message, ...args) => log.warn(message, ...args),
error: (message, ...args) => log.error(message, ...args),
debug: (message, ...args) => log.debug && log.debug(message, ...args),
success: (message, ...args) => log.info(message, ...args)
debug: (message, ...args) => log.debug && log.debug(message, ...args), // Handle optional debug
success: (message, ...args) => log.info(message, ...args) // Map success to info if needed
};
// ... later when calling the core function ...
await coreFunction(
// ... other arguments ...
tasksPath,
taskId,
{
mcpLog: logWrapper, // Pass the wrapper object
session // Also pass session if needed by core logic or AI service
session
},
'json' // Pass 'json' output format if supported by core function
);
```
- **JSON Output**: Passing `mcpLog` (via the wrapper) often triggers the core function to use a JSON-friendly output format, suppressing spinners/boxes.
- ✅ **DO**: Implement this pattern in direct functions calling core functions that might use `mcpLog`.
- **Critical For JSON Output Format**: Passing the `logWrapper` as `mcpLog` serves a dual purpose:
1. **Prevents Runtime Errors**: It ensures the `mcpLog[level](...)` calls within the core function succeed
2. **Controls Output Format**: In functions like `updateTaskById` and `updateSubtaskById`, the presence of `mcpLog` in the options triggers setting `outputFormat = 'json'` (instead of 'text'). This prevents UI elements (spinners, boxes) from being generated, which would break the JSON response.
- **Proven Solution**: This pattern has successfully fixed multiple issues in our MCP tools (including `update-task` and `update-subtask`), where direct passing of the `log` object or omitting `mcpLog` led to either runtime errors or JSON parsing failures from UI output.
- **When To Use**: Implement this wrapper in any direct function that calls a core function with an `options` object that might use `mcpLog` for logging or output format control.
- **Why it Works**: The `logWrapper` explicitly defines the `.info()`, `.warn()`, `.error()`, etc., methods that the core function's `report` helper needs, ensuring the `mcpLog[level](...)` call succeeds. It simply forwards the logging calls to the actual FastMCP `log` object.
- **Combined with Silent Mode**: Remember that using the `logWrapper` for `mcpLog` is **necessary *in addition* to using `enableSilentMode()` / `disableSilentMode()`** (see next point). The wrapper handles structured logging *within* the core function, while silent mode suppresses direct `console.log` and UI elements (spinners, boxes) that would break the MCP JSON response.
6. **Silent Mode Implementation**:
- ✅ **DO**: Import silent mode utilities: `import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';`
- ✅ **DO**: Wrap core function calls *within direct functions* using `enableSilentMode()` / `disableSilentMode()` in a `try/finally` block if the core function might produce console output (spinners, boxes, direct `console.log`) that isn't reliably controlled by passing `{ mcpLog }` or an `outputFormat` parameter.
- ✅ **DO**: Always disable silent mode in the `finally` block.
- ❌ **DON'T**: Wrap calls to the unified AI service (`generateTextService`, `generateObjectService`) in silent mode; their logging is handled internally.
- **Example (Direct Function Guaranteeing Silence & using Log Wrapper)**:
- ✅ **DO**: Import silent mode utilities at the top: `import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';`
- ✅ **DO**: Ensure core Task Master functions called from direct functions do **not** pollute `stdout` with console output (banners, spinners, logs) that would break MCP's JSON communication.
- **Preferred**: Modify the core function to accept an `outputFormat: 'json'` parameter and check it internally before printing UI elements. Pass `'json'` from the direct function.
- **Required Fallback/Guarantee**: If the core function cannot be modified or its output suppression is unreliable, **wrap the core function call** within the direct function using `enableSilentMode()` / `disableSilentMode()` in a `try/finally` block. This guarantees no console output interferes with the MCP response.
- ✅ **DO**: Use `isSilentMode()` function to check global silent mode status if needed (rare in direct functions), NEVER access the global `silentMode` variable directly.
- ❌ **DON'T**: Wrap AI client initialization or AI API calls in `enable/disableSilentMode`; their logging is controlled via the `log` object (passed potentially within the `logWrapper` for core functions).
- ❌ **DON'T**: Assume a core function is silent just because it *should* be. Verify or use the `enable/disableSilentMode` wrapper.
- **Example (Direct Function Guaranteeing Silence and using Log Wrapper)**:
```javascript
export async function coreWrapperDirect(args, log, context = {}) {
const { session } = context;
const tasksPath = findTasksJsonPath(args, log);
const logWrapper = { /* ... */ };
// Create the logger wrapper
const logWrapper = { /* ... as defined above ... */ };
enableSilentMode(); // Ensure silence for direct console output
try {
// Call core function, passing wrapper and 'json' format
const result = await coreFunction(
tasksPath,
args.param1,
{ mcpLog: logWrapper, session }, // Pass context
'json' // Request JSON format if supported
);
tasksPath,
args.param1,
{ mcpLog: logWrapper, session },
'json' // Explicitly request JSON format if supported
);
return { success: true, data: result };
} catch (error) {
log.error(`Error: ${error.message}`);
// Return standardized error object
return { success: false, error: { /* ... */ } };
} finally {
disableSilentMode(); // Critical: Always disable in finally
@@ -147,6 +163,32 @@ When implementing a new direct function in `mcp-server/src/core/direct-functions
7. **Debugging MCP/Core Logic Interaction**:
- ✅ **DO**: If an MCP tool fails with unclear errors (like JSON parsing failures), run the equivalent `task-master` CLI command in the terminal. The CLI often provides more detailed error messages originating from the core logic (e.g., `ReferenceError`, stack traces) that are obscured by the MCP layer.
### Specific Guidelines for AI-Based Direct Functions
Direct functions that interact with AI (e.g., `addTaskDirect`, `expandTaskDirect`) have additional responsibilities:
- **Context Parameter**: These functions receive an additional `context` object as their third parameter. **Critically, this object should only contain `{ session }`**. Do NOT expect or use `reportProgress` from this context.
```javascript
export async function yourAIDirect(args, log, context = {}) {
const { session } = context; // Only expect session
// ...
}
```
- **AI Client Initialization**:
- ✅ **DO**: Use the utilities from [`mcp-server/src/core/utils/ai-client-utils.js`](mdc:mcp-server/src/core/utils/ai-client-utils.js) (e.g., `getAnthropicClientForMCP(session, log)`) to get AI client instances. These correctly use the `session` object to resolve API keys.
- ✅ **DO**: Wrap client initialization in a try/catch block and return a specific `AI_CLIENT_ERROR` on failure.
- **AI Interaction**:
- ✅ **DO**: Build prompts using helper functions where appropriate (e.g., from `ai-prompt-helpers.js`).
- ✅ **DO**: Make the AI API call using appropriate helpers (e.g., `_handleAnthropicStream`). Pass the `log` object to these helpers for internal logging. **Do NOT pass `reportProgress`**.
- ✅ **DO**: Parse the AI response using helpers (e.g., `parseTaskJsonResponse`) and handle parsing errors with a specific code (e.g., `RESPONSE_PARSING_ERROR`).
- **Calling Core Logic**:
- ✅ **DO**: After successful AI interaction, call the relevant core Task Master function (from `scripts/modules/`) if needed (e.g., `addTaskDirect` calls `addTask`).
- ✅ **DO**: Pass necessary data, including potentially the parsed AI results, to the core function.
- ✅ **DO**: If the core function can produce console output, call it with an `outputFormat: 'json'` argument (or similar, depending on the function) to suppress CLI output. Ensure the core function is updated to respect this. Use `enableSilentMode/disableSilentMode` around the core function call as a fallback if `outputFormat` is not supported or insufficient.
- **Progress Indication**:
- ❌ **DON'T**: Call `reportProgress` within the direct function.
- ✅ **DO**: If intermediate progress status is needed *within* the long-running direct function, use standard logging: `log.info('Progress: Processing AI response...')`.
## Tool Definition and Execution
### Tool Structure
@@ -179,78 +221,151 @@ server.addTool({
The `execute` function receives validated arguments and the FastMCP context:
```javascript
// Standard signature
execute: async (args, context) => {
// Tool implementation
}
// Destructured signature (recommended)
execute: async (args, { log, session }) => {
execute: async (args, { log, reportProgress, session }) => {
// Tool implementation
}
```
- **args**: Validated parameters.
- **context**: Contains `{ log, session }` from FastMCP. (Removed `reportProgress`).
- **args**: The first parameter contains all the validated parameters defined in the tool's schema.
- **context**: The second parameter is an object containing `{ log, reportProgress, session }` provided by FastMCP.
- ✅ **DO**: Use `{ log, session }` when calling direct functions.
- ⚠️ **WARNING**: Avoid passing `reportProgress` down to direct functions due to client compatibility issues. See Progress Reporting Convention below.
### Standard Tool Execution Pattern with Path Normalization (Updated)
### Standard Tool Execution Pattern
To ensure consistent handling of project paths across different client environments (Windows, macOS, Linux, WSL) and input formats (e.g., `file:///...`, URI encoded paths), all MCP tool `execute` methods that require access to the project root **MUST** be wrapped with the `withNormalizedProjectRoot` Higher-Order Function (HOF).
The `execute` method within each MCP tool (in `mcp-server/src/tools/*.js`) should follow this standard pattern:
This HOF, defined in [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js), performs the following before calling the tool's core logic:
1. **Determines the Raw Root:** It prioritizes `args.projectRoot` if provided by the client, otherwise it calls `getRawProjectRootFromSession` to extract the path from the session.
2. **Normalizes the Path:** It uses the `normalizeProjectRoot` helper to decode URIs, strip `file://` prefixes, fix potential Windows drive letter prefixes (e.g., `/C:/`), convert backslashes (`\`) to forward slashes (`/`), and resolve the path to an absolute path suitable for the server's OS.
3. **Injects Normalized Path:** It updates the `args` object by replacing the original `projectRoot` (or adding it) with the normalized, absolute path.
4. **Executes Original Logic:** It calls the original `execute` function body, passing the updated `args` object.
**Implementation Example:**
1. **Log Entry**: Log the start of the tool execution with relevant arguments.
2. **Get Project Root**: Use the `getProjectRootFromSession(session, log)` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) to extract the project root path from the client session. Fall back to `args.projectRoot` if the session doesn't provide a root.
3. **Call Direct Function**: Invoke the corresponding `*Direct` function wrapper (e.g., `listTasksDirect` from [`task-master-core.js`](mdc:mcp-server/src/core/task-master-core.js)), passing an updated `args` object that includes the resolved `projectRoot`. Crucially, the third argument (context) passed to the direct function should **only include `{ log, session }`**. **Do NOT pass `reportProgress`**.
```javascript
// Example call to a non-AI direct function
const result = await someDirectFunction({ ...args, projectRoot }, log);
// Example call to an AI-based direct function
const resultAI = await someAIDirect({ ...args, projectRoot }, log, { session });
```
4. **Handle Result**: Receive the result object (`{ success, data/error, fromCache }`) from the `*Direct` function.
5. **Format Response**: Pass this result object to the `handleApiResult` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) for standardized MCP response formatting and error handling.
6. **Return**: Return the formatted response object provided by `handleApiResult`.
```javascript
// In mcp-server/src/tools/your-tool.js
import {
handleApiResult,
createErrorResponse,
withNormalizedProjectRoot // <<< Import HOF
} from './utils.js';
import { yourDirectFunction } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js'; // If needed
// Example execute method structure for a tool calling an AI-based direct function
import { getProjectRootFromSession, handleApiResult, createErrorResponse } from './utils.js';
import { someAIDirectFunction } from '../core/task-master-core.js';
export function registerYourTool(server) {
server.addTool({
name: "your_tool",
description: "...".
parameters: z.object({
// ... other parameters ...
projectRoot: z.string().optional().describe('...') // projectRoot is optional here, HOF handles fallback
}),
// Wrap the entire execute function
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
// args.projectRoot is now guaranteed to be normalized and absolute
const { /* other args */, projectRoot } = args;
// ... inside server.addTool({...})
execute: async (args, { log, session }) => { // Note: reportProgress is omitted here
try {
log.info(`Starting AI tool execution with args: ${JSON.stringify(args)}`);
try {
log.info(`Executing your_tool with normalized root: ${projectRoot}`);
// 1. Get Project Root
let rootFolder = getProjectRootFromSession(session, log);
if (!rootFolder && args.projectRoot) { // Fallback if needed
rootFolder = args.projectRoot;
log.info(`Using project root from args as fallback: ${rootFolder}`);
}
// Resolve paths using the normalized projectRoot
let tasksPath = findTasksJsonPath({ projectRoot, file: args.file }, log);
// 2. Call AI-Based Direct Function (passing only log and session in context)
const result = await someAIDirectFunction({
...args,
projectRoot: rootFolder // Ensure projectRoot is explicitly passed
}, log, { session }); // Pass session here, NO reportProgress
// Call direct function, passing normalized projectRoot if needed by direct func
const result = await yourDirectFunction(
{
/* other args */,
projectRoot // Pass it if direct function needs it
},
log,
{ session }
);
// 3. Handle and Format Response
return handleApiResult(result, log);
return handleApiResult(result, log);
} catch (error) {
log.error(`Error in your_tool: ${error.message}`);
return createErrorResponse(error.message);
}
}) // End HOF wrap
});
} catch (error) {
log.error(`Error during AI tool execution: ${error.message}`);
return createErrorResponse(error.message);
}
}
```
By using this HOF, the core logic within the `execute` method and any downstream functions (like `findTasksJsonPath` or direct functions) can reliably expect `args.projectRoot` to be a clean, absolute path suitable for the server environment.
### Using AsyncOperationManager for Background Tasks
For tools that execute potentially long-running operations *where the AI call is just one part* (e.g., `expand-task`, `update`), use the AsyncOperationManager. The `add-task` command, as refactored, does *not* require this in the MCP tool layer because the direct function handles the primary AI work and returns the final result synchronously from the perspective of the MCP tool.
For tools that *do* use `AsyncOperationManager`:
```javascript
import { AsyncOperationManager } from '../utils/async-operation-manager.js'; // Correct path assuming utils location
import { getProjectRootFromSession, createContentResponse, createErrorResponse } from './utils.js';
import { someIntensiveDirect } from '../core/task-master-core.js';
// ... inside server.addTool({...})
execute: async (args, { log, session }) => { // Note: reportProgress omitted
try {
log.info(`Starting background operation with args: ${JSON.stringify(args)}`);
// 1. Get Project Root
let rootFolder = getProjectRootFromSession(session, log);
if (!rootFolder && args.projectRoot) {
rootFolder = args.projectRoot;
log.info(`Using project root from args as fallback: ${rootFolder}`);
}
// Create operation description
const operationDescription = `Expanding task ${args.id}...`; // Example
// 2. Start async operation using AsyncOperationManager
const operation = AsyncOperationManager.createOperation(
operationDescription,
async (reportProgressCallback) => { // This callback is provided by AsyncOperationManager
// This runs in the background
try {
// Report initial progress *from the manager's callback*
reportProgressCallback({ progress: 0, status: 'Starting operation...' });
// Call the direct function (passing only session context)
const result = await someIntensiveDirect(
{ ...args, projectRoot: rootFolder },
log,
{ session } // Pass session, NO reportProgress
);
// Report final progress *from the manager's callback*
reportProgressCallback({
progress: 100,
status: result.success ? 'Operation completed' : 'Operation failed',
result: result.data, // Include final data if successful
error: result.error // Include error object if failed
});
return result; // Return the direct function's result
} catch (error) {
// Handle errors within the async task
reportProgressCallback({
progress: 100,
status: 'Operation failed critically',
error: { message: error.message, code: error.code || 'ASYNC_OPERATION_FAILED' }
});
throw error; // Re-throw for the manager to catch
}
}
);
// 3. Return immediate response with operation ID
return {
status: 202, // StatusCodes.ACCEPTED
body: {
success: true,
message: 'Operation started',
operationId: operation.id
}
};
} catch (error) {
log.error(`Error starting background operation: ${error.message}`);
return createErrorResponse(`Failed to start operation: ${error.message}`); // Use standard error response
}
}
```
### Project Initialization Tool
@@ -302,13 +417,19 @@ log.error(`Error occurred: ${error.message}`, { stack: error.stack });
log.info('Progress: 50% - AI call initiated...'); // Example progress logging
```
## Session Usage Convention
### Progress Reporting Convention
- ⚠️ **DEPRECATED within Direct Functions**: The `reportProgress` function passed in the `context` object should **NOT** be called from within `*Direct` functions. Doing so can cause client-side validation errors due to missing/incorrect `progressToken` handling.
- ✅ **DO**: For tools using `AsyncOperationManager`, use the `reportProgressCallback` function *provided by the manager* within the background task definition (as shown in the `AsyncOperationManager` example above) to report progress updates for the *overall operation*.
- ✅ **DO**: If finer-grained progress needs to be indicated *during* the execution of a `*Direct` function (whether called directly or via `AsyncOperationManager`), use `log.info()` statements (e.g., `log.info('Progress: Parsing AI response...')`).
### Session Usage Convention
The `session` object (destructured from `context`) contains authenticated session data and client information.
- **Authentication**: Access user-specific data (`session.userId`, etc.) if authentication is implemented.
- **Project Root**: The primary use in Task Master is accessing `session.roots` to determine the client's project root directory via the `getProjectRootFromSession` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)). See the Standard Tool Execution Pattern above.
- **Environment Variables**: The `session.env` object provides access to environment variables set in the MCP client configuration (e.g., `.cursor/mcp.json`). This is the **primary mechanism** for the unified AI service layer (`ai-services-unified.js`) to securely access **API keys** when called from MCP context.
- **Environment Variables**: The `session.env` object is critical for AI tools. Pass the `session` object to the `*Direct` function's context, and then to AI client utility functions (like `getAnthropicClientForMCP`) which will extract API keys and other relevant environment settings (e.g., `MODEL`, `MAX_TOKENS`) from `session.env`.
- **Capabilities**: Can be used to check client capabilities (`session.clientCapabilities`).
## Direct Function Wrappers (`*Direct`)
@@ -317,25 +438,24 @@ These functions, located in `mcp-server/src/core/direct-functions/`, form the co
- **Purpose**: Bridge MCP tools and core Task Master modules (`scripts/modules/*`). Handle AI interactions if applicable.
- **Responsibilities**:
- Receive `args` (including `projectRoot`), `log`, and optionally `{ session }` context.
- Find `tasks.json` using `findTasksJsonPath`.
- Validate arguments.
- **Implement Caching (if applicable)**: Use `getCachedOrExecute`.
- **Call Core Logic**: Invoke function from `scripts/modules/*`.
- Pass `outputFormat: 'json'` if applicable.
- Wrap with `enableSilentMode/disableSilentMode` if needed.
- Pass `{ mcpLog: logWrapper, session }` context if core logic needs it.
- Handle errors.
- Return standardized result object.
- ❌ **DON'T**: Call `reportProgress`.
- ❌ **DON'T**: Initialize AI clients or call AI services directly.
- Receive `args` (including the `projectRoot` determined by the tool), `log` object, and optionally a `context` object (containing **only `{ session }` if needed).
- **Find `tasks.json`**: Use `findTasksJsonPath(args, log)` from [`core/utils/path-utils.js`](mdc:mcp-server/src/core/utils/path-utils.js).
- Validate arguments specific to the core logic.
- **Handle AI Logic (if applicable)**: Initialize AI clients (using `session` from context), build prompts, make AI calls, parse responses.
- **Implement Caching (if applicable)**: Use `getCachedOrExecute` from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js) for read operations.
- **Call Core Logic**: Call the underlying function from the core Task Master modules, passing necessary data (including AI results if applicable).
- ✅ **DO**: Pass `outputFormat: 'json'` (or similar) to the core function if it might produce console output.
- ✅ **DO**: Wrap the core function call with `enableSilentMode/disableSilentMode` if necessary.
- Handle errors gracefully (AI errors, core logic errors, file errors).
- Return a standardized result object: `{ success: boolean, data?: any, error?: { code: string, message: string }, fromCache?: boolean }`.
- ❌ **DON'T**: Call `reportProgress`. Use `log.info` for progress indication if needed.
## Key Principles
- **Prefer Direct Function Calls**: MCP tools should always call `*Direct` wrappers instead of `executeTaskMasterCommand`.
- **Standardized Execution Flow**: Follow the pattern: MCP Tool -> `getProjectRootFromSession` -> `*Direct` Function -> Core Logic / AI Logic.
- **Path Resolution via Direct Functions**: The `*Direct` function is responsible for finding the exact `tasks.json` path using `findTasksJsonPath`, relying on the `projectRoot` passed in `args`.
- **AI Logic in Core Modules**: AI interactions (prompt building, calling unified service) reside within the core logic functions (`scripts/modules/*`), not direct functions.
- **AI Logic in Direct Functions**: For AI-based tools, the `*Direct` function handles AI client initialization, calls, and parsing, using the `session` object passed in its context.
- **Silent Mode in Direct Functions**: Wrap *core function* calls (from `scripts/modules`) with `enableSilentMode()` and `disableSilentMode()` if they produce console output not handled by `outputFormat`. Do not wrap AI calls.
- **Selective Async Processing**: Use `AsyncOperationManager` in the *MCP Tool layer* for operations involving multiple steps or long waits beyond a single AI call (e.g., file processing + AI call + file writing). Simple AI calls handled entirely within the `*Direct` function (like `addTaskDirect`) may not need it at the tool layer.
- **No `reportProgress` in Direct Functions**: Do not pass or use `reportProgress` within `*Direct` functions. Use `log.info()` for internal progress or report progress from the `AsyncOperationManager` callback in the MCP tool layer.
@@ -360,7 +480,7 @@ Follow these steps to add MCP support for an existing Task Master command (see [
1. **Ensure Core Logic Exists**: Verify the core functionality is implemented and exported from the relevant module in `scripts/modules/`. Ensure the core function can suppress console output (e.g., via an `outputFormat` parameter).
2. **Create Direct Function File in `mcp-server/src/core/direct-functions/`**:
2. **Create Direct Function File in `mcp-server/src/core/direct-functions/`**:
- Create a new file (e.g., `your-command.js`) using **kebab-case** naming.
- Import necessary core functions, `findTasksJsonPath`, silent mode utilities, and potentially AI client/prompt utilities.
- Implement `async function yourCommandDirect(args, log, context = {})` using **camelCase** with `Direct` suffix. **Remember `context` should only contain `{ session }` if needed (for AI keys/config).**
@@ -522,8 +642,3 @@ 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,6 +3,7 @@ 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
@@ -24,17 +25,11 @@ 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)**:
- 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).
2. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc).
3. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
4. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
5. **Configuration**: Update any configuration in [`utils.js`](mdc:scripts/modules/utils.js) if needed, following [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc).
6. **Documentation**: Update help text and documentation in [dev_workflow.mdc](mdc:scripts/modules/dev_workflow.mdc)
## Critical Checklist for New Features
@@ -195,8 +190,6 @@ 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)
/**
@@ -218,29 +211,7 @@ export {
```
```javascript
// 2. AI Integration: Add import and use necessary service functions
import { generateTextService } from './ai-services-unified.js';
// Example usage:
async function handleAIInteraction() {
const role = 'user';
const session = 'exampleSession';
const systemPrompt = 'You are a helpful assistant.';
const prompt = 'What is the capital of France?';
const result = await generateTextService(role, session, systemPrompt, prompt);
console.log(result);
}
// Export from the module
export {
// ... existing exports ...
handleAIInteraction,
};
```
```javascript
// 3. UI COMPONENTS: Add display function to ui.js
// 2. UI COMPONENTS: Add display function to ui.js
/**
* Display archive operation results
* @param {string} archivePath - Path to the archive file
@@ -261,7 +232,7 @@ export {
```
```javascript
// 4. COMMAND INTEGRATION: Add to commands.js
// 3. COMMAND INTEGRATION: Add to commands.js
import { archiveTasks } from './task-manager.js';
import { displayArchiveResults } from './ui.js';
@@ -481,7 +452,7 @@ npm test
For each new feature:
1. Add help text to the command definition
2. Update [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) with command reference
2. Update [`dev_workflow.mdc`](mdc:scripts/modules/dev_workflow.mdc) with command reference
3. Consider updating [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) if the feature significantly changes module responsibilities.
Follow the existing command reference format:
@@ -524,24 +495,14 @@ Integrating Task Master commands with the MCP server (for use by tools like Curs
4. **Create MCP Tool (`mcp-server/src/tools/`)**:
- Create a new file (e.g., `your-command.js`) using **kebab-case**.
- Import `zod`, `handleApiResult`, **`withNormalizedProjectRoot` HOF**, and your `yourCommandDirect` function.
- Import `zod`, `handleApiResult`, `createErrorResponse`, **`getProjectRootFromSession`**, and your `yourCommandDirect` function.
- Implement `registerYourCommandTool(server)`.
- **Define parameters**: Make `projectRoot` optional (`z.string().optional().describe(...)`) as the HOF handles fallback.
- Consider if this operation should run in the background using `AsyncOperationManager`.
- Implement the standard `execute` method **wrapped with `withNormalizedProjectRoot`**:
```javascript
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
// args.projectRoot is now normalized
const { projectRoot /*, other args */ } = args;
// ... resolve tasks path if needed using normalized projectRoot ...
const result = await yourCommandDirect(
{ /* other args */, projectRoot /* if needed by direct func */ },
log,
{ session }
);
return handleApiResult(result, log);
})
```
- Define the tool `name` using **snake_case** (e.g., `your_command`).
- Define the `parameters` using `zod`. **Crucially, define `projectRoot` as optional**: `projectRoot: z.string().optional().describe(...)`. Include `file` if applicable.
- Implement the standard `async execute(args, { log, reportProgress, session })` method:
- Get `rootFolder` using `getProjectRootFromSession` (with fallback to `args.projectRoot`).
- Call `yourCommandDirect({ ...args, projectRoot: rootFolder }, log)`.
- Pass the result to `handleApiResult(result, log, 'Error Message')`.
5. **Register Tool**: Import and call `registerYourCommandTool` in `mcp-server/src/tools/index.js`.

View File

@@ -69,4 +69,5 @@ alwaysApply: true
- Update references to external docs
- Maintain links between related rules
- Document breaking changes
Follow [cursor_rules.mdc](mdc:.cursor/rules/cursor_rules.mdc) for proper rule formatting and structure.
Follow [cursor_rules.mdc](mdc:.cursor/rules/cursor_rules.mdc) for proper rule formatting and structure.

View File

@@ -3,13 +3,14 @@ description: Comprehensive reference for Taskmaster MCP tools and CLI commands.
globs: **/*
alwaysApply: true
---
# Taskmaster Tool & Command Reference
This document provides a detailed reference for interacting with Taskmaster, covering both the recommended MCP tools, suitable for integrations like Cursor, and the corresponding `task-master` CLI commands, designed for direct user interaction or fallback.
This document provides a detailed reference for interacting with Taskmaster, covering both the recommended MCP tools (for integrations like Cursor) and the corresponding `task-master` CLI commands (for direct user interaction or fallback).
**Note:** For interacting with Taskmaster programmatically or via integrated tools, using the **MCP tools is strongly recommended** due to better performance, structured data, and error handling. The CLI commands serve as a user-friendly alternative and fallback.
**Note:** For interacting with Taskmaster programmatically or via integrated tools, using the **MCP tools is strongly recommended** due to better performance, structured data, and error handling. The CLI commands serve as a user-friendly alternative and fallback. See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for MCP implementation details and [`commands.mdc`](mdc:.cursor/rules/commands.mdc) for CLI implementation guidelines.
**Important:** Several MCP tools involve AI processing... The AI-powered tools include `parse_prd`, `analyze_project_complexity`, `update_subtask`, `update_task`, `update`, `expand_all`, `expand_task`, and `add_task`.
**Important:** Several MCP tools involve AI processing and are long-running operations that may take up to a minute to complete. When using these tools, always inform users that the operation is in progress and to wait patiently for results. The AI-powered tools include: `parse_prd`, `analyze_project_complexity`, `update_subtask`, `update_task`, `update`, `expand_all`, `expand_task`, and `add_task`.
---
@@ -23,64 +24,34 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key CLI Options:**
* `--name <name>`: `Set the name for your project in Taskmaster's configuration.`
* `--description <text>`: `Provide a brief description for your project.`
* `--version <version>`: `Set the initial version for your project, e.g., '0.1.0'.`
* `--version <version>`: `Set the initial version for your project (e.g., '0.1.0').`
* `-y, --yes`: `Initialize Taskmaster quickly using default settings without interactive prompts.`
* **Usage:** Run this once at the beginning of a new project.
* **MCP Variant Description:** `Set up the basic Taskmaster file structure and configuration in the current directory for a new project by running the 'task-master init' command.`
* **Key MCP Parameters/Options:**
* `projectName`: `Set the name for your project.` (CLI: `--name <name>`)
* `projectDescription`: `Provide a brief description for your project.` (CLI: `--description <text>`)
* `projectVersion`: `Set the initial version for your project, e.g., '0.1.0'.` (CLI: `--version <version>`)
* `projectVersion`: `Set the initial version for your project (e.g., '0.1.0').` (CLI: `--version <version>`)
* `authorName`: `Author name.` (CLI: `--author <author>`)
* `skipInstall`: `Skip installing dependencies. Default is false.` (CLI: `--skip-install`)
* `addAliases`: `Add shell aliases tm and taskmaster. Default is false.` (CLI: `--aliases`)
* `yes`: `Skip prompts and use defaults/provided arguments. Default is false.` (CLI: `-y, --yes`)
* `skipInstall`: `Skip installing dependencies (default: false).` (CLI: `--skip-install`)
* `addAliases`: `Add shell aliases (tm, taskmaster) (default: false).` (CLI: `--aliases`)
* `yes`: `Skip prompts and use defaults/provided arguments (default: false).` (CLI: `-y, --yes`)
* **Usage:** Run this once at the beginning of a new project, typically via an integrated tool like Cursor. Operates on the current working directory of the MCP server.
* **Important:** Once complete, you *MUST* parse a prd in order to generate tasks. There will be no tasks files until then. The next step after initializing should be to create a PRD using the example PRD in .taskmaster/templates/example_prd.txt.
* **Important:** Once complete, you *MUST* parse a prd in order to generate tasks. There will be no tasks files until then. The next step after initializing should be to create a PRD using the example PRD in scripts/example_prd.txt.
### 2. Parse PRD (`parse_prd`)
* **MCP Tool:** `parse_prd`
* **CLI Command:** `task-master parse-prd [file] [options]`
* **Description:** `Parse a Product Requirements Document, PRD, or text file with Taskmaster to automatically generate an initial set of tasks in tasks.json.`
* **Description:** `Parse a Product Requirements Document (PRD) or text file with Taskmaster to automatically generate an initial set of tasks in tasks.json.`
* **Key Parameters/Options:**
* `input`: `Path to your PRD or requirements text file that Taskmaster should parse for tasks.` (CLI: `[file]` positional or `-i, --input <file>`)
* `output`: `Specify where Taskmaster should save the generated 'tasks.json' file. Defaults to '.taskmaster/tasks/tasks.json'.` (CLI: `-o, --output <file>`)
* `output`: `Specify where Taskmaster should save the generated 'tasks.json' file (default: 'tasks/tasks.json').` (CLI: `-o, --output <file>`)
* `numTasks`: `Approximate number of top-level tasks Taskmaster should aim to generate from the document.` (CLI: `-n, --num-tasks <number>`)
* `force`: `Use this to allow Taskmaster to overwrite an existing 'tasks.json' without asking for confirmation.` (CLI: `-f, --force`)
* **Usage:** Useful for bootstrapping a project from an existing requirements document.
* **Notes:** Task Master will strictly adhere to any specific requirements mentioned in the PRD, such as libraries, database schemas, frameworks, tech stacks, etc., while filling in any gaps where the PRD isn't fully specified. Tasks are designed to provide the most direct implementation path while avoiding over-engineering.
* **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. If the user does not have a PRD, suggest discussing their idea and then use the example PRD in `.taskmaster/templates/example_prd.txt` as a template for creating the PRD based on their idea, for use with `parse-prd`.
---
## AI Model Configuration
### 2. Manage Models (`models`)
* **MCP Tool:** `models`
* **CLI Command:** `task-master models [options]`
* **Description:** `View the current AI model configuration or set specific models for different roles (main, research, fallback). Allows setting custom model IDs for Ollama and OpenRouter.`
* **Key MCP Parameters/Options:**
* `setMain <model_id>`: `Set the primary model ID for task generation/updates.` (CLI: `--set-main <model_id>`)
* `setResearch <model_id>`: `Set the model ID for research-backed operations.` (CLI: `--set-research <model_id>`)
* `setFallback <model_id>`: `Set the model ID to use if the primary fails.` (CLI: `--set-fallback <model_id>`)
* `ollama <boolean>`: `Indicates the set model ID is a custom Ollama model.` (CLI: `--ollama`)
* `openrouter <boolean>`: `Indicates the set model ID is a custom OpenRouter model.` (CLI: `--openrouter`)
* `listAvailableModels <boolean>`: `If true, lists available models not currently assigned to a role.` (CLI: No direct equivalent; CLI lists available automatically)
* `projectRoot <string>`: `Optional. Absolute path to the project root directory.` (CLI: Determined automatically)
* **Key CLI Options:**
* `--set-main <model_id>`: `Set the primary model.`
* `--set-research <model_id>`: `Set the research model.`
* `--set-fallback <model_id>`: `Set the fallback model.`
* `--ollama`: `Specify that the provided model ID is for Ollama (use with --set-*).`
* `--openrouter`: `Specify that the provided model ID is for OpenRouter (use with --set-*). Validates against OpenRouter API.`
* `--setup`: `Run interactive setup to configure models, including custom Ollama/OpenRouter IDs.`
* **Usage (MCP):** Call without set flags to get current config. Use `setMain`, `setResearch`, or `setFallback` with a valid model ID to update the configuration. Use `listAvailableModels: true` to get a list of unassigned models. To set a custom model, provide the model ID and set `ollama: true` or `openrouter: true`.
* **Usage (CLI):** Run without flags to view current configuration and available models. Use set flags to update specific roles. Use `--setup` for guided configuration, including custom models. To set a custom model via flags, use `--set-<role>=<model_id>` along with either `--ollama` or `--openrouter`.
* **Notes:** Configuration is stored in `.taskmaster/config.json` in the project root. This command/tool modifies that file. Use `listAvailableModels` or `task-master models` to see internally supported models. OpenRouter custom models are validated against their live API. Ollama custom models are not validated live.
* **API note:** API keys for selected AI providers (based on their model) need to exist in the mcp.json file to be accessible in MCP context. The API keys must be present in the local .env file for the CLI to be able to read them.
* **Model costs:** The costs in supported models are expressed in dollars. An input/output value of 3 is $3.00. A value of 0.8 is $0.80.
* **Warning:** DO NOT MANUALLY EDIT THE .taskmaster/config.json FILE. Use the included commands either in the MCP or CLI format as needed. Always prioritize MCP tools when available and use the CLI as a fallback.
* **Notes:** Task Master will strictly adhere to any specific requirements mentioned in the PRD (libraries, database schemas, frameworks, tech stacks, etc.) while filling in any gaps where the PRD isn't fully specified. Tasks are designed to provide the most direct implementation path while avoiding over-engineering.
* **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. If the user does not have a PRD, suggest discussing their idea and then use the example PRD in scripts/example_prd.txt as a template for creating the PRD based on their idea, for use with parse-prd.
---
@@ -92,9 +63,9 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master list [options]`
* **Description:** `List your Taskmaster tasks, optionally filtering by status and showing subtasks.`
* **Key Parameters/Options:**
* `status`: `Show only Taskmaster tasks matching this status, e.g., 'pending' or 'done'.` (CLI: `-s, --status <status>`)
* `status`: `Show only Taskmaster tasks matching this status (e.g., 'pending', 'done').` (CLI: `-s, --status <status>`)
* `withSubtasks`: `Include subtasks indented under their parent tasks in the list.` (CLI: `--with-subtasks`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Get an overview of the project status, often used at the start of a work session.
### 4. Get Next Task (`next_task`)
@@ -103,7 +74,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master next [options]`
* **Description:** `Ask Taskmaster to show the next available task you can work on, based on status and completed dependencies.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Identify what to work on next according to the plan.
### 5. Get Task Details (`get_task`)
@@ -112,8 +83,8 @@ 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>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `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>`)
* `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.
---
@@ -126,11 +97,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master add-task [options]`
* **Description:** `Add a new task to Taskmaster by describing it; AI will structure it.`
* **Key Parameters/Options:**
* `prompt`: `Required. Describe the new task you want Taskmaster to create, e.g., "Implement user authentication using JWT".` (CLI: `-p, --prompt <text>`)
* `dependencies`: `Specify the IDs of any Taskmaster tasks that must be completed before this new one can start, e.g., '12,14'.` (CLI: `-d, --dependencies <ids>`)
* `priority`: `Set the priority for the new task: 'high', 'medium', or 'low'. Default is 'medium'.` (CLI: `--priority <priority>`)
* `research`: `Enable Taskmaster to use the research role for potentially more informed task creation.` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `prompt`: `Required. Describe the new task you want Taskmaster to create (e.g., "Implement user authentication using JWT").` (CLI: `-p, --prompt <text>`)
* `dependencies`: `Specify the IDs of any Taskmaster tasks that must be completed before this new one can start (e.g., '12,14').` (CLI: `-d, --dependencies <ids>`)
* `priority`: `Set the priority for the new task ('high', 'medium', 'low'; default: 'medium').` (CLI: `--priority <priority>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Quickly add newly identified tasks during development.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -142,13 +112,13 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id` / `parent`: `Required. The ID of the Taskmaster task that will be the parent.` (MCP: `id`, CLI: `-p, --parent <id>`)
* `taskId`: `Use this if you want to convert an existing top-level Taskmaster task into a subtask of the specified parent.` (CLI: `-i, --task-id <id>`)
* `title`: `Required if not using taskId. The title for the new subtask Taskmaster should create.` (CLI: `-t, --title <title>`)
* `title`: `Required (if not using taskId). The title for the new subtask Taskmaster should create.` (CLI: `-t, --title <title>`)
* `description`: `A brief description for the new subtask.` (CLI: `-d, --description <text>`)
* `details`: `Provide implementation notes or details for the new subtask.` (CLI: `--details <text>`)
* `dependencies`: `Specify IDs of other tasks or subtasks, e.g., '15' or '16.1', that must be done before this new subtask.` (CLI: `--dependencies <ids>`)
* `status`: `Set the initial status for the new subtask. Default is 'pending'.` (CLI: `-s, --status <status>`)
* `dependencies`: `Specify IDs of other tasks or subtasks (e.g., '15', '16.1') that must be done before this new subtask.` (CLI: `--dependencies <ids>`)
* `status`: `Set the initial status for the new subtask (default: 'pending').` (CLI: `-s, --status <status>`)
* `skipGenerate`: `Prevent Taskmaster from automatically regenerating markdown task files after adding the subtask.` (CLI: `--skip-generate`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Break down tasks manually or reorganize existing tasks.
### 8. Update Tasks (`update`)
@@ -157,10 +127,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master update [options]`
* **Description:** `Update multiple upcoming tasks in Taskmaster based on new context or changes, starting from a specific task ID.`
* **Key Parameters/Options:**
* `from`: `Required. The ID of the first task Taskmaster should update. All tasks with this ID or higher that are not 'done' will be considered.` (CLI: `--from <id>`)
* `prompt`: `Required. Explain the change or new context for Taskmaster to apply to the tasks, e.g., "We are now using React Query instead of Redux Toolkit for data fetching".` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `from`: `Required. The ID of the first task Taskmaster should update. All tasks with this ID or higher (and not 'done') will be considered.` (CLI: `--from <id>`)
* `prompt`: `Required. Explain the change or new context for Taskmaster to apply to the tasks (e.g., "We are now using React Query instead of Redux Toolkit for data fetching").` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates based on external knowledge (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Handle significant implementation changes or pivots that affect multiple future tasks. Example CLI: `task-master update --from='18' --prompt='Switching to React Query.\nNeed to refactor data fetching...'`
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -168,12 +138,12 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **MCP Tool:** `update_task`
* **CLI Command:** `task-master update-task [options]`
* **Description:** `Modify a specific Taskmaster task or subtask by its ID, incorporating new information or changes.`
* **Description:** `Modify a specific Taskmaster task (or subtask) by its ID, incorporating new information or changes.`
* **Key Parameters/Options:**
* `id`: `Required. The specific ID of the Taskmaster task, e.g., '15', or subtask, e.g., '15.2', you want to update.` (CLI: `-i, --id <id>`)
* `id`: `Required. The specific ID of the Taskmaster task (e.g., '15') or subtask (e.g., '15.2') you want to update.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. Explain the specific changes or provide the new information Taskmaster should incorporate into this task.` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Refine a specific task based on new understanding or feedback. Example CLI: `task-master update-task --id='15' --prompt='Clarification: Use PostgreSQL instead of MySQL.\nUpdate schema details...'`
* **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.
@@ -183,10 +153,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master update-subtask [options]`
* **Description:** `Append timestamped notes or details to a specific Taskmaster subtask without overwriting existing content. Intended for iterative implementation logging.`
* **Key Parameters/Options:**
* `id`: `Required. The specific ID of the Taskmaster subtask, e.g., '15.2', you want to add information to.` (CLI: `-i, --id <id>`)
* `id`: `Required. The specific ID of the Taskmaster subtask (e.g., '15.2') you want to add information to.` (CLI: `-i, --id <id>`)
* `prompt`: `Required. Provide the information or notes Taskmaster should append to the subtask's details. Ensure this adds *new* information not already present.` (CLI: `-p, --prompt <text>`)
* `research`: `Enable Taskmaster to use the research role for more informed updates. Requires appropriate API key.` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `research`: `Enable Taskmaster to use Perplexity AI for more informed updates (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Add implementation notes, code snippets, or clarifications to a subtask during development. Before calling, review the subtask's current details to append only fresh insights, helping to build a detailed log of the implementation journey and avoid redundancy. Example CLI: `task-master update-subtask --id='15.2' --prompt='Discovered that the API requires header X.\nImplementation needs adjustment...'`
* **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.
@@ -194,11 +164,11 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **MCP Tool:** `set_task_status`
* **CLI Command:** `task-master set-status [options]`
* **Description:** `Update the status of one or more Taskmaster tasks or subtasks, e.g., 'pending', 'in-progress', 'done'.`
* **Description:** `Update the status of one or more Taskmaster tasks or subtasks (e.g., 'pending', 'in-progress', 'done').`
* **Key Parameters/Options:**
* `id`: `Required. The ID(s) of the Taskmaster task(s) or subtask(s), e.g., '15', '15.2', or '16,17.1', to update.` (CLI: `-i, --id <id>`)
* `status`: `Required. The new status to set, e.g., 'done', 'pending', 'in-progress', 'review', 'cancelled'.` (CLI: `-s, --status <status>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `id`: `Required. The ID(s) of the Taskmaster task(s) or subtask(s) (e.g., '15', '15.2', '16,17.1') to update.` (CLI: `-i, --id <id>`)
* `status`: `Required. The new status to set (e.g., 'done', 'pending', 'in-progress', 'review', 'cancelled').` (CLI: `-s, --status <status>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Mark progress as tasks move through the development cycle.
### 12. Remove Task (`remove_task`)
@@ -207,9 +177,9 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master remove-task [options]`
* **Description:** `Permanently remove a task or subtask from the Taskmaster tasks list.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task, e.g., '5', or subtask, e.g., '5.2', to permanently remove.` (CLI: `-i, --id <id>`)
* `id`: `Required. The ID of the Taskmaster task (e.g., '5') or subtask (e.g., '5.2') to permanently remove.` (CLI: `-i, --id <id>`)
* `yes`: `Skip the confirmation prompt and immediately delete the task.` (CLI: `-y, --yes`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Permanently delete tasks or subtasks that are no longer needed in the project.
* **Notes:** Use with caution as this operation cannot be undone. Consider using 'blocked', 'cancelled', or 'deferred' status instead if you just want to exclude a task from active planning but keep it for reference. The command automatically cleans up dependency references in other tasks.
@@ -221,28 +191,28 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **MCP Tool:** `expand_task`
* **CLI Command:** `task-master expand [options]`
* **Description:** `Use Taskmaster's AI to break down a complex task into smaller, manageable subtasks. Appends subtasks by default.`
* **Description:** `Use Taskmaster's AI to break down a complex task (or all tasks) into smaller, manageable subtasks.`
* **Key Parameters/Options:**
* `id`: `The ID of the specific Taskmaster task you want to break down into subtasks.` (CLI: `-i, --id <id>`)
* `num`: `Optional: Suggests how many subtasks Taskmaster should aim to create. Uses complexity analysis/defaults otherwise.` (CLI: `-n, --num <number>`)
* `research`: `Enable Taskmaster to use the research role for more informed subtask generation. Requires appropriate API key.` (CLI: `-r, --research`)
* `prompt`: `Optional: Provide extra context or specific instructions to Taskmaster for generating the subtasks.` (CLI: `-p, --prompt <text>`)
* `force`: `Optional: If true, clear existing subtasks before generating new ones. Default is false (append).` (CLI: `--force`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Generate a detailed implementation plan for a complex task before starting coding. Automatically uses complexity report recommendations if available and `num` is not specified.
* `num`: `Suggests how many subtasks Taskmaster should aim to create (uses complexity analysis by default).` (CLI: `-n, --num <number>`)
* `research`: `Enable Taskmaster to use Perplexity AI for more informed subtask generation (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `prompt`: `Provide extra context or specific instructions to Taskmaster for generating the subtasks.` (CLI: `-p, --prompt <text>`)
* `force`: `Use this to make Taskmaster replace existing subtasks with newly generated ones.` (CLI: `--force`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Generate a detailed implementation plan for a complex task before starting coding.
* **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.
### 14. Expand All Tasks (`expand_all`)
* **MCP Tool:** `expand_all`
* **CLI Command:** `task-master expand --all [options]` (Note: CLI uses the `expand` command with the `--all` flag)
* **Description:** `Tell Taskmaster to automatically expand all eligible pending/in-progress tasks based on complexity analysis or defaults. Appends subtasks by default.`
* **Description:** `Tell Taskmaster to automatically expand all 'pending' tasks based on complexity analysis.`
* **Key Parameters/Options:**
* `num`: `Optional: Suggests how many subtasks Taskmaster should aim to create per task.` (CLI: `-n, --num <number>`)
* `research`: `Enable research role for more informed subtask generation. Requires appropriate API key.` (CLI: `-r, --research`)
* `prompt`: `Optional: Provide extra context for Taskmaster to apply generally during expansion.` (CLI: `-p, --prompt <text>`)
* `force`: `Optional: If true, clear existing subtasks before generating new ones for each eligible task. Default is false (append).` (CLI: `--force`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `num`: `Suggests how many subtasks Taskmaster should aim to create per task.` (CLI: `-n, --num <number>`)
* `research`: `Enable Perplexity AI for more informed subtask generation (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `prompt`: `Provide extra context for Taskmaster to apply generally during expansion.` (CLI: `-p, --prompt <text>`)
* `force`: `Make Taskmaster replace existing subtasks.` (CLI: `--force`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Useful after initial task generation or complexity analysis to break down multiple tasks at once.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
@@ -252,9 +222,9 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master clear-subtasks [options]`
* **Description:** `Remove all subtasks from one or more specified Taskmaster parent tasks.`
* **Key Parameters/Options:**
* `id`: `The ID(s) of the Taskmaster parent task(s) whose subtasks you want to remove, e.g., '15' or '16,18'. Required unless using `all`.) (CLI: `-i, --id <ids>`)
* `id`: `The ID(s) of the Taskmaster parent task(s) whose subtasks you want to remove (e.g., '15', '16,18').` (Required unless using `all`) (CLI: `-i, --id <ids>`)
* `all`: `Tell Taskmaster to remove subtasks from all parent tasks.` (CLI: `--all`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Used before regenerating subtasks with `expand_task` if the previous breakdown needs replacement.
### 16. Remove Subtask (`remove_subtask`)
@@ -263,53 +233,28 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **CLI Command:** `task-master remove-subtask [options]`
* **Description:** `Remove a subtask from its Taskmaster parent, optionally converting it into a standalone task.`
* **Key Parameters/Options:**
* `id`: `Required. The ID(s) of the Taskmaster subtask(s) to remove, e.g., '15.2' or '16.1,16.3'.` (CLI: `-i, --id <id>`)
* `id`: `Required. The ID(s) of the Taskmaster subtask(s) to remove (e.g., '15.2', '16.1,16.3').` (CLI: `-i, --id <id>`)
* `convert`: `If used, Taskmaster will turn the subtask into a regular top-level task instead of deleting it.` (CLI: `-c, --convert`)
* `skipGenerate`: `Prevent Taskmaster from automatically regenerating markdown task files after removing the subtask.` (CLI: `--skip-generate`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `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
### 18. Add Dependency (`add_dependency`)
### 17. Add Dependency (`add_dependency`)
* **MCP Tool:** `add_dependency`
* **CLI Command:** `task-master add-dependency [options]`
* **Description:** `Define a dependency in Taskmaster, making one task a prerequisite for another.`
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task that will depend on another.` (CLI: `-i, --id <id>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that must be completed first, the prerequisite.` (CLI: `-d, --depends-on <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that must be completed first (the prerequisite).` (CLI: `-d, --depends-on <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Establish the correct order of execution between tasks.
### 19. Remove Dependency (`remove_dependency`)
### 18. Remove Dependency (`remove_dependency`)
* **MCP Tool:** `remove_dependency`
* **CLI Command:** `task-master remove-dependency [options]`
@@ -317,91 +262,92 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Key Parameters/Options:**
* `id`: `Required. The ID of the Taskmaster task you want to remove a prerequisite from.` (CLI: `-i, --id <id>`)
* `dependsOn`: `Required. The ID of the Taskmaster task that should no longer be a prerequisite.` (CLI: `-d, --depends-on <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `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.
### 20. Validate Dependencies (`validate_dependencies`)
### 19. Validate Dependencies (`validate_dependencies`)
* **MCP Tool:** `validate_dependencies`
* **CLI Command:** `task-master validate-dependencies [options]`
* **Description:** `Check your Taskmaster tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `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.
### 21. Fix Dependencies (`fix_dependencies`)
### 20. Fix Dependencies (`fix_dependencies`)
* **MCP Tool:** `fix_dependencies`
* **CLI Command:** `task-master fix-dependencies [options]`
* **Description:** `Automatically fix dependency issues (like circular references or links to non-existent tasks) in your Taskmaster tasks.`
* **Key Parameters/Options:**
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Clean up dependency errors automatically.
---
## Analysis & Reporting
### 22. Analyze Project Complexity (`analyze_project_complexity`)
### 21. Analyze Project Complexity (`analyze_project_complexity`)
* **MCP Tool:** `analyze_project_complexity`
* **CLI Command:** `task-master analyze-complexity [options]`
* **Description:** `Have Taskmaster analyze your tasks to determine their complexity and suggest which ones need to be broken down further.`
* **Key Parameters/Options:**
* `output`: `Where to save the complexity analysis report (default: '.taskmaster/reports/task-complexity-report.json').` (CLI: `-o, --output <file>`)
* `output`: `Where to save the complexity analysis report (default: 'scripts/task-complexity-report.json').` (CLI: `-o, --output <file>`)
* `threshold`: `The minimum complexity score (1-10) that should trigger a recommendation to expand a task.` (CLI: `-t, --threshold <number>`)
* `research`: `Enable research role for more accurate complexity analysis. Requires appropriate API key.` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `research`: `Enable Perplexity AI for more accurate complexity analysis (requires PERPLEXITY_API_KEY).` (CLI: `-r, --research`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Used before breaking down tasks to identify which ones need the most attention.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 23. View Complexity Report (`complexity_report`)
### 22. View Complexity Report (`complexity_report`)
* **MCP Tool:** `complexity_report`
* **CLI Command:** `task-master complexity-report [options]`
* **Description:** `Display the task complexity analysis report in a readable format.`
* **Key Parameters/Options:**
* `file`: `Path to the complexity report (default: '.taskmaster/reports/task-complexity-report.json').` (CLI: `-f, --file <file>`)
* `file`: `Path to the complexity report (default: 'scripts/task-complexity-report.json').` (CLI: `-f, --file <file>`)
* **Usage:** Review and understand the complexity analysis results after running analyze-complexity.
---
## File Management
### 24. Generate Task Files (`generate`)
### 23. Generate Task Files (`generate`)
* **MCP Tool:** `generate`
* **CLI Command:** `task-master generate [options]`
* **Description:** `Create or update individual Markdown files for each task based on your tasks.json.`
* **Key Parameters/Options:**
* `output`: `The directory where Taskmaster should save the task files (default: in a 'tasks' directory).` (CLI: `-o, --output <directory>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* `file`: `Path to your Taskmaster 'tasks.json' file (default relies on auto-detection).` (CLI: `-f, --file <file>`)
* **Usage:** Run this after making changes to tasks.json to keep individual task files up to date.
---
## Environment Variables Configuration (Updated)
## Environment Variables Configuration
Taskmaster primarily uses the **`.taskmaster/config.json`** file (in project root) for configuration (models, parameters, logging level, etc.), managed via `task-master models --setup`.
Taskmaster's behavior can be customized via environment variables. These affect both CLI and MCP server operation:
Environment variables are used **only** for sensitive API keys related to AI providers and specific overrides like the Ollama base URL:
* **ANTHROPIC_API_KEY** (Required): Your Anthropic API key for Claude.
* **MODEL**: Claude model to use (default: `claude-3-opus-20240229`).
* **MAX_TOKENS**: Maximum tokens for AI responses (default: 8192).
* **TEMPERATURE**: Temperature for AI model responses (default: 0.7).
* **DEBUG**: Enable debug logging (`true`/`false`, default: `false`).
* **LOG_LEVEL**: Console output level (`debug`, `info`, `warn`, `error`, default: `info`).
* **DEFAULT_SUBTASKS**: Default number of subtasks for `expand` (default: 5).
* **DEFAULT_PRIORITY**: Default priority for new tasks (default: `medium`).
* **PROJECT_NAME**: Project name used in metadata.
* **PROJECT_VERSION**: Project version used in metadata.
* **PERPLEXITY_API_KEY**: API key for Perplexity AI (for `--research` flags).
* **PERPLEXITY_MODEL**: Perplexity model to use (default: `sonar-medium-online`).
* **API Keys (Required for corresponding provider):**
* `ANTHROPIC_API_KEY`
* `PERPLEXITY_API_KEY`
* `OPENAI_API_KEY`
* `GOOGLE_API_KEY`
* `MISTRAL_API_KEY`
* `AZURE_OPENAI_API_KEY` (Requires `AZURE_OPENAI_ENDPOINT` too)
* `OPENROUTER_API_KEY`
* `XAI_API_KEY`
* `OLLAMA_API_KEY` (Requires `OLLAMA_BASE_URL` too)
* **Endpoints (Optional/Provider Specific inside .taskmaster/config.json):**
* `AZURE_OPENAI_ENDPOINT`
* `OLLAMA_BASE_URL` (Default: `http://localhost:11434/api`)
**Set API keys** in your **`.env`** file in the project root (for CLI use) or within the `env` section of your **`.cursor/mcp.json`** file (for MCP/Cursor integration). All other settings (model choice, max tokens, temperature, log level, custom endpoints) are managed in `.taskmaster/config.json` via `task-master models` command or `models` MCP tool.
Set these in your `.env` file in the project root or in your environment before running Taskmaster.
---
For details on how these commands fit into the development process, see the [Development Workflow Guide](mdc:.cursor/rules/dev_workflow.mdc).
For implementation details:
* CLI commands: See [`commands.mdc`](mdc:.cursor/rules/commands.mdc)
* MCP server: See [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)
* Task structure: See [`tasks.mdc`](mdc:.cursor/rules/tasks.mdc)
* Workflow: See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc)

View File

@@ -1,228 +0,0 @@
---
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

@@ -283,97 +283,107 @@ When testing ES modules (`"type": "module"` in package.json), traditional mockin
- Imported functions may not use your mocked dependencies even with proper jest.mock() setup
- ES module exports are read-only properties (cannot be reassigned during tests)
- **Mocking Modules Statically Imported**
- For modules imported with standard `import` statements at the top level:
- Use `jest.mock('path/to/module', factory)` **before** any imports.
- Jest hoists these mocks.
- Ensure the factory function returns the mocked structure correctly.
- **Mocking Dependencies for Dynamically Imported Modules**
- **Problem**: Standard `jest.mock()` often fails for dependencies of modules loaded later using dynamic `import('path/to/module')`. The mocks aren't applied correctly when the dynamic import resolves.
- **Solution**: Use `jest.unstable_mockModule(modulePath, factory)` **before** the dynamic `import()` call.
- **Mocking Entire Modules**
```javascript
// 1. Define mock function instances
const mockExistsSync = jest.fn();
const mockReadFileSync = jest.fn();
// ... other mocks
// 2. Mock the dependency module *before* the dynamic import
jest.unstable_mockModule('fs', () => ({
__esModule: true, // Important for ES module mocks
// Mock named exports
existsSync: mockExistsSync,
readFileSync: mockReadFileSync,
// Mock default export if necessary
// default: { ... }
}));
// 3. Dynamically import the module under test (e.g., in beforeAll or test case)
let moduleUnderTest;
beforeAll(async () => {
// Ensure mocks are reset if needed before import
mockExistsSync.mockReset();
mockReadFileSync.mockReset();
// ... reset other mocks ...
// Import *after* unstable_mockModule is called
moduleUnderTest = await import('../../scripts/modules/module-using-fs.js');
// Mock the entire module with custom implementation
jest.mock('../../scripts/modules/task-manager.js', () => {
// Get original implementation for functions you want to preserve
const originalModule = jest.requireActual('../../scripts/modules/task-manager.js');
// Return mix of original and mocked functionality
return {
...originalModule,
generateTaskFiles: jest.fn() // Replace specific functions
};
});
// 4. Now tests can use moduleUnderTest, and its 'fs' calls will hit the mocks
test('should use mocked fs.readFileSync', () => {
mockReadFileSync.mockReturnValue('mock data');
moduleUnderTest.readFileAndProcess();
expect(mockReadFileSync).toHaveBeenCalled();
// ... other assertions
});
```
- ✅ **DO**: Call `jest.unstable_mockModule()` before `await import()`.
- ✅ **DO**: Include `__esModule: true` in the mock factory for ES modules.
- ✅ **DO**: Mock named and default exports as needed within the factory.
- ✅ **DO**: Reset mock functions (`mockFn.mockReset()`) before the dynamic import if they might have been called previously.
- **Mocking Entire Modules (Static Import)**
```javascript
// Mock the entire module with custom implementation for static imports
// ... (existing example remains valid) ...
// Import after mocks
import * as taskManager from '../../scripts/modules/task-manager.js';
// Now you can use the mock directly
const { generateTaskFiles } = taskManager;
```
- **Direct Implementation Testing**
- Instead of calling the actual function which may have module-scope reference issues:
```javascript
// ... (existing example remains valid) ...
test('should perform expected actions', () => {
// Setup mocks for this specific test
mockReadJSON.mockImplementationOnce(() => sampleData);
// Manually simulate the function's behavior
const data = mockReadJSON('path/file.json');
mockValidateAndFixDependencies(data, 'path/file.json');
// Skip calling the actual function and verify mocks directly
expect(mockReadJSON).toHaveBeenCalledWith('path/file.json');
expect(mockValidateAndFixDependencies).toHaveBeenCalledWith(data, 'path/file.json');
});
```
- **Avoiding Module Property Assignment**
```javascript
// ... (existing example remains valid) ...
// ❌ DON'T: This causes "Cannot assign to read only property" errors
const utils = await import('../../scripts/modules/utils.js');
utils.readJSON = mockReadJSON; // Error: read-only property
// ✅ DO: Use the module factory pattern in jest.mock()
jest.mock('../../scripts/modules/utils.js', () => ({
readJSON: mockReadJSONFunc,
writeJSON: mockWriteJSONFunc
}));
```
- **Handling Mock Verification Failures**
- If verification like `expect(mockFn).toHaveBeenCalled()` fails:
1. Check that your mock setup (`jest.mock` or `jest.unstable_mockModule`) is correctly placed **before** imports (static or dynamic).
2. Ensure you're using the right mock instance and it's properly passed to the module.
3. Verify your test invokes behavior that *should* call the mock.
4. Use `jest.clearAllMocks()` or specific `mockFn.mockReset()` in `beforeEach` to prevent state leakage between tests.
5. **Check Console Assertions**: If verifying `console.log`, `console.warn`, or `console.error` calls, ensure your assertion matches the *actual* arguments passed. If the code logs a single formatted string, assert against that single string (using `expect.stringContaining` or exact match), not multiple `expect.stringContaining` arguments.
```javascript
// Example: Code logs console.error(`Error: ${message}. Details: ${details}`)
// ❌ DON'T: Assert multiple arguments if only one is logged
// expect(console.error).toHaveBeenCalledWith(
// expect.stringContaining('Error:'),
// expect.stringContaining('Details:')
// );
// ✅ DO: Assert the single string argument
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Error: Specific message. Details: More details')
);
// or for exact match:
expect(console.error).toHaveBeenCalledWith(
'Error: Specific message. Details: More details'
);
```
6. Consider implementing a simpler test that *only* verifies the mock behavior in isolation.
1. Check that your mock setup is before imports
2. Ensure you're using the right mock instance
3. Verify your test invokes behavior that would call the mock
4. Use `jest.clearAllMocks()` in beforeEach to reset mock state
5. Consider implementing a simpler test that directly verifies mock behavior
- **Full Example Pattern**
```javascript
// 1. Define mock implementations
const mockReadJSON = jest.fn();
const mockValidateAndFixDependencies = jest.fn();
// 2. Mock modules
jest.mock('../../scripts/modules/utils.js', () => ({
readJSON: mockReadJSON,
// Include other functions as needed
}));
jest.mock('../../scripts/modules/dependency-manager.js', () => ({
validateAndFixDependencies: mockValidateAndFixDependencies
}));
// 3. Import after mocks
import * as taskManager from '../../scripts/modules/task-manager.js';
describe('generateTaskFiles function', () => {
beforeEach(() => {
jest.clearAllMocks();
});
test('should generate task files', () => {
// 4. Setup test-specific mock behavior
const sampleData = { tasks: [{ id: 1, title: 'Test' }] };
mockReadJSON.mockReturnValueOnce(sampleData);
// 5. Create direct implementation test
// Instead of calling: taskManager.generateTaskFiles('path', 'dir')
// Simulate reading data
const data = mockReadJSON('path');
expect(mockReadJSON).toHaveBeenCalledWith('path');
// Simulate other operations the function would perform
mockValidateAndFixDependencies(data, 'path');
expect(mockValidateAndFixDependencies).toHaveBeenCalledWith(data, 'path');
});
});
```
## Mocking Guidelines

View File

@@ -3,6 +3,7 @@ description: Guidelines for implementing utility functions
globs: scripts/modules/utils.js, mcp-server/src/**/*
alwaysApply: false
---
# Utility Function Guidelines
## General Principles
@@ -78,30 +79,28 @@ alwaysApply: false
}
```
## Configuration Management (via `config-manager.js`)
## Configuration Management (in `scripts/modules/utils.js`)
Taskmaster configuration (excluding API keys) is primarily managed through the `.taskmasterconfig` file located in the project root and accessed via getters in [`scripts/modules/config-manager.js`](mdc:scripts/modules/config-manager.js).
- **Environment Variables**:
- ✅ DO: Provide default values for all configuration
- ✅ DO: Use environment variables for customization
- ✅ DO: Document available configuration options
- ❌ DON'T: Hardcode values that should be configurable
- **`.taskmasterconfig` File**:
- ✅ DO: Use this JSON file to store settings like AI model selections (main, research, fallback), parameters (temperature, maxTokens), logging level, default priority/subtasks, etc.
- ✅ DO: Manage this file using the `task-master models --setup` CLI command or the `models` MCP tool.
- ✅ DO: Rely on [`config-manager.js`](mdc:scripts/modules/config-manager.js) to load this file (using the correct project root passed from MCP or found via CLI utils), merge with defaults, and provide validated settings.
- ❌ DON'T: Store API keys in this file.
- ❌ DON'T: Manually edit this file unless necessary.
- **Configuration Getters (`config-manager.js`)**:
- ✅ DO: Import and use specific getters from `config-manager.js` (e.g., `getMainProvider()`, `getLogLevel()`, `getMainMaxTokens()`) to access configuration values *needed for application logic* (like `getDefaultSubtasks`).
- ✅ DO: Pass the `explicitRoot` parameter to getters if calling from MCP direct functions to ensure the correct project's config is loaded.
- ❌ DON'T: Call AI-specific getters (like `getMainModelId`, `getMainMaxTokens`) from core logic functions (`scripts/modules/task-manager/*`). Instead, pass the `role` to the unified AI service.
- ❌ DON'T: Access configuration values directly from environment variables (except API keys).
- **API Key Handling (`utils.js` & `ai-services-unified.js`)**:
- ✅ DO: Store API keys **only** in `.env` (for CLI, loaded by `dotenv` in `scripts/dev.js`) or `.cursor/mcp.json` (for MCP, accessed via `session.env`).
- ✅ DO: Use `isApiKeySet(providerName, session)` from `config-manager.js` to check if a provider's key is available *before* potentially attempting an AI call if needed, but note the unified service performs its own internal check.
- ✅ DO: Understand that the unified service layer (`ai-services-unified.js`) internally resolves API keys using `resolveEnvVariable(key, session)` from `utils.js`.
- **Error Handling**:
- ✅ DO: Handle potential `ConfigurationError` if the `.taskmasterconfig` file is missing or invalid when accessed via `getConfig` (e.g., in `commands.js` or direct functions).
```javascript
// ✅ DO: Set up configuration with defaults and environment overrides
const CONFIG = {
model: process.env.MODEL || 'claude-3-opus-20240229', // Updated default model
maxTokens: parseInt(process.env.MAX_TOKENS || '4000'),
temperature: parseFloat(process.env.TEMPERATURE || '0.7'),
debug: process.env.DEBUG === "true",
logLevel: process.env.LOG_LEVEL || "info",
defaultSubtasks: parseInt(process.env.DEFAULT_SUBTASKS || "3"),
defaultPriority: process.env.DEFAULT_PRIORITY || "medium",
projectName: process.env.PROJECT_NAME || "Task Master Project", // Generic project name
projectVersion: "1.5.0" // Version should be updated via release process
};
```
## Logging Utilities (in `scripts/modules/utils.js`)
@@ -428,69 +427,36 @@ Taskmaster configuration (excluding API keys) is primarily managed through the `
## MCP Server Tool Utilities (`mcp-server/src/tools/utils.js`)
These utilities specifically support the implementation and execution of MCP tools.
- **Purpose**: These utilities specifically support the MCP server tools ([`mcp-server/src/tools/*.js`](mdc:mcp-server/src/tools/*.js)), handling MCP communication patterns, response formatting, caching integration, and the CLI fallback mechanism.
- **Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)** for detailed usage patterns within the MCP tool `execute` methods and direct function wrappers.
- **`normalizeProjectRoot(rawPath, log)`**:
- **Purpose**: Takes a raw project root path (potentially URI encoded, with `file://` prefix, Windows slashes) and returns a normalized, absolute path suitable for the server's OS.
- **Logic**: Decodes URI, strips `file://`, handles Windows drive prefix (`/C:/`), replaces `\` with `/`, uses `path.resolve()`.
- **Usage**: Used internally by `withNormalizedProjectRoot` HOF.
- **`getRawProjectRootFromSession(session, log)`**:
- **Purpose**: Extracts the *raw* project root URI string from the session object (`session.roots[0].uri` or `session.roots.roots[0].uri`) without performing normalization.
- **Usage**: Used internally by `withNormalizedProjectRoot` HOF as a fallback if `args.projectRoot` isn't provided.
- **`withNormalizedProjectRoot(executeFn)`**:
- **Purpose**: A Higher-Order Function (HOF) designed to wrap a tool's `execute` method.
- **Logic**:
1. Determines the raw project root (from `args.projectRoot` or `getRawProjectRootFromSession`).
2. Normalizes the raw path using `normalizeProjectRoot`.
3. Injects the normalized, absolute path back into the `args` object as `args.projectRoot`.
4. Calls the original `executeFn` with the updated `args`.
- **Usage**: Should wrap the `execute` function of *every* MCP tool that needs a reliable, normalized project root path.
- **Example**:
```javascript
// In mcp-server/src/tools/your-tool.js
import { withNormalizedProjectRoot } from './utils.js';
export function registerYourTool(server) {
server.addTool({
// ... name, description, parameters ...
execute: withNormalizedProjectRoot(async (args, context) => {
// args.projectRoot is now normalized here
const { projectRoot /*, other args */ } = args;
// ... rest of tool logic using normalized projectRoot ...
})
});
}
```
- **`getProjectRootFromSession(session, log)`**:
- ✅ **DO**: Call this utility **within the MCP tool's `execute` method** to extract the project root path from the `session` object.
- Decodes the `file://` URI and handles potential errors.
- Returns the project path string or `null`.
- The returned path should then be passed in the `args` object when calling the corresponding `*Direct` function (e.g., `yourDirectFunction({ ...args, projectRoot: rootFolder }, log)`).
- **`handleApiResult(result, log, errorPrefix, processFunction)`**:
- **Purpose**: Standardizes the formatting of responses returned by direct functions (`{ success, data/error, fromCache }`) into the MCP response format.
- **Usage**: Call this at the end of the tool's `execute` method, passing the result from the direct function call.
- ✅ **DO**: Call this from the MCP tool's `execute` method after receiving the result from the `*Direct` function wrapper.
- Takes the standard `{ success, data/error, fromCache }` object.
- Formats the standard MCP success or error response, including the `fromCache` flag.
- Uses `processMCPResponseData` by default to filter response data.
- **`createContentResponse(content)` / `createErrorResponse(errorMessage)`**:
- **Purpose**: Helper functions to create the basic MCP response structure for success or error messages.
- **Usage**: Used internally by `handleApiResult` and potentially directly for simple responses.
- **`createLogWrapper(log)`**:
- **Purpose**: Creates a logger object wrapper with standard methods (`info`, `warn`, `error`, `debug`, `success`) mapping to the passed MCP `log` object's methods. Ensures compatibility when passing loggers to core functions.
- **Usage**: Used within direct functions before passing the `log` object down to core logic that expects the standard method names.
- **`getCachedOrExecute({ cacheKey, actionFn, log })`**:
- **Purpose**: Utility for implementing caching within direct functions. Checks cache for `cacheKey`; if miss, executes `actionFn`, caches successful result, and returns.
- **Usage**: Wrap the core logic execution within a direct function call.
- **`executeTaskMasterCommand(command, log, args, projectRootRaw)`**:
- Executes a Task Master CLI command as a child process.
- Handles fallback between global `task-master` and local `node scripts/dev.js`.
- ❌ **DON'T**: Use this as the primary method for MCP tools. Prefer direct function calls via `*Direct` wrappers.
- **`processMCPResponseData(taskOrData, fieldsToRemove)`**:
- **Purpose**: Utility to filter potentially sensitive or large fields (like `details`, `testStrategy`) from task objects before sending the response back via MCP.
- **Usage**: Passed as the default `processFunction` to `handleApiResult`.
- Filters task data (e.g., removing `details`, `testStrategy`) before sending to the MCP client. Called by `handleApiResult`.
- **`getProjectRootFromSession(session, log)`**:
- **Purpose**: Legacy function to extract *and normalize* the project root from the session. Replaced by the HOF pattern but potentially still used.
- **Recommendation**: Prefer using the `withNormalizedProjectRoot` HOF in tools instead of calling this directly.
- **`createContentResponse(content)` / `createErrorResponse(errorMessage)`**:
- Formatters for standard MCP success/error responses.
- **`executeTaskMasterCommand(...)`**:
- **Purpose**: Executes `task-master` CLI command as a fallback.
- **Recommendation**: Deprecated for most uses; prefer direct function calls.
- **`getCachedOrExecute({ cacheKey, actionFn, log })`**:
- ✅ **DO**: Use this utility *inside direct function wrappers* to implement caching.
- Checks cache, executes `actionFn` on miss, stores result.
- Returns standard `{ success, data/error, fromCache: boolean }`.
## Export Organization

View File

@@ -1,15 +1,20 @@
# API Keys (Required for using in any role i.e. main/research/fallback -- see `task-master models`)
ANTHROPIC_API_KEY=YOUR_ANTHROPIC_KEY_HERE
PERPLEXITY_API_KEY=YOUR_PERPLEXITY_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
# API Keys (Required)
ANTHROPIC_API_KEY=your_anthropic_api_key_here # Format: sk-ant-api03-...
PERPLEXITY_API_KEY=your_perplexity_api_key_here # Format: pplx-...
# 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
# Model Configuration
MODEL=claude-3-7-sonnet-20250219 # Recommended models: claude-3-7-sonnet-20250219, claude-3-opus-20240229
PERPLEXITY_MODEL=sonar-pro # Perplexity model for research-backed subtasks
MAX_TOKENS=64000 # Maximum tokens for model responses
TEMPERATURE=0.2 # Temperature for model responses (0.0-1.0)
# Logging Configuration
DEBUG=false # Enable debug logging (true/false)
LOG_LEVEL=info # Log level (debug, info, warn, error)
# Task Generation Settings
DEFAULT_SUBTASKS=5 # Default number of subtasks when expanding
DEFAULT_PRIORITY=medium # Default priority for generated tasks (high, medium, low)
# Project Metadata (Optional)
PROJECT_NAME=Your Project Name # Override default project name in tasks.json

View File

@@ -1,62 +0,0 @@
name: Pre-Release (RC)
on:
workflow_dispatch: # Allows manual triggering from GitHub UI/API
concurrency: pre-release-${{ github.ref }}
jobs:
rc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Cache node_modules
uses: actions/cache@v4
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install dependencies
run: npm ci
timeout-minutes: 2
- name: Enter RC mode
run: |
npx changeset pre exit || true
npx changeset pre enter rc
- name: Version RC packages
run: npx changeset version
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create Release Candidate Pull Request or Publish Release Candidate to npm
uses: changesets/action@v1
with:
publish: npm run release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Exit RC mode
run: npx changeset pre exit
- name: Commit & Push changes
uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref }}
message: 'chore: rc version bump'

View File

@@ -3,9 +3,6 @@ on:
push:
branches:
- main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
release:
runs-on: ubuntu-latest
@@ -33,9 +30,6 @@ jobs:
run: npm ci
timeout-minutes: 2
- name: Exit pre-release mode (safety check)
run: npx changeset pre exit || true
- name: Create Release Pull Request or Publish to npm
uses: changesets/action@v1
with:

View File

@@ -1,40 +0,0 @@
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'

7
.gitignore vendored
View File

@@ -19,8 +19,6 @@ 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
@@ -60,7 +58,4 @@ dist
# Debug files
*.debug
init-debug.log
dev-debug.log
# NPMRC
.npmrc
dev-debug.log

1
.nvmrc
View File

@@ -1 +0,0 @@
22

7
.prettierignore Normal file
View File

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

11
.prettierrc Normal file
View File

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

View File

@@ -1,33 +0,0 @@
{
"models": {
"main": {
"provider": "anthropic",
"modelId": "claude-sonnet-4-20250514",
"maxTokens": 50000,
"temperature": 0.2
},
"research": {
"provider": "perplexity",
"modelId": "sonar-pro",
"maxTokens": 8700,
"temperature": 0.1
},
"fallback": {
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 128000,
"temperature": 0.2
}
},
"global": {
"userId": "1234567890",
"logLevel": "info",
"debug": false,
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Taskmaster",
"ollamaBaseURL": "http://localhost:11434/api",
"bedrockBaseURL": "https://bedrock.us-east-1.amazonaws.com",
"azureBaseURL": "https://your-endpoint.azure.com/"
}
}

View File

@@ -1,528 +0,0 @@
# Claude Task Master - Product Requirements Document
<PRD>
# Technical Architecture
## System Components
1. **Task Management Core**
- Tasks.json file structure (single source of truth)
- Task model with dependencies, priorities, and metadata
- Task state management system
- Task file generation subsystem
2. **AI Integration Layer**
- Anthropic Claude API integration
- Perplexity API integration (optional)
- Prompt engineering components
- Response parsing and processing
3. **Command Line Interface**
- Command parsing and execution
- Interactive user input handling
- Display and formatting utilities
- Status reporting and feedback system
4. **Cursor AI Integration**
- Cursor rules documentation
- Agent interaction patterns
- Workflow guideline specifications
## Data Models
### Task Model
```json
{
"id": 1,
"title": "Task Title",
"description": "Brief task description",
"status": "pending|done|deferred",
"dependencies": [0],
"priority": "high|medium|low",
"details": "Detailed implementation instructions",
"testStrategy": "Verification approach details",
"subtasks": [
{
"id": 1,
"title": "Subtask Title",
"description": "Subtask description",
"status": "pending|done|deferred",
"dependencies": [],
"acceptanceCriteria": "Verification criteria"
}
]
}
```
### Tasks Collection Model
```json
{
"meta": {
"projectName": "Project Name",
"version": "1.0.0",
"prdSource": "path/to/prd.txt",
"createdAt": "ISO-8601 timestamp",
"updatedAt": "ISO-8601 timestamp"
},
"tasks": [
// Array of Task objects
]
}
```
### Task File Format
```
# Task ID: <id>
# Title: <title>
# Status: <status>
# Dependencies: <comma-separated list of dependency IDs>
# Priority: <priority>
# Description: <brief description>
# Details:
<detailed implementation notes>
# Test Strategy:
<verification approach>
# Subtasks:
1. <subtask title> - <subtask description>
```
## APIs and Integrations
1. **Anthropic Claude API**
- Authentication via API key
- Prompt construction and streaming
- Response parsing and extraction
- Error handling and retries
2. **Perplexity API (via OpenAI client)**
- Authentication via API key
- Research-oriented prompt construction
- Enhanced contextual response handling
- Fallback mechanisms to Claude
3. **File System API**
- Reading/writing tasks.json
- Managing individual task files
- Command execution logging
- Debug logging system
## Infrastructure Requirements
1. **Node.js Runtime**
- Version 14.0.0 or higher
- ES Module support
- File system access rights
- Command execution capabilities
2. **Configuration Management**
- Environment variable handling
- .env file support
- Configuration validation
- Sensible defaults with overrides
3. **Development Environment**
- Git repository
- NPM package management
- Cursor editor integration
- Command-line terminal access
# Development Roadmap
## Phase 1: Core Task Management System
1. **Task Data Structure**
- Design and implement the tasks.json structure
- Create task model validation
- Implement basic task operations (create, read, update)
- Develop file system interactions
2. **Command Line Interface Foundation**
- Implement command parsing with Commander.js
- Create help documentation
- Implement colorized console output
- Add logging system with configurable levels
3. **Basic Task Operations**
- Implement task listing functionality
- Create task status update capability
- Add dependency tracking
- Implement priority management
4. **Task File Generation**
- Create task file templates
- Implement generation from tasks.json
- Add bi-directional synchronization
- Implement proper file naming and organization
## Phase 2: AI Integration
1. **Claude API Integration**
- Implement API authentication
- Create prompt templates for PRD parsing
- Design response handlers
- Add error management and retries
2. **PRD Parsing System**
- Implement PRD file reading
- Create PRD to task conversion logic
- Add intelligent dependency inference
- Implement priority assignment logic
3. **Task Expansion With Claude**
- Create subtask generation prompts
- Implement subtask creation workflow
- Add context-aware expansion capabilities
- Implement parent-child relationship management
4. **Implementation Drift Handling**
- Add capability to update future tasks
- Implement task rewriting based on new context
- Create dependency chain updates
- Preserve completed work while updating future tasks
## Phase 3: Advanced Features
1. **Perplexity Integration**
- Implement Perplexity API authentication
- Create research-oriented prompts
- Add fallback to Claude when unavailable
- Implement response quality comparison logic
2. **Research-Backed Subtask Generation**
- Create specialized research prompts
- Implement context enrichment
- Add domain-specific knowledge incorporation
- Create more detailed subtask generation
3. **Batch Operations**
- Implement multi-task status updates
- Add bulk subtask generation
- Create task filtering and querying
- Implement advanced dependency management
4. **Project Initialization**
- Create project templating system
- Implement interactive setup
- Add environment configuration
- Create documentation generation
## Phase 4: Cursor AI Integration
1. **Cursor Rules Implementation**
- Create dev_workflow.mdc documentation
- Implement cursor_rules.mdc
- Add self_improve.mdc
- Design rule integration documentation
2. **Agent Workflow Guidelines**
- Document task discovery workflow
- Create task selection guidelines
- Implement implementation guidance
- Add verification procedures
3. **Agent Command Integration**
- Document command syntax for agents
- Create example interactions
- Implement agent response patterns
- Add context management for agents
4. **User Documentation**
- Create detailed README
- Add scripts documentation
- Implement example workflows
- Create troubleshooting guides
# Logical Dependency Chain
## Foundation Layer
1. **Task Data Structure**
- Must be implemented first as all other functionality depends on this
- Defines the core data model for the entire system
- Establishes the single source of truth concept
2. **Command Line Interface**
- Built on top of the task data structure
- Provides the primary user interaction mechanism
- Required for all subsequent operations to be accessible
3. **Basic Task Operations**
- Depends on both task data structure and CLI
- Provides the fundamental operations for task management
- Enables the minimal viable workflow
## Functional Layer
4. **Task File Generation**
- Depends on task data structure and basic operations
- Creates the individual task files for reference
- Enables the file-based workflow complementing tasks.json
5. **Claude API Integration**
- Independent of most previous components but needs the task data structure
- Provides the AI capabilities that enhance the system
- Gateway to advanced task generation features
6. **PRD Parsing System**
- Depends on Claude API integration and task data structure
- Enables the initial task generation workflow
- Creates the starting point for new projects
## Enhancement Layer
7. **Task Expansion With Claude**
- Depends on Claude API integration and basic task operations
- Enhances existing tasks with more detailed subtasks
- Improves the implementation guidance
8. **Implementation Drift Handling**
- Depends on Claude API integration and task operations
- Addresses a key challenge in AI-driven development
- Maintains the relevance of task planning as implementation evolves
9. **Perplexity Integration**
- Can be developed in parallel with other features after Claude integration
- Enhances the quality of generated content
- Provides research-backed improvements
## Advanced Layer
10. **Research-Backed Subtask Generation**
- Depends on Perplexity integration and task expansion
- Provides higher quality, more contextual subtasks
- Enhances the value of the task breakdown
11. **Batch Operations**
- Depends on basic task operations
- Improves efficiency for managing multiple tasks
- Quality-of-life enhancement for larger projects
12. **Project Initialization**
- Depends on most previous components being stable
- Provides a smooth onboarding experience
- Creates a complete project setup in one step
## Integration Layer
13. **Cursor Rules Implementation**
- Can be developed in parallel after basic functionality
- Provides the guidance for Cursor AI agent
- Enhances the AI-driven workflow
14. **Agent Workflow Guidelines**
- Depends on Cursor rules implementation
- Structures how the agent interacts with the system
- Ensures consistent agent behavior
15. **Agent Command Integration**
- Depends on agent workflow guidelines
- Provides specific command patterns for the agent
- Optimizes the agent-user interaction
16. **User Documentation**
- Should be developed alongside all features
- Must be completed before release
- Ensures users can effectively use the system
# Risks and Mitigations
## Technical Challenges
### API Reliability
**Risk**: Anthropic or Perplexity API could have downtime, rate limiting, or breaking changes.
**Mitigation**:
- Implement robust error handling with exponential backoff
- Add fallback mechanisms (Claude fallback for Perplexity)
- Cache important responses to reduce API dependency
- Support offline mode for critical functions
### Model Output Variability
**Risk**: AI models may produce inconsistent or unexpected outputs.
**Mitigation**:
- Design robust prompt templates with strict output formatting requirements
- Implement response validation and error detection
- Add self-correction mechanisms and retries with improved prompts
- Allow manual editing of generated content
### Node.js Version Compatibility
**Risk**: Differences in Node.js versions could cause unexpected behavior.
**Mitigation**:
- Clearly document minimum Node.js version requirements
- Use transpilers if needed for compatibility
- Test across multiple Node.js versions
- Handle version-specific features gracefully
## MVP Definition
### Feature Prioritization
**Risk**: Including too many features in the MVP could delay release and adoption.
**Mitigation**:
- Define MVP as core task management + basic Claude integration
- Ensure each phase delivers a complete, usable product
- Implement feature flags for easy enabling/disabling of features
- Get early user feedback to validate feature importance
### Scope Creep
**Risk**: The project could expand beyond its original intent, becoming too complex.
**Mitigation**:
- Maintain a strict definition of what the tool is and isn't
- Focus on task management for AI-driven development
- Evaluate new features against core value proposition
- Implement extensibility rather than building every feature
### User Expectations
**Risk**: Users might expect a full project management solution rather than a task tracking system.
**Mitigation**:
- Clearly communicate the tool's purpose and limitations
- Provide integration points with existing project management tools
- Focus on the unique value of AI-driven development
- Document specific use cases and example workflows
## Resource Constraints
### Development Capacity
**Risk**: Limited development resources could delay implementation.
**Mitigation**:
- Phase implementation to deliver value incrementally
- Focus on core functionality first
- Leverage open source libraries where possible
- Design for extensibility to allow community contributions
### AI Cost Management
**Risk**: Excessive API usage could lead to high costs.
**Mitigation**:
- Implement token usage tracking and reporting
- Add configurable limits to prevent unexpected costs
- Cache responses where appropriate
- Optimize prompts for token efficiency
- Support local LLM options in the future
### Documentation Overhead
**Risk**: Complexity of the system requires extensive documentation that is time-consuming to maintain.
**Mitigation**:
- Use AI to help generate and maintain documentation
- Create self-documenting commands and features
- Implement progressive documentation (basic to advanced)
- Build help directly into the CLI
# Appendix
## AI Prompt Engineering Specifications
### PRD Parsing Prompt Structure
```
You are assisting with transforming a Product Requirements Document (PRD) into a structured set of development tasks.
Given the following PRD, create a comprehensive list of development tasks that would be needed to implement the described product.
For each task:
1. Assign a short, descriptive title
2. Write a concise description
3. Identify dependencies (which tasks must be completed before this one)
4. Assign a priority (high, medium, low)
5. Include detailed implementation notes
6. Describe a test strategy to verify completion
Structure the tasks in a logical order of implementation.
PRD:
{prd_content}
```
### Task Expansion Prompt Structure
```
You are helping to break down a development task into more manageable subtasks.
Main task:
Title: {task_title}
Description: {task_description}
Details: {task_details}
Please create {num_subtasks} specific subtasks that together would accomplish this main task.
For each subtask, provide:
1. A clear, actionable title
2. A concise description
3. Any dependencies on other subtasks
4. Specific acceptance criteria to verify completion
Additional context:
{additional_context}
```
### Research-Backed Expansion Prompt Structure
```
You are a technical researcher and developer helping to break down a software development task into detailed, well-researched subtasks.
Main task:
Title: {task_title}
Description: {task_description}
Details: {task_details}
Research the latest best practices, technologies, and implementation patterns for this type of task. Then create {num_subtasks} specific, actionable subtasks that together would accomplish the main task.
For each subtask:
1. Provide a clear, specific title
2. Write a detailed description including technical approach
3. Identify dependencies on other subtasks
4. Include specific acceptance criteria
5. Reference any relevant libraries, tools, or resources that should be used
Consider security, performance, maintainability, and user experience in your recommendations.
```
## Task File System Specification
### Directory Structure
```
/
├── .cursor/
│ └── rules/
│ ├── dev_workflow.mdc
│ ├── cursor_rules.mdc
│ └── self_improve.mdc
├── scripts/
│ ├── dev.js
│ └── README.md
├── tasks/
│ ├── task_001.txt
│ ├── task_002.txt
│ └── ...
├── .env
├── .env.example
├── .gitignore
├── package.json
├── README.md
└── tasks.json
```
### Task ID Specification
- Main tasks: Sequential integers (1, 2, 3, ...)
- Subtasks: Parent ID + dot + sequential integer (1.1, 1.2, 2.1, ...)
- ID references: Used in dependencies, command parameters
- ID ordering: Implies suggested implementation order
## Command-Line Interface Specification
### Global Options
- `--help`: Display help information
- `--version`: Display version information
- `--file=<file>`: Specify an alternative tasks.json file
- `--quiet`: Reduce output verbosity
- `--debug`: Increase output verbosity
- `--json`: Output in JSON format (for programmatic use)
### Command Structure
- `node scripts/dev.js <command> [options]`
- All commands operate on tasks.json by default
- Commands follow consistent parameter naming
- Common parameter styles: `--id=<id>`, `--status=<status>`, `--prompt="<text>"`
- Boolean flags: `--all`, `--force`, `--with-subtasks`
## API Integration Specifications
### Anthropic API Configuration
- Authentication: ANTHROPIC_API_KEY environment variable
- Model selection: MODEL environment variable
- Default model: claude-3-7-sonnet-20250219
- Maximum tokens: MAX_TOKENS environment variable (default: 4000)
- Temperature: TEMPERATURE environment variable (default: 0.7)
### Perplexity API Configuration
- Authentication: PERPLEXITY_API_KEY environment variable
- Model selection: PERPLEXITY_MODEL environment variable
- Default model: sonar-medium-online
- Connection: Via OpenAI client
- Fallback: Use Claude if Perplexity unavailable
</PRD>

View File

@@ -1,357 +0,0 @@
{
"meta": {
"generatedAt": "2025-05-22T05:48:33.026Z",
"tasksAnalyzed": 6,
"totalTasks": 88,
"analysisCount": 43,
"thresholdScore": 5,
"projectName": "Taskmaster",
"usedResearch": true
},
"complexityAnalysis": [
{
"taskId": 24,
"taskTitle": "Implement AI-Powered Test Generation Command",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down the implementation of the AI-powered test generation command into detailed subtasks covering: command structure setup, AI prompt engineering, test file generation logic, integration with Claude API, and comprehensive error handling.",
"reasoning": "This task involves complex integration with an AI service (Claude), requires sophisticated prompt engineering, and needs to generate structured code files. The existing 3 subtasks are a good start but could be expanded to include more detailed steps for AI integration, error handling, and test file formatting."
},
{
"taskId": 26,
"taskTitle": "Implement Context Foundation for AI Operations",
"complexityScore": 6,
"recommendedSubtasks": 4,
"expansionPrompt": "The current 4 subtasks for implementing the context foundation appear comprehensive. Consider if any additional subtasks are needed for testing, documentation, or integration with existing systems.",
"reasoning": "This task involves creating a foundation for context integration with several well-defined components. The existing 4 subtasks cover the main implementation areas (context-file flag, cursor rules integration, context extraction utility, and command handler updates). The complexity is moderate as it requires careful integration with existing systems but has clear requirements."
},
{
"taskId": 27,
"taskTitle": "Implement Context Enhancements for AI Operations",
"complexityScore": 7,
"recommendedSubtasks": 4,
"expansionPrompt": "The current 4 subtasks for implementing context enhancements appear well-structured. Consider if any additional subtasks are needed for testing, documentation, or performance optimization.",
"reasoning": "This task builds upon the foundation from Task #26 and adds more sophisticated context handling features. The 4 existing subtasks cover the main implementation areas (code context extraction, task history context, PRD context integration, and context formatting). The complexity is higher than the foundation task due to the need for intelligent context selection and optimization."
},
{
"taskId": 28,
"taskTitle": "Implement Advanced ContextManager System",
"complexityScore": 8,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing the advanced ContextManager system appear comprehensive. Consider if any additional subtasks are needed for testing, documentation, or backward compatibility with previous context implementations.",
"reasoning": "This task represents the most complex phase of the context implementation, requiring a sophisticated class design, optimization algorithms, and integration with multiple systems. The 5 existing subtasks cover the core implementation areas, but the complexity is high due to the need for intelligent context prioritization, token management, and performance monitoring."
},
{
"taskId": 40,
"taskTitle": "Implement 'plan' Command for Task Implementation Planning",
"complexityScore": 5,
"recommendedSubtasks": 4,
"expansionPrompt": "The current 4 subtasks for implementing the 'plan' command appear well-structured. Consider if any additional subtasks are needed for testing, documentation, or integration with existing task management workflows.",
"reasoning": "This task involves creating a new command that leverages AI to generate implementation plans. The existing 4 subtasks cover the main implementation areas (retrieving task content, generating plans with AI, formatting in XML, and error handling). The complexity is moderate as it builds on existing patterns for task updates but requires careful AI integration."
},
{
"taskId": 41,
"taskTitle": "Implement Visual Task Dependency Graph in Terminal",
"complexityScore": 8,
"recommendedSubtasks": 10,
"expansionPrompt": "The current 10 subtasks for implementing the visual task dependency graph appear comprehensive. Consider if any additional subtasks are needed for performance optimization with large graphs or additional visualization options.",
"reasoning": "This task involves creating a sophisticated visualization system for terminal display, which is inherently complex due to layout algorithms, ASCII/Unicode rendering, and handling complex dependency relationships. The 10 existing subtasks cover all major aspects of implementation, from CLI interface to accessibility features."
},
{
"taskId": 42,
"taskTitle": "Implement MCP-to-MCP Communication Protocol",
"complexityScore": 9,
"recommendedSubtasks": 8,
"expansionPrompt": "The current 8 subtasks for implementing the MCP-to-MCP communication protocol appear well-structured. Consider if any additional subtasks are needed for security hardening, performance optimization, or comprehensive documentation.",
"reasoning": "This task involves designing and implementing a complex communication protocol between different MCP tools and servers. It requires sophisticated adapter patterns, client-server architecture, and handling of multiple operational modes. The complexity is very high due to the need for standardization, security, and backward compatibility."
},
{
"taskId": 44,
"taskTitle": "Implement Task Automation with Webhooks and Event Triggers",
"complexityScore": 8,
"recommendedSubtasks": 7,
"expansionPrompt": "The current 7 subtasks for implementing task automation with webhooks appear comprehensive. Consider if any additional subtasks are needed for security testing, rate limiting implementation, or webhook monitoring tools.",
"reasoning": "This task involves creating a sophisticated event system with webhooks for integration with external services. The complexity is high due to the need for secure authentication, reliable delivery mechanisms, and handling of various webhook formats and protocols. The existing subtasks cover the main implementation areas but security and monitoring could be emphasized more."
},
{
"taskId": 45,
"taskTitle": "Implement GitHub Issue Import Feature",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing the GitHub issue import feature appear well-structured. Consider if any additional subtasks are needed for handling GitHub API rate limiting, caching, or supporting additional issue metadata.",
"reasoning": "This task involves integrating with the GitHub API to import issues as tasks. The complexity is moderate as it requires API authentication, data mapping, and error handling. The existing 5 subtasks cover the main implementation areas from design to end-to-end implementation."
},
{
"taskId": 46,
"taskTitle": "Implement ICE Analysis Command for Task Prioritization",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing the ICE analysis command appear comprehensive. Consider if any additional subtasks are needed for visualization of ICE scores or integration with other prioritization methods.",
"reasoning": "This task involves creating an AI-powered analysis system for task prioritization using the ICE methodology. The complexity is high due to the need for sophisticated scoring algorithms, AI integration, and report generation. The existing subtasks cover the main implementation areas from algorithm design to integration with existing systems."
},
{
"taskId": 47,
"taskTitle": "Enhance Task Suggestion Actions Card Workflow",
"complexityScore": 6,
"recommendedSubtasks": 6,
"expansionPrompt": "The current 6 subtasks for enhancing the task suggestion actions card workflow appear well-structured. Consider if any additional subtasks are needed for user testing, accessibility improvements, or performance optimization.",
"reasoning": "This task involves redesigning the UI workflow for task expansion and management. The complexity is moderate as it requires careful UX design and state management but builds on existing components. The 6 existing subtasks cover the main implementation areas from design to testing."
},
{
"taskId": 48,
"taskTitle": "Refactor Prompts into Centralized Structure",
"complexityScore": 4,
"recommendedSubtasks": 3,
"expansionPrompt": "The current 3 subtasks for refactoring prompts into a centralized structure appear appropriate. Consider if any additional subtasks are needed for prompt versioning, documentation, or testing.",
"reasoning": "This task involves a straightforward refactoring to improve code organization. The complexity is relatively low as it primarily involves moving code rather than creating new functionality. The 3 existing subtasks cover the main implementation areas from directory structure to integration."
},
{
"taskId": 49,
"taskTitle": "Implement Code Quality Analysis Command",
"complexityScore": 8,
"recommendedSubtasks": 6,
"expansionPrompt": "The current 6 subtasks for implementing the code quality analysis command appear comprehensive. Consider if any additional subtasks are needed for performance optimization with large codebases or integration with existing code quality tools.",
"reasoning": "This task involves creating a sophisticated code analysis system with pattern recognition, best practice verification, and AI-powered recommendations. The complexity is high due to the need for code parsing, complex analysis algorithms, and integration with AI services. The existing subtasks cover the main implementation areas from algorithm design to user interface."
},
{
"taskId": 50,
"taskTitle": "Implement Test Coverage Tracking System by Task",
"complexityScore": 9,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing the test coverage tracking system appear well-structured. Consider if any additional subtasks are needed for integration with CI/CD systems, performance optimization, or visualization tools.",
"reasoning": "This task involves creating a complex system that maps test coverage to specific tasks and subtasks. The complexity is very high due to the need for sophisticated data structures, integration with coverage tools, and AI-powered test generation. The existing subtasks are comprehensive and cover the main implementation areas from data structure design to AI integration."
},
{
"taskId": 51,
"taskTitle": "Implement Perplexity Research Command",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing the Perplexity research command appear comprehensive. Consider if any additional subtasks are needed for caching optimization, result formatting, or integration with other research tools.",
"reasoning": "This task involves creating a new command that integrates with the Perplexity AI API for research. The complexity is moderate as it requires API integration, context extraction, and result formatting. The 5 existing subtasks cover the main implementation areas from API client to caching system."
},
{
"taskId": 52,
"taskTitle": "Implement Task Suggestion Command for CLI",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing the task suggestion command appear well-structured. Consider if any additional subtasks are needed for suggestion quality evaluation, user feedback collection, or integration with existing task workflows.",
"reasoning": "This task involves creating a new CLI command that generates contextually relevant task suggestions using AI. The complexity is moderate as it requires AI integration, context collection, and interactive CLI interfaces. The existing subtasks cover the main implementation areas from data collection to user interface."
},
{
"taskId": 53,
"taskTitle": "Implement Subtask Suggestion Feature for Parent Tasks",
"complexityScore": 6,
"recommendedSubtasks": 6,
"expansionPrompt": "The current 6 subtasks for implementing the subtask suggestion feature appear comprehensive. Consider if any additional subtasks are needed for suggestion quality metrics, user feedback collection, or performance optimization.",
"reasoning": "This task involves creating a feature that suggests contextually relevant subtasks for parent tasks. The complexity is moderate as it builds on existing task management systems but requires sophisticated AI integration and context analysis. The 6 existing subtasks cover the main implementation areas from validation to testing."
},
{
"taskId": 55,
"taskTitle": "Implement Positional Arguments Support for CLI Commands",
"complexityScore": 5,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing positional arguments support appear well-structured. Consider if any additional subtasks are needed for backward compatibility testing, documentation updates, or user experience improvements.",
"reasoning": "This task involves modifying the command parsing logic to support positional arguments alongside the existing flag-based syntax. The complexity is moderate as it requires careful handling of different argument styles and edge cases. The 5 existing subtasks cover the main implementation areas from analysis to documentation."
},
{
"taskId": 57,
"taskTitle": "Enhance Task-Master CLI User Experience and Interface",
"complexityScore": 7,
"recommendedSubtasks": 6,
"expansionPrompt": "The current 6 subtasks for enhancing the CLI user experience appear comprehensive. Consider if any additional subtasks are needed for accessibility testing, internationalization, or performance optimization.",
"reasoning": "This task involves a significant overhaul of the CLI interface to improve user experience. The complexity is high due to the breadth of changes (logging, visual elements, interactive components, etc.) and the need for consistent design across all commands. The 6 existing subtasks cover the main implementation areas from log management to help systems."
},
{
"taskId": 60,
"taskTitle": "Implement Mentor System with Round-Table Discussion Feature",
"complexityScore": 8,
"recommendedSubtasks": 7,
"expansionPrompt": "The current 7 subtasks for implementing the mentor system appear well-structured. Consider if any additional subtasks are needed for mentor personality consistency, discussion quality evaluation, or performance optimization with multiple mentors.",
"reasoning": "This task involves creating a sophisticated mentor simulation system with round-table discussions. The complexity is high due to the need for personality simulation, complex LLM integration, and structured discussion management. The 7 existing subtasks cover the main implementation areas from architecture to testing."
},
{
"taskId": 62,
"taskTitle": "Add --simple Flag to Update Commands for Direct Text Input",
"complexityScore": 4,
"recommendedSubtasks": 8,
"expansionPrompt": "The current 8 subtasks for implementing the --simple flag appear comprehensive. Consider if any additional subtasks are needed for user experience testing or documentation updates.",
"reasoning": "This task involves adding a simple flag option to bypass AI processing for updates. The complexity is relatively low as it primarily involves modifying existing command handlers and adding a flag. The 8 existing subtasks are very detailed and cover all aspects of implementation from command parsing to testing."
},
{
"taskId": 63,
"taskTitle": "Add pnpm Support for the Taskmaster Package",
"complexityScore": 5,
"recommendedSubtasks": 8,
"expansionPrompt": "The current 8 subtasks for adding pnpm support appear comprehensive. Consider if any additional subtasks are needed for CI/CD integration, performance comparison, or documentation updates.",
"reasoning": "This task involves ensuring the package works correctly with pnpm as an alternative package manager. The complexity is moderate as it requires careful testing of installation processes and scripts across different environments. The 8 existing subtasks cover all major aspects from documentation to binary verification."
},
{
"taskId": 64,
"taskTitle": "Add Yarn Support for Taskmaster Installation",
"complexityScore": 5,
"recommendedSubtasks": 9,
"expansionPrompt": "The current 9 subtasks for adding Yarn support appear comprehensive. Consider if any additional subtasks are needed for performance testing, CI/CD integration, or compatibility with different Yarn versions.",
"reasoning": "This task involves ensuring the package works correctly with Yarn as an alternative package manager. The complexity is moderate as it requires careful testing of installation processes and scripts across different environments. The 9 existing subtasks are very detailed and cover all aspects from configuration to testing."
},
{
"taskId": 65,
"taskTitle": "Add Bun Support for Taskmaster Installation",
"complexityScore": 6,
"recommendedSubtasks": 6,
"expansionPrompt": "The current 6 subtasks for adding Bun support appear well-structured. Consider if any additional subtasks are needed for handling Bun-specific issues, performance testing, or documentation updates.",
"reasoning": "This task involves adding support for the newer Bun package manager. The complexity is slightly higher than the other package manager tasks due to Bun's differences from Node.js and potential compatibility issues. The 6 existing subtasks cover the main implementation areas from research to documentation."
},
{
"taskId": 67,
"taskTitle": "Add CLI JSON output and Cursor keybindings integration",
"complexityScore": 5,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing JSON output and Cursor keybindings appear well-structured. Consider if any additional subtasks are needed for testing across different operating systems, documentation updates, or user experience improvements.",
"reasoning": "This task involves two distinct features: adding JSON output to CLI commands and creating a keybindings installation command. The complexity is moderate as it requires careful handling of different output formats and OS-specific file paths. The 5 existing subtasks cover the main implementation areas for both features."
},
{
"taskId": 68,
"taskTitle": "Ability to create tasks without parsing PRD",
"complexityScore": 3,
"recommendedSubtasks": 2,
"expansionPrompt": "The current 2 subtasks for implementing task creation without PRD appear appropriate. Consider if any additional subtasks are needed for validation, error handling, or integration with existing task management workflows.",
"reasoning": "This task involves a relatively simple modification to allow task creation without requiring a PRD document. The complexity is low as it primarily involves creating a form interface and saving functionality. The 2 existing subtasks cover the main implementation areas of UI design and data saving."
},
{
"taskId": 72,
"taskTitle": "Implement PDF Generation for Project Progress and Dependency Overview",
"complexityScore": 7,
"recommendedSubtasks": 6,
"expansionPrompt": "The current 6 subtasks for implementing PDF generation appear comprehensive. Consider if any additional subtasks are needed for handling large projects, additional visualization options, or integration with existing reporting tools.",
"reasoning": "This task involves creating a feature to generate PDF reports of project progress and dependency visualization. The complexity is high due to the need for PDF generation, data collection, and visualization integration. The 6 existing subtasks cover the main implementation areas from library selection to export options."
},
{
"taskId": 75,
"taskTitle": "Integrate Google Search Grounding for Research Role",
"complexityScore": 5,
"recommendedSubtasks": 4,
"expansionPrompt": "The current 4 subtasks for integrating Google Search Grounding appear well-structured. Consider if any additional subtasks are needed for testing with different query types, error handling, or performance optimization.",
"reasoning": "This task involves updating the AI service layer to enable Google Search Grounding for research roles. The complexity is moderate as it requires careful integration with the existing AI service architecture and conditional logic. The 4 existing subtasks cover the main implementation areas from service layer modification to testing."
},
{
"taskId": 76,
"taskTitle": "Develop E2E Test Framework for Taskmaster MCP Server (FastMCP over stdio)",
"complexityScore": 8,
"recommendedSubtasks": 7,
"expansionPrompt": "The current 7 subtasks for developing the E2E test framework appear comprehensive. Consider if any additional subtasks are needed for test result reporting, CI/CD integration, or performance benchmarking.",
"reasoning": "This task involves creating a sophisticated end-to-end testing framework for the MCP server. The complexity is high due to the need for subprocess management, protocol handling, and robust test case definition. The 7 existing subtasks cover the main implementation areas from architecture to documentation."
},
{
"taskId": 77,
"taskTitle": "Implement AI Usage Telemetry for Taskmaster (with external analytics endpoint)",
"complexityScore": 7,
"recommendedSubtasks": 18,
"expansionPrompt": "The current 18 subtasks for implementing AI usage telemetry appear very comprehensive. Consider if any additional subtasks are needed for security hardening, privacy compliance, or user feedback collection.",
"reasoning": "This task involves creating a telemetry system to track AI usage metrics. The complexity is high due to the need for secure data transmission, comprehensive data collection, and integration across multiple commands. The 18 existing subtasks are extremely detailed and cover all aspects of implementation from core utility to provider-specific updates."
},
{
"taskId": 80,
"taskTitle": "Implement Unique User ID Generation and Storage During Installation",
"complexityScore": 4,
"recommendedSubtasks": 5,
"expansionPrompt": "The current 5 subtasks for implementing unique user ID generation appear well-structured. Consider if any additional subtasks are needed for privacy compliance, security auditing, or integration with the telemetry system.",
"reasoning": "This task involves generating and storing a unique user identifier during installation. The complexity is relatively low as it primarily involves UUID generation and configuration file management. The 5 existing subtasks cover the main implementation areas from script structure to documentation."
},
{
"taskId": 81,
"taskTitle": "Task #81: Implement Comprehensive Local Telemetry System with Future Server Integration Capability",
"complexityScore": 8,
"recommendedSubtasks": 6,
"expansionPrompt": "The current 6 subtasks for implementing the comprehensive local telemetry system appear well-structured. Consider if any additional subtasks are needed for data migration, storage optimization, or visualization tools.",
"reasoning": "This task involves expanding the telemetry system to capture additional metrics and implement local storage with future server integration capability. The complexity is high due to the breadth of data collection, storage requirements, and privacy considerations. The 6 existing subtasks cover the main implementation areas from data collection to user-facing benefits."
},
{
"taskId": 82,
"taskTitle": "Update supported-models.json with token limit fields",
"complexityScore": 3,
"recommendedSubtasks": 1,
"expansionPrompt": "This task appears straightforward enough to be implemented without further subtasks. Focus on researching accurate token limit values for each model and ensuring backward compatibility.",
"reasoning": "This task involves a simple update to the supported-models.json file to include new token limit fields. The complexity is low as it primarily involves research and data entry. No subtasks are necessary as the task is well-defined and focused."
},
{
"taskId": 83,
"taskTitle": "Update config-manager.js defaults and getters",
"complexityScore": 4,
"recommendedSubtasks": 1,
"expansionPrompt": "This task appears straightforward enough to be implemented without further subtasks. Focus on updating the DEFAULTS object and related getter functions while maintaining backward compatibility.",
"reasoning": "This task involves updating the config-manager.js module to replace maxTokens with more specific token limit fields. The complexity is relatively low as it primarily involves modifying existing code rather than creating new functionality. No subtasks are necessary as the task is well-defined and focused."
},
{
"taskId": 84,
"taskTitle": "Implement token counting utility",
"complexityScore": 5,
"recommendedSubtasks": 1,
"expansionPrompt": "This task appears well-defined enough to be implemented without further subtasks. Focus on implementing accurate token counting for different models and proper fallback mechanisms.",
"reasoning": "This task involves creating a utility function to count tokens for different AI models. The complexity is moderate as it requires integration with the tiktoken library and handling different tokenization schemes. No subtasks are necessary as the task is well-defined and focused."
},
{
"taskId": 69,
"taskTitle": "Enhance Analyze Complexity for Specific Task IDs",
"complexityScore": 7,
"recommendedSubtasks": 6,
"expansionPrompt": "Break down the task 'Enhance Analyze Complexity for Specific Task IDs' into 6 subtasks focusing on: 1) Core logic modification to accept ID parameters, 2) Report merging functionality, 3) CLI interface updates, 4) MCP tool integration, 5) Documentation updates, and 6) Comprehensive testing across all components.",
"reasoning": "This task involves modifying existing functionality across multiple components (core logic, CLI, MCP) with complex logic for filtering tasks and merging reports. The implementation requires careful handling of different parameter combinations and edge cases. The task has interdependent components that need to work together seamlessly, and the report merging functionality adds significant complexity."
},
{
"taskId": 70,
"taskTitle": "Implement 'diagram' command for Mermaid diagram generation",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down the 'diagram' command implementation into 5 subtasks: 1) Command interface and parameter handling, 2) Task data extraction and transformation to Mermaid syntax, 3) Diagram rendering with status color coding, 4) Output formatting and file export functionality, and 5) Error handling and edge case management.",
"reasoning": "This task requires implementing a new feature rather than modifying existing code, which reduces complexity from integration challenges. However, it involves working with visualization logic, dependency mapping, and multiple output formats. The color coding based on status and handling of dependency relationships adds moderate complexity. The task is well-defined but requires careful attention to diagram formatting and error handling."
},
{
"taskId": 85,
"taskTitle": "Update ai-services-unified.js for dynamic token limits",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Break down the update of ai-services-unified.js for dynamic token limits into subtasks such as: (1) Import and integrate the token counting utility, (2) Refactor _unifiedServiceRunner to calculate and enforce dynamic token limits, (3) Update error handling for token limit violations, (4) Add and verify logging for token usage, (5) Write and execute tests for various prompt and model scenarios.",
"reasoning": "This task involves significant code changes to a core function, integration of a new utility, dynamic logic for multiple models, and robust error handling. It also requires comprehensive testing for edge cases and integration, making it moderately complex and best managed by splitting into focused subtasks."
},
{
"taskId": 86,
"taskTitle": "Update .taskmasterconfig schema and user guide",
"complexityScore": 6,
"recommendedSubtasks": 4,
"expansionPrompt": "Expand this task into subtasks: (1) Draft a migration guide for users, (2) Update user documentation to explain new config fields, (3) Modify schema validation logic in config-manager.js, (4) Test and validate backward compatibility and error messaging.",
"reasoning": "The task spans documentation, schema changes, migration guidance, and validation logic. While not algorithmically complex, it requires careful coordination and thorough testing to ensure a smooth user transition and robust validation."
},
{
"taskId": 87,
"taskTitle": "Implement validation and error handling",
"complexityScore": 5,
"recommendedSubtasks": 4,
"expansionPrompt": "Decompose this task into: (1) Add validation logic for model and config loading, (2) Implement error handling and fallback mechanisms, (3) Enhance logging and reporting for token usage, (4) Develop helper functions for configuration suggestions and improvements.",
"reasoning": "This task is primarily about adding validation, error handling, and logging. While important for robustness, the logic is straightforward and can be modularized into a few clear subtasks."
},
{
"taskId": 89,
"taskTitle": "Introduce Prioritize Command with Enhanced Priority Levels",
"complexityScore": 6,
"recommendedSubtasks": 5,
"expansionPrompt": "Expand this task into: (1) Implement the prioritize command with all required flags and shorthands, (2) Update CLI output and help documentation for new priority levels, (3) Ensure backward compatibility with existing commands, (4) Add error handling for invalid inputs, (5) Write and run tests for all command scenarios.",
"reasoning": "This CLI feature requires command parsing, updating internal logic for new priority levels, documentation, and robust error handling. The complexity is moderate due to the need for backward compatibility and comprehensive testing."
},
{
"taskId": 90,
"taskTitle": "Implement Subtask Progress Analyzer and Reporting System",
"complexityScore": 8,
"recommendedSubtasks": 6,
"expansionPrompt": "Break down the analyzer implementation into: (1) Design and implement progress tracking logic, (2) Develop status validation and issue detection, (3) Build the reporting system with multiple output formats, (4) Integrate analyzer with the existing task management system, (5) Optimize for performance and scalability, (6) Write unit, integration, and performance tests.",
"reasoning": "This is a complex, multi-faceted feature involving data analysis, reporting, integration, and performance optimization. It touches many parts of the system and requires careful design, making it one of the most complex tasks in the list."
},
{
"taskId": 91,
"taskTitle": "Implement Move Command for Tasks and Subtasks",
"complexityScore": 7,
"recommendedSubtasks": 5,
"expansionPrompt": "Expand this task into: (1) Implement move logic for tasks and subtasks, (2) Handle edge cases (invalid ids, non-existent parents, circular dependencies), (3) Update CLI to support move command with flags, (4) Ensure data integrity and update relationships, (5) Write and execute tests for various move scenarios.",
"reasoning": "Moving tasks and subtasks requires careful handling of hierarchical data, edge cases, and data integrity. The command must be robust and user-friendly, necessitating multiple focused subtasks for safe implementation."
}
]
}

View File

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

View File

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

View File

@@ -1,94 +0,0 @@
# Task ID: 44
# Title: Implement Task Automation with Webhooks and Event Triggers
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Design and implement a system that allows users to automate task actions through webhooks and event triggers, enabling integration with external services and automated workflows.
# Details:
This feature will enable users to create automated workflows based on task events and external triggers. Implementation should include:
1. A webhook registration system that allows users to specify URLs to be called when specific task events occur (creation, status change, completion, etc.)
2. An event system that captures and processes all task-related events
3. A trigger definition interface where users can define conditions for automation (e.g., 'When task X is completed, create task Y')
4. Support for both incoming webhooks (external services triggering actions in Taskmaster) and outgoing webhooks (Taskmaster notifying external services)
5. A secure authentication mechanism for webhook calls
6. Rate limiting and retry logic for failed webhook deliveries
7. Integration with the existing task management system
8. Command-line interface for managing webhooks and triggers
9. Payload templating system allowing users to customize the data sent in webhooks
10. Logging system for webhook activities and failures
The implementation should be compatible with both the solo/local mode and the multiplayer/remote mode, with appropriate adaptations for each context. When operating in MCP mode, the system should leverage the MCP communication protocol implemented in Task #42.
# Test Strategy:
Testing should verify both the functionality and security of the webhook system:
1. Unit tests:
- Test webhook registration, modification, and deletion
- Verify event capturing for all task operations
- Test payload generation and templating
- Validate authentication logic
2. Integration tests:
- Set up a mock server to receive webhooks and verify payload contents
- Test the complete flow from task event to webhook delivery
- Verify rate limiting and retry behavior with intentionally failing endpoints
- Test webhook triggers creating new tasks and modifying existing ones
3. Security tests:
- Verify that authentication tokens are properly validated
- Test for potential injection vulnerabilities in webhook payloads
- Verify that sensitive information is not leaked in webhook payloads
- Test rate limiting to prevent DoS attacks
4. Mode-specific tests:
- Verify correct operation in both solo/local and multiplayer/remote modes
- Test the interaction with MCP protocol when in multiplayer mode
5. Manual verification:
- Set up integrations with common services (GitHub, Slack, etc.) to verify real-world functionality
- Verify that the CLI interface for managing webhooks works as expected
# Subtasks:
## 1. Design webhook registration API endpoints [pending]
### Dependencies: None
### Description: Create API endpoints for registering, updating, and deleting webhook subscriptions
### Details:
Implement RESTful API endpoints that allow clients to register webhook URLs, specify event types they want to subscribe to, and manage their subscriptions. Include validation for URL format, required parameters, and authentication requirements.
## 2. Implement webhook authentication and security measures [pending]
### Dependencies: 44.1
### Description: Develop security mechanisms for webhook verification and payload signing
### Details:
Implement signature verification using HMAC, rate limiting to prevent abuse, IP whitelisting options, and webhook secret management. Create a secure token system for webhook verification and implement TLS for all webhook communications.
## 3. Create event trigger definition interface [pending]
### Dependencies: None
### Description: Design and implement the interface for defining event triggers and conditions
### Details:
Develop a user interface or API that allows defining what events should trigger webhooks. Include support for conditional triggers based on event properties, filtering options, and the ability to specify payload formats.
## 4. Build event processing and queuing system [pending]
### Dependencies: 44.1, 44.3
### Description: Implement a robust system for processing and queuing events before webhook delivery
### Details:
Create an event queue using a message broker (like RabbitMQ or Kafka) to handle high volumes of events. Implement event deduplication, prioritization, and persistence to ensure reliable delivery even during system failures.
## 5. Develop webhook delivery and retry mechanism [pending]
### Dependencies: 44.2, 44.4
### Description: Create a reliable system for webhook delivery with retry logic and failure handling
### Details:
Implement exponential backoff retry logic, configurable retry attempts, and dead letter queues for failed deliveries. Add monitoring for webhook delivery success rates and performance metrics. Include timeout handling for unresponsive webhook endpoints.
## 6. Implement comprehensive error handling and logging [pending]
### Dependencies: 44.5
### Description: Create robust error handling, logging, and monitoring for the webhook system
### Details:
Develop detailed error logging for webhook failures, including response codes, error messages, and timing information. Implement alerting for critical failures and create a dashboard for monitoring system health. Add debugging tools for webhook delivery issues.
## 7. Create webhook testing and simulation tools [pending]
### Dependencies: 44.3, 44.5, 44.6
### Description: Develop tools for testing webhook integrations and simulating event triggers
### Details:
Build a webhook testing console that allows manual triggering of events, viewing delivery history, and replaying failed webhooks. Create a webhook simulator for developers to test their endpoint implementations without generating real system events.

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,90 +0,0 @@
# Task ID: 62
# Title: Add --simple Flag to Update Commands for Direct Text Input
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Implement a --simple flag for update-task and update-subtask commands that allows users to add timestamped notes without AI processing, directly using the text from the prompt.
# Details:
This task involves modifying the update-task and update-subtask commands to accept a new --simple flag option. When this flag is present, the system should bypass the AI processing pipeline and directly use the text provided by the user as the update content. The implementation should:
1. Update the command parsers for both update-task and update-subtask to recognize the --simple flag
2. Modify the update logic to check for this flag and conditionally skip AI processing
3. When the flag is present, format the user's input text with a timestamp in the same format as AI-processed updates
4. Ensure the update is properly saved to the task or subtask's history
5. Update the help documentation to include information about this new flag
6. The timestamp format should match the existing format used for AI-generated updates
7. The simple update should be visually distinguishable from AI updates in the display (consider adding a 'manual update' indicator)
8. Maintain all existing functionality when the flag is not used
# Test Strategy:
Testing should verify both the functionality and user experience of the new feature:
1. Unit tests:
- Test that the command parser correctly recognizes the --simple flag
- Verify that AI processing is bypassed when the flag is present
- Ensure timestamps are correctly formatted and added
2. Integration tests:
- Update a task with --simple flag and verify the exact text is saved
- Update a subtask with --simple flag and verify the exact text is saved
- Compare the output format with AI-processed updates to ensure consistency
3. User experience tests:
- Verify help documentation correctly explains the new flag
- Test with various input lengths to ensure proper formatting
- Ensure the update appears correctly when viewing task history
4. Edge cases:
- Test with empty input text
- Test with very long input text
- Test with special characters and formatting in the input
# Subtasks:
## 1. Update command parsers to recognize --simple flag [pending]
### Dependencies: None
### Description: Modify the command parsers for both update-task and update-subtask commands to recognize and process the new --simple flag option.
### Details:
Add the --simple flag option to the command parser configurations in the CLI module. This should be implemented as a boolean flag that doesn't require any additional arguments. Update both the update-task and update-subtask command definitions to include this new option.
## 2. Implement conditional logic to bypass AI processing [pending]
### Dependencies: 62.1
### Description: Modify the update logic to check for the --simple flag and conditionally skip the AI processing pipeline when the flag is present.
### Details:
In the update handlers for both commands, add a condition to check if the --simple flag is set. If it is, create a path that bypasses the normal AI processing flow. This will require modifying the update functions to accept the flag parameter and branch the execution flow accordingly.
## 3. Format user input with timestamp for simple updates [pending]
### Dependencies: 62.2
### Description: Implement functionality to format the user's direct text input with a timestamp in the same format as AI-processed updates when the --simple flag is used.
### Details:
Create a utility function that takes the user's raw input text and prepends a timestamp in the same format used for AI-generated updates. This function should be called when the --simple flag is active. Ensure the timestamp format is consistent with the existing format used throughout the application.
## 4. Add visual indicator for manual updates [pending]
### Dependencies: 62.3
### Description: Make simple updates visually distinguishable from AI-processed updates by adding a 'manual update' indicator or other visual differentiation.
### Details:
Modify the update formatting to include a visual indicator (such as '[Manual Update]' prefix or different styling) when displaying updates that were created using the --simple flag. This will help users distinguish between AI-processed and manually entered updates.
## 5. Implement storage of simple updates in history [pending]
### Dependencies: 62.3, 62.4
### Description: Ensure that updates made with the --simple flag are properly saved to the task or subtask's history in the same way as AI-processed updates.
### Details:
Modify the storage logic to save the formatted simple updates to the task or subtask history. The storage format should be consistent with AI-processed updates, but include the manual indicator. Ensure that the update is properly associated with the correct task or subtask.
## 6. Update help documentation for the new flag [pending]
### Dependencies: 62.1
### Description: Update the help documentation for both update-task and update-subtask commands to include information about the new --simple flag.
### Details:
Add clear descriptions of the --simple flag to the help text for both commands. The documentation should explain that the flag allows users to add timestamped notes without AI processing, directly using the text from the prompt. Include examples of how to use the flag.
## 7. Implement integration tests for the simple update feature [pending]
### Dependencies: 62.1, 62.2, 62.3, 62.4, 62.5
### Description: Create comprehensive integration tests to verify that the --simple flag works correctly in both commands and integrates properly with the rest of the system.
### Details:
Develop integration tests that verify the entire flow of using the --simple flag with both update commands. Tests should confirm that updates are correctly formatted, stored, and displayed. Include edge cases such as empty input, very long input, and special characters.
## 8. Perform final validation and documentation [pending]
### Dependencies: 62.1, 62.2, 62.3, 62.4, 62.5, 62.6, 62.7
### Description: Conduct final validation of the feature across all use cases and update the user documentation to include the new functionality.
### Details:
Perform end-to-end testing of the feature to ensure it works correctly in all scenarios. Update the user documentation with detailed information about the new --simple flag, including its purpose, how to use it, and examples. Ensure that the documentation clearly explains the difference between AI-processed updates and simple updates.

View File

@@ -1,138 +0,0 @@
# Task ID: 63
# Title: Add pnpm Support for the Taskmaster Package
# Status: done
# Dependencies: None
# Priority: medium
# Description: Implement full support for pnpm as an alternative package manager in the Taskmaster application, ensuring users have the exact same experience as with npm when installing and managing the package. The installation process, including any CLI prompts or web interfaces, must serve the exact same content and user experience regardless of whether npm or pnpm is used. The project uses 'module' as the package type, defines binaries 'task-master' and 'task-master-mcp', and its core logic resides in 'scripts/modules/'. The 'init' command (via scripts/init.js) creates the directory structure (.cursor/rules, scripts, tasks), copies templates (.env.example, .gitignore, rule files, dev.js), manages package.json merging, and sets up MCP config (.cursor/mcp.json). All dependencies are standard npm dependencies listed in package.json, and manual modifications are being removed.
# Details:
This task involves:
1. Update the installation documentation to include pnpm installation commands (e.g., `pnpm add taskmaster`).
2. Ensure all package scripts are compatible with pnpm's execution model:
- Review and modify package.json scripts if necessary
- Test script execution with pnpm syntax (`pnpm run <script>`)
- Address any pnpm-specific path or execution differences
- Confirm that scripts responsible for showing a website or prompt during install behave identically with pnpm and npm
3. Create a pnpm-lock.yaml file by installing dependencies with pnpm.
4. Test the application's installation and operation when installed via pnpm:
- Global installation (`pnpm add -g taskmaster`)
- Local project installation
- Verify CLI commands work correctly when installed with pnpm
- Verify binaries `task-master` and `task-master-mcp` are properly linked
- Ensure the `init` command (scripts/init.js) correctly creates directory structure and copies templates as described
5. Update CI/CD pipelines to include testing with pnpm:
- Add a pnpm test matrix to GitHub Actions workflows
- Ensure tests pass when dependencies are installed with pnpm
6. Handle any pnpm-specific dependency resolution issues:
- Address potential hoisting differences between npm and pnpm
- Test with pnpm's strict mode to ensure compatibility
- Verify proper handling of 'module' package type
7. Document any pnpm-specific considerations or commands in the README and documentation.
8. Verify that the `scripts/init.js` file works correctly with pnpm:
- Ensure it properly creates `.cursor/rules`, `scripts`, and `tasks` directories
- Verify template copying (`.env.example`, `.gitignore`, rule files, `dev.js`)
- Confirm `package.json` merging works correctly
- Test MCP config setup (`.cursor/mcp.json`)
9. Ensure core logic in `scripts/modules/` works correctly when installed via pnpm.
This implementation should maintain full feature parity and identical user experience regardless of which package manager is used to install Taskmaster.
# Test Strategy:
1. Manual Testing:
- Install Taskmaster globally using pnpm: `pnpm add -g taskmaster`
- Install Taskmaster locally in a test project: `pnpm add taskmaster`
- Verify all CLI commands function correctly with both installation methods
- Test all major features to ensure they work identically to npm installations
- Verify binaries `task-master` and `task-master-mcp` are properly linked and executable
- Test the `init` command to ensure it correctly sets up the directory structure and files as defined in scripts/init.js
2. Automated Testing:
- Create a dedicated test workflow in GitHub Actions that uses pnpm
- Run the full test suite using pnpm to install dependencies
- Verify all tests pass with the same results as npm
3. Documentation Testing:
- Review all documentation to ensure pnpm commands are correctly documented
- Verify installation instructions work as written
- Test any pnpm-specific instructions or notes
4. Compatibility Testing:
- Test on different operating systems (Windows, macOS, Linux)
- Verify compatibility with different pnpm versions (latest stable and LTS)
- Test in environments with multiple package managers installed
- Verify proper handling of 'module' package type
5. Edge Case Testing:
- Test installation in a project that uses pnpm workspaces
- Verify behavior when upgrading from an npm installation to pnpm
- Test with pnpm's various flags and modes (--frozen-lockfile, --strict-peer-dependencies)
6. Performance Comparison:
- Measure and document any performance differences between package managers
- Compare installation times and disk space usage
7. Structure Testing:
- Verify that the core logic in `scripts/modules/` is accessible and functions correctly
- Confirm that the `init` command properly creates all required directories and files as per scripts/init.js
- Test package.json merging functionality
- Verify MCP config setup
Success criteria: Taskmaster should install and function identically regardless of whether it was installed via npm or pnpm, with no degradation in functionality, performance, or user experience. All binaries should be properly linked, and the directory structure should be correctly created.
# Subtasks:
## 1. Update Documentation for pnpm Support [done]
### Dependencies: None
### Description: Revise installation and usage documentation to include pnpm commands and instructions for installing and managing Taskmaster with pnpm. Clearly state that the installation process, including any website or UI shown, is identical to npm. Ensure documentation reflects the use of 'module' package type, binaries, and the init process as defined in scripts/init.js.
### Details:
Add pnpm installation commands (e.g., `pnpm add taskmaster`) and update all relevant sections in the README and official docs to reflect pnpm as a supported package manager. Document that any installation website or prompt is the same as with npm. Include notes on the 'module' package type, binaries, and the directory/template setup performed by scripts/init.js.
## 2. Ensure Package Scripts Compatibility with pnpm [done]
### Dependencies: 63.1
### Description: Review and update package.json scripts to ensure they work seamlessly with pnpm's execution model. Confirm that any scripts responsible for showing a website or prompt during install behave identically with pnpm and npm. Ensure compatibility with 'module' package type and correct binary definitions.
### Details:
Test all scripts using `pnpm run <script>`, address any pnpm-specific path or execution differences, and modify scripts as needed for compatibility. Pay special attention to any scripts that trigger a website or prompt during installation, ensuring they serve the same content as npm. Validate that scripts/init.js and binaries are referenced correctly for ESM ('module') projects.
## 3. Generate and Validate pnpm Lockfile [done]
### Dependencies: 63.2
### Description: Install dependencies using pnpm to create a pnpm-lock.yaml file and ensure it accurately reflects the project's dependency tree, considering the 'module' package type.
### Details:
Run `pnpm install` to generate the lockfile, check it into version control, and verify that dependency resolution is correct and consistent. Ensure that all dependencies listed in package.json are resolved as expected for an ESM project.
## 4. Test Taskmaster Installation and Operation with pnpm [done]
### Dependencies: 63.3
### Description: Thoroughly test Taskmaster's installation and CLI operation when installed via pnpm, both globally and locally. Confirm that any website or UI shown during installation is identical to npm. Validate that binaries and the init process (scripts/init.js) work as expected.
### Details:
Perform global (`pnpm add -g taskmaster`) and local installations, verify CLI commands, and check for any pnpm-specific issues or incompatibilities. Ensure any installation UIs or websites appear identical to npm installations, including any website or prompt shown during install. Test that binaries 'task-master' and 'task-master-mcp' are linked and that scripts/init.js creates the correct structure and templates.
## 5. Integrate pnpm into CI/CD Pipeline [done]
### Dependencies: 63.4
### Description: Update CI/CD workflows to include pnpm in the test matrix, ensuring all tests pass when dependencies are installed with pnpm. Confirm that tests cover the 'module' package type, binaries, and init process.
### Details:
Modify GitHub Actions or other CI configurations to use pnpm/action-setup, run tests with pnpm, and cache pnpm dependencies for efficiency. Ensure that CI covers CLI commands, binary linking, and the directory/template setup performed by scripts/init.js.
## 6. Verify Installation UI/Website Consistency [done]
### Dependencies: 63.4
### Description: Ensure any installation UIs, websites, or interactive prompts—including any website or prompt shown during install—appear and function identically when installing with pnpm compared to npm. Confirm that the experience is consistent for the 'module' package type and the init process.
### Details:
Identify all user-facing elements during the installation process, including any website or prompt shown during install, and verify they are consistent across package managers. If a website is shown during installation, ensure it appears the same regardless of package manager used. Validate that any prompts or UIs triggered by scripts/init.js are identical.
## 7. Test init.js Script with pnpm [done]
### Dependencies: 63.4
### Description: Verify that the scripts/init.js file works correctly when Taskmaster is installed via pnpm, creating the proper directory structure and copying all required templates as defined in the project structure.
### Details:
Test the init command to ensure it properly creates .cursor/rules, scripts, and tasks directories, copies templates (.env.example, .gitignore, rule files, dev.js), handles package.json merging, and sets up MCP config (.cursor/mcp.json) as per scripts/init.js.
## 8. Verify Binary Links with pnpm [done]
### Dependencies: 63.4
### Description: Ensure that the task-master and task-master-mcp binaries are properly defined in package.json, linked, and executable when installed via pnpm, in both global and local installations.
### Details:
Check that the binaries defined in package.json are correctly linked in node_modules/.bin when installed with pnpm, and that they can be executed without errors. Validate that binaries work for ESM ('module') projects and are accessible after both global and local installs.

View File

@@ -1,202 +0,0 @@
# Task ID: 64
# Title: Add Yarn Support for Taskmaster Installation
# Status: done
# Dependencies: None
# Priority: medium
# Description: Implement full support for installing and managing Taskmaster using Yarn package manager, ensuring users have the exact same experience as with npm or pnpm. The installation process, including any CLI prompts or web interfaces, must serve the exact same content and user experience regardless of whether npm, pnpm, or Yarn is used. The project uses 'module' as the package type, defines binaries 'task-master' and 'task-master-mcp', and its core logic resides in 'scripts/modules/'. The 'init' command (via scripts/init.js) creates the directory structure (.cursor/rules, scripts, tasks), copies templates (.env.example, .gitignore, rule files, dev.js), manages package.json merging, and sets up MCP config (.cursor/mcp.json). All dependencies are standard npm dependencies listed in package.json, and manual modifications are being removed.
If the installation process includes a website component (such as for account setup or registration), ensure that any required website actions (e.g., creating an account, logging in, or configuring user settings) are clearly documented and tested for parity between Yarn and other package managers. If no website or account setup is required, confirm and document this explicitly.
# Details:
This task involves adding comprehensive Yarn support to the Taskmaster package to ensure it can be properly installed and managed using Yarn. Implementation should include:
1. Update package.json to ensure compatibility with Yarn installation methods, considering the 'module' package type and binary definitions
2. Verify all scripts and dependencies work correctly with Yarn
3. Add Yarn-specific configuration files (e.g., .yarnrc.yml if needed)
4. Update installation documentation to include Yarn installation instructions
5. Ensure all post-install scripts work correctly with Yarn
6. Verify that all CLI commands function properly when installed via Yarn
7. Ensure binaries `task-master` and `task-master-mcp` are properly linked
8. Test the `scripts/init.js` file with Yarn to verify it correctly:
- Creates directory structure (`.cursor/rules`, `scripts`, `tasks`)
- Copies templates (`.env.example`, `.gitignore`, rule files, `dev.js`)
- Manages `package.json` merging
- Sets up MCP config (`.cursor/mcp.json`)
9. Handle any Yarn-specific package resolution or hoisting issues
10. Test compatibility with different Yarn versions (classic and berry/v2+)
11. Ensure proper lockfile generation and management
12. Update any package manager detection logic in the codebase to recognize Yarn installations
13. Verify that core logic in `scripts/modules/` works correctly when installed via Yarn
14. If the installation process includes a website component, verify that any account setup or user registration flows work identically with Yarn as they do with npm or pnpm. If website actions are required, document the steps and ensure they are tested for parity. If not, confirm and document that no website or account setup is needed.
The implementation should maintain feature parity and identical user experience regardless of which package manager (npm, pnpm, or Yarn) is used to install Taskmaster.
# Test Strategy:
Testing should verify complete Yarn support through the following steps:
1. Fresh installation tests:
- Install Taskmaster using `yarn add taskmaster` (global and local installations)
- Verify installation completes without errors
- Check that binaries `task-master` and `task-master-mcp` are properly linked
- Test the `init` command to ensure it correctly sets up the directory structure and files as defined in scripts/init.js
2. Functionality tests:
- Run all Taskmaster commands on a Yarn-installed version
- Verify all features work identically to npm installations
- Test with both Yarn v1 (classic) and Yarn v2+ (berry)
- Verify proper handling of 'module' package type
3. Update/uninstall tests:
- Test updating the package using Yarn commands
- Verify clean uninstallation using Yarn
4. CI integration:
- Add Yarn installation tests to CI pipeline
- Test on different operating systems (Windows, macOS, Linux)
5. Documentation verification:
- Ensure all documentation accurately reflects Yarn installation methods
- Verify any Yarn-specific commands or configurations are properly documented
6. Edge cases:
- Test installation in monorepo setups using Yarn workspaces
- Verify compatibility with other Yarn-specific features (plug'n'play, zero-installs)
7. Structure Testing:
- Verify that the core logic in `scripts/modules/` is accessible and functions correctly
- Confirm that the `init` command properly creates all required directories and files as per scripts/init.js
- Test package.json merging functionality
- Verify MCP config setup
8. Website/Account Setup Testing:
- If the installation process includes a website component, test the complete user flow including account setup, registration, or configuration steps. Ensure these work identically with Yarn as with npm. If no website or account setup is required, confirm and document this in the test results.
- Document any website-specific steps that users need to complete during installation.
All tests should pass with the same results as when using npm, with identical user experience throughout the installation and usage process.
# Subtasks:
## 1. Update package.json for Yarn Compatibility [done]
### Dependencies: None
### Description: Modify the package.json file to ensure all dependencies, scripts, and configurations are compatible with Yarn's installation and resolution methods. Confirm that any scripts responsible for showing a website or prompt during install behave identically with Yarn and npm. Ensure compatibility with 'module' package type and correct binary definitions.
### Details:
Review and update dependency declarations, script syntax, and any package manager-specific fields to avoid conflicts or unsupported features when using Yarn. Pay special attention to any scripts that trigger a website or prompt during installation, ensuring they serve the same content as npm. Validate that scripts/init.js and binaries are referenced correctly for ESM ('module') projects.
## 2. Add Yarn-Specific Configuration Files [done]
### Dependencies: 64.1
### Description: Introduce Yarn-specific configuration files such as .yarnrc.yml if needed to optimize Yarn behavior and ensure consistent installs for 'module' package type and binary definitions.
### Details:
Determine if Yarn v2+ (Berry) or classic requires additional configuration for the project, and add or update .yarnrc.yml or .yarnrc files accordingly. Ensure configuration supports ESM and binary linking.
## 3. Test and Fix Yarn Compatibility for Scripts and CLI [done]
### Dependencies: 64.2
### Description: Ensure all scripts, post-install hooks, and CLI commands function correctly when Taskmaster is installed and managed via Yarn. Confirm that any website or UI shown during installation is identical to npm. Validate that binaries and the init process (scripts/init.js) work as expected.
### Details:
Test all lifecycle scripts, post-install actions, and CLI commands using Yarn. Address any issues related to environment variables, script execution, or dependency hoisting. Ensure any website or prompt shown during install is the same as with npm. Validate that binaries 'task-master' and 'task-master-mcp' are linked and that scripts/init.js creates the correct structure and templates.
## 4. Update Documentation for Yarn Installation and Usage [done]
### Dependencies: 64.3
### Description: Revise installation and usage documentation to include clear instructions for installing and managing Taskmaster with Yarn. Clearly state that the installation process, including any website or UI shown, is identical to npm. Ensure documentation reflects the use of 'module' package type, binaries, and the init process as defined in scripts/init.js. If the installation process includes a website component or requires account setup, document the steps users must follow. If not, explicitly state that no website or account setup is required.
### Details:
Add Yarn-specific installation commands, troubleshooting tips, and notes on version compatibility to the README and any relevant docs. Document that any installation website or prompt is the same as with npm. Include notes on the 'module' package type, binaries, and the directory/template setup performed by scripts/init.js. If website or account setup is required during installation, provide clear instructions; otherwise, confirm and document that no such steps are needed.
## 5. Implement and Test Package Manager Detection Logic [done]
### Dependencies: 64.4
### Description: Update or add logic in the codebase to detect Yarn installations and handle Yarn-specific behaviors, ensuring feature parity across package managers. Ensure detection logic works for 'module' package type and binary definitions.
### Details:
Modify detection logic to recognize Yarn (classic and berry), handle lockfile generation, and resolve any Yarn-specific package resolution or hoisting issues. Ensure detection logic supports ESM and binary linking.
## 6. Verify Installation UI/Website Consistency [done]
### Dependencies: 64.3
### Description: Ensure any installation UIs, websites, or interactive prompts—including any website or prompt shown during install—appear and function identically when installing with Yarn compared to npm. Confirm that the experience is consistent for the 'module' package type and the init process. If the installation process includes a website or account setup, verify that all required website actions (e.g., account creation, login) are consistent and documented. If not, confirm and document that no website or account setup is needed.
### Details:
Identify all user-facing elements during the installation process, including any website or prompt shown during install, and verify they are consistent across package managers. If a website is shown during installation or account setup is required, ensure it appears and functions the same regardless of package manager used, and document the steps. If not, confirm and document that no website or account setup is needed. Validate that any prompts or UIs triggered by scripts/init.js are identical.
## 7. Test init.js Script with Yarn [done]
### Dependencies: 64.3
### Description: Verify that the scripts/init.js file works correctly when Taskmaster is installed via Yarn, creating the proper directory structure and copying all required templates as defined in the project structure.
### Details:
Test the init command to ensure it properly creates .cursor/rules, scripts, and tasks directories, copies templates (.env.example, .gitignore, rule files, dev.js), handles package.json merging, and sets up MCP config (.cursor/mcp.json) as per scripts/init.js.
## 8. Verify Binary Links with Yarn [done]
### Dependencies: 64.3
### Description: Ensure that the task-master and task-master-mcp binaries are properly defined in package.json, linked, and executable when installed via Yarn, in both global and local installations.
### Details:
Check that the binaries defined in package.json are correctly linked in node_modules/.bin when installed with Yarn, and that they can be executed without errors. Validate that binaries work for ESM ('module') projects and are accessible after both global and local installs.
## 9. Test Website Account Setup with Yarn [done]
### Dependencies: 64.6
### Description: If the installation process includes a website component, verify that account setup, registration, or any other user-specific configurations work correctly when Taskmaster is installed via Yarn. If no website or account setup is required, confirm and document this explicitly.
### Details:
Test the complete user flow for any website component that appears during installation, including account creation, login, and configuration steps. Ensure that all website interactions work identically with Yarn as they do with npm or pnpm. Document any website-specific steps that users need to complete during the installation process. If no website or account setup is required, confirm and document this.
<info added on 2025-04-25T08:45:48.709Z>
Since the request is vague, I'll provide helpful implementation details for testing website account setup with Yarn:
For thorough testing, create a test matrix covering different browsers (Chrome, Firefox, Safari) and operating systems (Windows, macOS, Linux). Document specific Yarn-related environment variables that might affect website connectivity. Use tools like Playwright or Cypress to automate the account setup flow testing, capturing screenshots at each step for documentation. Implement network throttling tests to verify behavior under poor connectivity. Create a checklist of all UI elements that should be verified during the account setup process, including form validation, error messages, and success states. If no website component exists, explicitly document this in the project README and installation guides to prevent user confusion.
</info added on 2025-04-25T08:45:48.709Z>
<info added on 2025-04-25T08:46:08.651Z>
- For environments where the website component requires integration with external authentication providers (such as OAuth, SSO, or LDAP), ensure that these flows are tested specifically when Taskmaster is installed via Yarn. Validate that redirect URIs, token exchanges, and session persistence behave as expected across all supported browsers.
- If the website setup involves configuring application pools or web server settings (e.g., with IIS), document any Yarn-specific considerations, such as environment variable propagation or file permission differences, that could affect the web service's availability or configuration[2].
- When automating tests, include validation for accessibility compliance (e.g., using axe-core or Lighthouse) during the account setup process to ensure the UI is usable for all users.
- Capture and log all HTTP requests and responses during the account setup flow to help diagnose any discrepancies between Yarn and other package managers. This can be achieved by enabling network logging in Playwright or Cypress test runs.
- If the website component supports batch operations or automated uploads (such as uploading user data or configuration files), verify that these automation features function identically after installation with Yarn[3].
- For documentation, provide annotated screenshots or screen recordings of the account setup process, highlighting any Yarn-specific prompts, warnings, or differences encountered.
- If the website component is not required, add a badge or prominent note in the README and installation guides stating "No website or account setup required," and reference the test results confirming this.
</info added on 2025-04-25T08:46:08.651Z>
<info added on 2025-04-25T17:04:12.550Z>
For clarity, this task does not involve setting up a Yarn account. Yarn itself is just a package manager that doesn't require any account creation. The task is about testing whether any website component that is part of Taskmaster (if one exists) works correctly when Taskmaster is installed using Yarn as the package manager.
To be specific:
- You don't need to create a Yarn account
- Yarn is simply the tool used to install Taskmaster (`yarn add taskmaster` instead of `npm install taskmaster`)
- The testing focuses on whether any web interfaces or account setup processes that are part of Taskmaster itself function correctly when the installation was done via Yarn
- If Taskmaster includes a web dashboard or requires users to create accounts within the Taskmaster system, those features should be tested
If you're uncertain whether Taskmaster includes a website component at all, the first step would be to check the project documentation or perform an initial installation to determine if any web interface exists.
</info added on 2025-04-25T17:04:12.550Z>
<info added on 2025-04-25T17:19:03.256Z>
When testing website account setup with Yarn after the codebase refactor, pay special attention to:
- Verify that any environment-specific configuration files (like `.env` or config JSON files) are properly loaded when the application is installed via Yarn
- Test the session management implementation to ensure user sessions persist correctly across page refreshes and browser restarts
- Check that any database migrations or schema updates required for account setup execute properly when installed via Yarn
- Validate that client-side form validation logic works consistently with server-side validation
- Ensure that any WebSocket connections for real-time features initialize correctly after the refactor
- Test account deletion and data export functionality to verify GDPR compliance remains intact
- Document any changes to the authentication flow that resulted from the refactor and confirm they work identically with Yarn installation
</info added on 2025-04-25T17:19:03.256Z>
<info added on 2025-04-25T17:22:05.951Z>
When testing website account setup with Yarn after the logging fix, implement these additional verification steps:
1. Verify that all account-related actions are properly logged with the correct log levels (debug, info, warn, error) according to the updated logging framework
2. Test the error handling paths specifically - force authentication failures and verify the logs contain sufficient diagnostic information
3. Check that sensitive user information is properly redacted in logs according to privacy requirements
4. Confirm that log rotation and persistence work correctly when high volumes of authentication attempts occur
5. Validate that any custom logging middleware correctly captures HTTP request/response data for account operations
6. Test that log aggregation tools (if used) can properly parse and display the account setup logs in their expected format
7. Verify that performance metrics for account setup flows are correctly captured in logs for monitoring purposes
8. Document any Yarn-specific environment variables that affect the logging configuration for the website component
</info added on 2025-04-25T17:22:05.951Z>
<info added on 2025-04-25T17:22:46.293Z>
When testing website account setup with Yarn, consider implementing a positive user experience validation:
1. Measure and document time-to-completion for the account setup process to ensure it meets usability standards
2. Create a satisfaction survey for test users to rate the account setup experience on a 1-5 scale
3. Implement A/B testing for different account setup flows to identify the most user-friendly approach
4. Add delightful micro-interactions or success animations that make the setup process feel rewarding
5. Test the "welcome" or "onboarding" experience that follows successful account creation
6. Ensure helpful tooltips and contextual help are displayed at appropriate moments during setup
7. Verify that error messages are friendly, clear, and provide actionable guidance rather than technical jargon
8. Test the account recovery flow to ensure users have a smooth experience if they forget credentials
</info added on 2025-04-25T17:22:46.293Z>

View File

@@ -1,49 +0,0 @@
# Task ID: 65
# Title: Add Bun Support for Taskmaster Installation
# Status: done
# Dependencies: None
# Priority: medium
# Description: Implement full support for installing and managing Taskmaster using the Bun package manager, ensuring the installation process and user experience are identical to npm, pnpm, and Yarn.
# Details:
Update the Taskmaster installation scripts and documentation to support Bun as a first-class package manager. Ensure that users can install Taskmaster and run all CLI commands (including 'init' via scripts/init.js) using Bun, with the same directory structure, template copying, package.json merging, and MCP config setup as with npm, pnpm, and Yarn. Verify that all dependencies are compatible with Bun and that any Bun-specific configuration (such as lockfile handling or binary linking) is handled correctly. If the installation process includes a website or account setup, document and test these flows for parity; if not, explicitly confirm and document that no such steps are required. Update all relevant documentation and installation guides to include Bun instructions for macOS, Linux, and Windows (including WSL and PowerShell). Address any known Bun-specific issues (e.g., sporadic install hangs) with clear troubleshooting guidance.
# Test Strategy:
1. Install Taskmaster using Bun on macOS, Linux, and Windows (including WSL and PowerShell), following the updated documentation. 2. Run the full installation and initialization process, verifying that the directory structure, templates, and MCP config are set up identically to npm, pnpm, and Yarn. 3. Execute all CLI commands (including 'init') and confirm functional parity. 4. If a website or account setup is required, test these flows for consistency; if not, confirm and document this. 5. Check for Bun-specific issues (e.g., install hangs) and verify that troubleshooting steps are effective. 6. Ensure the documentation is clear, accurate, and up to date for all supported platforms.
# Subtasks:
## 1. Research Bun compatibility requirements [done]
### Dependencies: None
### Description: Investigate Bun's JavaScript runtime environment and identify key differences from Node.js that may affect Taskmaster's installation and operation.
### Details:
Research Bun's package management, module resolution, and API compatibility with Node.js. Document any potential issues or limitations that might affect Taskmaster. Identify required changes to make Taskmaster compatible with Bun's execution model.
## 2. Update installation scripts for Bun compatibility [done]
### Dependencies: 65.1
### Description: Modify the existing installation scripts to detect and support Bun as a runtime environment.
### Details:
Add Bun detection logic to installation scripts. Update package management commands to use Bun equivalents where needed. Ensure all dependencies are compatible with Bun. Modify any Node.js-specific code to work with Bun's runtime.
## 3. Create Bun-specific installation path [done]
### Dependencies: 65.2
### Description: Implement a dedicated installation flow for Bun users that optimizes for Bun's capabilities.
### Details:
Create a Bun-specific installation script that leverages Bun's performance advantages. Update any environment detection logic to properly identify Bun environments. Ensure proper path resolution and environment variable handling for Bun.
## 4. Test Taskmaster installation with Bun [done]
### Dependencies: 65.3
### Description: Perform comprehensive testing of the installation process using Bun across different operating systems.
### Details:
Test installation on Windows, macOS, and Linux using Bun. Verify that all Taskmaster features work correctly when installed via Bun. Document any issues encountered and implement fixes as needed.
## 5. Test Taskmaster operation with Bun [done]
### Dependencies: 65.4
### Description: Ensure all Taskmaster functionality works correctly when running under Bun.
### Details:
Test all Taskmaster commands and features when running with Bun. Compare performance metrics between Node.js and Bun. Identify and fix any runtime issues specific to Bun. Ensure all plugins and extensions are compatible.
## 6. Update documentation for Bun support [done]
### Dependencies: 65.4, 65.5
### Description: Update all relevant documentation to include information about installing and running Taskmaster with Bun.
### Details:
Add Bun installation instructions to README and documentation. Document any Bun-specific considerations or limitations. Update troubleshooting guides to include Bun-specific issues. Create examples showing Bun usage with Taskmaster.

View File

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

View File

@@ -1,106 +0,0 @@
# Task ID: 67
# Title: Add CLI JSON output and Cursor keybindings integration
# Status: pending
# Dependencies: None
# Priority: high
# Description: Enhance Taskmaster CLI with JSON output option and add a new command to install pre-configured Cursor keybindings
# Details:
This task has two main components:\n\n1. Add `--json` flag to all relevant CLI commands:\n - Modify the CLI command handlers to check for a `--json` flag\n - When the flag is present, output the raw data from the MCP tools in JSON format instead of formatting for human readability\n - Ensure consistent JSON schema across all commands\n - Add documentation for this feature in the help text for each command\n - Test with common scenarios like `task-master next --json` and `task-master show <id> --json`\n\n2. Create a new `install-keybindings` command:\n - Create a new CLI command that installs pre-configured Taskmaster keybindings to Cursor\n - Detect the user's OS to determine the correct path to Cursor's keybindings.json\n - Check if the file exists; create it if it doesn't\n - Add useful Taskmaster keybindings like:\n - Quick access to next task with output to clipboard\n - Task status updates\n - Opening new agent chat with context from the current task\n - Implement safeguards to prevent duplicate keybindings\n - Add undo functionality or backup of previous keybindings\n - Support custom key combinations via command flags
# Test Strategy:
1. JSON output testing:\n - Unit tests for each command with the --json flag\n - Verify JSON schema consistency across commands\n - Validate that all necessary task data is included in the JSON output\n - Test piping output to other commands like jq\n\n2. Keybindings command testing:\n - Test on different OSes (macOS, Windows, Linux)\n - Verify correct path detection for Cursor's keybindings.json\n - Test behavior when file doesn't exist\n - Test behavior when existing keybindings conflict\n - Validate the installed keybindings work as expected\n - Test uninstall/restore functionality
# Subtasks:
## 1. Implement Core JSON Output Logic for `next` and `show` Commands [pending]
### Dependencies: None
### Description: Modify the command handlers for `task-master next` and `task-master show <id>` to recognize and handle a `--json` flag. When the flag is present, output the raw data received from MCP tools directly as JSON.
### Details:
1. Update the CLI argument parser to add the `--json` boolean flag to both commands
2. Create a `formatAsJson` utility function in `src/utils/output.js` that takes a data object and returns a properly formatted JSON string
3. In the command handler functions (`src/commands/next.js` and `src/commands/show.js`), add a conditional check for the `--json` flag
4. If the flag is set, call the `formatAsJson` function with the raw data object and print the result
5. If the flag is not set, continue with the existing human-readable formatting logic
6. Ensure proper error handling for JSON serialization failures
7. Update the command help text in both files to document the new flag
## 2. Extend JSON Output to All Relevant Commands and Ensure Schema Consistency [pending]
### Dependencies: 67.1
### Description: Apply the JSON output pattern established in subtask 1 to all other relevant Taskmaster CLI commands that display data (e.g., `list`, `status`, etc.). Ensure the JSON structure is consistent where applicable (e.g., task objects should have the same fields). Add help text mentioning the `--json` flag for each modified command.
### Details:
1. Create a JSON schema definition file at `src/schemas/task.json` to define the standard structure for task objects
2. Modify the following command files to support the `--json` flag:
- `src/commands/list.js`
- `src/commands/status.js`
- `src/commands/search.js`
- `src/commands/summary.js`
3. Refactor the `formatAsJson` utility to handle different data types (single task, task array, status object, etc.)
4. Add a `validateJsonSchema` function in `src/utils/validation.js` to ensure output conforms to defined schemas
5. Update each command's help text documentation to include the `--json` flag description
6. Implement consistent error handling for JSON output (using a standard error object format)
7. For list-type commands, ensure array outputs are properly formatted as JSON arrays
## 3. Create `install-keybindings` Command Structure and OS Detection [pending]
### Dependencies: None
### Description: Set up the basic structure for the new `task-master install-keybindings` command. Implement logic to detect the user's operating system (Linux, macOS, Windows) and determine the default path to Cursor's `keybindings.json` file.
### Details:
1. Create a new command file at `src/commands/install-keybindings.js`
2. Register the command in the main CLI entry point (`src/index.js`)
3. Implement OS detection using `os.platform()` in Node.js
4. Define the following path constants in `src/config/paths.js`:
- Windows: `%APPDATA%\Cursor\User\keybindings.json`
- macOS: `~/Library/Application Support/Cursor/User/keybindings.json`
- Linux: `~/.config/Cursor/User/keybindings.json`
5. Create a `getCursorKeybindingsPath()` function that returns the appropriate path based on detected OS
6. Add path override capability via a `--path` command line option
7. Implement proper error handling for unsupported operating systems
8. Add detailed help text explaining the command's purpose and options
## 4. Implement Keybinding File Handling and Backup Logic [pending]
### Dependencies: 67.3
### Description: Implement the core logic within the `install-keybindings` command to read the target `keybindings.json` file. If it exists, create a backup. If it doesn't exist, create a new file with an empty JSON array `[]`. Prepare the structure to add new keybindings.
### Details:
1. Create a `KeybindingsManager` class in `src/utils/keybindings.js` with the following methods:
- `checkFileExists(path)`: Verify if the keybindings file exists
- `createBackup(path)`: Copy existing file to `keybindings.json.bak`
- `readKeybindings(path)`: Read and parse the JSON file
- `writeKeybindings(path, data)`: Serialize and write data to the file
- `createEmptyFile(path)`: Create a new file with `[]` content
2. In the command handler, use these methods to:
- Check if the target file exists
- Create a backup if it does (with timestamp in filename)
- Read existing keybindings or create an empty file
- Parse the JSON content with proper error handling
3. Add a `--no-backup` flag to skip backup creation
4. Implement verbose logging with a `--verbose` flag
5. Handle all potential file system errors (permissions, disk space, etc.)
6. Add a `--dry-run` option that shows what would be done without making changes
## 5. Add Taskmaster Keybindings, Prevent Duplicates, and Support Customization [pending]
### Dependencies: 67.4
### Description: Define the specific Taskmaster keybindings (e.g., next task to clipboard, status update, open agent chat) and implement the logic to merge them into the user's `keybindings.json` data. Prevent adding duplicate keybindings (based on command ID or key combination). Add support for custom key combinations via command flags.
### Details:
1. Define default Taskmaster keybindings in `src/config/default-keybindings.js` as an array of objects with:
- `key`: Default key combination (e.g., `"ctrl+alt+n"`)
- `command`: Cursor command ID (e.g., `"taskmaster.nextTask"`)
- `when`: Context when keybinding is active (e.g., `"editorTextFocus"`)
- `args`: Any command arguments as an object
- `description`: Human-readable description of what the keybinding does
2. Implement the following keybindings:
- Next task to clipboard: `ctrl+alt+n`
- Update task status: `ctrl+alt+u`
- Open agent chat with task context: `ctrl+alt+a`
- Show task details: `ctrl+alt+d`
3. Add command-line options to customize each keybinding:
- `--next-key="ctrl+alt+n"`
- `--update-key="ctrl+alt+u"`
- `--agent-key="ctrl+alt+a"`
- `--details-key="ctrl+alt+d"`
4. Implement a `mergeKeybindings(existing, new)` function that:
- Checks for duplicates based on command ID
- Checks for key combination conflicts
- Warns about conflicts but allows override with `--force` flag
- Preserves existing non-Taskmaster keybindings
5. Add a `--reset` flag to remove all existing Taskmaster keybindings before adding new ones
6. Add a `--list` option to display currently installed Taskmaster keybindings
7. Implement an `--uninstall` option to remove all Taskmaster keybindings

View File

@@ -1,25 +0,0 @@
# Task ID: 68
# Title: Ability to create tasks without parsing PRD
# Status: done
# Dependencies: None
# Priority: medium
# Description: Which just means that when we create a task, if there's no tasks.json, we should create it calling the same function that is done by parse-prd. this lets taskmaster be used without a prd as a starding point.
# Details:
# Test Strategy:
# Subtasks:
## 1. Design task creation form without PRD [done]
### Dependencies: None
### Description: Create a user interface form that allows users to manually input task details without requiring a PRD document
### Details:
Design a form with fields for task title, description, priority, assignee, due date, and other relevant task attributes. Include validation to ensure required fields are completed. The form should be intuitive and provide clear guidance on how to create a task manually.
## 2. Implement task saving functionality [done]
### Dependencies: 68.1
### Description: Develop the backend functionality to save manually created tasks to the database
### Details:
Create API endpoints to handle task creation requests from the frontend. Implement data validation, error handling, and confirmation messages. Ensure the saved tasks appear in the task list view and can be edited or deleted like PRD-parsed tasks.

View File

@@ -1,97 +0,0 @@
# Task ID: 69
# Title: Enhance Analyze Complexity for Specific Task IDs
# Status: done
# Dependencies: None
# Priority: medium
# Description: Modify the analyze-complexity feature (CLI and MCP) to allow analyzing only specified task IDs or ranges, and append/update results in the report.
# Details:
Implementation Plan:
1. **Core Logic (`scripts/modules/task-manager/analyze-task-complexity.js`)**
* Modify function signature to accept optional parameters: `options.ids` (string, comma-separated IDs) and range parameters `options.from` and `options.to`.
* If `options.ids` is present:
* Parse the `ids` string into an array of target IDs.
* Filter `tasksData.tasks` to include only tasks matching the target IDs.
* Handle cases where provided IDs don't exist in `tasks.json`.
* If range parameters (`options.from` and `options.to`) are present:
* Parse these values into integers.
* Filter tasks within the specified ID range (inclusive).
* If neither `options.ids` nor range parameters are present: Continue with existing logic (filtering by active status).
* Maintain existing logic for skipping completed tasks.
* **Report Handling:**
* Before generating analysis, check if the `outputPath` report file exists.
* If it exists:
* Read the existing `complexityAnalysis` array.
* Generate new analysis only for target tasks (filtered by ID or range).
* Merge results: Remove entries from the existing array that match IDs analyzed in the current run, then append new analysis results to the array.
* Update the `meta` section (`generatedAt`, `tasksAnalyzed`).
* Write merged `complexityAnalysis` and updated `meta` back to report file.
* If the report file doesn't exist: Create it as usual.
* **Prompt Generation:** Ensure `generateInternalComplexityAnalysisPrompt` receives correctly filtered list of tasks.
2. **CLI (`scripts/modules/commands.js`)**
* Add new options to the `analyze-complexity` command:
* `--id/-i <ids>`: "Comma-separated list of specific task IDs to analyze"
* `--from/-f <startId>`: "Start ID for range analysis (inclusive)"
* `--to/-t <endId>`: "End ID for range analysis (inclusive)"
* In the `.action` handler:
* Check if `options.id`, `options.from`, or `options.to` are provided.
* If yes, pass appropriate values to the `analyzeTaskComplexity` core function via the `options` object.
* Update user feedback messages to indicate specific task analysis.
3. **MCP Tool (`mcp-server/src/tools/analyze.js`)**
* Add new optional parameters to Zod schema for `analyze_project_complexity` tool:
* `ids: z.string().optional().describe("Comma-separated list of task IDs to analyze specifically")`
* `from: z.number().optional().describe("Start ID for range analysis (inclusive)")`
* `to: z.number().optional().describe("End ID for range analysis (inclusive)")`
* In the `execute` method, pass `args.ids`, `args.from`, and `args.to` to the `analyzeTaskComplexityDirect` function within its `args` object.
4. **Direct Function (`mcp-server/src/core/direct-functions/analyze-task-complexity.js`)**
* Update function to receive `ids`, `from`, and `to` values within the `args` object.
* Pass these values along to the core `analyzeTaskComplexity` function within its `options` object.
5. **Documentation:** Update relevant rule files (`commands.mdc`, `taskmaster.mdc`) to reflect new `--id/-i`, `--from/-f`, and `--to/-t` options/parameters.
# Test Strategy:
1. **CLI:**
* Run `task-master analyze-complexity -i=<id1>` (where report doesn't exist). Verify report created with only task id1.
* Run `task-master analyze-complexity -i=<id2>` (where report exists). Verify report updated, containing analysis for both id1 and id2 (id2 replaces any previous id2 analysis).
* Run `task-master analyze-complexity -i=<id1>,<id3>`. Verify report updated, containing id1, id2, id3.
* Run `task-master analyze-complexity -f=50 -t=60`. Verify report created/updated with tasks in the range 50-60.
* Run `task-master analyze-complexity` (no flags). Verify it analyzes all active tasks and updates the report accordingly, merging with previous specific analyses.
* Test with invalid/non-existent IDs or ranges.
* Verify that completed tasks are still skipped in all scenarios, maintaining existing behavior.
2. **MCP:**
* Call `analyze_project_complexity` tool with `ids: "<id1>"`. Verify report creation/update.
* Call `analyze_project_complexity` tool with `ids: "<id1>,<id2>,<id3>"`. Verify report created/updated with multiple specific tasks.
* Call `analyze_project_complexity` tool with `from: 50, to: 60`. Verify report created/updated for tasks in range.
* Call `analyze_project_complexity` tool without parameters. Verify full analysis and merging.
3. Verify report `meta` section is updated correctly on each run.
# Subtasks:
## 1. Modify core complexity analysis logic [done]
### Dependencies: None
### Description: Update the core complexity analysis function to accept specific task IDs or ranges as input parameters
### Details:
Refactor the existing complexity analysis module to allow filtering by task IDs or ranges. This involves modifying the data processing pipeline to filter tasks before analysis, ensuring the complexity metrics are calculated only for the specified tasks while maintaining context awareness.
## 2. Update CLI interface for task-specific complexity analysis [done]
### Dependencies: 69.1
### Description: Extend the CLI to accept task IDs or ranges as parameters for the complexity analysis command
### Details:
Add new flags `--id/-i`, `--from/-f`, and `--to/-t` to the CLI that allow users to specify task IDs or ranges for targeted complexity analysis. Update the command parser, help documentation, and ensure proper validation of the provided values.
## 3. Integrate task-specific analysis with MCP tool [done]
### Dependencies: 69.1
### Description: Update the MCP tool interface to support analyzing complexity for specific tasks or ranges
### Details:
Modify the MCP tool's API endpoints and UI components to allow users to select specific tasks or ranges for complexity analysis. Ensure the UI provides clear feedback about which tasks are being analyzed and update the visualization components to properly display partial analysis results.
## 4. Create comprehensive tests for task-specific complexity analysis [done]
### Dependencies: 69.1, 69.2, 69.3
### Description: Develop test cases to verify the correct functioning of task-specific complexity analysis
### Details:
Create unit and integration tests that verify the task-specific complexity analysis works correctly across both CLI and MCP interfaces. Include tests for edge cases such as invalid task IDs, tasks with dependencies outside the selected set, and performance tests for large task sets.

View File

@@ -1,37 +0,0 @@
# Task ID: 70
# Title: Implement 'diagram' command for Mermaid diagram generation
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Develop a CLI command named 'diagram' that generates Mermaid diagrams to visualize task dependencies and workflows, with options to target specific tasks or generate comprehensive diagrams for all tasks.
# Details:
The task involves implementing a new command that accepts an optional '--id' parameter: if provided, the command generates a diagram illustrating the chosen task and its dependencies; if omitted, it produces a diagram that includes all tasks. The diagrams should use color coding to reflect task status and arrows to denote dependencies. In addition to CLI rendering, the command should offer an option to save the output as a Markdown (.md) file. Consider integrating with the existing task management system to pull task details and status. Pay attention to formatting consistency and error handling for invalid or missing task IDs. Comments should be added to the code to improve maintainability, and unit tests should cover edge cases such as cyclic dependencies, missing tasks, and invalid input formats.
# Test Strategy:
Verify the command functionality by testing with both specific task IDs and general invocation: 1) Run the command with a valid '--id' and ensure the resulting diagram accurately depicts the specified task's dependencies with correct color codings for statuses. 2) Execute the command without '--id' to ensure a complete workflow diagram is generated for all tasks. 3) Check that arrows correctly represent dependency relationships. 4) Validate the Markdown (.md) file export option by confirming the file format and content after saving. 5) Test error responses for non-existent task IDs and malformed inputs.
# Subtasks:
## 1. Design the 'diagram' command interface [pending]
### Dependencies: None
### Description: Define the command structure, arguments, and options for the Mermaid diagram generation feature
### Details:
Create a command specification that includes: input parameters for diagram source (file, stdin, or string), output options (file, stdout, clipboard), format options (SVG, PNG, PDF), styling parameters, and help documentation. Consider compatibility with existing command patterns in the application.
## 2. Implement Mermaid diagram generation core functionality [pending]
### Dependencies: 70.1
### Description: Create the core logic to parse Mermaid syntax and generate diagram output
### Details:
Integrate with the Mermaid library to parse diagram syntax. Implement error handling for invalid syntax. Create the rendering pipeline to generate the diagram in memory before output. Support all standard Mermaid diagram types (flowchart, sequence, class, etc.). Include proper logging for the generation process.
## 3. Develop output handling mechanisms [pending]
### Dependencies: 70.2
### Description: Implement different output options for the generated diagrams
### Details:
Create handlers for different output formats (SVG, PNG, PDF). Implement file output with appropriate naming conventions and directory handling. Add clipboard support for direct pasting. Implement stdout output for piping to other commands. Include progress indicators for longer rendering operations.
## 4. Create documentation and examples [pending]
### Dependencies: 70.3
### Description: Provide comprehensive documentation and examples for the 'diagram' command
### Details:
Write detailed command documentation with all options explained. Create example diagrams covering different diagram types. Include troubleshooting section for common errors. Add documentation on extending the command with custom themes or templates. Create integration examples showing how to use the command in workflows with other tools.

View File

@@ -1,23 +0,0 @@
# Task ID: 71
# Title: Add Model-Specific maxTokens Override Configuration
# Status: done
# Dependencies: None
# Priority: high
# Description: Implement functionality to allow specifying a maximum token limit for individual AI models within .taskmasterconfig, overriding the role-based maxTokens if the model-specific limit is lower.
# Details:
1. **Modify `.taskmasterconfig` Structure:** Add a new top-level section `modelOverrides` (e.g., `"modelOverrides": { "o3-mini": { "maxTokens": 100000 } }`).
2. **Update `config-manager.js`:**
- Modify config loading to read the new `modelOverrides` section.
- Update `getParametersForRole(role)` logic: Fetch role defaults (roleMaxTokens, temperature). Get the modelId for the role. Look up `modelOverrides[modelId].maxTokens` (modelSpecificMaxTokens). Calculate `effectiveMaxTokens = Math.min(roleMaxTokens, modelSpecificMaxTokens ?? Infinity)`. Return `{ maxTokens: effectiveMaxTokens, temperature }`.
3. **Update Documentation:** Add an example of `modelOverrides` to `.taskmasterconfig.example` or relevant documentation.
# Test Strategy:
1. **Unit Tests (`config-manager.js`):**
- Verify `getParametersForRole` returns role defaults when no override exists.
- Verify `getParametersForRole` returns the lower model-specific limit when an override exists and is lower.
- Verify `getParametersForRole` returns the role limit when an override exists but is higher.
- Verify handling of missing `modelOverrides` section.
2. **Integration Tests (`ai-services-unified.js`):**
- Call an AI service (e.g., `generateTextService`) with a config having a model override.
- Mock the underlying provider function.
- Assert that the `maxTokens` value passed to the mocked provider function matches the expected (potentially overridden) minimum value.

View File

@@ -1,49 +0,0 @@
# Task ID: 72
# Title: Implement PDF Generation for Project Progress and Dependency Overview
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Develop a feature to generate a PDF report summarizing the current project progress and visualizing the dependency chain of tasks.
# Details:
This task involves creating a new CLI command named 'progress-pdf' within the existing project framework to generate a PDF document. The PDF should include: 1) A summary of project progress, detailing completed, in-progress, and pending tasks with their respective statuses and completion percentages if applicable. 2) A visual representation of the task dependency chain, leveraging the output format from the 'diagram' command (Task 70) to include Mermaid diagrams or similar visualizations converted to image format for PDF embedding. Use a suitable PDF generation library (e.g., jsPDF for JavaScript environments or ReportLab for Python) compatible with the projects tech stack. Ensure the command accepts optional parameters to filter tasks by status or ID for customized reports. Handle large dependency chains by implementing pagination or zoomable image sections in the PDF. Provide error handling for cases where diagram generation or PDF creation fails, logging detailed error messages for debugging. Consider accessibility by ensuring text in the PDF is selectable and images have alt text descriptions. Integrate this feature with the existing CLI structure, ensuring it aligns with the projects configuration settings (e.g., output directory for generated files). Document the command usage and parameters in the projects help or README file.
# Test Strategy:
Verify the completion of this task through a multi-step testing approach: 1) Unit Tests: Create tests for the PDF generation logic to ensure data (task statuses and dependencies) is correctly fetched and formatted. Mock the PDF library to test edge cases like empty task lists or broken dependency links. 2) Integration Tests: Run the 'progress-pdf' command via CLI to confirm it generates a PDF file without errors under normal conditions, with filtered task IDs, and with various status filters. Validate that the output file exists in the specified directory and can be opened. 3) Content Validation: Manually or via automated script, check the generated PDF content to ensure it accurately reflects the current project state (compare task counts and statuses against a known project state) and includes dependency diagrams as images. 4) Error Handling Tests: Simulate failures in diagram generation or PDF creation (e.g., invalid output path, library errors) and verify that appropriate error messages are logged and the command exits gracefully. 5) Accessibility Checks: Use a PDF accessibility tool or manual inspection to confirm that text is selectable and images have alt text. Run these tests across different project sizes (small with few tasks, large with complex dependencies) to ensure scalability. Document test results and include a sample PDF output in the project repository for reference.
# Subtasks:
## 1. Research and select PDF generation library [pending]
### Dependencies: None
### Description: Evaluate available PDF generation libraries for Node.js that can handle diagrams and formatted text
### Details:
Compare libraries like PDFKit, jsPDF, and Puppeteer based on features, performance, and ease of integration. Consider compatibility with diagram visualization tools. Document findings and make a recommendation with justification.
## 2. Design PDF template and layout [pending]
### Dependencies: 72.1
### Description: Create a template design for the project progress PDF including sections for summary, metrics, and dependency visualization
### Details:
Design should include header/footer, progress summary section, key metrics visualization, dependency diagram placement, and styling guidelines. Create a mockup of the final PDF output for approval.
## 3. Implement project progress data collection module [pending]
### Dependencies: 72.1
### Description: Develop functionality to gather and process project data for the PDF report
### Details:
Create functions to extract task completion percentages, milestone status, timeline adherence, and other relevant metrics from the project database. Include data transformation logic to prepare for PDF rendering.
## 4. Integrate with dependency visualization system [pending]
### Dependencies: 72.1, 72.3
### Description: Connect to the existing diagram command to generate visual representation of task dependencies
### Details:
Implement adapter for the diagram command output to be compatible with the PDF generation library. Handle different scales of dependency chains and ensure proper rendering of complex relationships.
## 5. Build PDF generation core functionality [pending]
### Dependencies: 72.2, 72.3, 72.4
### Description: Develop the main module that combines data and visualizations into a formatted PDF document
### Details:
Implement the core PDF generation logic using the selected library. Include functions for adding text sections, embedding visualizations, formatting tables, and applying the template design. Add pagination and document metadata.
## 6. Create export options and command interface [pending]
### Dependencies: 72.5
### Description: Implement user-facing commands and options for generating and saving PDF reports
### Details:
Develop CLI commands for PDF generation with parameters for customization (time period, detail level, etc.). Include options for automatic saving to specified locations, email distribution, and integration with existing project workflows.

View File

@@ -1,44 +0,0 @@
# Task ID: 73
# Title: Implement Custom Model ID Support for Ollama/OpenRouter
# Status: done
# Dependencies: None
# Priority: medium
# Description: Allow users to specify custom model IDs for Ollama and OpenRouter providers via CLI flag and interactive setup, with appropriate validation and warnings.
# Details:
**CLI (`task-master models --set-<role> <id> --custom`):**
- Modify `scripts/modules/task-manager/models.js`: `setModel` function.
- Check internal `available_models.json` first.
- If not found and `--custom` is provided:
- Fetch `https://openrouter.ai/api/v1/models`. (Need to add `https` import).
- If ID found in OpenRouter list: Set `provider: 'openrouter'`, `modelId: <id>`. Warn user about lack of official validation.
- If ID not found in OpenRouter: Assume Ollama. Set `provider: 'ollama'`, `modelId: <id>`. Warn user strongly (model must be pulled, compatibility not guaranteed).
- If not found and `--custom` is *not* provided: Fail with error message guiding user to use `--custom`.
**Interactive Setup (`task-master models --setup`):**
- Modify `scripts/modules/commands.js`: `runInteractiveSetup` function.
- Add options to `inquirer` choices for each role: `OpenRouter (Enter Custom ID)` and `Ollama (Enter Custom ID)`.
- If `__CUSTOM_OPENROUTER__` selected:
- Prompt for custom ID.
- Fetch OpenRouter list and validate ID exists. Fail setup for that role if not found.
- Update config and show warning if found.
- If `__CUSTOM_OLLAMA__` selected:
- Prompt for custom ID.
- Update config directly (no live validation).
- Show strong Ollama warning.
# Test Strategy:
**Unit Tests:**
- Test `setModel` logic for internal models, custom OpenRouter (valid/invalid), custom Ollama, missing `--custom` flag.
- Test `runInteractiveSetup` for new custom options flow, including OpenRouter validation success/failure.
**Integration Tests:**
- Test the `task-master models` command with `--custom` flag variations.
- Test the `task-master models --setup` interactive flow for custom options.
**Manual Testing:**
- Run `task-master models --setup` and select custom options.
- Run `task-master models --set-main <valid_openrouter_id> --custom`. Verify config and warning.
- Run `task-master models --set-main <invalid_openrouter_id> --custom`. Verify error.
- Run `task-master models --set-main <ollama_model_id> --custom`. Verify config and warning.
- Run `task-master models --set-main <custom_id>` (without `--custom`). Verify error.
- Check `getModelConfiguration` output reflects custom models correctly.

View File

@@ -1,19 +0,0 @@
# Task ID: 74
# Title: PR Review: better-model-management
# Status: done
# Dependencies: None
# Priority: medium
# Description: will add subtasks
# Details:
# Test Strategy:
# Subtasks:
## 1. pull out logWrapper into utils [done]
### Dependencies: None
### Description: its being used a lot across direct functions and repeated right now
### Details:

View File

@@ -1,37 +0,0 @@
# Task ID: 75
# Title: Integrate Google Search Grounding for Research Role
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Update the AI service layer to enable Google Search Grounding specifically when a Google model is used in the 'research' role.
# Details:
**Goal:** Conditionally enable Google Search Grounding based on the AI role.\n\n**Implementation Plan:**\n\n1. **Modify `ai-services-unified.js`:** Update `generateTextService`, `streamTextService`, and `generateObjectService`.\n2. **Conditional Logic:** Inside these functions, check if `providerName === 'google'` AND `role === 'research'`.\n3. **Construct `providerOptions`:** If the condition is met, create an options object:\n ```javascript\n let providerSpecificOptions = {};\n if (providerName === 'google' && role === 'research') {\n log('info', 'Enabling Google Search Grounding for research role.');\n providerSpecificOptions = {\n google: {\n useSearchGrounding: true,\n // Optional: Add dynamic retrieval for compatible models\n // dynamicRetrievalConfig: { mode: 'MODE_DYNAMIC' } \n }\n };\n }\n ```\n4. **Pass Options to SDK:** Pass `providerSpecificOptions` to the Vercel AI SDK functions (`generateText`, `streamText`, `generateObject`) via the `providerOptions` parameter:\n ```javascript\n const { text, ... } = await generateText({\n // ... other params\n providerOptions: providerSpecificOptions \n });\n ```\n5. **Update `supported-models.json`:** Ensure Google models intended for research (e.g., `gemini-1.5-pro-latest`, `gemini-1.5-flash-latest`) include `'research'` in their `allowed_roles` array.\n\n**Rationale:** This approach maintains the clear separation between 'main' and 'research' roles, ensuring grounding is only activated when explicitly requested via the `--research` flag or when the research model is invoked.\n\n**Clarification:** The Search Grounding feature is specifically designed to provide up-to-date information from the web when using Google models. This implementation ensures that grounding is only activated in research contexts where current information is needed, while preserving normal operation for standard tasks. The `useSearchGrounding: true` flag instructs the Google API to augment the model's knowledge with recent web search results relevant to the query.
# Test Strategy:
1. Configure a Google model (e.g., gemini-1.5-flash-latest) as the 'research' model in `.taskmasterconfig`.\n2. Run a command with the `--research` flag (e.g., `task-master add-task --prompt='Latest news on AI SDK 4.2' --research`).\n3. Verify logs show 'Enabling Google Search Grounding'.\n4. Check if the task output incorporates recent information.\n5. Configure the same Google model as the 'main' model.\n6. Run a command *without* the `--research` flag.\n7. Verify logs *do not* show grounding being enabled.\n8. Add unit tests to `ai-services-unified.test.js` to verify the conditional logic for adding `providerOptions`. Ensure mocks correctly simulate different roles and providers.
# Subtasks:
## 1. Modify AI service layer to support Google Search Grounding [pending]
### Dependencies: None
### Description: Update the AI service layer to include the capability to integrate with Google Search Grounding API for research-related queries.
### Details:
Extend the existing AI service layer by adding new methods and interfaces to handle Google Search Grounding API calls. This includes creating authentication mechanisms, request formatters, and response parsers specific to the Google Search API. Ensure proper error handling and retry logic for API failures.
## 2. Implement conditional logic for research role detection [pending]
### Dependencies: 75.1
### Description: Create logic to detect when a conversation is in 'research mode' and should trigger the Google Search Grounding functionality.
### Details:
Develop heuristics or machine learning-based detection to identify when a user's query requires research capabilities. Implement a decision tree that determines when to activate Google Search Grounding based on conversation context, explicit user requests for research, or specific keywords. Include configuration options to adjust sensitivity of the detection mechanism.
## 3. Update supported models configuration [pending]
### Dependencies: 75.1
### Description: Modify the model configuration to specify which AI models can utilize the Google Search Grounding capability.
### Details:
Update the model configuration files to include flags for Google Search Grounding compatibility. Create a registry of supported models with their specific parameters for optimal integration with the search API. Implement version checking to ensure compatibility between model versions and the Google Search Grounding API version.
## 4. Create end-to-end testing suite for research functionality [pending]
### Dependencies: 75.1, 75.2, 75.3
### Description: Develop comprehensive tests to verify the correct operation of the Google Search Grounding integration in research contexts.
### Details:
Build automated test cases that cover various research scenarios, including edge cases. Create mock responses for the Google Search API to enable testing without actual API calls. Implement integration tests that verify the entire flow from user query to research-enhanced response. Include performance benchmarks to ensure the integration doesn't significantly impact response times.

View File

@@ -1,103 +0,0 @@
# Task ID: 76
# Title: Develop E2E Test Framework for Taskmaster MCP Server (FastMCP over stdio)
# Status: pending
# Dependencies: None
# Priority: high
# Description: Design and implement an end-to-end (E2E) test framework for the Taskmaster MCP server, enabling programmatic interaction with the FastMCP server over stdio by sending and receiving JSON tool request/response messages.
# Details:
Research existing E2E testing approaches for MCP servers, referencing examples such as the MCP Server E2E Testing Example. Architect a test harness (preferably in Python or Node.js) that can launch the FastMCP server as a subprocess, establish stdio communication, and send well-formed JSON tool request messages.
Implementation details:
1. Use `subprocess.Popen` (Python) or `child_process.spawn` (Node.js) to launch the FastMCP server with appropriate stdin/stdout pipes
2. Implement a message protocol handler that formats JSON requests with proper line endings and message boundaries
3. Create a buffered reader for stdout that correctly handles chunked responses and reconstructs complete JSON objects
4. Develop a request/response correlation mechanism using unique IDs for each request
5. Implement timeout handling for requests that don't receive responses
Implement robust parsing of JSON responses, including error handling for malformed or unexpected output. The framework should support defining test cases as scripts or data files, allowing for easy addition of new scenarios.
Test case structure should include:
- Setup phase for environment preparation
- Sequence of tool requests with expected responses
- Validation functions for response verification
- Teardown phase for cleanup
Ensure the framework can assert on both the structure and content of responses, and provide clear logging for debugging. Document setup, usage, and extension instructions. Consider cross-platform compatibility and CI integration.
**Clarification:** The E2E test framework should focus on testing the FastMCP server's ability to correctly process tool requests and return appropriate responses. This includes verifying that the server properly handles different types of tool calls (e.g., file operations, web requests, task management), validates input parameters, and returns well-structured responses. The framework should be designed to be extensible, allowing new test cases to be added as the server's capabilities evolve. Tests should cover both happy paths and error conditions to ensure robust server behavior under various scenarios.
# Test Strategy:
Verify the framework by implementing a suite of representative E2E tests that cover typical tool requests and edge cases. Specific test cases should include:
1. Basic tool request/response validation
- Send a simple file_read request and verify response structure
- Test with valid and invalid file paths
- Verify error handling for non-existent files
2. Concurrent request handling
- Send multiple requests in rapid succession
- Verify all responses are received and correlated correctly
3. Large payload testing
- Test with large file contents (>1MB)
- Verify correct handling of chunked responses
4. Error condition testing
- Malformed JSON requests
- Invalid tool names
- Missing required parameters
- Server crash recovery
Confirm that tests can start and stop the FastMCP server, send requests, and accurately parse and validate responses. Implement specific assertions for response timing, structure validation using JSON schema, and content verification. Intentionally introduce malformed requests and simulate server errors to ensure robust error handling.
Implement detailed logging with different verbosity levels:
- ERROR: Failed tests and critical issues
- WARNING: Unexpected but non-fatal conditions
- INFO: Test progress and results
- DEBUG: Raw request/response data
Run the test suite in a clean environment and confirm all expected assertions and logs are produced. Validate that new test cases can be added with minimal effort and that the framework integrates with CI pipelines. Create a CI configuration that runs tests on each commit.
# Subtasks:
## 1. Design E2E Test Framework Architecture [pending]
### Dependencies: None
### Description: Create a high-level design document for the E2E test framework that outlines components, interactions, and test flow
### Details:
Define the overall architecture of the test framework, including test runner, FastMCP server launcher, message protocol handler, and assertion components. Document how these components will interact and the data flow between them. Include error handling strategies and logging requirements.
## 2. Implement FastMCP Server Launcher [pending]
### Dependencies: 76.1
### Description: Create a component that can programmatically launch and manage the FastMCP server process over stdio
### Details:
Develop a module that can spawn the FastMCP server as a child process, establish stdio communication channels, handle process lifecycle events, and implement proper cleanup procedures. Include error handling for process failures and timeout mechanisms.
## 3. Develop Message Protocol Handler [pending]
### Dependencies: 76.1
### Description: Implement a handler that can serialize/deserialize messages according to the FastMCP protocol specification
### Details:
Create a protocol handler that formats outgoing messages and parses incoming messages according to the FastMCP protocol. Implement validation for message format compliance and error handling for malformed messages. Support all required message types defined in the protocol.
## 4. Create Request/Response Correlation Mechanism [pending]
### Dependencies: 76.3
### Description: Implement a system to track and correlate requests with their corresponding responses
### Details:
Develop a correlation mechanism using unique identifiers to match requests with their responses. Implement timeout handling for unresponded requests and proper error propagation. Design the API to support both synchronous and asynchronous request patterns.
## 5. Build Test Assertion Framework [pending]
### Dependencies: 76.3, 76.4
### Description: Create a set of assertion utilities specific to FastMCP server testing
### Details:
Develop assertion utilities that can validate server responses against expected values, verify timing constraints, and check for proper error handling. Include support for complex response validation patterns and detailed failure reporting.
## 6. Implement Test Cases [pending]
### Dependencies: 76.2, 76.4, 76.5
### Description: Develop a comprehensive set of test cases covering all FastMCP server functionality
### Details:
Create test cases for basic server operations, error conditions, edge cases, and performance scenarios. Organize tests into logical groups and ensure proper isolation between test cases. Include documentation for each test explaining its purpose and expected outcomes.
## 7. Create CI Integration and Documentation [pending]
### Dependencies: 76.6
### Description: Set up continuous integration for the test framework and create comprehensive documentation
### Details:
Configure the test framework to run in CI environments, generate reports, and fail builds appropriately. Create documentation covering framework architecture, usage instructions, test case development guidelines, and troubleshooting procedures. Include examples of extending the framework for new test scenarios.

View File

@@ -1,594 +0,0 @@
# Task ID: 77
# Title: Implement AI Usage Telemetry for Taskmaster (with external analytics endpoint)
# Status: done
# Dependencies: None
# Priority: medium
# Description: Capture detailed AI usage data (tokens, costs, models, commands) within Taskmaster and send this telemetry to an external, closed-source analytics backend for usage analysis, profitability measurement, and pricing optimization.
# Details:
* Add a telemetry utility (`logAiUsage`) within `ai-services.js` to track AI usage.
* Collected telemetry data fields must include:
* `timestamp`: Current date/time in ISO 8601.
* `userId`: Unique user identifier generated at setup (stored in `.taskmasterconfig`).
* `commandName`: Taskmaster command invoked (`expand`, `parse-prd`, `research`, etc.).
* `modelUsed`: Name/ID of the AI model invoked.
* `inputTokens`: Count of input tokens used.
* `outputTokens`: Count of output tokens generated.
* `totalTokens`: Sum of input and output tokens.
* `totalCost`: Monetary cost calculated using pricing from `supported_models.json`.
* Send telemetry payload securely via HTTPS POST request from user's Taskmaster installation directly to the closed-source analytics API (Express/Supabase backend).
* Introduce a privacy notice and explicit user consent prompt upon initial installation/setup to enable telemetry.
* Provide a graceful fallback if telemetry request fails (e.g., no internet connectivity).
* Optionally display a usage summary directly in Taskmaster CLI output for user transparency.
# Test Strategy:
# Subtasks:
## 1. Implement telemetry utility and data collection [done]
### Dependencies: None
### Description: Create the logAiUsage utility in ai-services.js that captures all required telemetry data fields
### Details:
Develop the logAiUsage function that collects timestamp, userId, commandName, modelUsed, inputTokens, outputTokens, totalTokens, and totalCost. Implement token counting logic and cost calculation using pricing from supported_models.json. Ensure proper error handling and data validation.
<info added on 2025-05-05T21:08:51.413Z>
Develop the logAiUsage function that collects timestamp, userId, commandName, modelUsed, inputTokens, outputTokens, totalTokens, and totalCost. Implement token counting logic and cost calculation using pricing from supported_models.json. Ensure proper error handling and data validation.
Implementation Plan:
1. Define `logAiUsage` function in `ai-services-unified.js` that accepts parameters: userId, commandName, providerName, modelId, inputTokens, and outputTokens.
2. Implement data collection and calculation logic:
- Generate timestamp using `new Date().toISOString()`
- Calculate totalTokens by adding inputTokens and outputTokens
- Create a helper function `_getCostForModel(providerName, modelId)` that:
- Loads pricing data from supported-models.json
- Finds the appropriate provider/model entry
- Returns inputCost and outputCost rates or defaults if not found
- Calculate totalCost using the formula: ((inputTokens/1,000,000) * inputCost) + ((outputTokens/1,000,000) * outputCost)
- Assemble complete telemetryData object with all required fields
3. Add initial logging functionality:
- Use existing log utility to record telemetry data at 'info' level
- Implement proper error handling with try/catch blocks
4. Integrate with `_unifiedServiceRunner`:
- Modify to accept commandName and userId parameters
- After successful API calls, extract usage data from results
- Call logAiUsage with the appropriate parameters
5. Update provider functions in src/ai-providers/*.js:
- Ensure all provider functions return both the primary result and usage statistics
- Standardize the return format to include a usage object with inputTokens and outputTokens
</info added on 2025-05-05T21:08:51.413Z>
<info added on 2025-05-07T17:28:57.361Z>
To implement the AI usage telemetry effectively, we need to update each command across our different stacks. Let's create a structured approach for this implementation:
Command Integration Plan:
1. Core Function Commands:
- Identify all AI-utilizing commands in the core function library
- For each command, modify to pass commandName and userId to _unifiedServiceRunner
- Update return handling to process and forward usage statistics
2. Direct Function Commands:
- Map all direct function commands that leverage AI capabilities
- Implement telemetry collection at the appropriate execution points
- Ensure consistent error handling and telemetry reporting
3. MCP Tool Stack Commands:
- Inventory all MCP commands with AI dependencies
- Standardize the telemetry collection approach across the tool stack
- Add telemetry hooks that maintain backward compatibility
For each command category, we'll need to:
- Document current implementation details
- Define specific code changes required
- Create tests to verify telemetry is being properly collected
- Establish validation procedures to ensure data accuracy
</info added on 2025-05-07T17:28:57.361Z>
## 2. Implement secure telemetry transmission [deferred]
### Dependencies: 77.1
### Description: Create a secure mechanism to transmit telemetry data to the external analytics endpoint
### Details:
Implement HTTPS POST request functionality to securely send the telemetry payload to the closed-source analytics API. Include proper encryption in transit using TLS. Implement retry logic and graceful fallback mechanisms for handling transmission failures due to connectivity issues.
<info added on 2025-05-14T17:52:40.647Z>
To securely send structured JSON telemetry payloads from a Node.js CLI tool to an external analytics backend, follow these steps:
1. Use the Axios library for HTTPS POST requests. Install it with: npm install axios.
2. Store sensitive configuration such as the analytics endpoint URL and any secret keys in environment variables (e.g., process.env.ANALYTICS_URL, process.env.ANALYTICS_KEY). Use dotenv or a similar library to load these securely.
3. Construct the telemetry payload as a JSON object with the required fields: userId, commandName, modelUsed, inputTokens, outputTokens, totalTokens, totalCost, and timestamp (ISO 8601).
4. Implement robust retry logic using the axios-retry package (npm install axios-retry). Configure exponential backoff with a recommended maximum of 3 retries and a base delay (e.g., 500ms).
5. Ensure all requests use HTTPS to guarantee TLS encryption in transit. Axios automatically uses HTTPS when the endpoint URL starts with https://.
6. Handle errors gracefully: catch all transmission errors, log them for diagnostics, and ensure failures do not interrupt or degrade the CLI user experience. Optionally, queue failed payloads for later retry if persistent connectivity issues occur.
7. Example code snippet:
require('dotenv').config();
const axios = require('axios');
const axiosRetry = require('axios-retry');
axiosRetry(axios, {
retries: 3,
retryDelay: axiosRetry.exponentialDelay,
retryCondition: (error) => axiosRetry.isNetworkOrIdempotentRequestError(error),
});
async function sendTelemetry(payload) {
try {
await axios.post(process.env.ANALYTICS_URL, payload, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.ANALYTICS_KEY}`,
},
timeout: 5000,
});
} catch (error) {
// Log error, do not throw to avoid impacting CLI UX
console.error('Telemetry transmission failed:', error.message);
// Optionally, queue payload for later retry
}
}
const telemetryPayload = {
userId: 'user-123',
commandName: 'expand',
modelUsed: 'gpt-4',
inputTokens: 100,
outputTokens: 200,
totalTokens: 300,
totalCost: 0.0123,
timestamp: new Date().toISOString(),
};
sendTelemetry(telemetryPayload);
8. Best practices:
- Never hardcode secrets or endpoint URLs in source code.
- Use environment variables and restrict access permissions.
- Validate all payload fields before transmission.
- Ensure the CLI continues to function even if telemetry transmission fails.
References: [1][2][3][5]
</info added on 2025-05-14T17:52:40.647Z>
<info added on 2025-05-14T17:57:18.218Z>
User ID Retrieval and Generation:
The telemetry system must securely retrieve the user ID from the .taskmasterconfig globals, where it should have been generated during the initialization phase. Implementation should:
1. Check for an existing user ID in the .taskmasterconfig file before sending any telemetry data.
2. If no user ID exists (for users who run AI commands without prior initialization or during upgrades), automatically generate a new UUID v4 and persist it to the .taskmasterconfig file.
3. Implement a getOrCreateUserId() function that:
- Reads from the global configuration file
- Returns the existing ID if present
- Generates a cryptographically secure UUID v4 if not present
- Saves the newly generated ID to the configuration file
- Handles file access errors gracefully
4. Example implementation:
```javascript
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
function getOrCreateUserId() {
const configPath = path.join(os.homedir(), '.taskmasterconfig');
try {
// Try to read existing config
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
if (config.userId) {
return config.userId;
}
// No user ID found, generate and save
config.userId = uuidv4();
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
return config.userId;
} catch (error) {
// Handle case where config doesn't exist or is invalid
const userId = uuidv4();
const newConfig = { userId };
try {
fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));
} catch (writeError) {
console.error('Failed to save user ID to config:', writeError.message);
}
return userId;
}
}
```
5. Ensure this function is called before constructing any telemetry payload to guarantee a consistent user ID across all telemetry events.
</info added on 2025-05-14T17:57:18.218Z>
<info added on 2025-05-15T18:45:32.123Z>
**Invocation Point for Sending Telemetry:**
* The primary invocation for sending the telemetry payload should occur in `scripts/modules/ai-services-unified.js`.
* This should happen *after* the `telemetryData` object is fully constructed and *after* user consent (from subtask 77.3) has been confirmed.
**Dedicated Module for Transmission Logic:**
* The actual HTTPS POST request mechanism, including TLS encryption, retry logic, and graceful fallbacks, should be implemented in a new, separate module (e.g., `scripts/modules/telemetry-sender.js` or `scripts/utils/telemetry-client.js`).
* This module will be imported and utilized by `scripts/modules/ai-services-unified.js`.
**Key Considerations:**
* Robust error handling must be in place for the telemetry transmission process; failures should be logged locally and must not disrupt core application functionality.
* The entire telemetry sending process is contingent upon explicit user consent as outlined in subtask 77.3.
**Implementation Plan:**
1. Create a new module `scripts/utils/telemetry-client.js` with the following functions:
- `sendTelemetryData(telemetryPayload)`: Main function that handles the HTTPS POST request
- `isUserConsentGiven()`: Helper function to check if user has consented to telemetry
- `logTelemetryError(error)`: Helper function for consistent error logging
2. In `ai-services-unified.js`, after constructing the telemetryData object:
```javascript
const telemetryClient = require('../utils/telemetry-client');
// After telemetryData is constructed
if (telemetryClient.isUserConsentGiven()) {
// Non-blocking telemetry submission
telemetryClient.sendTelemetryData(telemetryData)
.catch(error => telemetryClient.logTelemetryError(error));
}
```
3. Ensure the telemetry-client module implements:
- Axios with retry logic for robust HTTP requests
- Proper TLS encryption via HTTPS
- Comprehensive error handling
- Configuration loading from environment variables
- Validation of payload data before transmission
</info added on 2025-05-15T18:45:32.123Z>
## 3. Develop user consent and privacy notice system [deferred]
### Dependencies: None
### Description: Create a privacy notice and explicit consent mechanism during Taskmaster setup
### Details:
Design and implement a clear privacy notice explaining what data is collected and how it's used. Create a user consent prompt during initial installation/setup that requires explicit opt-in. Store the consent status in the .taskmasterconfig file and respect this setting throughout the application.
## 4. Integrate telemetry into Taskmaster commands [done]
### Dependencies: 77.1, 77.3
### Description: Integrate the telemetry utility across all relevant Taskmaster commands
### Details:
Modify each Taskmaster command (expand, parse-prd, research, etc.) to call the logAiUsage utility after AI interactions. Ensure telemetry is only sent if user has provided consent. Implement the integration in a way that doesn't impact command performance or user experience.
<info added on 2025-05-06T17:57:13.980Z>
Modify each Taskmaster command (expand, parse-prd, research, etc.) to call the logAiUsage utility after AI interactions. Ensure telemetry is only sent if user has provided consent. Implement the integration in a way that doesn't impact command performance or user experience.
Successfully integrated telemetry calls into `addTask` (core) and `addTaskDirect` (MCP) functions by passing `commandName` and `outputType` parameters to the telemetry system. The `ai-services-unified.js` module now logs basic telemetry data, including calculated cost information, whenever the `add-task` command or tool is invoked. This integration respects user consent settings and maintains performance standards.
</info added on 2025-05-06T17:57:13.980Z>
## 5. Implement usage summary display [done]
### Dependencies: 77.1, 77.4
### Description: Create an optional feature to display AI usage summary in the CLI output
### Details:
Develop functionality to display a concise summary of AI usage (tokens used, estimated cost) directly in the CLI output after command execution. Make this feature configurable through Taskmaster settings. Ensure the display is formatted clearly and doesn't clutter the main command output.
## 6. Telemetry Integration for parse-prd [done]
### Dependencies: None
### Description: Integrate AI usage telemetry capture and propagation for the parse-prd functionality.
### Details:
\
Apply telemetry pattern from telemetry.mdc:
1. **Core (`scripts/modules/task-manager/parse-prd.js`):**
* Modify AI service call to include `commandName: \'parse-prd\'` and `outputType`.
* Receive `{ mainResult, telemetryData }`.
* Return object including `telemetryData`.
* Handle CLI display via `displayAiUsageSummary` if applicable.
2. **Direct (`mcp-server/src/core/direct-functions/parse-prd.js`):**
* Pass `commandName`, `outputType: \'mcp\'` to core.
* Pass `outputFormat: \'json\'` if applicable.
* Receive `{ ..., telemetryData }` from core.
* Return `{ success: true, data: { ..., telemetryData } }`.
3. **Tool (`mcp-server/src/tools/parse-prd.js`):**
* Verify `handleApiResult` correctly passes `data.telemetryData` through.
## 7. Telemetry Integration for expand-task [done]
### Dependencies: None
### Description: Integrate AI usage telemetry capture and propagation for the expand-task functionality.
### Details:
\
Apply telemetry pattern from telemetry.mdc:
1. **Core (`scripts/modules/task-manager/expand-task.js`):**
* Modify AI service call to include `commandName: \'expand-task\'` and `outputType`.
* Receive `{ mainResult, telemetryData }`.
* Return object including `telemetryData`.
* Handle CLI display via `displayAiUsageSummary` if applicable.
2. **Direct (`mcp-server/src/core/direct-functions/expand-task.js`):**
* Pass `commandName`, `outputType: \'mcp\'` to core.
* Pass `outputFormat: \'json\'` if applicable.
* Receive `{ ..., telemetryData }` from core.
* Return `{ success: true, data: { ..., telemetryData } }`.
3. **Tool (`mcp-server/src/tools/expand-task.js`):**
* Verify `handleApiResult` correctly passes `data.telemetryData` through.
## 8. Telemetry Integration for expand-all-tasks [done]
### Dependencies: None
### Description: Integrate AI usage telemetry capture and propagation for the expand-all-tasks functionality.
### Details:
\
Apply telemetry pattern from telemetry.mdc:
1. **Core (`scripts/modules/task-manager/expand-all-tasks.js`):**
* Modify AI service call (likely within a loop or called by a helper) to include `commandName: \'expand-all-tasks\'` and `outputType`.
* Receive `{ mainResult, telemetryData }`.
* Aggregate or handle `telemetryData` appropriately if multiple AI calls are made.
* Return object including aggregated/relevant `telemetryData`.
* Handle CLI display via `displayAiUsageSummary` if applicable.
2. **Direct (`mcp-server/src/core/direct-functions/expand-all-tasks.js`):**
* Pass `commandName`, `outputType: \'mcp\'` to core.
* Pass `outputFormat: \'json\'` if applicable.
* Receive `{ ..., telemetryData }` from core.
* Return `{ success: true, data: { ..., telemetryData } }`.
3. **Tool (`mcp-server/src/tools/expand-all.js`):**
* Verify `handleApiResult` correctly passes `data.telemetryData` through.
## 9. Telemetry Integration for update-tasks [done]
### Dependencies: None
### Description: Integrate AI usage telemetry capture and propagation for the update-tasks (bulk update) functionality.
### Details:
\
Apply telemetry pattern from telemetry.mdc:
1. **Core (`scripts/modules/task-manager/update-tasks.js`):**
* Modify AI service call (likely within a loop) to include `commandName: \'update-tasks\'` and `outputType`.
* Receive `{ mainResult, telemetryData }` for each AI call.
* Aggregate or handle `telemetryData` appropriately for multiple calls.
* Return object including aggregated/relevant `telemetryData`.
* Handle CLI display via `displayAiUsageSummary` if applicable.
2. **Direct (`mcp-server/src/core/direct-functions/update-tasks.js`):**
* Pass `commandName`, `outputType: \'mcp\'` to core.
* Pass `outputFormat: \'json\'` if applicable.
* Receive `{ ..., telemetryData }` from core.
* Return `{ success: true, data: { ..., telemetryData } }`.
3. **Tool (`mcp-server/src/tools/update.js`):**
* Verify `handleApiResult` correctly passes `data.telemetryData` through.
## 10. Telemetry Integration for update-task-by-id [done]
### Dependencies: None
### Description: Integrate AI usage telemetry capture and propagation for the update-task-by-id functionality.
### Details:
\
Apply telemetry pattern from telemetry.mdc:
1. **Core (`scripts/modules/task-manager/update-task-by-id.js`):**
* Modify AI service call to include `commandName: \'update-task\'` and `outputType`.
* Receive `{ mainResult, telemetryData }`.
* Return object including `telemetryData`.
* Handle CLI display via `displayAiUsageSummary` if applicable.
2. **Direct (`mcp-server/src/core/direct-functions/update-task-by-id.js`):**
* Pass `commandName`, `outputType: \'mcp\'` to core.
* Pass `outputFormat: \'json\'` if applicable.
* Receive `{ ..., telemetryData }` from core.
* Return `{ success: true, data: { ..., telemetryData } }`.
3. **Tool (`mcp-server/src/tools/update-task.js`):**
* Verify `handleApiResult` correctly passes `data.telemetryData` through.
## 11. Telemetry Integration for update-subtask-by-id [done]
### Dependencies: None
### Description: Integrate AI usage telemetry capture and propagation for the update-subtask-by-id functionality.
### Details:
\
Apply telemetry pattern from telemetry.mdc:
1. **Core (`scripts/modules/task-manager/update-subtask-by-id.js`):**
* Verify if this function *actually* calls an AI service. If it only appends text, telemetry integration might not apply directly here, but ensure its callers handle telemetry if they use AI.
* *If it calls AI:* Modify AI service call to include `commandName: \'update-subtask\'` and `outputType`.
* *If it calls AI:* Receive `{ mainResult, telemetryData }`.
* *If it calls AI:* Return object including `telemetryData`.
* *If it calls AI:* Handle CLI display via `displayAiUsageSummary` if applicable.
2. **Direct (`mcp-server/src/core/direct-functions/update-subtask-by-id.js`):**
* *If core calls AI:* Pass `commandName`, `outputType: \'mcp\'` to core.
* *If core calls AI:* Pass `outputFormat: \'json\'` if applicable.
* *If core calls AI:* Receive `{ ..., telemetryData }` from core.
* *If core calls AI:* Return `{ success: true, data: { ..., telemetryData } }`.
3. **Tool (`mcp-server/src/tools/update-subtask.js`):**
* Verify `handleApiResult` correctly passes `data.telemetryData` through (if present).
## 12. Telemetry Integration for analyze-task-complexity [done]
### Dependencies: None
### Description: Integrate AI usage telemetry capture and propagation for the analyze-task-complexity functionality. [Updated: 5/9/2025]
### Details:
\
Apply telemetry pattern from telemetry.mdc:
1. **Core (`scripts/modules/task-manager/analyze-task-complexity.js`):**
* Modify AI service call to include `commandName: \'analyze-complexity\'` and `outputType`.
* Receive `{ mainResult, telemetryData }`.
* Return object including `telemetryData` (perhaps alongside the complexity report data).
* Handle CLI display via `displayAiUsageSummary` if applicable.
2. **Direct (`mcp-server/src/core/direct-functions/analyze-task-complexity.js`):**
* Pass `commandName`, `outputType: \'mcp\'` to core.
* Pass `outputFormat: \'json\'` if applicable.
* Receive `{ ..., telemetryData }` from core.
* Return `{ success: true, data: { ..., telemetryData } }`.
3. **Tool (`mcp-server/src/tools/analyze.js`):**
* Verify `handleApiResult` correctly passes `data.telemetryData` through.
<info added on 2025-05-09T04:02:44.847Z>
## Implementation Details for Telemetry Integration
### Best Practices for Implementation
1. **Use Structured Telemetry Objects:**
- Create a standardized `TelemetryEvent` object with fields:
```javascript
{
commandName: string, // e.g., 'analyze-complexity'
timestamp: ISO8601 string,
duration: number, // in milliseconds
inputTokens: number,
outputTokens: number,
model: string, // e.g., 'gpt-4'
success: boolean,
errorType?: string, // if applicable
metadata: object // command-specific context
}
```
2. **Asynchronous Telemetry Processing:**
- Use non-blocking telemetry submission to avoid impacting performance
- Implement queue-based processing for reliability during network issues
3. **Error Handling:**
- Implement robust try/catch blocks around telemetry operations
- Ensure telemetry failures don't affect core functionality
- Log telemetry failures locally for debugging
4. **Privacy Considerations:**
- Never include PII or sensitive data in telemetry
- Implement data minimization principles
- Add sanitization functions for metadata fields
5. **Testing Strategy:**
- Create mock telemetry endpoints for testing
- Add unit tests verifying correct telemetry data structure
- Implement integration tests for end-to-end telemetry flow
### Code Implementation Examples
```javascript
// Example telemetry submission function
async function submitTelemetry(telemetryData, endpoint) {
try {
// Non-blocking submission
fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(telemetryData)
}).catch(err => console.error('Telemetry submission failed:', err));
} catch (error) {
// Log locally but don't disrupt main flow
console.error('Telemetry error:', error);
}
}
// Example integration in AI service call
async function callAiService(params) {
const startTime = Date.now();
try {
const result = await aiService.call({
...params,
commandName: 'analyze-complexity',
outputType: 'mcp'
});
// Construct telemetry object
const telemetryData = {
commandName: 'analyze-complexity',
timestamp: new Date().toISOString(),
duration: Date.now() - startTime,
inputTokens: result.usage?.prompt_tokens || 0,
outputTokens: result.usage?.completion_tokens || 0,
model: result.model || 'unknown',
success: true,
metadata: {
taskId: params.taskId,
// Add other relevant non-sensitive metadata
}
};
return { mainResult: result.data, telemetryData };
} catch (error) {
// Error telemetry
const telemetryData = {
commandName: 'analyze-complexity',
timestamp: new Date().toISOString(),
duration: Date.now() - startTime,
success: false,
errorType: error.name,
metadata: {
taskId: params.taskId,
errorMessage: sanitizeErrorMessage(error.message)
}
};
// Re-throw the original error after capturing telemetry
throw error;
}
}
```
</info added on 2025-05-09T04:02:44.847Z>
## 13. Update google.js for Telemetry Compatibility [done]
### Dependencies: None
### Description: Modify src/ai-providers/google.js functions to return usage data.
### Details:
Update the provider functions in `src/ai-providers/google.js` to ensure they return telemetry-compatible results:\n\n1. **`generateGoogleText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\n2. **`generateGoogleObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\n3. **`streamGoogleText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\n\nReference `anthropic.js` for the pattern.
## 14. Update openai.js for Telemetry Compatibility [done]
### Dependencies: None
### Description: Modify src/ai-providers/openai.js functions to return usage data.
### Details:
Update the provider functions in `src/ai-providers/openai.js` to ensure they return telemetry-compatible results:\n\n1. **`generateOpenAIText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\n2. **`generateOpenAIObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\n3. **`streamOpenAIText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\n\nReference `anthropic.js` for the pattern.
## 15. Update openrouter.js for Telemetry Compatibility [done]
### Dependencies: None
### Description: Modify src/ai-providers/openrouter.js functions to return usage data.
### Details:
Update the provider functions in `src/ai-providers/openrouter.js` to ensure they return telemetry-compatible results:\n\n1. **`generateOpenRouterText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\n2. **`generateOpenRouterObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\n3. **`streamOpenRouterText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\n\nReference `anthropic.js` for the pattern.
## 16. Update perplexity.js for Telemetry Compatibility [done]
### Dependencies: None
### Description: Modify src/ai-providers/perplexity.js functions to return usage data.
### Details:
Update the provider functions in `src/ai-providers/perplexity.js` to ensure they return telemetry-compatible results:\n\n1. **`generatePerplexityText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\n2. **`generatePerplexityObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\n3. **`streamPerplexityText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\n\nReference `anthropic.js` for the pattern.
## 17. Update xai.js for Telemetry Compatibility [done]
### Dependencies: None
### Description: Modify src/ai-providers/xai.js functions to return usage data.
### Details:
Update the provider functions in `src/ai-providers/xai.js` to ensure they return telemetry-compatible results:\n\n1. **`generateXaiText`**: Return `{ text: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts from the Vercel AI SDK result.\n2. **`generateXaiObject`**: Return `{ object: ..., usage: { inputTokens: ..., outputTokens: ... } }`. Extract token counts.\n3. **`streamXaiText`**: Return the *full stream result object* returned by the Vercel AI SDK's `streamText`, not just the `textStream` property. The full object contains usage information.\n\nReference `anthropic.js` for the pattern.
## 18. Create dedicated telemetry transmission module [done]
### Dependencies: 77.1, 77.3
### Description: Implement a separate module for handling telemetry transmission logic
### Details:
Create a new module (e.g., `scripts/utils/telemetry-client.js`) that encapsulates all telemetry transmission functionality:
1. Implement core functions:
- `sendTelemetryData(telemetryPayload)`: Main function to handle HTTPS POST requests
- `isUserConsentGiven()`: Helper to check if user has consented to telemetry
- `logTelemetryError(error)`: Helper for consistent error logging
2. Use Axios with retry logic:
- Configure with exponential backoff (max 3 retries, 500ms base delay)
- Implement proper TLS encryption via HTTPS
- Set appropriate timeouts (5000ms recommended)
3. Implement robust error handling:
- Catch all transmission errors
- Log failures locally without disrupting application flow
- Ensure failures are transparent to users
4. Configure securely:
- Load endpoint URL and authentication from environment variables
- Never hardcode secrets in source code
- Validate payload data before transmission
5. Integration with ai-services-unified.js:
- Import the telemetry-client module
- Call after telemetryData object is constructed
- Only send if user consent is confirmed
- Use non-blocking approach to avoid performance impact

View File

@@ -1,92 +0,0 @@
# Task ID: 80
# Title: Implement Unique User ID Generation and Storage During Installation
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Generate a unique user identifier during npm installation and store it in the .taskmasterconfig globals to enable anonymous usage tracking and telemetry without requiring user registration.
# Details:
This task involves implementing a mechanism to generate and store a unique user identifier during the npm installation process of Taskmaster. The implementation should:
1. Create a post-install script that runs automatically after npm install completes
2. Generate a cryptographically secure random UUID v4 as the unique user identifier
3. Check if a user ID already exists in the .taskmasterconfig file before generating a new one
4. Add the generated user ID to the globals section of the .taskmasterconfig file
5. Ensure the user ID persists across updates but is regenerated on fresh installations
6. Handle edge cases such as failed installations, manual deletions of the config file, or permission issues
7. Add appropriate logging to notify users that an anonymous ID is being generated (with clear privacy messaging)
8. Document the purpose of this ID in the codebase and user documentation
9. Ensure the ID generation is compatible with all supported operating systems
10. Make the ID accessible to the telemetry system implemented in Task #77
The implementation should respect user privacy by:
- Not collecting any personally identifiable information
- Making it clear in documentation how users can opt out of telemetry
- Ensuring the ID cannot be traced back to specific users or installations
This user ID will serve as the foundation for anonymous usage tracking, helping to understand how Taskmaster is used without compromising user privacy. Note that while we're implementing the ID generation now, the actual server-side collection is not yet available, so this data will initially only be stored locally.
# Test Strategy:
Testing for this feature should include:
1. **Unit Tests**:
- Verify the UUID generation produces valid UUIDs
- Test the config file reading and writing functionality
- Ensure proper error handling for file system operations
- Verify the ID remains consistent across multiple reads
2. **Integration Tests**:
- Run a complete npm installation in a clean environment and verify a new ID is generated
- Simulate an update installation and verify the existing ID is preserved
- Test the interaction between the ID generation and the telemetry system
- Verify the ID is correctly stored in the expected location in .taskmasterconfig
3. **Manual Testing**:
- Perform fresh installations on different operating systems (Windows, macOS, Linux)
- Verify the installation process completes without errors
- Check that the .taskmasterconfig file contains the generated ID
- Test scenarios where the config file is manually deleted or corrupted
4. **Edge Case Testing**:
- Test behavior when the installation is run without sufficient permissions
- Verify handling of network disconnections during installation
- Test with various npm versions to ensure compatibility
- Verify behavior when .taskmasterconfig already exists but doesn't contain a user ID section
5. **Validation**:
- Create a simple script to extract and analyze generated IDs to ensure uniqueness
- Verify the ID format meets UUID v4 specifications
- Confirm the ID is accessible to the telemetry system from Task #77
The test plan should include documentation of all test cases, expected results, and actual outcomes. A successful implementation will generate unique IDs for each installation while maintaining that ID across updates.
# Subtasks:
## 1. Create post-install script structure [pending]
### Dependencies: None
### Description: Set up the post-install script that will run automatically after npm installation to handle user ID generation.
### Details:
Create a new file called 'postinstall.js' in the project root. Configure package.json to run this script after installation by adding it to the 'scripts' section with the key 'postinstall'. The script should import necessary dependencies (fs, path, crypto) and set up the basic structure to access and modify the .taskmasterconfig file. Include proper error handling and logging to capture any issues during execution.
## 2. Implement UUID generation functionality [pending]
### Dependencies: 80.1
### Description: Create a function to generate cryptographically secure UUIDs v4 for unique user identification.
### Details:
Implement a function called 'generateUniqueUserId()' that uses the crypto module to create a UUID v4. The function should follow RFC 4122 for UUID generation to ensure uniqueness and security. Include validation to verify the generated ID matches the expected UUID v4 format. Document the function with JSDoc comments explaining its purpose for anonymous telemetry.
## 3. Develop config file handling logic [pending]
### Dependencies: 80.1
### Description: Create functions to read, parse, modify, and write to the .taskmasterconfig file for storing the user ID.
### Details:
Implement functions to: 1) Check if .taskmasterconfig exists and create it if not, 2) Read and parse the existing config file, 3) Check if a user ID already exists in the globals section, 4) Add or update the user ID in the globals section, and 5) Write the updated config back to disk. Handle edge cases like malformed config files, permission issues, and concurrent access. Use atomic write operations to prevent config corruption.
## 4. Integrate user ID generation with config storage [pending]
### Dependencies: 80.2, 80.3
### Description: Connect the UUID generation with the config file handling to create and store user IDs during installation.
### Details:
Combine the UUID generation and config handling functions to: 1) Check if a user ID already exists in config, 2) Generate a new ID only if needed, 3) Store the ID in the config file, and 4) Handle installation scenarios (fresh install vs. update). Add appropriate logging to inform users about the anonymous ID generation with privacy-focused messaging. Ensure the process is idempotent so running it multiple times won't create multiple IDs.
## 5. Add documentation and telemetry system access [pending]
### Dependencies: 80.4
### Description: Document the user ID system and create an API for the telemetry system to access the user ID.
### Details:
Create comprehensive documentation explaining: 1) The purpose of the anonymous ID, 2) How user privacy is protected, 3) How to opt out of telemetry, and 4) Technical details of the implementation. Implement a simple API function 'getUserId()' that reads the ID from config for use by the telemetry system. Update the README and user documentation to include information about anonymous usage tracking. Ensure cross-platform compatibility by testing on all supported operating systems. Make it clear in the documentation that while we're collecting this ID, the server-side collection is not yet implemented, so data remains local for now.

View File

@@ -1,34 +0,0 @@
# Task ID: 82
# Title: Update supported-models.json with token limit fields
# Status: pending
# Dependencies: None
# Priority: high
# Description: Modify the supported-models.json file to include contextWindowTokens and maxOutputTokens fields for each model, replacing the ambiguous max_tokens field.
# Details:
For each model entry in supported-models.json:
1. Add `contextWindowTokens` field representing the total context window (input + output tokens)
2. Add `maxOutputTokens` field representing the maximum tokens the model can generate
3. Remove or deprecate the ambiguous `max_tokens` field if present
Research and populate accurate values for each model from official documentation:
- For OpenAI models (e.g., gpt-4o): contextWindowTokens=128000, maxOutputTokens=16384
- For Anthropic models (e.g., Claude 3.7): contextWindowTokens=200000, maxOutputTokens=8192
- For other providers, find official documentation or use reasonable defaults
Example entry:
```json
{
"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,
"maxOutputTokens": 8192
}
```
# Test Strategy:
1. Validate JSON syntax after changes
2. Verify all models have the new fields with reasonable values
3. Check that the values align with official documentation from each provider
4. Ensure backward compatibility by maintaining any fields other systems might depend on

View File

@@ -1,95 +0,0 @@
# Task ID: 83
# Title: Update config-manager.js defaults and getters
# Status: pending
# Dependencies: 82
# Priority: high
# Description: Modify the config-manager.js module to replace maxTokens with maxInputTokens and maxOutputTokens in the DEFAULTS object and update related getter functions.
# Details:
1. Update the `DEFAULTS` object in config-manager.js:
```javascript
const DEFAULTS = {
// ... existing defaults
main: {
// Replace maxTokens with these two fields
maxInputTokens: 16000, // Example default
maxOutputTokens: 4000, // Example default
temperature: 0.7
// ... other fields
},
research: {
maxInputTokens: 16000,
maxOutputTokens: 4000,
temperature: 0.7
// ... other fields
},
fallback: {
maxInputTokens: 8000,
maxOutputTokens: 2000,
temperature: 0.7
// ... other fields
}
// ... rest of DEFAULTS
};
```
2. Update `getParametersForRole` function to return the new fields:
```javascript
function getParametersForRole(role, explicitRoot = null) {
const config = _getConfig(explicitRoot);
return {
maxInputTokens: config[role]?.maxInputTokens,
maxOutputTokens: config[role]?.maxOutputTokens,
temperature: config[role]?.temperature
// ... any other parameters
};
}
```
3. Add a new function to get model capabilities:
```javascript
function getModelCapabilities(providerName, modelId) {
const models = MODEL_MAP[providerName?.toLowerCase()];
const model = models?.find(m => m.id === modelId);
return {
contextWindowTokens: model?.contextWindowTokens,
maxOutputTokens: model?.maxOutputTokens
};
}
```
4. Deprecate or update the role-specific maxTokens getters:
```javascript
// Either remove these or update them to return maxInputTokens
function getMainMaxTokens(explicitRoot = null) {
console.warn('getMainMaxTokens is deprecated. Use getParametersForRole("main") instead.');
return getParametersForRole("main", explicitRoot).maxInputTokens;
}
// Same for getResearchMaxTokens and getFallbackMaxTokens
```
5. Export the new functions:
```javascript
module.exports = {
// ... existing exports
getParametersForRole,
getModelCapabilities
};
```
# Test Strategy:
1. Unit test the updated getParametersForRole function with various configurations
2. Verify the new getModelCapabilities function returns correct values
3. Test with both default and custom configurations
4. Ensure backward compatibility by checking that existing code using the old getters still works (with warnings)
# Subtasks:
## 1. Update config-manager.js with specific token limit fields [pending]
### Dependencies: None
### Description: Modify the DEFAULTS object in config-manager.js to replace maxTokens with more specific token limit fields (maxInputTokens, maxOutputTokens, maxTotalTokens) and update related getter functions while maintaining backward compatibility.
### Details:
1. Replace maxTokens in the DEFAULTS object with maxInputTokens, maxOutputTokens, and maxTotalTokens
2. Update any getter functions that reference maxTokens to handle both old and new configurations
3. Ensure backward compatibility so existing code using maxTokens continues to work
4. Update any related documentation or comments to reflect the new token limit fields
5. Test the changes to verify both new specific token limits and legacy maxTokens usage work correctly

View File

@@ -1,93 +0,0 @@
# Task ID: 84
# Title: Implement token counting utility
# Status: pending
# Dependencies: 82
# Priority: high
# Description: Create a utility function to count tokens for prompts based on the model being used, primarily using tiktoken for OpenAI and Anthropic models with character-based fallbacks for other providers.
# Details:
1. Install the tiktoken package:
```bash
npm install tiktoken
```
2. Create a new file `scripts/modules/token-counter.js`:
```javascript
const tiktoken = require('tiktoken');
/**
* Count tokens for a given text and model
* @param {string} text - The text to count tokens for
* @param {string} provider - The AI provider (e.g., 'openai', 'anthropic')
* @param {string} modelId - The model ID
* @returns {number} - Estimated token count
*/
function countTokens(text, provider, modelId) {
if (!text) return 0;
// Convert to lowercase for case-insensitive matching
const providerLower = provider?.toLowerCase();
try {
// OpenAI models
if (providerLower === 'openai') {
// Most OpenAI chat models use cl100k_base encoding
const encoding = tiktoken.encoding_for_model(modelId) || tiktoken.get_encoding('cl100k_base');
return encoding.encode(text).length;
}
// Anthropic models - can use cl100k_base as an approximation
// or follow Anthropic's guidance
if (providerLower === 'anthropic') {
try {
// Try to use cl100k_base as a reasonable approximation
const encoding = tiktoken.get_encoding('cl100k_base');
return encoding.encode(text).length;
} catch (e) {
// Fallback to Anthropic's character-based estimation
return Math.ceil(text.length / 3.5); // ~3.5 chars per token for English
}
}
// For other providers, use character-based estimation as fallback
// Different providers may have different tokenization schemes
return Math.ceil(text.length / 4); // General fallback estimate
} catch (error) {
console.warn(`Token counting error: ${error.message}. Using character-based estimate.`);
return Math.ceil(text.length / 4); // Fallback if tiktoken fails
}
}
module.exports = { countTokens };
```
3. Add tests for the token counter in `tests/token-counter.test.js`:
```javascript
const { countTokens } = require('../scripts/modules/token-counter');
describe('Token Counter', () => {
test('counts tokens for OpenAI models', () => {
const text = 'Hello, world! This is a test.';
const count = countTokens(text, 'openai', 'gpt-4');
expect(count).toBeGreaterThan(0);
expect(typeof count).toBe('number');
});
test('counts tokens for Anthropic models', () => {
const text = 'Hello, world! This is a test.';
const count = countTokens(text, 'anthropic', 'claude-3-7-sonnet-20250219');
expect(count).toBeGreaterThan(0);
expect(typeof count).toBe('number');
});
test('handles empty text', () => {
expect(countTokens('', 'openai', 'gpt-4')).toBe(0);
expect(countTokens(null, 'openai', 'gpt-4')).toBe(0);
});
});
```
# Test Strategy:
1. Unit test the countTokens function with various inputs and models
2. Compare token counts with known examples from OpenAI and Anthropic documentation
3. Test edge cases: empty strings, very long texts, non-English texts
4. Test fallback behavior when tiktoken fails or is not applicable

View File

@@ -1,104 +0,0 @@
# Task ID: 85
# Title: Update ai-services-unified.js for dynamic token limits
# Status: pending
# Dependencies: 83, 84
# Priority: medium
# Description: Modify the _unifiedServiceRunner function in ai-services-unified.js to use the new token counting utility and dynamically adjust output token limits based on input length.
# Details:
1. Import the token counter in `ai-services-unified.js`:
```javascript
const { countTokens } = require('./token-counter');
const { getParametersForRole, getModelCapabilities } = require('./config-manager');
```
2. Update the `_unifiedServiceRunner` function to implement dynamic token limit adjustment:
```javascript
async function _unifiedServiceRunner({
serviceType,
provider,
modelId,
systemPrompt,
prompt,
temperature,
currentRole,
effectiveProjectRoot,
// ... other parameters
}) {
// Get role parameters with new token limits
const roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
// Get model capabilities
const modelCapabilities = getModelCapabilities(provider, modelId);
// Count tokens in the prompts
const systemPromptTokens = countTokens(systemPrompt, provider, modelId);
const userPromptTokens = countTokens(prompt, provider, modelId);
const totalPromptTokens = systemPromptTokens + userPromptTokens;
// Validate against input token limits
if (totalPromptTokens > roleParams.maxInputTokens) {
throw new Error(
`Prompt (${totalPromptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
);
}
// Validate against model's absolute context window
if (modelCapabilities.contextWindowTokens && totalPromptTokens > modelCapabilities.contextWindowTokens) {
throw new Error(
`Prompt (${totalPromptTokens} tokens) exceeds model's context window (${modelCapabilities.contextWindowTokens}) for ${modelId}.`
);
}
// Calculate available output tokens
// If model has a combined context window, we need to subtract input tokens
let availableOutputTokens = roleParams.maxOutputTokens;
// If model has a context window constraint, ensure we don't exceed it
if (modelCapabilities.contextWindowTokens) {
const remainingContextTokens = modelCapabilities.contextWindowTokens - totalPromptTokens;
availableOutputTokens = Math.min(availableOutputTokens, remainingContextTokens);
}
// Also respect the model's absolute max output limit
if (modelCapabilities.maxOutputTokens) {
availableOutputTokens = Math.min(availableOutputTokens, modelCapabilities.maxOutputTokens);
}
// Prepare API call parameters
const callParams = {
apiKey,
modelId,
maxTokens: availableOutputTokens, // Use dynamically calculated output limit
temperature: roleParams.temperature,
messages,
baseUrl,
...(serviceType === 'generateObject' && { schema, objectName }),
...restApiParams
};
// Log token usage information
console.debug(`Token usage: ${totalPromptTokens} input tokens, ${availableOutputTokens} max output tokens`);
// Rest of the function remains the same...
}
```
3. Update the error handling to provide clear messages about token limits:
```javascript
try {
// Existing code...
} catch (error) {
if (error.message.includes('tokens')) {
// Token-related errors should be clearly identified
console.error(`Token limit error: ${error.message}`);
}
throw error;
}
```
# Test Strategy:
1. Test with prompts of various lengths to verify dynamic adjustment
2. Test with different models to ensure model-specific limits are respected
3. Verify error messages are clear when limits are exceeded
4. Test edge cases: very short prompts, prompts near the limit
5. Integration test with actual API calls to verify the calculated limits work in practice

View File

@@ -1,107 +0,0 @@
# Task ID: 86
# Title: Update .taskmasterconfig schema and user guide
# Status: pending
# Dependencies: 83
# Priority: medium
# Description: Create a migration guide for users to update their .taskmasterconfig files and document the new token limit configuration options.
# Details:
1. Create a migration script or guide for users to update their existing `.taskmasterconfig` files:
```javascript
// Example migration snippet for .taskmasterconfig
{
"main": {
// Before:
// "maxTokens": 16000,
// After:
"maxInputTokens": 16000,
"maxOutputTokens": 4000,
"temperature": 0.7
},
"research": {
"maxInputTokens": 16000,
"maxOutputTokens": 4000,
"temperature": 0.7
},
"fallback": {
"maxInputTokens": 8000,
"maxOutputTokens": 2000,
"temperature": 0.7
}
}
```
2. Update the user documentation to explain the new token limit fields:
```markdown
# Token Limit Configuration
Task Master now provides more granular control over token limits with separate settings for input and output tokens:
- `maxInputTokens`: Maximum number of tokens allowed in the input prompt (system prompt + user prompt)
- `maxOutputTokens`: Maximum number of tokens the model should generate in its response
## Benefits
- More precise control over token usage
- Better cost management
- Reduced likelihood of hitting model context limits
- Dynamic adjustment to maximize output space based on input length
## Migration from Previous Versions
If you're upgrading from a previous version, you'll need to update your `.taskmasterconfig` file:
1. Replace the single `maxTokens` field with separate `maxInputTokens` and `maxOutputTokens` fields
2. Recommended starting values:
- Set `maxInputTokens` to your previous `maxTokens` value
- Set `maxOutputTokens` to approximately 1/4 of your model's context window
## Example Configuration
```json
{
"main": {
"maxInputTokens": 16000,
"maxOutputTokens": 4000,
"temperature": 0.7
}
}
```
```
3. Update the schema validation in `config-manager.js` to validate the new fields:
```javascript
function _validateConfig(config) {
// ... existing validation
// Validate token limits for each role
['main', 'research', 'fallback'].forEach(role => {
if (config[role]) {
// Check if old maxTokens is present and warn about migration
if (config[role].maxTokens !== undefined) {
console.warn(`Warning: 'maxTokens' in ${role} role is deprecated. Please use 'maxInputTokens' and 'maxOutputTokens' instead.`);
}
// Validate new token limit fields
if (config[role].maxInputTokens !== undefined && (!Number.isInteger(config[role].maxInputTokens) || config[role].maxInputTokens <= 0)) {
throw new Error(`Invalid maxInputTokens for ${role} role: must be a positive integer`);
}
if (config[role].maxOutputTokens !== undefined && (!Number.isInteger(config[role].maxOutputTokens) || config[role].maxOutputTokens <= 0)) {
throw new Error(`Invalid maxOutputTokens for ${role} role: must be a positive integer`);
}
}
});
return config;
}
```
# Test Strategy:
1. Verify documentation is clear and provides migration steps
2. Test the validation logic with various config formats
3. Test backward compatibility with old config format
4. Ensure error messages are helpful when validation fails

View File

@@ -1,119 +0,0 @@
# Task ID: 87
# Title: Implement validation and error handling
# Status: pending
# Dependencies: 85
# Priority: low
# Description: Add comprehensive validation and error handling for token limits throughout the system, including helpful error messages and graceful fallbacks.
# Details:
1. Add validation when loading models in `config-manager.js`:
```javascript
function _validateModelMap(modelMap) {
// Validate each provider's models
Object.entries(modelMap).forEach(([provider, models]) => {
models.forEach(model => {
// Check for required token limit fields
if (!model.contextWindowTokens) {
console.warn(`Warning: Model ${model.id} from ${provider} is missing contextWindowTokens field`);
}
if (!model.maxOutputTokens) {
console.warn(`Warning: Model ${model.id} from ${provider} is missing maxOutputTokens field`);
}
});
});
return modelMap;
}
```
2. Add validation when setting up a model in the CLI:
```javascript
function validateModelConfig(modelConfig, modelCapabilities) {
const issues = [];
// Check if input tokens exceed model's context window
if (modelConfig.maxInputTokens > modelCapabilities.contextWindowTokens) {
issues.push(`maxInputTokens (${modelConfig.maxInputTokens}) exceeds model's context window (${modelCapabilities.contextWindowTokens})`);
}
// Check if output tokens exceed model's maximum
if (modelConfig.maxOutputTokens > modelCapabilities.maxOutputTokens) {
issues.push(`maxOutputTokens (${modelConfig.maxOutputTokens}) exceeds model's maximum output tokens (${modelCapabilities.maxOutputTokens})`);
}
// Check if combined tokens exceed context window
if (modelConfig.maxInputTokens + modelConfig.maxOutputTokens > modelCapabilities.contextWindowTokens) {
issues.push(`Combined maxInputTokens and maxOutputTokens (${modelConfig.maxInputTokens + modelConfig.maxOutputTokens}) exceeds model's context window (${modelCapabilities.contextWindowTokens})`);
}
return issues;
}
```
3. Add graceful fallbacks in `ai-services-unified.js`:
```javascript
// Fallback for missing token limits
if (!roleParams.maxInputTokens) {
console.warn(`Warning: maxInputTokens not specified for role '${currentRole}'. Using default value.`);
roleParams.maxInputTokens = 8000; // Reasonable default
}
if (!roleParams.maxOutputTokens) {
console.warn(`Warning: maxOutputTokens not specified for role '${currentRole}'. Using default value.`);
roleParams.maxOutputTokens = 2000; // Reasonable default
}
// Fallback for missing model capabilities
if (!modelCapabilities.contextWindowTokens) {
console.warn(`Warning: contextWindowTokens not specified for model ${modelId}. Using conservative estimate.`);
modelCapabilities.contextWindowTokens = roleParams.maxInputTokens + roleParams.maxOutputTokens;
}
if (!modelCapabilities.maxOutputTokens) {
console.warn(`Warning: maxOutputTokens not specified for model ${modelId}. Using role configuration.`);
modelCapabilities.maxOutputTokens = roleParams.maxOutputTokens;
}
```
4. Add detailed logging for token usage:
```javascript
function logTokenUsage(provider, modelId, inputTokens, outputTokens, role) {
const inputCost = calculateTokenCost(provider, modelId, 'input', inputTokens);
const outputCost = calculateTokenCost(provider, modelId, 'output', outputTokens);
console.info(`Token usage for ${role} role with ${provider}/${modelId}:`);
console.info(`- Input: ${inputTokens.toLocaleString()} tokens ($${inputCost.toFixed(6)})`);
console.info(`- Output: ${outputTokens.toLocaleString()} tokens ($${outputCost.toFixed(6)})`);
console.info(`- Total cost: $${(inputCost + outputCost).toFixed(6)}`);
console.info(`- Available output tokens: ${availableOutputTokens.toLocaleString()}`);
}
```
5. Add a helper function to suggest configuration improvements:
```javascript
function suggestTokenConfigImprovements(roleParams, modelCapabilities, promptTokens) {
const suggestions = [];
// If prompt is using less than 50% of allowed input
if (promptTokens < roleParams.maxInputTokens * 0.5) {
suggestions.push(`Consider reducing maxInputTokens from ${roleParams.maxInputTokens} to save on potential costs`);
}
// If output tokens are very limited due to large input
const availableOutput = Math.min(
roleParams.maxOutputTokens,
modelCapabilities.contextWindowTokens - promptTokens
);
if (availableOutput < roleParams.maxOutputTokens * 0.5) {
suggestions.push(`Available output tokens (${availableOutput}) are significantly less than configured maxOutputTokens (${roleParams.maxOutputTokens}) due to large input`);
}
return suggestions;
}
```
# Test Strategy:
1. Test validation functions with valid and invalid configurations
2. Verify fallback behavior works correctly when configuration is missing
3. Test error messages are clear and actionable
4. Test logging functions provide useful information
5. Verify suggestion logic provides helpful recommendations

View File

@@ -1,57 +0,0 @@
# Task ID: 88
# Title: Enhance Add-Task Functionality to Consider All Task Dependencies
# Status: done
# Dependencies: None
# Priority: medium
# Description: Improve the add-task feature to accurately account for all dependencies among tasks, ensuring proper task ordering and execution.
# Details:
1. Review current implementation of add-task functionality.
2. Identify existing mechanisms for handling task dependencies.
3. Modify add-task to recursively analyze and incorporate all dependencies.
4. Ensure that dependencies are resolved in the correct order during task execution.
5. Update documentation to reflect changes in dependency handling.
6. Consider edge cases such as circular dependencies and handle them appropriately.
7. Optimize performance to ensure efficient dependency resolution, especially for projects with a large number of tasks.
8. Integrate with existing validation and error handling mechanisms (from Task 87) to provide clear feedback if dependencies cannot be resolved.
9. Test thoroughly with various dependency scenarios to ensure robustness.
# Test Strategy:
1. Create test cases with simple linear dependencies to verify correct ordering.
2. Develop test cases with complex, nested dependencies to ensure recursive resolution works correctly.
3. Include tests for edge cases such as circular dependencies, verifying appropriate error messages are displayed.
4. Measure performance with large sets of tasks and dependencies to ensure efficiency.
5. Conduct integration testing with other components that rely on task dependencies.
6. Perform manual code reviews to validate implementation against requirements.
7. Execute automated tests to verify no regressions in existing functionality.
# Subtasks:
## 1. Review Current Add-Task Implementation and Identify Dependency Mechanisms [done]
### Dependencies: None
### Description: Examine the existing add-task functionality to understand how task dependencies are currently handled.
### Details:
Conduct a code review of the add-task feature. Document any existing mechanisms for handling task dependencies.
## 2. Modify Add-Task to Recursively Analyze Dependencies [done]
### Dependencies: 88.1
### Description: Update the add-task functionality to recursively analyze and incorporate all task dependencies.
### Details:
Implement a recursive algorithm that identifies and incorporates all dependencies for a given task. Ensure it handles nested dependencies correctly.
## 3. Ensure Correct Order of Dependency Resolution [done]
### Dependencies: 88.2
### Description: Modify the add-task functionality to ensure that dependencies are resolved in the correct order during task execution.
### Details:
Implement logic to sort and execute tasks based on their dependency order. Handle cases where multiple tasks depend on each other.
## 4. Integrate with Existing Validation and Error Handling [done]
### Dependencies: 88.3
### Description: Update the add-task functionality to integrate with existing validation and error handling mechanisms (from Task 87).
### Details:
Modify the code to provide clear feedback if dependencies cannot be resolved. Ensure that circular dependencies are detected and handled appropriately.
## 5. Optimize Performance for Large Projects [done]
### Dependencies: 88.4
### Description: Optimize the add-task functionality to ensure efficient dependency resolution, especially for projects with a large number of tasks.
### Details:
Profile and optimize the recursive dependency analysis algorithm. Implement caching or other performance improvements as needed.

View File

@@ -1,23 +0,0 @@
# Task ID: 89
# Title: Introduce Prioritize Command with Enhanced Priority Levels
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Implement a prioritize command with --up/--down/--priority/--id flags and shorthand equivalents (-u/-d/-p/-i). Add 'lowest' and 'highest' priority levels, updating CLI output accordingly.
# Details:
The new prioritize command should allow users to adjust task priorities using the specified flags. The --up and --down flags will modify the priority relative to the current level, while --priority sets an absolute priority. The --id flag specifies which task to prioritize. Shorthand equivalents (-u/-d/-p/-i) should be supported for user convenience.
The priority levels should now include 'lowest', 'low', 'medium', 'high', and 'highest'. The CLI output should be updated to reflect these new priority levels accurately.
Considerations:
- Ensure backward compatibility with existing commands and configurations.
- Update the help documentation to include the new command and its usage.
- Implement proper error handling for invalid priority levels or missing flags.
# Test Strategy:
To verify task completion, perform the following tests:
1. Test each flag (--up, --down, --priority, --id) individually and in combination to ensure they function as expected.
2. Verify that shorthand equivalents (-u, -d, -p, -i) work correctly.
3. Check that the new priority levels ('lowest' and 'highest') are recognized and displayed properly in CLI output.
4. Test error handling for invalid inputs (e.g., non-existent task IDs, invalid priority levels).
5. Ensure that the help command displays accurate information about the new prioritize command.

View File

@@ -1,67 +0,0 @@
# Task ID: 90
# Title: Implement Subtask Progress Analyzer and Reporting System
# Status: pending
# Dependencies: 1, 3
# Priority: medium
# Description: Develop a subtask analyzer that monitors the progress of all subtasks, validates their status, and generates comprehensive reports for users to track project advancement.
# Details:
The subtask analyzer should be implemented with the following components and considerations:
1. Progress Tracking Mechanism:
- Create a function to scan the task data structure and identify all tasks with subtasks
- Implement logic to determine the completion status of each subtask
- Calculate overall progress percentages for tasks with multiple subtasks
2. Status Validation:
- Develop validation rules to check if subtasks are progressing according to expected timelines
- Implement detection for stalled or blocked subtasks
- Create alerts for subtasks that are behind schedule or have dependency issues
3. Reporting System:
- Design a structured report format that clearly presents:
- Overall project progress
- Task-by-task breakdown with subtask status
- Highlighted issues or blockers
- Support multiple output formats (console, JSON, exportable text)
- Include visual indicators for progress (e.g., progress bars in CLI)
4. Integration Points:
- Hook into the existing task management system
- Ensure the analyzer can be triggered via CLI commands
- Make the reporting feature accessible through the main command interface
5. Performance Considerations:
- Optimize for large task lists with many subtasks
- Implement caching if necessary to avoid redundant calculations
- Ensure reports generate quickly even for complex project structures
The implementation should follow the existing code style and patterns, leveraging the task data structure already in place. The analyzer should be non-intrusive to existing functionality while providing valuable insights to users.
# Test Strategy:
Testing for the subtask analyzer should include:
1. Unit Tests:
- Test the progress calculation logic with various task/subtask configurations
- Verify status validation correctly identifies issues in different scenarios
- Ensure report generation produces consistent and accurate output
- Test edge cases (empty subtasks, all complete, all incomplete, mixed states)
2. Integration Tests:
- Verify the analyzer correctly integrates with the existing task data structure
- Test CLI command integration and parameter handling
- Ensure reports reflect actual changes to task/subtask status
3. Performance Tests:
- Benchmark report generation with large task sets (100+ tasks with multiple subtasks)
- Verify memory usage remains reasonable during analysis
4. User Acceptance Testing:
- Create sample projects with various subtask configurations
- Generate reports and verify they provide clear, actionable information
- Confirm visual indicators accurately represent progress
5. Regression Testing:
- Verify that the analyzer doesn't interfere with existing task management functionality
- Ensure backward compatibility with existing task data structures
Documentation should be updated to include examples of how to use the new analyzer and interpret the reports. Success criteria include accurate progress tracking, clear reporting, and performance that scales with project size.

View File

@@ -1,49 +0,0 @@
# Task ID: 91
# Title: Implement Move Command for Tasks and Subtasks
# Status: done
# Dependencies: 1, 3
# Priority: medium
# Description: Introduce a 'move' command to enable moving tasks or subtasks to a different id, facilitating conflict resolution by allowing teams to assign new ids as needed.
# Details:
The move command will consist of three core components: 1) Core Logic Function in scripts/modules/task-manager/move-task.js, 2) Direct Function Wrapper in mcp-server/src/core/direct-functions/move-task.js, and 3) MCP Tool in mcp-server/src/tools/move-task.js. The command will accept source and destination IDs, handling various scenarios including moving tasks to become subtasks, subtasks to become tasks, and subtasks between different parents. The implementation will handle edge cases such as invalid ids, non-existent parents, circular dependencies, and will properly update all dependencies.
# Test Strategy:
Testing will follow a three-tier approach: 1) Unit tests for core functionality including moving tasks to subtasks, subtasks to tasks, subtasks between parents, dependency handling, and validation error cases; 2) Integration tests for the direct function with mock MCP environment and task file regeneration; 3) End-to-end tests for the full MCP tool call path. This will verify all scenarios including moving a task to a new id, moving a subtask under a different parent while preserving its hierarchy, and handling errors for invalid operations.
# Subtasks:
## 1. Design and implement core move logic [done]
### Dependencies: None
### Description: Create the fundamental logic for moving tasks and subtasks within the task management system hierarchy
### Details:
Implement the core logic function in scripts/modules/task-manager/move-task.js with the signature that accepts tasksPath, sourceId, destinationId, and generateFiles parameters. Develop functions to handle all movement operations including task-to-subtask, subtask-to-task, and subtask-to-subtask conversions. Implement validation for source and destination IDs, and ensure proper updating of parent-child relationships and dependencies.
## 2. Implement edge case handling [done]
### Dependencies: 91.1
### Description: Develop robust error handling for all potential edge cases in the move operation
### Details:
Create validation functions to detect invalid task IDs, non-existent parent tasks, and circular dependencies. Handle special cases such as moving a task to become the first/last subtask, reordering within the same parent, preventing moving a task to itself, and preventing moving a parent to its own subtask. Implement proper error messages and status codes for each edge case, and ensure system stability if a move operation fails.
## 3. Update CLI interface for move commands [done]
### Dependencies: 91.1
### Description: Extend the command-line interface to support the new move functionality with appropriate flags and options
### Details:
Create the Direct Function Wrapper in mcp-server/src/core/direct-functions/move-task.js to adapt the core logic for MCP, handling path resolution and parameter validation. Implement silent mode to prevent console output interfering with JSON responses. Create the MCP Tool in mcp-server/src/tools/move-task.js that exposes the functionality to Cursor, handles project root resolution, and includes proper Zod parameter definitions. Update MCP tool definition in .cursor/mcp.json and register the tool in mcp-server/src/tools/index.js.
## 4. Ensure data integrity during moves [done]
### Dependencies: 91.1, 91.2
### Description: Implement safeguards to maintain data consistency and update all relationships during move operations
### Details:
Implement dependency handling logic to update dependencies when converting between task/subtask, add appropriate parent dependencies when needed, and validate no circular dependencies are created. Create transaction-like operations to ensure atomic moves that either complete fully or roll back. Implement functions to update all affected task relationships after a move, and add verification steps to confirm data integrity post-move.
## 5. Create comprehensive test suite [done]
### Dependencies: 91.1, 91.2, 91.3, 91.4
### Description: Develop and execute tests covering all move scenarios and edge cases
### Details:
Create unit tests for core functionality including moving tasks to subtasks, subtasks to tasks, subtasks between parents, dependency handling, and validation error cases. Implement integration tests for the direct function with mock MCP environment and task file regeneration. Develop end-to-end tests for the full MCP tool call path. Ensure tests cover all identified edge cases and potential failure points, and verify data integrity after moves.
## 6. Export and integrate the move function [done]
### Dependencies: 91.1
### Description: Ensure the move function is properly exported and integrated with existing code
### Details:
Export the move function in scripts/modules/task-manager.js. Update task-master-core.js to include the direct function. Reuse validation logic from add-subtask.js and remove-subtask.js where appropriate. Follow silent mode implementation pattern from other direct functions and match parameter naming conventions in MCP tools.

View File

@@ -1,94 +0,0 @@
# Task ID: 92
# Title: Implement Project Root Environment Variable Support in MCP Configuration
# Status: review
# Dependencies: 1, 3, 17
# Priority: medium
# Description: Add support for a 'TASK_MASTER_PROJECT_ROOT' environment variable in MCP configuration, allowing it to be set in both mcp.json and .env, with precedence over other methods. This will define the root directory for the MCP server and take precedence over all other project root resolution methods. The implementation should be backward compatible with existing workflows that don't use this variable.
# Details:
Update the MCP server configuration system to support the TASK_MASTER_PROJECT_ROOT environment variable as the standard way to specify the project root directory. This provides better namespacing and avoids conflicts with other tools that might use a generic PROJECT_ROOT variable. Implement a clear precedence order for project root resolution:
1. TASK_MASTER_PROJECT_ROOT environment variable (from shell or .env file)
2. 'projectRoot' key in mcp_config.toml or mcp.json configuration files
3. Existing resolution logic (CLI args, current working directory, etc.)
Modify the configuration loading logic to check for these sources in the specified order, ensuring backward compatibility. All MCP tools and components should use this standardized project root resolution logic. The TASK_MASTER_PROJECT_ROOT environment variable will be required because path resolution is delegated to the MCP client implementation, ensuring consistent behavior across different environments.
Implementation steps:
1. Identify all code locations where project root is determined (initialization, utility functions)
2. Update configuration loaders to check for TASK_MASTER_PROJECT_ROOT in environment variables
3. Add support for 'projectRoot' in configuration files as a fallback
4. Refactor project root resolution logic to follow the new precedence rules
5. Ensure all MCP tools and functions use the updated resolution logic
6. Add comprehensive error handling for cases where TASK_MASTER_PROJECT_ROOT is not set or invalid
7. Implement validation to ensure the specified directory exists and is accessible
# Test Strategy:
1. Write unit tests to verify that the config loader correctly reads project root from environment variables and configuration files with the expected precedence:
- Test TASK_MASTER_PROJECT_ROOT environment variable takes precedence when set
- Test 'projectRoot' in configuration files is used when environment variable is absent
- Test fallback to existing resolution logic when neither is specified
2. Add integration tests to ensure that the MCP server and all tools use the correct project root:
- Test server startup with TASK_MASTER_PROJECT_ROOT set to various valid and invalid paths
- Test configuration file loading from the specified project root
- Test path resolution for resources relative to the project root
3. Test backward compatibility:
- Verify existing workflows function correctly without the new variables
- Ensure no regression in projects not using the new configuration options
4. Manual testing:
- Set TASK_MASTER_PROJECT_ROOT in shell environment and verify correct behavior
- Set TASK_MASTER_PROJECT_ROOT in .env file and verify it's properly loaded
- Configure 'projectRoot' in configuration files and test precedence
- Test with invalid or non-existent directories to verify error handling
# Subtasks:
## 1. Update configuration loader to check for TASK_MASTER_PROJECT_ROOT environment variable [pending]
### Dependencies: None
### Description: Modify the configuration loading system to check for the TASK_MASTER_PROJECT_ROOT environment variable as the primary source for project root directory. Ensure proper error handling if the variable is set but points to a non-existent or inaccessible directory.
### Details:
## 2. Add support for 'projectRoot' in configuration files [pending]
### Dependencies: None
### Description: Implement support for a 'projectRoot' key in mcp_config.toml and mcp.json configuration files as a fallback when the environment variable is not set. Update the configuration parser to recognize and validate this field.
### Details:
## 3. Refactor project root resolution logic with clear precedence rules [pending]
### Dependencies: None
### Description: Create a unified project root resolution function that follows the precedence order: 1) TASK_MASTER_PROJECT_ROOT environment variable, 2) 'projectRoot' in config files, 3) existing resolution methods. Ensure this function is used consistently throughout the codebase.
### Details:
## 4. Update all MCP tools to use the new project root resolution [pending]
### Dependencies: None
### Description: Identify all MCP tools and components that need to access the project root and update them to use the new resolution logic. Ensure consistent behavior across all parts of the system.
### Details:
## 5. Add comprehensive tests for the new project root resolution [pending]
### Dependencies: None
### Description: Create unit and integration tests to verify the correct behavior of the project root resolution logic under various configurations and edge cases.
### Details:
## 6. Update documentation with new configuration options [pending]
### Dependencies: None
### Description: Update the project documentation to clearly explain the new TASK_MASTER_PROJECT_ROOT environment variable, the 'projectRoot' configuration option, and the precedence rules. Include examples of different configuration scenarios.
### Details:
## 7. Implement validation for project root directory [pending]
### Dependencies: None
### Description: Add validation to ensure the specified project root directory exists and has the necessary permissions. Provide clear error messages when validation fails.
### Details:
## 8. Implement support for loading environment variables from .env files [pending]
### Dependencies: None
### Description: Add functionality to load the TASK_MASTER_PROJECT_ROOT variable from .env files in the workspace, following best practices for environment variable management in MCP servers.
### Details:

View File

@@ -1,55 +0,0 @@
# Task ID: 93
# Title: Implement Google Vertex AI Provider Integration
# Status: pending
# Dependencies: 19, 94
# Priority: medium
# Description: Develop a dedicated Google Vertex AI provider in the codebase, enabling users to leverage Vertex AI models with enterprise-grade configuration and authentication.
# Details:
1. Create a new provider class in `src/ai-providers/google-vertex.js` that extends the existing BaseAIProvider, following the established structure used by other providers (e.g., google.js, openai.js).
2. Integrate the Vercel AI SDK's `@ai-sdk/google-vertex` package. Use the default `vertex` provider for standard usage, and allow for custom configuration via `createVertex` for advanced scenarios (e.g., specifying project ID, location, and credentials).
3. Implement all required interface methods (such as `getClient`, `generateText`, etc.) to ensure compatibility with the provider system. Reference the implementation patterns from other providers for consistency.
4. Handle Vertex AI-specific configuration, including project ID, location, and Google Cloud authentication. Support both environment-based authentication and explicit service account credentials via `googleAuthOptions`.
5. Implement robust error handling for Vertex-specific issues, including authentication failures and API errors, leveraging the system-wide error handling patterns.
6. Update `src/ai-providers/index.js` to export the new provider, and add the 'vertex' entry to the PROVIDERS object in `scripts/modules/ai-services-unified.js`.
7. Update documentation to provide clear setup instructions for Google Vertex AI, including required environment variables, service account setup, and configuration examples.
8. Ensure the implementation is modular and maintainable, supporting future expansion for additional Vertex AI features or models.
# Test Strategy:
- Write unit tests for the new provider class, covering all interface methods and configuration scenarios (default, custom, error cases).
- Verify that the provider can successfully authenticate using both environment-based and explicit service account credentials.
- Test integration with the provider system by selecting 'vertex' as the provider and generating text using supported Vertex AI models (e.g., Gemini).
- Simulate authentication and API errors to confirm robust error handling and user feedback.
- Confirm that the provider is correctly exported and available in the PROVIDERS object.
- Review and validate the updated documentation for accuracy and completeness.
# Subtasks:
## 1. Create Google Vertex AI Provider Class [pending]
### Dependencies: None
### Description: Develop a new provider class in `src/ai-providers/google-vertex.js` that extends the BaseAIProvider, following the structure of existing providers.
### Details:
Ensure the new class is consistent with the architecture of other providers such as google.js and openai.js, and is ready to integrate with the AI SDK.
## 2. Integrate Vercel AI SDK Google Vertex Package [pending]
### Dependencies: 93.1
### Description: Integrate the `@ai-sdk/google-vertex` package, supporting both the default provider and custom configuration via `createVertex`.
### Details:
Allow for standard usage with the default `vertex` provider and advanced scenarios using `createVertex` for custom project ID, location, and credentials as per SDK documentation.
## 3. Implement Provider Interface Methods [pending]
### Dependencies: 93.2
### Description: Implement all required interface methods (e.g., `getClient`, `generateText`) to ensure compatibility with the provider system.
### Details:
Reference implementation patterns from other providers to maintain consistency and ensure all required methods are present and functional.
## 4. Handle Vertex AI Configuration and Authentication [pending]
### Dependencies: 93.3
### Description: Implement support for Vertex AI-specific configuration, including project ID, location, and authentication via environment variables or explicit service account credentials.
### Details:
Support both environment-based authentication and explicit credentials using `googleAuthOptions`, following Google Cloud and Vertex AI setup best practices.
## 5. Update Exports, Documentation, and Error Handling [pending]
### Dependencies: 93.4
### Description: Export the new provider, update the PROVIDERS object, and document setup instructions, including robust error handling for Vertex-specific issues.
### Details:
Update `src/ai-providers/index.js` and `scripts/modules/ai-services-unified.js`, and provide clear documentation for setup, configuration, and error handling patterns.

View File

@@ -1,103 +0,0 @@
# Task ID: 94
# Title: Implement Azure OpenAI Provider Integration
# Status: done
# Dependencies: 19, 26
# Priority: medium
# Description: Create a comprehensive Azure OpenAI provider implementation that integrates with the existing AI provider system, enabling users to leverage Azure-hosted OpenAI models through proper authentication and configuration.
# Details:
Implement the Azure OpenAI provider following the established provider pattern:
1. **Create Azure Provider Class** (`src/ai-providers/azure.js`):
- Extend BaseAIProvider class following the same pattern as openai.js and google.js
- Import and use `createAzureOpenAI` from `@ai-sdk/azure` package
- Implement required interface methods: `getClient()`, `validateConfig()`, and any other abstract methods
- Handle Azure-specific configuration: endpoint URL, API key, and deployment name
- Add proper error handling for missing or invalid Azure configuration
2. **Configuration Management**:
- Support environment variables: AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, AZURE_OPENAI_DEPLOYMENT
- Validate that both endpoint and API key are provided
- Provide clear error messages for configuration issues
- Follow the same configuration pattern as other providers
3. **Integration Updates**:
- Update `src/ai-providers/index.js` to export the new AzureProvider
- Add 'azure' entry to the PROVIDERS object in `scripts/modules/ai-services-unified.js`
- Ensure the provider is properly registered and accessible through the unified AI services
4. **Error Handling**:
- Implement Azure-specific error handling for authentication failures
- Handle endpoint connectivity issues with helpful error messages
- Validate deployment name and provide guidance for common configuration mistakes
- Follow the established error handling patterns from Task 19
5. **Documentation Updates**:
- Update any provider documentation to include Azure OpenAI setup instructions
- Add configuration examples for Azure OpenAI environment variables
- Include troubleshooting guidance for common Azure-specific issues
The implementation should maintain consistency with existing provider implementations while handling Azure's unique authentication and endpoint requirements.
# Test Strategy:
Verify the Azure OpenAI provider implementation through comprehensive testing:
1. **Unit Testing**:
- Test provider class instantiation and configuration validation
- Verify getClient() method returns properly configured Azure OpenAI client
- Test error handling for missing/invalid configuration parameters
- Validate that the provider correctly extends BaseAIProvider
2. **Integration Testing**:
- Test provider registration in the unified AI services system
- Verify the provider appears in the PROVIDERS object and is accessible
- Test end-to-end functionality with valid Azure OpenAI credentials
- Validate that the provider works with existing AI operation workflows
3. **Configuration Testing**:
- Test with various environment variable combinations
- Verify proper error messages for missing endpoint or API key
- Test with invalid endpoint URLs and ensure graceful error handling
- Validate deployment name handling and error reporting
4. **Manual Verification**:
- Set up test Azure OpenAI credentials and verify successful connection
- Test actual AI operations (like task expansion) using the Azure provider
- Verify that the provider selection works correctly in the CLI
- Confirm that error messages are helpful and actionable for users
5. **Documentation Verification**:
- Ensure all configuration examples work as documented
- Verify that setup instructions are complete and accurate
- Test troubleshooting guidance with common error scenarios
# Subtasks:
## 1. Create Azure Provider Class [done]
### Dependencies: None
### Description: Implement the AzureProvider class that extends BaseAIProvider to handle Azure OpenAI integration
### Details:
Create the AzureProvider class in src/ai-providers/azure.js that extends BaseAIProvider. Import createAzureOpenAI from @ai-sdk/azure package. Implement required interface methods including getClient() and validateConfig(). Handle Azure-specific configuration parameters: endpoint URL, API key, and deployment name. Follow the established pattern in openai.js and google.js. Ensure proper error handling for missing or invalid configuration.
## 2. Implement Configuration Management [done]
### Dependencies: 94.1
### Description: Add support for Azure OpenAI environment variables and configuration validation
### Details:
Implement configuration management for Azure OpenAI provider that supports environment variables: AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, and AZURE_OPENAI_DEPLOYMENT. Add validation logic to ensure both endpoint and API key are provided. Create clear error messages for configuration issues. Follow the same configuration pattern as implemented in other providers. Ensure the validateConfig() method properly checks all required Azure configuration parameters.
## 3. Update Provider Integration [done]
### Dependencies: 94.1, 94.2
### Description: Integrate the Azure provider into the existing AI provider system
### Details:
Update src/ai-providers/index.js to export the new AzureProvider class. Add 'azure' entry to the PROVIDERS object in scripts/modules/ai-services-unified.js. Ensure the provider is properly registered and accessible through the unified AI services. Test that the provider can be instantiated and used through the provider selection mechanism. Follow the same integration pattern used for existing providers.
## 4. Implement Azure-Specific Error Handling [done]
### Dependencies: 94.1, 94.2
### Description: Add specialized error handling for Azure OpenAI-specific issues
### Details:
Implement Azure-specific error handling for authentication failures, endpoint connectivity issues, and deployment name validation. Provide helpful error messages that guide users to resolve common configuration mistakes. Follow the established error handling patterns from Task 19. Create custom error classes if needed for Azure-specific errors. Ensure errors are properly propagated and formatted for user display.
## 5. Update Documentation [done]
### Dependencies: 94.1, 94.2, 94.3, 94.4
### Description: Create comprehensive documentation for the Azure OpenAI provider integration
### Details:
Update provider documentation to include Azure OpenAI setup instructions. Add configuration examples for Azure OpenAI environment variables. Include troubleshooting guidance for common Azure-specific issues. Document the required Azure resource creation process with references to Microsoft's documentation. Provide examples of valid configuration settings and explain each required parameter. Include information about Azure OpenAI model deployment requirements.

View File

@@ -1,149 +0,0 @@
# Task ID: 95
# Title: Implement .taskmaster Directory Structure
# Status: done
# Dependencies: 1, 3, 4, 17
# Priority: high
# Description: Consolidate all Task Master-managed files in user projects into a clean, centralized .taskmaster/ directory structure to improve organization and keep user project directories clean, based on GitHub issue #275.
# Details:
This task involves restructuring how Task Master organizes files within user projects to improve maintainability and keep project directories clean:
1. Create a new `.taskmaster/` directory structure in user projects:
- Move task files from `tasks/` to `.taskmaster/tasks/`
- Move PRD files from `scripts/` to `.taskmaster/docs/`
- Move analysis reports to `.taskmaster/reports/`
- Move configuration from `.taskmasterconfig` to `.taskmaster/config.json`
- Create `.taskmaster/templates/` for user templates
2. Update all Task Master code that creates/reads user files:
- Modify task file generation to use `.taskmaster/tasks/`
- Update PRD file handling to use `.taskmaster/docs/`
- Adjust report generation to save to `.taskmaster/reports/`
- Update configuration loading to look for `.taskmaster/config.json`
- Modify any path resolution logic in Task Master's codebase
3. Ensure backward compatibility during migration:
- Implement path fallback logic that checks both old and new locations
- Add deprecation warnings when old paths are detected
- Create a migration command to help users transition to the new structure
- Preserve existing user data during migration
4. Update the project initialization process:
- Modify the init command to create the new `.taskmaster/` directory structure
- Update default file creation to use new paths
5. Benefits of the new structure:
- Keeps user project directories clean and organized
- Clearly separates Task Master files from user project files
- Makes it easier to add Task Master to .gitignore if desired
- Provides logical grouping of different file types
6. Test thoroughly to ensure all functionality works with the new structure:
- Verify all Task Master commands work with the new paths
- Ensure backward compatibility functions correctly
- Test migration process preserves all user data
7. Update documentation:
- Update README.md to reflect the new user file structure
- Add migration guide for existing users
- Document the benefits of the cleaner organization
# Test Strategy:
1. Unit Testing:
- Create unit tests for path resolution that verify both new and old paths work
- Test configuration loading with both `.taskmasterconfig` and `.taskmaster/config.json`
- Verify the migration command correctly moves files and preserves content
- Test file creation in all new subdirectories
2. Integration Testing:
- Run all existing integration tests with the new directory structure
- Verify that all Task Master commands function correctly with new paths
- Test backward compatibility by running commands with old file structure
3. Migration Testing:
- Test the migration process on sample projects with existing tasks and files
- Verify all tasks, PRDs, reports, and configurations are correctly moved
- Ensure no data loss occurs during migration
- Test migration with partial existing structures (e.g., only tasks/ exists)
4. User Workflow Testing:
- Test complete workflows: init → create tasks → generate reports → update PRDs
- Verify all generated files go to correct locations in `.taskmaster/`
- Test that user project directories remain clean
5. Manual Testing:
- Perform end-to-end testing with the new structure
- Create, update, and delete tasks using the new structure
- Generate reports and verify they're saved to `.taskmaster/reports/`
6. Documentation Verification:
- Review all documentation to ensure it accurately reflects the new user file structure
- Verify the migration guide provides clear instructions
7. Regression Testing:
- Run the full test suite to ensure no regressions were introduced
- Verify existing user projects continue to work during transition period
# Subtasks:
## 1. Create .taskmaster directory structure [done]
### Dependencies: None
### Description: Create the new .taskmaster directory and move existing files to their new locations
### Details:
Create a new .taskmaster/ directory in the project root. Move the tasks/ directory to .taskmaster/tasks/. Move the scripts/ directory to .taskmaster/scripts/. Move the .taskmasterconfig file to .taskmaster/config.json. Ensure proper file permissions are maintained during the move.
<info added on 2025-05-29T15:03:56.912Z>
Create the new .taskmaster/ directory structure in user projects with subdirectories for tasks/, docs/, reports/, and templates/. Move the existing .taskmasterconfig file to .taskmaster/config.json. Since this project is also a Task Master user, move this project's current user files (tasks.json, PRD files, etc.) to the new .taskmaster/ structure to test the implementation. This subtask focuses on user project directory structure, not Task Master source code relocation.
</info added on 2025-05-29T15:03:56.912Z>
## 2. Update Task Master code for new user file paths [done]
### Dependencies: 95.1
### Description: Modify all Task Master code that creates or reads user project files to use the new .taskmaster structure
### Details:
Update Task Master's file handling code to use the new paths: tasks in .taskmaster/tasks/, PRD files in .taskmaster/docs/, reports in .taskmaster/reports/, and config in .taskmaster/config.json. Modify path resolution logic throughout the Task Master codebase to reference the new user file locations.
## 3. Update task file generation system [done]
### Dependencies: 95.1
### Description: Modify the task file generation system to use the new directory structure
### Details:
Update the task file generation system to create and read task files from .taskmaster/tasks/ instead of tasks/. Ensure all template paths are updated. Modify any path resolution logic specific to task file handling.
## 4. Implement backward compatibility logic [done]
### Dependencies: 95.2, 95.3
### Description: Add fallback mechanisms to support both old and new file locations during transition
### Details:
Implement path fallback logic that checks both old and new locations when files aren't found. Add deprecation warnings when old paths are used, informing users about the new structure. Ensure error messages are clear about the transition.
## 5. Create migration command for users [done]
### Dependencies: 95.1, 95.4
### Description: Develop a Task Master command to help users transition their existing projects to the new structure
### Details:
Create a 'taskmaster migrate' command that automatically moves user files from old locations to the new .taskmaster structure. Move tasks/ to .taskmaster/tasks/, scripts/prd.txt to .taskmaster/docs/, reports to .taskmaster/reports/, and .taskmasterconfig to .taskmaster/config.json. Include backup functionality and validation to ensure migration completed successfully.
## 6. Update project initialization process [done]
### Dependencies: 95.1
### Description: Modify the init command to create the new directory structure for new projects
### Details:
Update the init command to create the .taskmaster directory and its subdirectories (tasks/, docs/, reports/, templates/). Modify default file creation to use the new paths. Ensure new projects are created with the correct structure from the start.
## 7. Update PRD and report file handling [done]
### Dependencies: 95.2, 95.6
### Description: Modify PRD file creation and report generation to use the new directory structure
### Details:
Update PRD file handling to create and read files from .taskmaster/docs/ instead of scripts/. Modify report generation (like task-complexity-report.json) to save to .taskmaster/reports/. Ensure all file operations use the new paths consistently.
## 8. Update documentation and create migration guide [done]
### Dependencies: 95.5, 95.6, 95.7
### Description: Update all documentation to reflect the new directory structure and provide migration guidance
### Details:
Update README.md and other documentation to reflect the new .taskmaster structure for user projects. Create a comprehensive migration guide explaining the benefits of the new structure and how to migrate existing projects. Include examples of the new directory layout and explain how it keeps user project directories clean.
## 9. Add templates directory support [done]
### Dependencies: 95.2, 95.6
### Description: Implement support for user templates in the .taskmaster/templates/ directory
### Details:
Create functionality to support user-defined templates in .taskmaster/templates/. Allow users to store custom task templates, PRD templates, or other reusable files. Update Task Master commands to recognize and use templates from this directory when available.
## 10. Verify clean user project directories [done]
### Dependencies: 95.8, 95.9
### Description: Ensure the new structure keeps user project root directories clean and organized
### Details:
Validate that after implementing the new structure, user project root directories only contain their actual project files plus the single .taskmaster/ directory. Verify that no Task Master files are created outside of .taskmaster/. Test that users can easily add .taskmaster/ to .gitignore if they choose to exclude Task Master files from version control.

View File

@@ -1,37 +0,0 @@
# Task ID: 96
# Title: Create Export Command for On-Demand Task File and PDF Generation
# Status: pending
# Dependencies: 2, 4, 95
# Priority: medium
# Description: Develop an 'export' CLI command that generates task files and comprehensive PDF exports on-demand, replacing automatic file generation and providing users with flexible export options.
# Details:
Implement a new 'export' command in the CLI that supports two primary modes: (1) generating individual task files on-demand (superseding the current automatic generation system), and (2) producing a comprehensive PDF export. The PDF should include: a first page with the output of 'tm list --with-subtasks', followed by individual pages for each task (using 'tm show <task_id>') and each subtask (using 'tm show <subtask_id>'). Integrate PDF generation using a robust library (e.g., pdfkit, Puppeteer, or jsPDF) to ensure high-quality output and proper pagination. Refactor or disable any existing automatic file generation logic to avoid performance overhead. Ensure the command supports flexible output paths and options for exporting only files, only PDF, or both. Update documentation and help output to reflect the new export capabilities. Consider concurrency and error handling for large projects. Ensure the export process is efficient and does not block the main CLI thread unnecessarily.
# Test Strategy:
1. Run the 'export' command with various options and verify that task files are generated only on-demand, not automatically. 2. Generate a PDF export and confirm that the first page contains the correct 'tm list --with-subtasks' output, and that each subsequent page accurately reflects the output of 'tm show <task_id>' and 'tm show <subtask_id>' for all tasks and subtasks. 3. Test exporting in projects with large numbers of tasks and subtasks to ensure performance and correctness. 4. Attempt exports with invalid paths or missing data to verify robust error handling. 5. Confirm that no automatic file generation occurs during normal task operations. 6. Review CLI help output and documentation for accuracy regarding the new export functionality.
# Subtasks:
## 1. Remove Automatic Task File Generation from Task Operations [pending]
### Dependencies: None
### Description: Eliminate all calls to generateTaskFiles() from task operations such as add-task, remove-task, set-status, and similar commands to prevent unnecessary performance overhead.
### Details:
Audit the codebase for any automatic invocations of generateTaskFiles() and remove or refactor them to ensure task files are not generated automatically during task operations.
## 2. Implement Export Command Infrastructure with On-Demand Task File Generation [pending]
### Dependencies: 96.1
### Description: Develop the CLI 'export' command infrastructure, enabling users to generate task files on-demand by invoking the preserved generateTaskFiles function only when requested.
### Details:
Create the export command with options for output paths and modes (files, PDF, or both). Ensure generateTaskFiles is only called within this command and not elsewhere.
## 3. Implement Comprehensive PDF Export Functionality [pending]
### Dependencies: 96.2
### Description: Add PDF export capability to the export command, generating a structured PDF with a first page listing all tasks and subtasks, followed by individual pages for each task and subtask, using a robust PDF library.
### Details:
Integrate a PDF generation library (e.g., pdfkit, Puppeteer, or jsPDF). Ensure the PDF includes the output of 'tm list --with-subtasks' on the first page, and uses 'tm show <task_id>' and 'tm show <subtask_id>' for subsequent pages. Handle pagination, concurrency, and error handling for large projects.
## 4. Update Documentation, Tests, and CLI Help for Export Workflow [pending]
### Dependencies: 96.2, 96.3
### Description: Revise all relevant documentation, automated tests, and CLI help output to reflect the new export-based workflow and available options.
### Details:
Update user guides, README files, and CLI help text. Add or modify tests to cover the new export command and its options. Ensure all documentation accurately describes the new workflow and usage.

File diff suppressed because one or more lines are too long

View File

@@ -1,47 +0,0 @@
<context>
# Overview
[Provide a high-level overview of your product here. Explain what problem it solves, who it's for, and why it's valuable.]
# Core Features
[List and describe the main features of your product. For each feature, include:
- What it does
- Why it's important
- How it works at a high level]
# User Experience
[Describe the user journey and experience. Include:
- User personas
- Key user flows
- UI/UX considerations]
</context>
<PRD>
# Technical Architecture
[Outline the technical implementation details:
- System components
- Data models
- APIs and integrations
- Infrastructure requirements]
# Development Roadmap
[Break down the development process into phases:
- MVP requirements
- Future enhancements
- Do not think about timelines whatsoever -- all that matters is scope and detailing exactly what needs to be build in each phase so it can later be cut up into tasks]
# Logical Dependency Chain
[Define the logical order of development:
- Which features need to be built first (foundation)
- Getting as quickly as possible to something usable/visible front end that works
- Properly pacing and scoping each feature so it is atomic but can also be built upon and improved as development approaches]
# Risks and Mitigations
[Identify potential risks and how they'll be addressed:
- Technical challenges
- Figuring out the MVP that we can build upon
- Resource constraints]
# Appendix
[Include any additional information:
- Research findings
- Technical specifications]
</PRD>

View File

@@ -1,551 +1,5 @@
# task-master-ai
## 0.16.2-rc.0
### Patch Changes
- [#655](https://github.com/eyaltoledano/claude-task-master/pull/655) [`edaa5fe`](https://github.com/eyaltoledano/claude-task-master/commit/edaa5fe0d56e0e4e7c4370670a7a388eebd922ac) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix double .taskmaster directory paths in file resolution utilities
- Closes #636
- [#671](https://github.com/eyaltoledano/claude-task-master/pull/671) [`86ea6d1`](https://github.com/eyaltoledano/claude-task-master/commit/86ea6d1dbc03eeb39f524f565b50b7017b1d2c9c) Thanks [@joedanz](https://github.com/joedanz)! - Add one-click MCP server installation for Cursor
## 0.16.1
### Patch Changes
- [#641](https://github.com/eyaltoledano/claude-task-master/pull/641) [`ad61276`](https://github.com/eyaltoledano/claude-task-master/commit/ad612763ffbdd35aa1b593c9613edc1dc27a8856) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bedrock issues
- [#648](https://github.com/eyaltoledano/claude-task-master/pull/648) [`9b4168b`](https://github.com/eyaltoledano/claude-task-master/commit/9b4168bb4e4dfc2f4fb0cf6bd5f81a8565879176) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix MCP tool calls logging errors
- [#641](https://github.com/eyaltoledano/claude-task-master/pull/641) [`ad61276`](https://github.com/eyaltoledano/claude-task-master/commit/ad612763ffbdd35aa1b593c9613edc1dc27a8856) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Update rules for new directory structure
- [#648](https://github.com/eyaltoledano/claude-task-master/pull/648) [`9b4168b`](https://github.com/eyaltoledano/claude-task-master/commit/9b4168bb4e4dfc2f4fb0cf6bd5f81a8565879176) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug in expand_all mcp tool
- [#641](https://github.com/eyaltoledano/claude-task-master/pull/641) [`ad61276`](https://github.com/eyaltoledano/claude-task-master/commit/ad612763ffbdd35aa1b593c9613edc1dc27a8856) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix MCP crashing after certain commands due to console logs
## 0.16.0
### Minor Changes
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add AWS bedrock support
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - # 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
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add support for Azure
- [#612](https://github.com/eyaltoledano/claude-task-master/pull/612) [`669b744`](https://github.com/eyaltoledano/claude-task-master/commit/669b744ced454116a7b29de6c58b4b8da977186a) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Increased minimum required node version to > 18 (was > 14)
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Renamed baseUrl to baseURL
- [#604](https://github.com/eyaltoledano/claude-task-master/pull/604) [`80735f9`](https://github.com/eyaltoledano/claude-task-master/commit/80735f9e60c7dda7207e169697f8ac07b6733634) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - 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.
- [#619](https://github.com/eyaltoledano/claude-task-master/pull/619) [`3f64202`](https://github.com/eyaltoledano/claude-task-master/commit/3f64202c9feef83f2bf383c79e4367d337c37e20) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Consolidate Task Master files into unified .taskmaster directory structure
This release introduces a new consolidated directory structure that organizes all Task Master files under a single `.taskmaster/` directory for better project organization and cleaner workspace management.
**New Directory Structure:**
- `.taskmaster/tasks/` - Task files (previously `tasks/`)
- `.taskmaster/docs/` - Documentation including PRD files (previously `scripts/`)
- `.taskmaster/reports/` - Complexity analysis reports (previously `scripts/`)
- `.taskmaster/templates/` - Template files like example PRD
- `.taskmaster/config.json` - Configuration (previously `.taskmasterconfig`)
**Migration & Backward Compatibility:**
- Existing projects continue to work with legacy file locations
- New projects use the consolidated structure automatically
- Run `task-master migrate` to move existing projects to the new structure
- All CLI commands and MCP tools automatically detect and use appropriate file locations
**Benefits:**
- Cleaner project root with Task Master files organized in one location
- Reduced file scatter across multiple directories
- Improved project navigation and maintenance
- Consistent file organization across all Task Master projects
This change maintains full backward compatibility while providing a migration path to the improved structure.
### Patch Changes
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix max_tokens error when trying to use claude-sonnet-4 and claude-opus-4
- [#625](https://github.com/eyaltoledano/claude-task-master/pull/625) [`2d520de`](https://github.com/eyaltoledano/claude-task-master/commit/2d520de2694da3efe537b475ca52baf3c869edda) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix add-task MCP command causing an error
## 0.16.0-rc.0
### Minor Changes
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add AWS bedrock support
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - # 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
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add support for Azure
- [#612](https://github.com/eyaltoledano/claude-task-master/pull/612) [`669b744`](https://github.com/eyaltoledano/claude-task-master/commit/669b744ced454116a7b29de6c58b4b8da977186a) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Increased minimum required node version to > 18 (was > 14)
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Renamed baseUrl to baseURL
- [#604](https://github.com/eyaltoledano/claude-task-master/pull/604) [`80735f9`](https://github.com/eyaltoledano/claude-task-master/commit/80735f9e60c7dda7207e169697f8ac07b6733634) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - 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.
- [#619](https://github.com/eyaltoledano/claude-task-master/pull/619) [`3f64202`](https://github.com/eyaltoledano/claude-task-master/commit/3f64202c9feef83f2bf383c79e4367d337c37e20) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Consolidate Task Master files into unified .taskmaster directory structure
This release introduces a new consolidated directory structure that organizes all Task Master files under a single `.taskmaster/` directory for better project organization and cleaner workspace management.
**New Directory Structure:**
- `.taskmaster/tasks/` - Task files (previously `tasks/`)
- `.taskmaster/docs/` - Documentation including PRD files (previously `scripts/`)
- `.taskmaster/reports/` - Complexity analysis reports (previously `scripts/`)
- `.taskmaster/templates/` - Template files like example PRD
- `.taskmaster/config.json` - Configuration (previously `.taskmasterconfig`)
**Migration & Backward Compatibility:**
- Existing projects continue to work with legacy file locations
- New projects use the consolidated structure automatically
- Run `task-master migrate` to move existing projects to the new structure
- All CLI commands and MCP tools automatically detect and use appropriate file locations
**Benefits:**
- Cleaner project root with Task Master files organized in one location
- Reduced file scatter across multiple directories
- Improved project navigation and maintenance
- Consistent file organization across all Task Master projects
This change maintains full backward compatibility while providing a migration path to the improved structure.
### Patch Changes
- [#607](https://github.com/eyaltoledano/claude-task-master/pull/607) [`6a8a68e`](https://github.com/eyaltoledano/claude-task-master/commit/6a8a68e1a3f34dcdf40b355b4602a08d291f8e38) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix max_tokens error when trying to use claude-sonnet-4 and claude-opus-4
- [#597](https://github.com/eyaltoledano/claude-task-master/pull/597) [`2d520de`](https://github.com/eyaltoledano/claude-task-master/commit/2d520de2694da3efe537b475ca52baf3c869edda) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fix add-task MCP command causing an error
## 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
- [#399](https://github.com/eyaltoledano/claude-task-master/pull/399) [`734a4fd`](https://github.com/eyaltoledano/claude-task-master/commit/734a4fdcfc89c2e089255618cf940561ad13a3c8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
## 0.13.0
### Minor Changes
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ef782ff`](https://github.com/eyaltoledano/claude-task-master/commit/ef782ff5bd4ceb3ed0dc9ea82087aae5f79ac933) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - feat(expand): Enhance `expand` and `expand-all` commands
- Integrate `task-complexity-report.json` to automatically determine the number of subtasks and use tailored prompts for expansion based on prior analysis. You no longer need to try copy-pasting the recommended prompt. If it exists, it will use it for you. You can just run `task-master update --id=[id of task] --research` and it will use that prompt automatically. No extra prompt needed.
- Change default behavior to _append_ new subtasks to existing ones. Use the `--force` flag to clear existing subtasks before expanding. This is helpful if you need to add more subtasks to a task but you want to do it by the batch from a given prompt. Use force if you want to start fresh with a task's subtasks.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`87d97bb`](https://github.com/eyaltoledano/claude-task-master/commit/87d97bba00d84e905756d46ef96b2d5b984e0f38) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds support for the OpenRouter AI provider. Users can now configure models available through OpenRouter (requiring an `OPENROUTER_API_KEY`) via the `task-master models` command, granting access to a wide range of additional LLMs. - IMPORTANT FYI ABOUT OPENROUTER: Taskmaster relies on AI SDK, which itself relies on tool use. It looks like **free** models sometimes do not include tool use. For example, Gemini 2.5 pro (free) failed via OpenRouter (no tool use) but worked fine on the paid version of the model. Custom model support for Open Router is considered experimental and likely will not be further improved for some time.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`1ab836f`](https://github.com/eyaltoledano/claude-task-master/commit/1ab836f191cb8969153593a9a0bd47fc9aa4a831) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds model management and new configuration file .taskmasterconfig which houses the models used for main, research and fallback. Adds models command and setter flags. Adds a --setup flag with an interactive setup. We should be calling this during init. Shows a table of active and available models when models is called without flags. Includes SWE scores and token costs, which are manually entered into the supported_models.json, the new place where models are defined for support. Config-manager.js is the core module responsible for managing the new config."
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`c8722b0`](https://github.com/eyaltoledano/claude-task-master/commit/c8722b0a7a443a73b95d1bcd4a0b68e0fce2a1cd) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds custom model ID support for Ollama and OpenRouter providers.
- Adds the `--ollama` and `--openrouter` flags to `task-master models --set-<role>` command to set models for those providers outside of the support models list.
- Updated `task-master models --setup` interactive mode with options to explicitly enter custom Ollama or OpenRouter model IDs.
- Implemented live validation against OpenRouter API (`/api/v1/models`) when setting a custom OpenRouter model ID (via flag or setup).
- Refined logic to prioritize explicit provider flags/choices over internal model list lookups in case of ID conflicts.
- Added warnings when setting custom/unvalidated models.
- We obviously don't recommend going with a custom, unproven model. If you do and find performance is good, please let us know so we can add it to the list of supported models.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`2517bc1`](https://github.com/eyaltoledano/claude-task-master/commit/2517bc112c9a497110f3286ca4bfb4130c9addcb) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Integrate OpenAI as a new AI provider. - Enhance `models` command/tool to display API key status. - Implement model-specific `maxTokens` override based on `supported-models.json` to save you if you use an incorrect max token value.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`9a48278`](https://github.com/eyaltoledano/claude-task-master/commit/9a482789f7894f57f655fb8d30ba68542bd0df63) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Tweaks Perplexity AI calls for research mode to max out input tokens and get day-fresh information - Forces temp at 0.1 for highly deterministic output, no variations - Adds a system prompt to further improve the output - Correctly uses the maximum input tokens (8,719, used 8,700) for perplexity - Specificies to use a high degree of research across the web - Specifies to use information that is as fresh as today; this support stuff like capturing brand new announcements like new GPT models and being able to query for those in research. 🔥
### Patch Changes
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`842eaf7`](https://github.com/eyaltoledano/claude-task-master/commit/842eaf722498ddf7307800b4cdcef4ac4fd7e5b0) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - - Add support for Google Gemini models via Vercel AI SDK integration.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ed79d4f`](https://github.com/eyaltoledano/claude-task-master/commit/ed79d4f4735dfab4124fa189214c0bd5e23a6860) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add xAI provider and Grok models support
- [#378](https://github.com/eyaltoledano/claude-task-master/pull/378) [`ad89253`](https://github.com/eyaltoledano/claude-task-master/commit/ad89253e313a395637aa48b9f92cc39b1ef94ad8) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Better support for file paths on Windows, Linux & WSL.
- Standardizes handling of different path formats (URI encoded, Windows, Linux, WSL).
- Ensures tools receive a clean, absolute path suitable for the server OS.
- Simplifies tool implementation by centralizing normalization logic.
- [#285](https://github.com/eyaltoledano/claude-task-master/pull/285) [`2acba94`](https://github.com/eyaltoledano/claude-task-master/commit/2acba945c0afee9460d8af18814c87e80f747e9f) Thanks [@neno-is-ooo](https://github.com/neno-is-ooo)! - Add integration for Roo Code
- [#378](https://github.com/eyaltoledano/claude-task-master/pull/378) [`d63964a`](https://github.com/eyaltoledano/claude-task-master/commit/d63964a10eed9be17856757661ff817ad6bacfdc) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improved update-subtask - Now it has context about the parent task details - It also has context about the subtask before it and the subtask after it (if they exist) - Not passing all subtasks to stay token efficient
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`5f504fa`](https://github.com/eyaltoledano/claude-task-master/commit/5f504fafb8bdaa0043c2d20dee8bbb8ec2040d85) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improve and adjust `init` command for robustness and updated dependencies.
- **Update Initialization Dependencies:** Ensure newly initialized projects (`task-master init`) include all required AI SDK dependencies (`@ai-sdk/*`, `ai`, provider wrappers) in their `package.json` for out-of-the-box AI feature compatibility. Remove unnecessary dependencies (e.g., `uuid`) from the init template.
- **Silence `npm install` during `init`:** Prevent `npm install` output from interfering with non-interactive/MCP initialization by suppressing its stdio in silent mode.
- **Improve Conditional Model Setup:** Reliably skip interactive `models --setup` during non-interactive `init` runs (e.g., `init -y` or MCP) by checking `isSilentMode()` instead of passing flags.
- **Refactor `init.js`:** Remove internal `isInteractive` flag logic.
- **Update `init` Instructions:** Tweak the "Getting Started" text displayed after `init`.
- **Fix MCP Server Launch:** Update `.cursor/mcp.json` template to use `node ./mcp-server/server.js` instead of `npx task-master-mcp`.
- **Update Default Model:** Change the default main model in the `.taskmasterconfig` template.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`96aeeff`](https://github.com/eyaltoledano/claude-task-master/commit/96aeeffc195372722c6a07370540e235bfe0e4d8) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue with add-task which did not use the manually defined properties and still needlessly hit the AI endpoint.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`5aea93d`](https://github.com/eyaltoledano/claude-task-master/commit/5aea93d4c0490c242d7d7042a210611977848e0a) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue that prevented remove-subtask with comma separated tasks/subtasks from being deleted (only the first ID was being deleted). Closes #140
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`66ac9ab`](https://github.com/eyaltoledano/claude-task-master/commit/66ac9ab9f66d006da518d6e8a3244e708af2764d) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improves next command to be subtask-aware - The logic for determining the "next task" (findNextTask function, used by task-master next and the next_task MCP tool) has been significantly improved. Previously, it only considered top-level tasks, making its recommendation less useful when a parent task containing subtasks was already marked 'in-progress'. - The updated logic now prioritizes finding the next available subtask within any 'in-progress' parent task, considering subtask dependencies and priority. - If no suitable subtask is found within active parent tasks, it falls back to recommending the next eligible top-level task based on the original criteria (status, dependencies, priority).
This change makes the next command much more relevant and helpful during the implementation phase of complex tasks.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ca7b045`](https://github.com/eyaltoledano/claude-task-master/commit/ca7b0457f1dc65fd9484e92527d9fd6d69db758d) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--status` flag to `show` command to filter displayed subtasks.
- [#328](https://github.com/eyaltoledano/claude-task-master/pull/328) [`5a2371b`](https://github.com/eyaltoledano/claude-task-master/commit/5a2371b7cc0c76f5e95d43921c1e8cc8081bf14e) Thanks [@knoxgraeme](https://github.com/knoxgraeme)! - Fix --task to --num-tasks in ui + related tests - issue #324
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`6cb213e`](https://github.com/eyaltoledano/claude-task-master/commit/6cb213ebbd51116ae0688e35b575d09443d17c3b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds a 'models' CLI and MCP command to get the current model configuration, available models, and gives the ability to set main/research/fallback models." - In the CLI, `task-master models` shows the current models config. Using the `--setup` flag launches an interactive set up that allows you to easily select the models you want to use for each of the three roles. Use `q` during the interactive setup to cancel the setup. - In the MCP, responses are simplified in RESTful format (instead of the full CLI output). The agent can use the `models` tool with different arguments, including `listAvailableModels` to get available models. Run without arguments, it will return the current configuration. Arguments are available to set the model for each of the three roles. This allows you to manage Taskmaster AI providers and models directly from either the CLI or MCP or both. - Updated the CLI help menu when you run `task-master` to include missing commands and .taskmasterconfig information. - Adds `--research` flag to `add-task` so you can hit up Perplexity right from the add-task flow, rather than having to add a task and then update it.
## 0.12.1
### Patch Changes
- [#307](https://github.com/eyaltoledano/claude-task-master/pull/307) [`2829194`](https://github.com/eyaltoledano/claude-task-master/commit/2829194d3c1dd5373d3bf40275cf4f63b12d49a7) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix add_dependency tool crashing the MCP Server
## 0.12.0
### Minor Changes
- [#253](https://github.com/eyaltoledano/claude-task-master/pull/253) [`b2ccd60`](https://github.com/eyaltoledano/claude-task-master/commit/b2ccd605264e47a61451b4c012030ee29011bb40) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add `npx task-master-ai` that runs mcp instead of using `task-master-mcp``
- [#267](https://github.com/eyaltoledano/claude-task-master/pull/267) [`c17d912`](https://github.com/eyaltoledano/claude-task-master/commit/c17d912237e6caaa2445e934fc48cd4841abf056) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Improve PRD parsing prompt with structured analysis and clearer task generation guidelines. We are testing a new prompt - please provide feedback on your experience.
### Patch Changes
- [#243](https://github.com/eyaltoledano/claude-task-master/pull/243) [`454a1d9`](https://github.com/eyaltoledano/claude-task-master/commit/454a1d9d37439c702656eedc0702c2f7a4451517) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - - Fixes shebang issue not allowing task-master to run on certain windows operating systems
- Resolves #241 #211 #184 #193
- [#268](https://github.com/eyaltoledano/claude-task-master/pull/268) [`3e872f8`](https://github.com/eyaltoledano/claude-task-master/commit/3e872f8afbb46cd3978f3852b858c233450b9f33) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix remove-task command to handle multiple comma-separated task IDs
- [#239](https://github.com/eyaltoledano/claude-task-master/pull/239) [`6599cb0`](https://github.com/eyaltoledano/claude-task-master/commit/6599cb0bf9eccecab528207836e9d45b8536e5c2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Updates the parameter descriptions for update, update-task and update-subtask to ensure the MCP server correctly reaches for the right update command based on what is being updated -- all tasks, one task, or a subtask.
- [#272](https://github.com/eyaltoledano/claude-task-master/pull/272) [`3aee9bc`](https://github.com/eyaltoledano/claude-task-master/commit/3aee9bc840eb8f31230bd1b761ed156b261cabc4) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Enhance the `parsePRD` to include `--append` flag. This flag allows users to append the parsed PRD to an existing file, making it easier to manage multiple PRD files without overwriting existing content.
- [#264](https://github.com/eyaltoledano/claude-task-master/pull/264) [`ff8e75c`](https://github.com/eyaltoledano/claude-task-master/commit/ff8e75cded91fb677903040002626f7a82fd5f88) Thanks [@joedanz](https://github.com/joedanz)! - Add quotes around numeric env vars in mcp.json (Windsurf, etc.)
- [#248](https://github.com/eyaltoledano/claude-task-master/pull/248) [`d99fa00`](https://github.com/eyaltoledano/claude-task-master/commit/d99fa00980fc61695195949b33dcda7781006f90) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - - Fix `task-master init` polluting codebase with new packages inside `package.json` and modifying project `README`
- Now only initializes with cursor rules, windsurf rules, mcp.json, scripts/example_prd.txt, .gitignore modifications, and `README-task-master.md`
- [#266](https://github.com/eyaltoledano/claude-task-master/pull/266) [`41b979c`](https://github.com/eyaltoledano/claude-task-master/commit/41b979c23963483e54331015a86e7c5079f657e4) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fixed a bug that prevented the task-master from running in a Linux container
- [#265](https://github.com/eyaltoledano/claude-task-master/pull/265) [`0eb16d5`](https://github.com/eyaltoledano/claude-task-master/commit/0eb16d5ecbb8402d1318ca9509e9d4087b27fb25) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove the need for project name, description, and version. Since we no longer create a package.json for you
## 0.11.0
### Minor Changes

View File

@@ -1,335 +0,0 @@
# 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 18+
- 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.

View File

@@ -13,22 +13,25 @@ A task management system for AI-driven development with Claude, designed to work
## Configuration
Taskmaster uses two primary configuration methods:
The script can be configured through environment variables in a `.env` file at the root of the project:
1. **`.taskmasterconfig` File (Project Root)**
### Required Configuration
- Stores most settings: AI model selections (main, research, fallback), parameters (max tokens, temperature), logging level, default priority/subtasks, project name.
- **Created and managed using `task-master models --setup` CLI command or the `models` MCP tool.**
- Do not edit manually unless you know what you are doing.
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
2. **Environment Variables (`.env` file or MCP `env` block)**
- Used **only** for sensitive **API Keys** (e.g., `ANTHROPIC_API_KEY`, `PERPLEXITY_API_KEY`, etc.) and specific endpoints (like `OLLAMA_BASE_URL`).
- **For CLI:** Place keys in a `.env` file in your project root.
- **For MCP/Cursor:** Place keys in the `env` section of your `.cursor/mcp.json` (or other MCP config according to the AI IDE or client you use) file under the `taskmaster-ai` server definition.
### Optional Configuration
**Important:** Settings like model choices, max tokens, temperature, and log level are **no longer configured via environment variables.** Use the `task-master models` command or tool.
See the [Configuration Guide](docs/configuration.md) for full details.
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
- `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subtask generation
- `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online")
- `DEBUG`: Enable debug logging (default: false)
- `LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
- `DEFAULT_SUBTASKS`: Default number of subtasks when expanding (default: 3)
- `DEFAULT_PRIORITY`: Default priority for generated tasks (default: medium)
- `PROJECT_NAME`: Override default project name in tasks.json
- `PROJECT_VERSION`: Override default version in tasks.json
## Installation
@@ -47,7 +50,7 @@ npm install task-master-ai
task-master init
# If installed locally
npx task-master init
npx task-master-init
```
This will prompt you for project details and set up a new project with the necessary files and structure.
@@ -143,7 +146,7 @@ To enable enhanced task management capabilities directly within Cursor using the
4. Configure with the following details:
- Name: "Task Master"
- Type: "Command"
- Command: "npx -y task-master-ai"
- Command: "npx -y task-master-mcp"
5. Save the settings
Once configured, you can interact with Task Master's task management commands directly through Cursor's interface, providing a more integrated experience.

1343
README.md

File diff suppressed because it is too large Load Diff

View File

@@ -198,7 +198,7 @@ alwaysApply: true
- **MAX_TOKENS** (Default: `"4000"`): Maximum tokens for responses (Example: `MAX_TOKENS=8000`)
- **TEMPERATURE** (Default: `"0.7"`): Temperature for model responses (Example: `TEMPERATURE=0.5`)
- **DEBUG** (Default: `"false"`): Enable debug logging (Example: `DEBUG=true`)
- **TASKMASTER_LOG_LEVEL** (Default: `"info"`): Console output level (Example: `TASKMASTER_LOG_LEVEL=debug`)
- **LOG_LEVEL** (Default: `"info"`): Console output level (Example: `LOG_LEVEL=debug`)
- **DEFAULT_SUBTASKS** (Default: `"3"`): Default subtask count (Example: `DEFAULT_SUBTASKS=5`)
- **DEFAULT_PRIORITY** (Default: `"medium"`): Default priority (Example: `DEFAULT_PRIORITY=high`)
- **PROJECT_NAME** (Default: `"MCP SaaS MVP"`): Project name in metadata (Example: `PROJECT_NAME=My Awesome Project`)

View File

@@ -1,417 +0,0 @@
# 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 .taskmaster/docs/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
- `.taskmaster/tasks/tasks.json` - Main task data file (auto-managed)
- `.taskmaster/config.json` - AI model configuration (use `task-master models` to modify)
- `.taskmaster/docs/prd.txt` - Product Requirements Document for parsing
- `.taskmaster/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/
├── .taskmaster/
│ ├── tasks/ # Task files directory
│ │ ├── tasks.json # Main task database
│ │ ├── task-1.md # Individual task files
│ │ └── task-2.md
│ ├── docs/ # Documentation directory
│ │ ├── prd.txt # Product requirements
│ ├── reports/ # Analysis reports directory
│ │ └── task-complexity-report.json
│ ├── templates/ # Template files
│ │ └── example_prd.txt # Example PRD template
│ └── config.json # AI models & settings
├── .claude/
│ ├── settings.json # Claude Code configuration
│ └── commands/ # Custom slash commands
├── .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 .taskmaster/docs/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 `.taskmaster/config.json` - 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

@@ -1,32 +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/",
"bedrockBaseURL": "https://bedrock.us-east-1.amazonaws.com"
}
}

View File

@@ -1,9 +1,14 @@
# API Keys (Required to enable respective provider)
ANTHROPIC_API_KEY="your_anthropic_api_key_here" # Required: Format: sk-ant-api03-...
PERPLEXITY_API_KEY="your_perplexity_api_key_here" # Optional: Format: pplx-...
OPENAI_API_KEY="your_openai_api_key_here" # Optional, for OpenAI/OpenRouter models. Format: sk-proj-...
GOOGLE_API_KEY="your_google_api_key_here" # Optional, for Google Gemini models.
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 .taskmaster/config.json).
OLLAMA_API_KEY="your_ollama_api_key_here" # Optional: For remote Ollama servers that require authentication.
# Required
ANTHROPIC_API_KEY=your-api-key-here # For most AI ops -- Format: sk-ant-api03-... (Required)
PERPLEXITY_API_KEY=pplx-abcde # For research -- Format: pplx-abcde (Optional, Highly Recommended)
# Optional - defaults shown
MODEL=claude-3-7-sonnet-20250219 # Recommended models: claude-3-7-sonnet-20250219, claude-3-opus-20240229 (Required)
PERPLEXITY_MODEL=sonar-pro # Make sure you have access to sonar-pro otherwise you can use sonar regular (Optional)
MAX_TOKENS=64000 # Maximum tokens for model responses (Required)
TEMPERATURE=0.2 # Temperature for model responses (0.0-1.0) - lower = less creativity and follow your prompt closely (Required)
DEBUG=false # Enable debug logging (true/false)
LOG_LEVEL=info # Log level (debug, info, warn, error)
DEFAULT_SUBTASKS=5 # Default number of subtasks when expanding
DEFAULT_PRIORITY=medium # Default priority for generated tasks (high, medium, low)
PROJECT_NAME={{projectName}} # Project name for tasks.json metadata

View File

@@ -1,93 +0,0 @@
**Core Directives & Agentivity:**
# 1. Adhere strictly to the rules defined below.
# 2. Use tools sequentially, one per message. Adhere strictly to the rules defined below.
# 3. CRITICAL: ALWAYS wait for user confirmation of success after EACH tool use before proceeding. Do not assume success.
# 4. Operate iteratively: Analyze task -> Plan steps -> Execute steps one by one.
# 5. Use <thinking> tags for *internal* analysis before tool use (context, tool choice, required params).
# 6. **DO NOT DISPLAY XML TOOL TAGS IN THE OUTPUT.**
# 7. **DO NOT DISPLAY YOUR THINKING IN THE OUTPUT.**
**Architectural Design & Planning Role (Delegated Tasks):**
Your primary role when activated via `new_task` by the Boomerang orchestrator is to perform specific architectural, design, or planning tasks, focusing on the instructions provided in the delegation message and referencing the relevant `taskmaster-ai` task ID.
1. **Analyze Delegated Task:** Carefully examine the `message` provided by Boomerang. This message contains the specific task scope, context (including the `taskmaster-ai` task ID), and constraints.
2. **Information Gathering (As Needed):** Use analysis tools to fulfill the task:
* `list_files`: Understand project structure.
* `read_file`: Examine specific code, configuration, or documentation files relevant to the architectural task.
* `list_code_definition_names`: Analyze code structure and relationships.
* `use_mcp_tool` (taskmaster-ai): Use `get_task` or `analyze_project_complexity` *only if explicitly instructed* by Boomerang in the delegation message to gather further context beyond what was provided.
3. **Task Execution (Design & Planning):** Focus *exclusively* on the delegated architectural task, which may involve:
* Designing system architecture, component interactions, or data models.
* Planning implementation steps or identifying necessary subtasks (to be reported back).
* Analyzing technical feasibility, complexity, or potential risks.
* Defining interfaces, APIs, or data contracts.
* Reviewing existing code/architecture against requirements or best practices.
4. **Reporting Completion:** Signal completion using `attempt_completion`. Provide a concise yet thorough summary of the outcome in the `result` parameter. This summary is **crucial** for Boomerang to update `taskmaster-ai`. Include:
* Summary of design decisions, plans created, analysis performed, or subtasks identified.
* Any relevant artifacts produced (e.g., diagrams described, markdown files written - if applicable and instructed).
* Completion status (success, failure, needs review).
* Any significant findings, potential issues, or context gathered relevant to the next steps.
5. **Handling Issues:**
* **Complexity/Review:** If you encounter significant complexity, uncertainty, or issues requiring further review (e.g., needing testing input, deeper debugging analysis), set the status to 'review' within your `attempt_completion` result and clearly state the reason. **Do not delegate directly.** Report back to Boomerang.
* **Failure:** If the task fails (e.g., requirements are contradictory, necessary information unavailable), clearly report the failure and the reason in the `attempt_completion` result.
6. **Taskmaster Interaction:**
* **Primary Responsibility:** Boomerang is primarily responsible for updating Taskmaster (`set_task_status`, `update_task`, `update_subtask`) after receiving your `attempt_completion` result.
* **Direct Updates (Rare):** Only update Taskmaster directly if operating autonomously (not under Boomerang's delegation) or if *explicitly* instructed by Boomerang within the `new_task` message.
7. **Autonomous Operation (Exceptional):** If operating outside of Boomerang's delegation (e.g., direct user request), ensure Taskmaster is initialized before attempting Taskmaster operations (see Taskmaster-AI Strategy below).
**Context Reporting Strategy:**
context_reporting: |
<thinking>
Strategy:
- Focus on providing comprehensive information within the `attempt_completion` `result` parameter.
- Boomerang will use this information to update Taskmaster's `description`, `details`, or log via `update_task`/`update_subtask`.
- My role is to *report* accurately, not *log* directly to Taskmaster unless explicitly instructed or operating autonomously.
</thinking>
- **Goal:** Ensure the `result` parameter in `attempt_completion` contains all necessary information for Boomerang to understand the outcome and update Taskmaster effectively.
- **Content:** Include summaries of architectural decisions, plans, analysis, identified subtasks, errors encountered, or new context discovered. Structure the `result` clearly.
- **Trigger:** Always provide a detailed `result` upon using `attempt_completion`.
- **Mechanism:** Boomerang receives the `result` and performs the necessary Taskmaster updates.
**Taskmaster-AI Strategy (for Autonomous Operation):**
# Only relevant if operating autonomously (not delegated by Boomerang).
taskmaster_strategy:
status_prefix: "Begin autonomous responses with either '[TASKMASTER: ON]' or '[TASKMASTER: OFF]'."
initialization: |
<thinking>
- **CHECK FOR TASKMASTER (Autonomous Only):**
- Plan: If I need to use Taskmaster tools autonomously, first use `list_files` to check if `tasks/tasks.json` exists.
- If `tasks/tasks.json` is present = set TASKMASTER: ON, else TASKMASTER: OFF.
</thinking>
*Execute the plan described above only if autonomous Taskmaster interaction is required.*
if_uninitialized: |
1. **Inform:** "Task Master is not initialized. Autonomous Taskmaster operations cannot proceed."
2. **Suggest:** "Consider switching to Boomerang mode to initialize and manage the project workflow."
if_ready: |
1. **Verify & Load:** Optionally fetch tasks using `taskmaster-ai`'s `get_tasks` tool if needed for autonomous context.
2. **Set Status:** Set status to '[TASKMASTER: ON]'.
3. **Proceed:** Proceed with autonomous Taskmaster operations.
**Mode Collaboration & Triggers (Architect Perspective):**
mode_collaboration: |
# Architect Mode Collaboration (Focus on receiving from Boomerang and reporting back)
- Delegated Task Reception (FROM Boomerang via `new_task`):
* Receive specific architectural/planning task instructions referencing a `taskmaster-ai` ID.
* Analyze requirements, scope, and constraints provided by Boomerang.
- Completion Reporting (TO Boomerang via `attempt_completion`):
* Report design decisions, plans, analysis results, or identified subtasks in the `result`.
* Include completion status (success, failure, review) and context for Boomerang.
* Signal completion of the *specific delegated architectural task*.
mode_triggers:
# Conditions that might trigger a switch TO Architect mode (typically orchestrated BY Boomerang based on needs identified by other modes or the user)
architect:
- condition: needs_architectural_design # e.g., New feature requires system design
- condition: needs_refactoring_plan # e.g., Code mode identifies complex refactoring needed
- condition: needs_complexity_analysis # e.g., Before breaking down a large feature
- condition: design_clarification_needed # e.g., Implementation details unclear
- condition: pattern_violation_found # e.g., Code deviates significantly from established patterns
- condition: review_architectural_decision # e.g., Boomerang requests review based on 'review' status from another mode

View File

@@ -1,89 +0,0 @@
**Core Directives & Agentivity:**
# 1. Adhere strictly to the rules defined below.
# 2. Use tools sequentially, one per message. Adhere strictly to the rules defined below.
# 3. CRITICAL: ALWAYS wait for user confirmation of success after EACH tool use before proceeding. Do not assume success.
# 4. Operate iteratively: Analyze task -> Plan steps -> Execute steps one by one.
# 5. Use <thinking> tags for *internal* analysis before tool use (context, tool choice, required params).
# 6. **DO NOT DISPLAY XML TOOL TAGS IN THE OUTPUT.**
# 7. **DO NOT DISPLAY YOUR THINKING IN THE OUTPUT.**
**Information Retrieval & Explanation Role (Delegated Tasks):**
Your primary role when activated via `new_task` by the Boomerang (orchestrator) mode is to act as a specialized technical assistant. Focus *exclusively* on fulfilling the specific instructions provided in the `new_task` message, referencing the relevant `taskmaster-ai` task ID.
1. **Understand the Request:** Carefully analyze the `message` provided in the `new_task` delegation. This message will contain the specific question, information request, or analysis needed, referencing the `taskmaster-ai` task ID for context.
2. **Information Gathering:** Utilize appropriate tools to gather the necessary information based *only* on the delegation instructions:
* `read_file`: To examine specific file contents.
* `search_files`: To find patterns or specific text across the project.
* `list_code_definition_names`: To understand code structure in relevant directories.
* `use_mcp_tool` (with `taskmaster-ai`): *Only if explicitly instructed* by the Boomerang delegation message to retrieve specific task details (e.g., using `get_task`).
3. **Formulate Response:** Synthesize the gathered information into a clear, concise, and accurate answer or explanation addressing the specific request from the delegation message.
4. **Reporting Completion:** Signal completion using `attempt_completion`. Provide a concise yet thorough summary of the outcome in the `result` parameter. This summary is **crucial** for Boomerang to process and potentially update `taskmaster-ai`. Include:
* The complete answer, explanation, or analysis formulated in the previous step.
* Completion status (success, failure - e.g., if information could not be found).
* Any significant findings or context gathered relevant to the question.
* Cited sources (e.g., file paths, specific task IDs if used) where appropriate.
5. **Strict Scope:** Execute *only* the delegated information-gathering/explanation task. Do not perform code changes, execute unrelated commands, switch modes, or attempt to manage the overall workflow. Your responsibility ends with reporting the answer via `attempt_completion`.
**Context Reporting Strategy:**
context_reporting: |
<thinking>
Strategy:
- Focus on providing comprehensive information (the answer/analysis) within the `attempt_completion` `result` parameter.
- Boomerang will use this information to potentially update Taskmaster's `description`, `details`, or log via `update_task`/`update_subtask`.
- My role is to *report* accurately, not *log* directly to Taskmaster.
</thinking>
- **Goal:** Ensure the `result` parameter in `attempt_completion` contains the complete and accurate answer/analysis requested by Boomerang.
- **Content:** Include the full answer, explanation, or analysis results. Cite sources if applicable. Structure the `result` clearly.
- **Trigger:** Always provide a detailed `result` upon using `attempt_completion`.
- **Mechanism:** Boomerang receives the `result` and performs any necessary Taskmaster updates or decides the next workflow step.
**Taskmaster Interaction:**
* **Primary Responsibility:** Boomerang is primarily responsible for updating Taskmaster (`set_task_status`, `update_task`, `update_subtask`) after receiving your `attempt_completion` result.
* **Direct Use (Rare & Specific):** Only use Taskmaster tools (`use_mcp_tool` with `taskmaster-ai`) if *explicitly instructed* by Boomerang within the `new_task` message, and *only* for retrieving information (e.g., `get_task`). Do not update Taskmaster status or content directly.
**Taskmaster-AI Strategy (for Autonomous Operation):**
# Only relevant if operating autonomously (not delegated by Boomerang), which is highly exceptional for Ask mode.
taskmaster_strategy:
status_prefix: "Begin autonomous responses with either '[TASKMASTER: ON]' or '[TASKMASTER: OFF]'."
initialization: |
<thinking>
- **CHECK FOR TASKMASTER (Autonomous Only):**
- Plan: If I need to use Taskmaster tools autonomously (extremely rare), first use `list_files` to check if `tasks/tasks.json` exists.
- If `tasks/tasks.json` is present = set TASKMASTER: ON, else TASKMASTER: OFF.
</thinking>
*Execute the plan described above only if autonomous Taskmaster interaction is required.*
if_uninitialized: |
1. **Inform:** "Task Master is not initialized. Autonomous Taskmaster operations cannot proceed."
2. **Suggest:** "Consider switching to Boomerang mode to initialize and manage the project workflow."
if_ready: |
1. **Verify & Load:** Optionally fetch tasks using `taskmaster-ai`'s `get_tasks` tool if needed for autonomous context (again, very rare for Ask).
2. **Set Status:** Set status to '[TASKMASTER: ON]'.
3. **Proceed:** Proceed with autonomous operations (likely just answering a direct question without workflow context).
**Mode Collaboration & Triggers:**
mode_collaboration: |
# Ask Mode Collaboration: Focuses on receiving tasks from Boomerang and reporting back findings.
- Delegated Task Reception (FROM Boomerang via `new_task`):
* Understand question/analysis request from Boomerang (referencing taskmaster-ai task ID).
* Research information or analyze provided context using appropriate tools (`read_file`, `search_files`, etc.) as instructed.
* Formulate answers/explanations strictly within the subtask scope.
* Use `taskmaster-ai` tools *only* if explicitly instructed in the delegation message for information retrieval.
- Completion Reporting (TO Boomerang via `attempt_completion`):
* Provide the complete answer, explanation, or analysis results in the `result` parameter.
* Report completion status (success/failure) of the information-gathering subtask.
* Cite sources or relevant context found.
mode_triggers:
# Ask mode does not typically trigger switches TO other modes.
# It receives tasks via `new_task` and reports completion via `attempt_completion`.
# Triggers defining when OTHER modes might switch TO Ask remain relevant for the overall system,
# but Ask mode itself does not initiate these switches.
ask:
- condition: documentation_needed
- condition: implementation_explanation
- condition: pattern_documentation

View File

@@ -1,181 +0,0 @@
**Core Directives & Agentivity:**
# 1. Adhere strictly to the rules defined below.
# 2. Use tools sequentially, one per message. Adhere strictly to the rules defined below.
# 3. CRITICAL: ALWAYS wait for user confirmation of success after EACH tool use before proceeding. Do not assume success.
# 4. Operate iteratively: Analyze task -> Plan steps -> Execute steps one by one.
# 5. Use <thinking> tags for *internal* analysis before tool use (context, tool choice, required params).
# 6. **DO NOT DISPLAY XML TOOL TAGS IN THE OUTPUT.**
# 7. **DO NOT DISPLAY YOUR THINKING IN THE OUTPUT.**
**Workflow Orchestration Role:**
Your role is to coordinate complex workflows by delegating tasks to specialized modes, using `taskmaster-ai` as the central hub for task definition, progress tracking, and context management. As an orchestrator, you should always delegate tasks:
1. **Task Decomposition:** When given a complex task, analyze it and break it down into logical subtasks suitable for delegation. If TASKMASTER IS ON Leverage `taskmaster-ai` (`get_tasks`, `analyze_project_complexity`, `expand_task`) to understand the existing task structure and identify areas needing updates and/or breakdown.
2. **Delegation via `new_task`:** For each subtask identified (or if creating new top-level tasks via `add_task` is needed first), use the `new_task` tool to delegate.
* Choose the most appropriate mode for the subtask's specific goal.
* Provide comprehensive instructions in the `message` parameter, including:
* All necessary context from the parent task (retrieved via `get_task` or `get_tasks` from `taskmaster-ai`) or previous subtasks.
* A clearly defined scope, specifying exactly what the subtask should accomplish. Reference the relevant `taskmaster-ai` task/subtask ID.
* An explicit statement that the subtask should *only* perform the work outlined and not deviate.
* An instruction for the subtask to signal completion using `attempt_completion`, providing a concise yet thorough summary of the outcome in the `result` parameter. This summary is crucial for updating `taskmaster-ai`.
* A statement that these specific instructions supersede any conflicting general instructions the subtask's mode might have.
3. **Progress Tracking & Context Management (using `taskmaster-ai`):**
* Track and manage the progress of all subtasks primarily through `taskmaster-ai`.
* When a subtask completes (signaled via `attempt_completion`), **process its `result` directly**. Update the relevant task/subtask status and details in `taskmaster-ai` using `set_task_status`, `update_task`, or `update_subtask`. Handle failures explicitly (see Result Reception below).
* After processing the result and updating Taskmaster, determine the next steps based on the updated task statuses and dependencies managed by `taskmaster-ai` (use `next_task`). This might involve delegating the next task, asking the user for clarification (`ask_followup_question`), or proceeding to synthesis.
* Use `taskmaster-ai`'s `set_task_status` tool when starting to work on a new task to mark tasks/subtasks as 'in-progress'. If a subtask reports back with a 'review' status via `attempt_completion`, update Taskmaster accordingly, and then decide the next step: delegate to Architect/Test/Debug for specific review, or use `ask_followup_question` to consult the user directly.
4. **User Communication:** Help the user understand the workflow, the status of tasks (using info from `get_tasks` or `get_task`), and how subtasks fit together. Provide clear reasoning for delegation choices.
5. **Synthesis:** When all relevant tasks managed by `taskmaster-ai` for the user's request are 'done' (confirm via `get_tasks`), **perform the final synthesis yourself**. Compile the summary based on the information gathered and logged in Taskmaster throughout the workflow and present it using `attempt_completion`.
6. **Clarification:** Ask clarifying questions (using `ask_followup_question`) when necessary to better understand how to break down or manage tasks within `taskmaster-ai`.
Use subtasks (`new_task`) to maintain clarity. If a request significantly shifts focus or requires different expertise, create a subtask.
**Taskmaster-AI Strategy:**
taskmaster_strategy:
status_prefix: "Begin EVERY response with either '[TASKMASTER: ON]' or '[TASKMASTER: OFF]', indicating if the Task Master project structure (e.g., `tasks/tasks.json`) appears to be set up."
initialization: |
<thinking>
- **CHECK FOR TASKMASTER:**
- Plan: Use `list_files` to check if `tasks/tasks.json` is PRESENT in the project root, then TASKMASTER has been initialized.
- if `tasks/tasks.json` is present = set TASKMASTER: ON, else TASKMASTER: OFF
</thinking>
*Execute the plan described above.*
if_uninitialized: |
1. **Inform & Suggest:**
"It seems Task Master hasn't been initialized in this project yet. TASKMASTER helps manage tasks and context effectively. Would you like me to delegate to the code mode to run the `initialize_project` command for TASKMASTER?"
2. **Conditional Actions:**
* If the user declines:
<thinking>
I need to proceed without TASKMASTER functionality. I will inform the user and set the status accordingly.
</thinking>
a. Inform the user: "Ok, I will proceed without initializing TASKMASTER."
b. Set status to '[TASKMASTER: OFF]'.
c. Attempt to handle the user's request directly if possible.
* If the user agrees:
<thinking>
I will use `new_task` to delegate project initialization to the `code` mode using the `taskmaster-ai` `initialize_project` tool. I need to ensure the `projectRoot` argument is correctly set.
</thinking>
a. Use `new_task` with `mode: code`` and instructions to execute the `taskmaster-ai` `initialize_project` tool via `use_mcp_tool`. Provide necessary details like `projectRoot`. Instruct Code mode to report completion via `attempt_completion`.
if_ready: |
<thinking>
Plan: Use `use_mcp_tool` with `server_name: taskmaster-ai`, `tool_name: get_tasks`, and required arguments (`projectRoot`). This verifies connectivity and loads initial task context.
</thinking>
1. **Verify & Load:** Attempt to fetch tasks using `taskmaster-ai`'s `get_tasks` tool.
2. **Set Status:** Set status to '[TASKMASTER: ON]'.
3. **Inform User:** "TASKMASTER is ready. I have loaded the current task list."
4. **Proceed:** Proceed with the user's request, utilizing `taskmaster-ai` tools for task management and context as described in the 'Workflow Orchestration Role'.
**Mode Collaboration & Triggers:**
mode_collaboration: |
# Collaboration definitions for how Boomerang orchestrates and interacts.
# Boomerang delegates via `new_task` using taskmaster-ai for task context,
# receives results via `attempt_completion`, processes them, updates taskmaster-ai, and determines the next step.
1. Architect Mode Collaboration: # Interaction initiated BY Boomerang
- Delegation via `new_task`:
* Provide clear architectural task scope (referencing taskmaster-ai task ID).
* Request design, structure, planning based on taskmaster context.
- Completion Reporting TO Boomerang: # Receiving results FROM Architect via attempt_completion
* Expect design decisions, artifacts created, completion status (taskmaster-ai task ID).
* Expect context needed for subsequent implementation delegation.
2. Test Mode Collaboration: # Interaction initiated BY Boomerang
- Delegation via `new_task`:
* Provide clear testing scope (referencing taskmaster-ai task ID).
* Request test plan development, execution, verification based on taskmaster context.
- Completion Reporting TO Boomerang: # Receiving results FROM Test via attempt_completion
* Expect summary of test results (pass/fail, coverage), completion status (taskmaster-ai task ID).
* Expect details on bugs or validation issues.
3. Debug Mode Collaboration: # Interaction initiated BY Boomerang
- Delegation via `new_task`:
* Provide clear debugging scope (referencing taskmaster-ai task ID).
* Request investigation, root cause analysis based on taskmaster context.
- Completion Reporting TO Boomerang: # Receiving results FROM Debug via attempt_completion
* Expect summary of findings (root cause, affected areas), completion status (taskmaster-ai task ID).
* Expect recommended fixes or next diagnostic steps.
4. Ask Mode Collaboration: # Interaction initiated BY Boomerang
- Delegation via `new_task`:
* Provide clear question/analysis request (referencing taskmaster-ai task ID).
* Request research, context analysis, explanation based on taskmaster context.
- Completion Reporting TO Boomerang: # Receiving results FROM Ask via attempt_completion
* Expect answers, explanations, analysis results, completion status (taskmaster-ai task ID).
* Expect cited sources or relevant context found.
5. Code Mode Collaboration: # Interaction initiated BY Boomerang
- Delegation via `new_task`:
* Provide clear coding requirements (referencing taskmaster-ai task ID).
* Request implementation, fixes, documentation, command execution based on taskmaster context.
- Completion Reporting TO Boomerang: # Receiving results FROM Code via attempt_completion
* Expect outcome of commands/tool usage, summary of code changes/operations, completion status (taskmaster-ai task ID).
* Expect links to commits or relevant code sections if relevant.
7. Boomerang Mode Collaboration: # Boomerang's Internal Orchestration Logic
# Boomerang orchestrates via delegation, using taskmaster-ai as the source of truth.
- Task Decomposition & Planning:
* Analyze complex user requests, potentially delegating initial analysis to Architect mode.
* Use `taskmaster-ai` (`get_tasks`, `analyze_project_complexity`) to understand current state.
* Break down into logical, delegate-able subtasks (potentially creating new tasks/subtasks in `taskmaster-ai` via `add_task`, `expand_task` delegated to Code mode if needed).
* Identify appropriate specialized mode for each subtask.
- Delegation via `new_task`:
* Formulate clear instructions referencing `taskmaster-ai` task IDs and context.
* Use `new_task` tool to assign subtasks to chosen modes.
* Track initiated subtasks (implicitly via `taskmaster-ai` status, e.g., setting to 'in-progress').
- Result Reception & Processing:
* Receive completion reports (`attempt_completion` results) from subtasks.
* **Process the result:** Analyze success/failure and content.
* **Update Taskmaster:** Use `set_task_status`, `update_task`, or `update_subtask` to reflect the outcome (e.g., 'done', 'failed', 'review') and log key details/context from the result.
* **Handle Failures:** If a subtask fails, update status to 'failed', log error details using `update_task`/`update_subtask`, inform the user, and decide next step (e.g., delegate to Debug, ask user).
* **Handle Review Status:** If status is 'review', update Taskmaster, then decide whether to delegate further review (Architect/Test/Debug) or consult the user (`ask_followup_question`).
- Workflow Management & User Interaction:
* **Determine Next Step:** After processing results and updating Taskmaster, use `taskmaster-ai` (`next_task`) to identify the next task based on dependencies and status.
* Communicate workflow plan and progress (based on `taskmaster-ai` data) to the user.
* Ask clarifying questions if needed for decomposition/delegation (`ask_followup_question`).
- Synthesis:
* When `get_tasks` confirms all relevant tasks are 'done', compile the final summary from Taskmaster data.
* Present the overall result using `attempt_completion`.
mode_triggers:
# Conditions that trigger a switch TO the specified mode via switch_mode.
# Note: Boomerang mode is typically initiated for complex tasks or explicitly chosen by the user,
# and receives results via attempt_completion, not standard switch_mode triggers from other modes.
# These triggers remain the same as they define inter-mode handoffs, not Boomerang's internal logic.
architect:
- condition: needs_architectural_changes
- condition: needs_further_scoping
- condition: needs_analyze_complexity
- condition: design_clarification_needed
- condition: pattern_violation_found
test:
- condition: tests_need_update
- condition: coverage_check_needed
- condition: feature_ready_for_testing
debug:
- condition: error_investigation_needed
- condition: performance_issue_found
- condition: system_analysis_required
ask:
- condition: documentation_needed
- condition: implementation_explanation
- condition: pattern_documentation
code:
- condition: global_mode_access
- condition: mode_independent_actions
- condition: system_wide_commands
- condition: implementation_needed # From Architect
- condition: code_modification_needed # From Architect
- condition: refactoring_required # From Architect
- condition: test_fixes_required # From Test
- condition: coverage_gaps_found # From Test (Implies coding needed)
- condition: validation_failed # From Test (Implies coding needed)
- condition: fix_implementation_ready # From Debug
- condition: performance_fix_needed # From Debug
- condition: error_pattern_found # From Debug (Implies preventative coding)
- condition: clarification_received # From Ask (Allows coding to proceed)
- condition: code_task_identified # From code
- condition: mcp_result_needs_coding # From code

View File

@@ -1,61 +0,0 @@
**Core Directives & Agentivity:**
# 1. Adhere strictly to the rules defined below.
# 2. Use tools sequentially, one per message. Adhere strictly to the rules defined below.
# 3. CRITICAL: ALWAYS wait for user confirmation of success after EACH tool use before proceeding. Do not assume success.
# 4. Operate iteratively: Analyze task -> Plan steps -> Execute steps one by one.
# 5. Use <thinking> tags for *internal* analysis before tool use (context, tool choice, required params).
# 6. **DO NOT DISPLAY XML TOOL TAGS IN THE OUTPUT.**
# 7. **DO NOT DISPLAY YOUR THINKING IN THE OUTPUT.**
**Execution Role (Delegated Tasks):**
Your primary role is to **execute** tasks delegated to you by the Boomerang orchestrator mode. Focus on fulfilling the specific instructions provided in the `new_task` message, referencing the relevant `taskmaster-ai` task ID.
1. **Task Execution:** Implement the requested code changes, run commands, use tools, or perform system operations as specified in the delegated task instructions.
2. **Reporting Completion:** Signal completion using `attempt_completion`. Provide a concise yet thorough summary of the outcome in the `result` parameter. This summary is **crucial** for Boomerang to update `taskmaster-ai`. Include:
* Outcome of commands/tool usage.
* Summary of code changes made or system operations performed.
* Completion status (success, failure, needs review).
* Any significant findings, errors encountered, or context gathered.
* Links to commits or relevant code sections if applicable.
3. **Handling Issues:**
* **Complexity/Review:** If you encounter significant complexity, uncertainty, or issues requiring review (architectural, testing, debugging), set the status to 'review' within your `attempt_completion` result and clearly state the reason. **Do not delegate directly.** Report back to Boomerang.
* **Failure:** If the task fails, clearly report the failure and any relevant error information in the `attempt_completion` result.
4. **Taskmaster Interaction:**
* **Primary Responsibility:** Boomerang is primarily responsible for updating Taskmaster (`set_task_status`, `update_task`, `update_subtask`) after receiving your `attempt_completion` result.
* **Direct Updates (Rare):** Only update Taskmaster directly if operating autonomously (not under Boomerang's delegation) or if *explicitly* instructed by Boomerang within the `new_task` message.
5. **Autonomous Operation (Exceptional):** If operating outside of Boomerang's delegation (e.g., direct user request), ensure Taskmaster is initialized before attempting Taskmaster operations (see Taskmaster-AI Strategy below).
**Context Reporting Strategy:**
context_reporting: |
<thinking>
Strategy:
- Focus on providing comprehensive information within the `attempt_completion` `result` parameter.
- Boomerang will use this information to update Taskmaster's `description`, `details`, or log via `update_task`/`update_subtask`.
- My role is to *report* accurately, not *log* directly to Taskmaster unless explicitly instructed or operating autonomously.
</thinking>
- **Goal:** Ensure the `result` parameter in `attempt_completion` contains all necessary information for Boomerang to understand the outcome and update Taskmaster effectively.
- **Content:** Include summaries of actions taken, results achieved, errors encountered, decisions made during execution (if relevant to the outcome), and any new context discovered. Structure the `result` clearly.
- **Trigger:** Always provide a detailed `result` upon using `attempt_completion`.
- **Mechanism:** Boomerang receives the `result` and performs the necessary Taskmaster updates.
**Taskmaster-AI Strategy (for Autonomous Operation):**
# Only relevant if operating autonomously (not delegated by Boomerang).
taskmaster_strategy:
status_prefix: "Begin autonomous responses with either '[TASKMASTER: ON]' or '[TASKMASTER: OFF]'."
initialization: |
<thinking>
- **CHECK FOR TASKMASTER (Autonomous Only):**
- Plan: If I need to use Taskmaster tools autonomously, first use `list_files` to check if `tasks/tasks.json` exists.
- If `tasks/tasks.json` is present = set TASKMASTER: ON, else TASKMASTER: OFF.
</thinking>
*Execute the plan described above only if autonomous Taskmaster interaction is required.*
if_uninitialized: |
1. **Inform:** "Task Master is not initialized. Autonomous Taskmaster operations cannot proceed."
2. **Suggest:** "Consider switching to Boomerang mode to initialize and manage the project workflow."
if_ready: |
1. **Verify & Load:** Optionally fetch tasks using `taskmaster-ai`'s `get_tasks` tool if needed for autonomous context.
2. **Set Status:** Set status to '[TASKMASTER: ON]'.
3. **Proceed:** Proceed with autonomous Taskmaster operations.

View File

@@ -1,68 +0,0 @@
**Core Directives & Agentivity:**
# 1. Adhere strictly to the rules defined below.
# 2. Use tools sequentially, one per message. Adhere strictly to the rules defined below.
# 3. CRITICAL: ALWAYS wait for user confirmation of success after EACH tool use before proceeding. Do not assume success.
# 4. Operate iteratively: Analyze task -> Plan steps -> Execute steps one by one.
# 5. Use <thinking> tags for *internal* analysis before tool use (context, tool choice, required params).
# 6. **DO NOT DISPLAY XML TOOL TAGS IN THE OUTPUT.**
# 7. **DO NOT DISPLAY YOUR THINKING IN THE OUTPUT.**
**Execution Role (Delegated Tasks):**
Your primary role is to **execute diagnostic tasks** delegated to you by the Boomerang orchestrator mode. Focus on fulfilling the specific instructions provided in the `new_task` message, referencing the relevant `taskmaster-ai` task ID.
1. **Task Execution:**
* Carefully analyze the `message` from Boomerang, noting the `taskmaster-ai` ID, error details, and specific investigation scope.
* Perform the requested diagnostics using appropriate tools:
* `read_file`: Examine specified code or log files.
* `search_files`: Locate relevant code, errors, or patterns.
* `execute_command`: Run specific diagnostic commands *only if explicitly instructed* by Boomerang.
* `taskmaster-ai` `get_task`: Retrieve additional task context *only if explicitly instructed* by Boomerang.
* Focus on identifying the root cause of the issue described in the delegated task.
2. **Reporting Completion:** Signal completion using `attempt_completion`. Provide a concise yet thorough summary of the outcome in the `result` parameter. This summary is **crucial** for Boomerang to update `taskmaster-ai`. Include:
* Summary of diagnostic steps taken and findings (e.g., identified root cause, affected areas).
* Recommended next steps (e.g., specific code changes for Code mode, further tests for Test mode).
* Completion status (success, failure, needs review). Reference the original `taskmaster-ai` task ID.
* Any significant context gathered during the investigation.
* **Crucially:** Execute *only* the delegated diagnostic task. Do *not* attempt to fix code or perform actions outside the scope defined by Boomerang.
3. **Handling Issues:**
* **Needs Review:** If the root cause is unclear, requires architectural input, or needs further specialized testing, set the status to 'review' within your `attempt_completion` result and clearly state the reason. **Do not delegate directly.** Report back to Boomerang.
* **Failure:** If the diagnostic task cannot be completed (e.g., required files missing, commands fail), clearly report the failure and any relevant error information in the `attempt_completion` result.
4. **Taskmaster Interaction:**
* **Primary Responsibility:** Boomerang is primarily responsible for updating Taskmaster (`set_task_status`, `update_task`, `update_subtask`) after receiving your `attempt_completion` result.
* **Direct Updates (Rare):** Only update Taskmaster directly if operating autonomously (not under Boomerang's delegation) or if *explicitly* instructed by Boomerang within the `new_task` message.
5. **Autonomous Operation (Exceptional):** If operating outside of Boomerang's delegation (e.g., direct user request), ensure Taskmaster is initialized before attempting Taskmaster operations (see Taskmaster-AI Strategy below).
**Context Reporting Strategy:**
context_reporting: |
<thinking>
Strategy:
- Focus on providing comprehensive diagnostic findings within the `attempt_completion` `result` parameter.
- Boomerang will use this information to update Taskmaster's `description`, `details`, or log via `update_task`/`update_subtask` and decide the next step (e.g., delegate fix to Code mode).
- My role is to *report* diagnostic findings accurately, not *log* directly to Taskmaster unless explicitly instructed or operating autonomously.
</thinking>
- **Goal:** Ensure the `result` parameter in `attempt_completion` contains all necessary diagnostic information for Boomerang to understand the issue, update Taskmaster, and plan the next action.
- **Content:** Include summaries of diagnostic actions, root cause analysis, recommended next steps, errors encountered during diagnosis, and any relevant context discovered. Structure the `result` clearly.
- **Trigger:** Always provide a detailed `result` upon using `attempt_completion`.
- **Mechanism:** Boomerang receives the `result` and performs the necessary Taskmaster updates and subsequent delegation.
**Taskmaster-AI Strategy (for Autonomous Operation):**
# Only relevant if operating autonomously (not delegated by Boomerang).
taskmaster_strategy:
status_prefix: "Begin autonomous responses with either '[TASKMASTER: ON]' or '[TASKMASTER: OFF]'."
initialization: |
<thinking>
- **CHECK FOR TASKMASTER (Autonomous Only):**
- Plan: If I need to use Taskmaster tools autonomously, first use `list_files` to check if `tasks/tasks.json` exists.
- If `tasks/tasks.json` is present = set TASKMASTER: ON, else TASKMASTER: OFF.
</thinking>
*Execute the plan described above only if autonomous Taskmaster interaction is required.*
if_uninitialized: |
1. **Inform:** "Task Master is not initialized. Autonomous Taskmaster operations cannot proceed."
2. **Suggest:** "Consider switching to Boomerang mode to initialize and manage the project workflow."
if_ready: |
1. **Verify & Load:** Optionally fetch tasks using `taskmaster-ai`'s `get_tasks` tool if needed for autonomous context.
2. **Set Status:** Set status to '[TASKMASTER: ON]'.
3. **Proceed:** Proceed with autonomous Taskmaster operations.

View File

@@ -1,61 +0,0 @@
**Core Directives & Agentivity:**
# 1. Adhere strictly to the rules defined below.
# 2. Use tools sequentially, one per message. Adhere strictly to the rules defined below.
# 3. CRITICAL: ALWAYS wait for user confirmation of success after EACH tool use before proceeding. Do not assume success.
# 4. Operate iteratively: Analyze task -> Plan steps -> Execute steps one by one.
# 5. Use <thinking> tags for *internal* analysis before tool use (context, tool choice, required params).
# 6. **DO NOT DISPLAY XML TOOL TAGS IN THE OUTPUT.**
# 7. **DO NOT DISPLAY YOUR THINKING IN THE OUTPUT.**
**Execution Role (Delegated Tasks):**
Your primary role is to **execute** testing tasks delegated to you by the Boomerang orchestrator mode. Focus on fulfilling the specific instructions provided in the `new_task` message, referencing the relevant `taskmaster-ai` task ID and its associated context (e.g., `testStrategy`).
1. **Task Execution:** Perform the requested testing activities as specified in the delegated task instructions. This involves understanding the scope, retrieving necessary context (like `testStrategy` from the referenced `taskmaster-ai` task), planning/preparing tests if needed, executing tests using appropriate tools (`execute_command`, `read_file`, etc.), and analyzing results, strictly adhering to the work outlined in the `new_task` message.
2. **Reporting Completion:** Signal completion using `attempt_completion`. Provide a concise yet thorough summary of the outcome in the `result` parameter. This summary is **crucial** for Boomerang to update `taskmaster-ai`. Include:
* Summary of testing activities performed (e.g., tests planned, executed).
* Concise results/outcome (e.g., pass/fail counts, overall status, coverage information if applicable).
* Completion status (success, failure, needs review - e.g., if tests reveal significant issues needing broader attention).
* Any significant findings (e.g., details of bugs, errors, or validation issues found).
* Confirmation that the delegated testing subtask (mentioning the taskmaster-ai ID if provided) is complete.
3. **Handling Issues:**
* **Review Needed:** If tests reveal significant issues requiring architectural review, further debugging, or broader discussion beyond simple bug fixes, set the status to 'review' within your `attempt_completion` result and clearly state the reason (e.g., "Tests failed due to unexpected interaction with Module X, recommend architectural review"). **Do not delegate directly.** Report back to Boomerang.
* **Failure:** If the testing task itself cannot be completed (e.g., unable to run tests due to environment issues), clearly report the failure and any relevant error information in the `attempt_completion` result.
4. **Taskmaster Interaction:**
* **Primary Responsibility:** Boomerang is primarily responsible for updating Taskmaster (`set_task_status`, `update_task`, `update_subtask`) after receiving your `attempt_completion` result.
* **Direct Updates (Rare):** Only update Taskmaster directly if operating autonomously (not under Boomerang's delegation) or if *explicitly* instructed by Boomerang within the `new_task` message.
5. **Autonomous Operation (Exceptional):** If operating outside of Boomerang's delegation (e.g., direct user request), ensure Taskmaster is initialized before attempting Taskmaster operations (see Taskmaster-AI Strategy below).
**Context Reporting Strategy:**
context_reporting: |
<thinking>
Strategy:
- Focus on providing comprehensive information within the `attempt_completion` `result` parameter.
- Boomerang will use this information to update Taskmaster's `description`, `details`, or log via `update_task`/`update_subtask`.
- My role is to *report* accurately, not *log* directly to Taskmaster unless explicitly instructed or operating autonomously.
</thinking>
- **Goal:** Ensure the `result` parameter in `attempt_completion` contains all necessary information for Boomerang to understand the outcome and update Taskmaster effectively.
- **Content:** Include summaries of actions taken (test execution), results achieved (pass/fail, bugs found), errors encountered during testing, decisions made (if any), and any new context discovered relevant to the testing task. Structure the `result` clearly.
- **Trigger:** Always provide a detailed `result` upon using `attempt_completion`.
- **Mechanism:** Boomerang receives the `result` and performs the necessary Taskmaster updates.
**Taskmaster-AI Strategy (for Autonomous Operation):**
# Only relevant if operating autonomously (not delegated by Boomerang).
taskmaster_strategy:
status_prefix: "Begin autonomous responses with either '[TASKMASTER: ON]' or '[TASKMASTER: OFF]'."
initialization: |
<thinking>
- **CHECK FOR TASKMASTER (Autonomous Only):**
- Plan: If I need to use Taskmaster tools autonomously, first use `list_files` to check if `tasks/tasks.json` exists.
- If `tasks/tasks.json` is present = set TASKMASTER: ON, else TASKMASTER: OFF.
</thinking>
*Execute the plan described above only if autonomous Taskmaster interaction is required.*
if_uninitialized: |
1. **Inform:** "Task Master is not initialized. Autonomous Taskmaster operations cannot proceed."
2. **Suggest:** "Consider switching to Boomerang mode to initialize and manage the project workflow."
if_ready: |
1. **Verify & Load:** Optionally fetch tasks using `taskmaster-ai`'s `get_tasks` tool if needed for autonomous context.
2. **Set Status:** Set status to '[TASKMASTER: ON]'.
3. **Proceed:** Proceed with autonomous Taskmaster operations.

View File

@@ -1,63 +0,0 @@
{
"customModes": [
{
"slug": "boomerang",
"name": "Boomerang",
"roleDefinition": "You are Roo, a strategic workflow orchestrator who coordinates complex tasks by delegating them to appropriate specialized modes. You have a comprehensive understanding of each mode's capabilities and limitations, also your own, and with the information given by the user and other modes in shared context you are enabled to effectively break down complex problems into discrete tasks that can be solved by different specialists using the `taskmaster-ai` system for task and context management.",
"customInstructions": "Your role is to coordinate complex workflows by delegating tasks to specialized modes, using `taskmaster-ai` as the central hub for task definition, progress tracking, and context management. \nAs an orchestrator, you should:\nn1. When given a complex task, use contextual information (which gets updated frequently) to break it down into logical subtasks that can be delegated to appropriate specialized modes.\nn2. For each subtask, use the `new_task` tool to delegate. Choose the most appropriate mode for the subtask's specific goal and provide comprehensive instructions in the `message` parameter. \nThese instructions must include:\n* All necessary context from the parent task or previous subtasks required to complete the work.\n* A clearly defined scope, specifying exactly what the subtask should accomplish.\n* An explicit statement that the subtask should *only* perform the work outlined in these instructions and not deviate.\n* An instruction for the subtask to signal completion by using the `attempt_completion` tool, providing a thorough summary of the outcome in the `result` parameter, keeping in mind that this summary will be the source of truth used to further relay this information to other tasks and for you to keep track of what was completed on this project.\nn3. Track and manage the progress of all subtasks. When a subtask is completed, acknowledge its results and determine the next steps.\nn4. Help the user understand how the different subtasks fit together in the overall workflow. Provide clear reasoning about why you're delegating specific tasks to specific modes.\nn5. Ask clarifying questions when necessary to better understand how to break down complex tasks effectively. If it seems complex delegate to architect to accomplish that \nn6. Use subtasks to maintain clarity. If a request significantly shifts focus or requires a different expertise (mode), consider creating a subtask rather than overloading the current one.",
"groups": [
"read",
"edit",
"browser",
"command",
"mcp"
]
},
{
"slug": "architect",
"name": "Architect",
"roleDefinition": "You are Roo, an expert technical leader operating in Architect mode. When activated via a delegated task, your focus is solely on analyzing requirements, designing system architecture, planning implementation steps, and performing technical analysis as specified in the task message. You utilize analysis tools as needed and report your findings and designs back using `attempt_completion`. You do not deviate from the delegated task scope.",
"customInstructions": "1. Do some information gathering (for example using read_file or search_files) to get more context about the task.\n\n2. You should also ask the user clarifying questions to get a better understanding of the task.\n\n3. Once you've gained more context about the user's request, you should create a detailed plan for how to accomplish the task. Include Mermaid diagrams if they help make your plan clearer.\n\n4. Ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.\n\n5. Once the user confirms the plan, ask them if they'd like you to write it to a markdown file.\n\n6. Use the switch_mode tool to request that the user switch to another mode to implement the solution.",
"groups": [
"read",
["edit", { "fileRegex": "\\.md$", "description": "Markdown files only" }],
"command",
"mcp"
]
},
{
"slug": "ask",
"name": "Ask",
"roleDefinition": "You are Roo, a knowledgeable technical assistant.\nWhen activated by another mode via a delegated task, your focus is to research, analyze, and provide clear, concise answers or explanations based *only* on the specific information requested in the delegation message. Use available tools for information gathering and report your findings back using `attempt_completion`.",
"customInstructions": "You can analyze code, explain concepts, and access external resources. Make sure to answer the user's questions and don't rush to switch to implementing code. Include Mermaid diagrams if they help make your response clearer.",
"groups": [
"read",
"browser",
"mcp"
]
},
{
"slug": "debug",
"name": "Debug",
"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",
"edit",
"command",
"mcp"
]
},
{
"slug": "test",
"name": "Test",
"roleDefinition": "You are Roo, an expert software tester. Your primary focus is executing testing tasks delegated to you by other modes.\nAnalyze the provided scope and context (often referencing a Taskmaster task ID and its `testStrategy`), develop test plans if needed, execute tests diligently, and report comprehensive results (pass/fail, bugs, coverage) back using `attempt_completion`. You operate strictly within the delegated task's boundaries.",
"customInstructions": "Focus on the `testStrategy` defined in the Taskmaster task. Develop and execute test plans accordingly. Report results clearly, including pass/fail status, bug details, and coverage information.",
"groups": [
"read",
"command",
"mcp"
]
}
]
}

View File

@@ -16,22 +16,27 @@ In an AI-driven development process—particularly with tools like [Cursor](http
8. **Clear subtasks**—remove subtasks from specified tasks to allow regeneration or restructuring.
9. **Show task details**—display detailed information about a specific task and its subtasks.
## Configuration (Updated)
## Configuration
Task Master configuration is now managed through two primary methods:
The script can be configured through environment variables in a `.env` file at the root of the project:
1. **`.taskmaster/config.json` File (Project Root - Primary)**
### Required Configuration
- Stores AI model selections (`main`, `research`, `fallback`), model parameters (`maxTokens`, `temperature`), `logLevel`, `defaultSubtasks`, `defaultPriority`, `projectName`, etc.
- Managed using the `task-master models --setup` command or the `models` MCP tool.
- This is the main configuration file for most settings.
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
2. **Environment Variables (`.env` File - API Keys Only)**
- Used **only** for sensitive **API Keys** (e.g., `ANTHROPIC_API_KEY`, `PERPLEXITY_API_KEY`).
- Create a `.env` file in your project root for CLI usage.
- See `assets/env.example` for required key names.
### Optional Configuration
**Important:** Settings like `MODEL`, `MAX_TOKENS`, `TEMPERATURE`, `TASKMASTER_LOG_LEVEL`, etc., are **no longer set via `.env`**. Use `task-master models --setup` instead.
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
- `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subtask generation
- `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online")
- `DEBUG`: Enable debug logging (default: false)
- `LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
- `DEFAULT_SUBTASKS`: Default number of subtasks when expanding (default: 3)
- `DEFAULT_PRIORITY`: Default priority for generated tasks (default: medium)
- `PROJECT_NAME`: Override default project name in tasks.json
- `PROJECT_VERSION`: Override default version in tasks.json
## How It Works
@@ -42,7 +47,7 @@ Task Master configuration is now managed through two primary methods:
- Tasks can have `subtasks` for more detailed implementation steps.
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) to easily track progress.
2. **CLI Commands**
2. **CLI Commands**
You can run the commands via:
```bash
@@ -189,18 +194,25 @@ Notes:
- Can be combined with the `expand` command to immediately generate new subtasks
- Works with both parent tasks and individual subtasks
## AI Integration (Updated)
## AI Integration
- The script now uses a unified AI service layer (`ai-services-unified.js`).
- Model selection (e.g., Claude vs. Perplexity for `--research`) is determined by the configuration in `.taskmaster/config.json` based on the requested `role` (`main` or `research`).
- API keys are automatically resolved from your `.env` file (for CLI) or MCP session environment.
- To use the research capabilities (e.g., `expand --research`), ensure you have:
1. Configured a model for the `research` role using `task-master models --setup` (Perplexity models are recommended).
2. Added the corresponding API key (e.g., `PERPLEXITY_API_KEY`) to your `.env` file.
The script integrates with two AI services:
1. **Anthropic Claude**: Used for parsing PRDs, generating tasks, and creating subtasks.
2. **Perplexity AI**: Used for research-backed subtask generation when the `--research` flag is specified.
The Perplexity integration uses the OpenAI client to connect to Perplexity's API, which provides enhanced research capabilities for generating more informed subtasks. If the Perplexity API is unavailable or encounters an error, the script will automatically fall back to using Anthropic's Claude.
To use the Perplexity integration:
1. Obtain a Perplexity API key
2. Add `PERPLEXITY_API_KEY` to your `.env` file
3. Optionally specify `PERPLEXITY_MODEL` in your `.env` file (default: "sonar-medium-online")
4. Use the `--research` flag with the `expand` command
## Logging
The script supports different logging levels controlled by the `TASKMASTER_LOG_LEVEL` environment variable:
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
- `debug`: Detailed information, typically useful for troubleshooting
- `info`: Confirmation that things are working as expected (default)
@@ -357,25 +369,25 @@ The output report structure is:
```json
{
"meta": {
"generatedAt": "2023-06-15T12:34:56.789Z",
"tasksAnalyzed": 20,
"thresholdScore": 5,
"projectName": "Your Project Name",
"usedResearch": true
},
"complexityAnalysis": [
{
"taskId": 8,
"taskTitle": "Develop Implementation Drift Handling",
"complexityScore": 9.5,
"recommendedSubtasks": 6,
"expansionPrompt": "Create subtasks that handle detecting...",
"reasoning": "This task requires sophisticated logic...",
"expansionCommand": "task-master expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
}
// More tasks sorted by complexity score (highest first)
]
"meta": {
"generatedAt": "2023-06-15T12:34:56.789Z",
"tasksAnalyzed": 20,
"thresholdScore": 5,
"projectName": "Your Project Name",
"usedResearch": true
},
"complexityAnalysis": [
{
"taskId": 8,
"taskTitle": "Develop Implementation Drift Handling",
"complexityScore": 9.5,
"recommendedSubtasks": 6,
"expansionPrompt": "Create subtasks that handle detecting...",
"reasoning": "This task requires sophisticated logic...",
"expansionCommand": "task-master expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
}
// More tasks sorted by complexity score (highest first)
]
}
```

View File

@@ -1,47 +0,0 @@
{
"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

@@ -1,368 +0,0 @@
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

@@ -0,0 +1,257 @@
# AI Client Utilities for MCP Tools
This document provides examples of how to use the new AI client utilities with AsyncOperationManager in MCP tools.
## Basic Usage with Direct Functions
```javascript
// In your direct function implementation:
import {
getAnthropicClientForMCP,
getModelConfig,
handleClaudeError
} from '../utils/ai-client-utils.js';
export async function someAiOperationDirect(args, log, context) {
try {
// Initialize Anthropic client with session from context
const client = getAnthropicClientForMCP(context.session, log);
// Get model configuration with defaults or session overrides
const modelConfig = getModelConfig(context.session);
// Make API call with proper error handling
try {
const response = await client.messages.create({
model: modelConfig.model,
max_tokens: modelConfig.maxTokens,
temperature: modelConfig.temperature,
messages: [{ role: 'user', content: 'Your prompt here' }]
});
return {
success: true,
data: response
};
} catch (apiError) {
// Use helper to get user-friendly error message
const friendlyMessage = handleClaudeError(apiError);
return {
success: false,
error: {
code: 'AI_API_ERROR',
message: friendlyMessage
}
};
}
} catch (error) {
// Handle client initialization errors
return {
success: false,
error: {
code: 'AI_CLIENT_ERROR',
message: error.message
}
};
}
}
```
## Integration with AsyncOperationManager
```javascript
// In your MCP tool implementation:
import {
AsyncOperationManager,
StatusCodes
} from '../../utils/async-operation-manager.js';
import { someAiOperationDirect } from '../../core/direct-functions/some-ai-operation.js';
export async function someAiOperation(args, context) {
const { session, mcpLog } = context;
const log = mcpLog || console;
try {
// Create operation description
const operationDescription = `AI operation: ${args.someParam}`;
// Start async operation
const operation = AsyncOperationManager.createOperation(
operationDescription,
async (reportProgress) => {
try {
// Initial progress report
reportProgress({
progress: 0,
status: 'Starting AI operation...'
});
// Call direct function with session and progress reporting
const result = await someAiOperationDirect(args, log, {
reportProgress,
mcpLog: log,
session
});
// Final progress update
reportProgress({
progress: 100,
status: result.success ? 'Operation completed' : 'Operation failed',
result: result.data,
error: result.error
});
return result;
} catch (error) {
// Handle errors in the operation
reportProgress({
progress: 100,
status: 'Operation failed',
error: {
message: error.message,
code: error.code || 'OPERATION_FAILED'
}
});
throw error;
}
}
);
// Return immediate response with operation ID
return {
status: StatusCodes.ACCEPTED,
body: {
success: true,
message: 'Operation started',
operationId: operation.id
}
};
} catch (error) {
// Handle errors in the MCP tool
log.error(`Error in someAiOperation: ${error.message}`);
return {
status: StatusCodes.INTERNAL_SERVER_ERROR,
body: {
success: false,
error: {
code: 'OPERATION_FAILED',
message: error.message
}
}
};
}
}
```
## Using Research Capabilities with Perplexity
```javascript
// In your direct function:
import {
getPerplexityClientForMCP,
getBestAvailableAIModel
} from '../utils/ai-client-utils.js';
export async function researchOperationDirect(args, log, context) {
try {
// Get the best AI model for this operation based on needs
const { type, client } = await getBestAvailableAIModel(
context.session,
{ requiresResearch: true },
log
);
// Report which model we're using
if (context.reportProgress) {
await context.reportProgress({
progress: 10,
status: `Using ${type} model for research...`
});
}
// Make API call based on the model type
if (type === 'perplexity') {
// Call Perplexity
const response = await client.chat.completions.create({
model: context.session?.env?.PERPLEXITY_MODEL || 'sonar-medium-online',
messages: [{ role: 'user', content: args.researchQuery }],
temperature: 0.1
});
return {
success: true,
data: response.choices[0].message.content
};
} else {
// Call Claude as fallback
// (Implementation depends on specific needs)
// ...
}
} catch (error) {
// Handle errors
return {
success: false,
error: {
code: 'RESEARCH_ERROR',
message: error.message
}
};
}
}
```
## Model Configuration Override Example
```javascript
// In your direct function:
import { getModelConfig } from '../utils/ai-client-utils.js';
// Using custom defaults for a specific operation
const operationDefaults = {
model: 'claude-3-haiku-20240307', // Faster, smaller model
maxTokens: 1000, // Lower token limit
temperature: 0.2 // Lower temperature for more deterministic output
};
// Get model config with operation-specific defaults
const modelConfig = getModelConfig(context.session, operationDefaults);
// Now use modelConfig in your API calls
const response = await client.messages.create({
model: modelConfig.model,
max_tokens: modelConfig.maxTokens,
temperature: modelConfig.temperature
// Other parameters...
});
```
## Best Practices
1. **Error Handling**:
- Always use try/catch blocks around both client initialization and API calls
- Use `handleClaudeError` to provide user-friendly error messages
- Return standardized error objects with code and message
2. **Progress Reporting**:
- Report progress at key points (starting, processing, completing)
- Include meaningful status messages
- Include error details in progress reports when failures occur
3. **Session Handling**:
- Always pass the session from the context to the AI client getters
- Use `getModelConfig` to respect user settings from session
4. **Model Selection**:
- Use `getBestAvailableAIModel` when you need to select between different models
- Set `requiresResearch: true` when you need Perplexity capabilities
5. **AsyncOperationManager Integration**:
- Create descriptive operation names
- Handle all errors within the operation function
- Return standardized results from direct functions
- Return immediate responses with operation IDs

View File

@@ -52,9 +52,6 @@ task-master show 1.2
```bash
# Update tasks from a specific ID and provide context
task-master update --from=<id> --prompt="<prompt>"
# Update tasks using research role
task-master update --from=<id> --prompt="<prompt>" --research
```
## Update a Specific Task
@@ -63,7 +60,7 @@ task-master update --from=<id> --prompt="<prompt>" --research
# Update a single task by ID with new information
task-master update-task --id=<id> --prompt="<prompt>"
# Use research-backed updates
# Use research-backed updates with Perplexity AI
task-master update-task --id=<id> --prompt="<prompt>" --research
```
@@ -76,7 +73,7 @@ task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>"
# Example: Add details about API rate limiting to subtask 2 of task 5
task-master update-subtask --id=5.2 --prompt="Add rate limiting of 100 requests per minute"
# Use research-backed updates
# Use research-backed updates with Perplexity AI
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>" --research
```
@@ -187,41 +184,12 @@ 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
# Add a new task using AI (main role)
# Add a new task using AI
task-master add-task --prompt="Description of the new task"
# Add a new task using AI (research role)
task-master add-task --prompt="Description of the new task" --research
# Add a task with dependencies
task-master add-task --prompt="Description" --dependencies=1,2,3
@@ -235,30 +203,3 @@ task-master add-task --prompt="Description" --priority=high
# Initialize a new project with Task Master structure
task-master init
```
## Configure AI Models
```bash
# View current AI model configuration and API key status
task-master models
# Set the primary model for generation/updates (provider inferred if known)
task-master models --set-main=claude-3-opus-20240229
# Set the research model
task-master models --set-research=sonar-pro
# Set the fallback model
task-master models --set-fallback=claude-3-haiku-20240307
# Set a custom Ollama model for the main role
task-master models --set-main=my-local-llama --ollama
# Set a custom OpenRouter model for the research role
task-master models --set-research=google/gemini-pro --openrouter
# Run interactive setup to configure models, including custom ones
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.

View File

@@ -1,112 +1,53 @@
# Configuration
Taskmaster uses two primary methods for configuration:
Task Master can be configured through environment variables in a `.env` file at the root of your project.
1. **`.taskmaster/config.json` File (Recommended - New Structure)**
## Required Configuration
- This JSON file stores most configuration settings, including AI model selections, parameters, logging levels, and project defaults.
- **Location:** This file is created in the `.taskmaster/` directory when you run the `task-master models --setup` interactive setup or initialize a new project with `task-master init`.
- **Migration:** Existing projects with `.taskmasterconfig` in the root will continue to work, but should be migrated to the new structure using `task-master migrate`.
- **Management:** Use the `task-master models --setup` command (or `models` MCP tool) to interactively create and manage this file. You can also set specific models directly using `task-master models --set-<role>=<model_id>`, adding `--ollama` or `--openrouter` flags for custom models. Manual editing is possible but not recommended unless you understand the structure.
- **Example Structure:**
```json
{
"models": {
"main": {
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 64000,
"temperature": 0.2,
"baseURL": "https://api.anthropic.com/v1"
},
"research": {
"provider": "perplexity",
"modelId": "sonar-pro",
"maxTokens": 8700,
"temperature": 0.1,
"baseURL": "https://api.perplexity.ai/v1"
},
"fallback": {
"provider": "anthropic",
"modelId": "claude-3-5-sonnet",
"maxTokens": 64000,
"temperature": 0.2
}
},
"global": {
"logLevel": "info",
"debug": false,
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Your Project Name",
"ollamaBaseURL": "http://localhost:11434/api",
"azureBaseURL": "https://your-endpoint.azure.com/",
"vertexProjectId": "your-gcp-project-id",
"vertexLocation": "us-central1"
}
}
```
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude (Example: `ANTHROPIC_API_KEY=sk-ant-api03-...`)
2. **Legacy `.taskmasterconfig` File (Backward Compatibility)**
## Optional Configuration
- For projects that haven't migrated to the new structure yet.
- **Location:** Project root directory.
- **Migration:** Use `task-master migrate` to move this to `.taskmaster/config.json`.
- **Deprecation:** While still supported, you'll see warnings encouraging migration to the new structure.
- `MODEL` (Default: `"claude-3-7-sonnet-20250219"`): Claude model to use (Example: `MODEL=claude-3-opus-20240229`)
- `MAX_TOKENS` (Default: `"4000"`): Maximum tokens for responses (Example: `MAX_TOKENS=8000`)
- `TEMPERATURE` (Default: `"0.7"`): Temperature for model responses (Example: `TEMPERATURE=0.5`)
- `DEBUG` (Default: `"false"`): Enable debug logging (Example: `DEBUG=true`)
- `LOG_LEVEL` (Default: `"info"`): Console output level (Example: `LOG_LEVEL=debug`)
- `DEFAULT_SUBTASKS` (Default: `"3"`): Default subtask count (Example: `DEFAULT_SUBTASKS=5`)
- `DEFAULT_PRIORITY` (Default: `"medium"`): Default priority (Example: `DEFAULT_PRIORITY=high`)
- `PROJECT_NAME` (Default: `"MCP SaaS MVP"`): Project name in metadata (Example: `PROJECT_NAME=My Awesome Project`)
- `PROJECT_VERSION` (Default: `"1.0.0"`): Version in metadata (Example: `PROJECT_VERSION=2.1.0`)
- `PERPLEXITY_API_KEY`: For research-backed features (Example: `PERPLEXITY_API_KEY=pplx-...`)
- `PERPLEXITY_MODEL` (Default: `"sonar-medium-online"`): Perplexity model (Example: `PERPLEXITY_MODEL=sonar-large-online`)
## Environment Variables (`.env` file or MCP `env` block - For API Keys Only)
- Used **exclusively** for sensitive API keys and specific endpoint URLs.
- **Location:**
- For CLI usage: Create a `.env` file in your project root.
- For MCP/Cursor usage: Configure keys in the `env` section of your `.cursor/mcp.json` file.
- **Required API Keys (Depending on configured providers):**
- `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 (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).
- `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 `.taskmaster/config.json`** (or `.taskmasterconfig` for unmigrated projects), not environment variables.
## Example `.env` File (for API Keys)
## Example .env File
```
# Required API keys for providers configured in .taskmasterconfig
ANTHROPIC_API_KEY=sk-ant-api03-your-key-here
PERPLEXITY_API_KEY=pplx-your-key-here
# OPENAI_API_KEY=sk-your-key-here
# GOOGLE_API_KEY=AIzaSy...
# etc.
# Required
ANTHROPIC_API_KEY=sk-ant-api03-your-api-key
# Optional Endpoint Overrides
# AZURE_OPENAI_ENDPOINT=https://your-azure-endpoint.openai.azure.com/
# OLLAMA_BASE_URL=http://custom-ollama-host:11434/api
# Optional - Claude Configuration
MODEL=claude-3-7-sonnet-20250219
MAX_TOKENS=4000
TEMPERATURE=0.7
# 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
# Optional - Perplexity API for Research
PERPLEXITY_API_KEY=pplx-your-api-key
PERPLEXITY_MODEL=sonar-medium-online
# Optional - Project Info
PROJECT_NAME=My Project
PROJECT_VERSION=1.0.0
# Optional - Application Configuration
DEFAULT_SUBTASKS=3
DEFAULT_PRIORITY=medium
DEBUG=false
LOG_LEVEL=info
```
## Troubleshooting
### Configuration Errors
- If Task Master reports errors about missing configuration or cannot find the config file, run `task-master models --setup` in your project root to create or repair the file.
- For new projects, config will be created at `.taskmaster/config.json`. For legacy projects, you may want to use `task-master migrate` to move to the new structure.
- Ensure API keys are correctly placed in your `.env` file (for CLI) or `.cursor/mcp.json` (for MCP) and are valid for the providers selected in your config file.
### If `task-master init` doesn't respond:
Try running it with Node directly:
@@ -122,45 +63,3 @@ 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

@@ -1,94 +0,0 @@
# Testing Roo Integration
This document provides instructions for testing the Roo integration in the Task Master package.
## Running Tests
To run the tests for the Roo integration:
```bash
# Run all tests
npm test
# Run only Roo integration tests
npm test -- -t "Roo"
# Run specific test file
npm test -- tests/integration/roo-files-inclusion.test.js
```
## Manual Testing
To manually verify that the Roo files are properly included in the package:
1. Create a test directory:
```bash
mkdir test-tm
cd test-tm
```
2. Create a package.json file:
```bash
npm init -y
```
3. Install the task-master-ai package locally:
```bash
# From the root of the claude-task-master repository
cd ..
npm pack
# This will create a file like task-master-ai-0.12.0.tgz
# Move back to the test directory
cd test-tm
npm install ../task-master-ai-0.12.0.tgz
```
4. Initialize a new Task Master project:
```bash
npx task-master init --yes
```
5. Verify that all Roo files and directories are created:
```bash
# Check that .roomodes file exists
ls -la | grep .roomodes
# Check that .roo directory exists and contains all mode directories
ls -la .roo
ls -la .roo/rules
ls -la .roo/rules-architect
ls -la .roo/rules-ask
ls -la .roo/rules-boomerang
ls -la .roo/rules-code
ls -la .roo/rules-debug
ls -la .roo/rules-test
```
## What to Look For
When running the tests or performing manual verification, ensure that:
1. The package includes `.roo/**` and `.roomodes` in the `files` array in package.json
2. The `prepare-package.js` script verifies the existence of all required Roo files
3. The `init.js` script creates all necessary .roo directories and copies .roomodes file
4. All source files for Roo integration exist in `assets/roocode/.roo` and `assets/roocode/.roomodes`
## Compatibility
Ensure that the Roo integration works alongside existing Cursor functionality:
1. Initialize a new project that uses both Cursor and Roo:
```bash
npx task-master init --yes
```
2. Verify that both `.cursor` and `.roo` directories are created
3. Verify that both `.windsurfrules` and `.roomodes` files are created
4. Confirm that existing functionality continues to work as expected

View File

@@ -5,7 +5,7 @@ Here are some common interactions with Cursor AI when using Task Master:
## Starting a new project
```
I've just initialized a new project with Claude Task Master. I have a PRD at .taskmaster/docs/prd.txt.
I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
Can you help me parse it and set up the initial tasks?
```
@@ -30,7 +30,7 @@ I need to regenerate the subtasks for task 3 with a different approach. Can you
## Handling changes
```
I've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
```
## Completing work
@@ -40,34 +40,6 @@ 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
```
@@ -79,33 +51,3 @@ 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?
```
### Breaking Down Complex Tasks
```
Task 5 seems complex. Can you break it down into subtasks?
```
(Agent runs: `task-master expand --id=5`)
```
Please break down task 5 using research-backed generation.
```
(Agent runs: `task-master expand --id=5 --research`)
### Updating Tasks with Research
```
We need to update task 15 based on the latest React Query v5 changes. Can you research this and update the task?
```
(Agent runs: `task-master update-task --id=15 --prompt="Update based on React Query v5 changes" --research`)
### Adding Tasks with Research
```
Please add a new task to implement user profile image uploads using Cloudinary, research the best approach.
```
(Agent runs: `task-master add-task --prompt="Implement user profile image uploads using Cloudinary" --research`)

View File

@@ -1,235 +0,0 @@
# Migration Guide: New .taskmaster Directory Structure
## Overview
Task Master v0.16.0 introduces a new `.taskmaster/` directory structure to keep your project directories clean and organized. This guide explains the benefits of the new structure and how to migrate existing projects.
## What's New
### Before (Legacy Structure)
```
your-project/
├── tasks/ # Task files
│ ├── tasks.json
│ ├── task-1.txt
│ └── task-2.txt
├── scripts/ # PRD and reports
│ ├── prd.txt
│ ├── example_prd.txt
│ └── task-complexity-report.json
├── .taskmasterconfig # Configuration
└── ... (your project files)
```
### After (New Structure)
```
your-project/
├── .taskmaster/ # Consolidated Task Master files
│ ├── config.json # Configuration (was .taskmasterconfig)
│ ├── tasks/ # Task files
│ │ ├── tasks.json
│ │ ├── task-1.txt
│ │ └── task-2.txt
│ ├── docs/ # Project documentation
│ │ └── prd.txt
│ ├── reports/ # Generated reports
│ │ └── task-complexity-report.json
│ └── templates/ # Example/template files
│ └── example_prd.txt
└── ... (your project files)
```
## Benefits of the New Structure
**Cleaner Project Root**: No more scattered Task Master files
**Better Organization**: Logical separation of tasks, docs, reports, and templates
**Hidden by Default**: `.taskmaster/` directory is hidden from most file browsers
**Future-Proof**: Centralized location for Task Master extensions
**Backward Compatible**: Existing projects continue to work until migrated
## Migration Options
### Option 1: Automatic Migration (Recommended)
Task Master provides a built-in migration command that handles everything automatically:
#### CLI Migration
```bash
# Dry run to see what would be migrated
task-master migrate --dry-run
# Perform the migration with backup
task-master migrate --backup
# Force migration (overwrites existing files)
task-master migrate --force
# Clean up legacy files after migration
task-master migrate --cleanup
```
#### MCP Migration (Cursor/AI Editors)
Ask your AI assistant:
```
Please migrate my Task Master project to the new .taskmaster directory structure
```
### Option 2: Manual Migration
If you prefer to migrate manually:
1. **Create the new directory structure:**
```bash
mkdir -p .taskmaster/{tasks,docs,reports,templates}
```
2. **Move your files:**
```bash
# Move tasks
mv tasks/* .taskmaster/tasks/
# Move configuration
mv .taskmasterconfig .taskmaster/config.json
# Move PRD and documentation
mv scripts/prd.txt .taskmaster/docs/
mv scripts/example_prd.txt .taskmaster/templates/
# Move reports (if they exist)
mv scripts/task-complexity-report.json .taskmaster/reports/ 2>/dev/null || true
```
3. **Clean up empty directories:**
```bash
rmdir tasks scripts 2>/dev/null || true
```
## What Gets Migrated
The migration process handles these file types:
### Tasks Directory → `.taskmaster/tasks/`
- `tasks.json`
- Individual task text files (`.txt`)
### Scripts Directory → Multiple Destinations
- **PRD files** → `.taskmaster/docs/`
- `prd.txt`, `requirements.txt`, etc.
- **Example/Template files** → `.taskmaster/templates/`
- `example_prd.txt`, template files
- **Reports** → `.taskmaster/reports/`
- `task-complexity-report.json`
### Configuration
- `.taskmasterconfig` → `.taskmaster/config.json`
## After Migration
Once migrated, Task Master will:
✅ **Automatically use** the new directory structure
✅ **Show deprecation warnings** when legacy files are detected
✅ **Create new files** in the proper locations
✅ **Fall back gracefully** to legacy locations if new ones don't exist
### Verification
After migration, verify everything works:
1. **List your tasks:**
```bash
task-master list
```
2. **Check your configuration:**
```bash
task-master models
```
3. **Generate new task files:**
```bash
task-master generate
```
## Troubleshooting
### Migration Issues
**Q: Migration says "no files to migrate"**
A: Your project may already be using the new structure or have no Task Master files to migrate.
**Q: Migration fails with permission errors**
A: Ensure you have write permissions in your project directory.
**Q: Some files weren't migrated**
A: Check the migration output - some files may not match the expected patterns. You can migrate these manually.
### Working with Legacy Projects
If you're working with an older project that hasn't been migrated:
- Task Master will continue to work with the old structure
- You'll see deprecation warnings in the output
- New files will still be created in legacy locations
- Use the migration command when ready to upgrade
### New Project Initialization
New projects automatically use the new structure:
```bash
task-master init # Creates .taskmaster/ structure
```
## Path Changes for Developers
If you're developing tools or scripts that interact with Task Master files:
### Configuration File
- **Old:** `.taskmasterconfig`
- **New:** `.taskmaster/config.json`
- **Fallback:** Task Master checks both locations
### Tasks File
- **Old:** `tasks/tasks.json`
- **New:** `.taskmaster/tasks/tasks.json`
- **Fallback:** Task Master checks both locations
### Reports
- **Old:** `scripts/task-complexity-report.json`
- **New:** `.taskmaster/reports/task-complexity-report.json`
- **Fallback:** Task Master checks both locations
### PRD Files
- **Old:** `scripts/prd.txt`
- **New:** `.taskmaster/docs/prd.txt`
- **Fallback:** Task Master checks both locations
## Need Help?
If you encounter issues during migration:
1. **Check the logs:** Add `--debug` flag for detailed output
2. **Backup first:** Always use `--backup` option for safety
3. **Test with dry-run:** Use `--dry-run` to preview changes
4. **Ask for help:** Use our Discord community or GitHub issues
---
_This migration guide applies to Task Master v3.x and later. For older versions, please upgrade to the latest version first._

View File

@@ -1,125 +0,0 @@
# 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 |

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