Compare commits
82 Commits
v0.14.0-rc
...
gateway
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16e6326010 | ||
|
|
a9c1b6bbcf | ||
|
|
f12fc476d3 | ||
|
|
31178e2f43 | ||
|
|
3fa3be4e1b | ||
|
|
685365270d | ||
|
|
58aa0992f6 | ||
|
|
2819be51d3 | ||
|
|
9b87dd23de | ||
|
|
769275b3bc | ||
|
|
4e9d58a1b0 | ||
|
|
e573db3b3b | ||
|
|
75b7b93fa4 | ||
|
|
6ec3a10083 | ||
|
|
8ad31ac5eb | ||
|
|
2773e347f9 | ||
|
|
bfc39dd377 | ||
|
|
9e6c190af3 | ||
|
|
ab64437ad2 | ||
|
|
cb95a07771 | ||
|
|
c096f3fe9d | ||
|
|
b6a3b8d385 | ||
|
|
78397fe0be | ||
|
|
f9b89dc25c | ||
|
|
ca69e1294f | ||
|
|
ce09d9cdc3 | ||
|
|
669b744ced | ||
|
|
f058543888 | ||
|
|
b5c2cf47b0 | ||
|
|
acd5c1ea3d | ||
|
|
682b54e103 | ||
|
|
6a8a68e1a3 | ||
|
|
80735f9e60 | ||
|
|
ac36e2497e | ||
|
|
1d4b80fe6f | ||
|
|
48732d5423 | ||
|
|
2d520de269 | ||
|
|
023f51c579 | ||
|
|
1e020023ed | ||
|
|
325f5a2aa3 | ||
|
|
de46bfd84b | ||
|
|
cc26c36366 | ||
|
|
15ad34928d | ||
|
|
f74d639110 | ||
|
|
de58e9ede5 | ||
|
|
947541e4ee | ||
|
|
275cd55da7 | ||
|
|
67ac212973 | ||
|
|
235371ff47 | ||
|
|
b60e1cf835 | ||
|
|
d1e45ff50e | ||
|
|
1513858da4 | ||
|
|
59dcf4bd64 | ||
|
|
a09ba021c5 | ||
|
|
e906166141 | ||
|
|
231e569e84 | ||
|
|
09add37423 | ||
|
|
91fc779714 | ||
|
|
8c69c0aafd | ||
|
|
43ad75c7fa | ||
|
|
a59dd037cf | ||
|
|
3293c7858b | ||
|
|
b371808524 | ||
|
|
86d8f00af8 | ||
|
|
0c55ce0165 | ||
|
|
5a91941913 | ||
|
|
04af16de27 | ||
|
|
edf0f23005 | ||
|
|
e0e1155260 | ||
|
|
70f4054f26 | ||
|
|
34c769bcd0 | ||
|
|
34df2c8bbd | ||
|
|
5e9bc28abe | ||
|
|
d2e64318e2 | ||
|
|
4c835264ac | ||
|
|
c882f89a8c | ||
|
|
20e1b72a17 | ||
|
|
db631f43a5 | ||
|
|
3b9402f1f8 | ||
|
|
c8c0fc2a57 | ||
|
|
60b8e97a1c | ||
|
|
3a6d6dd671 |
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Resolve all issues related to MCP
|
||||
44
.changeset/bright-windows-sing.md
Normal file
44
.changeset/bright-windows-sing.md
Normal file
@@ -0,0 +1,44 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add comprehensive AI-powered research command with intelligent context gathering and interactive follow-ups.
|
||||
|
||||
The new `research` command provides AI-powered research capabilities that automatically gather relevant project context to answer your questions. The command intelligently selects context from multiple sources and supports interactive follow-up questions in CLI mode.
|
||||
|
||||
**Key Features:**
|
||||
- **Intelligent Task Discovery**: Automatically finds relevant tasks and subtasks using fuzzy search based on your query keywords, supplementing any explicitly provided task IDs
|
||||
- **Multi-Source Context**: Gathers context from tasks, files, project structure, and custom text to provide comprehensive answers
|
||||
- **Interactive Follow-ups**: CLI users can ask follow-up questions that build on the conversation history while allowing fresh context discovery for each question
|
||||
- **Flexible Detail Levels**: Choose from low (concise), medium (balanced), or high (comprehensive) response detail levels
|
||||
- **Token Transparency**: Displays detailed token breakdown showing context size, sources, and estimated costs
|
||||
- **Enhanced Display**: Syntax-highlighted code blocks and structured output with clear visual separation
|
||||
|
||||
**Usage Examples:**
|
||||
```bash
|
||||
# Basic research with auto-discovered context
|
||||
task-master research "How should I implement user authentication?"
|
||||
|
||||
# Research with specific task context
|
||||
task-master research "What's the best approach for this?" --id=15,23.2
|
||||
|
||||
# Research with file context and project tree
|
||||
task-master research "How does the current auth system work?" --files=src/auth.js,config/auth.json --tree
|
||||
|
||||
# Research with custom context and low detail
|
||||
task-master research "Quick implementation steps?" --context="Using JWT tokens" --detail=low
|
||||
```
|
||||
|
||||
**Context Sources:**
|
||||
- **Tasks**: Automatically discovers relevant tasks/subtasks via fuzzy search, plus any explicitly specified via `--id`
|
||||
- **Files**: Include specific files via `--files` for code-aware responses
|
||||
- **Project Tree**: Add `--tree` to include project structure overview
|
||||
- **Custom Context**: Provide additional context via `--context` for domain-specific information
|
||||
|
||||
**Interactive Features (CLI only):**
|
||||
- Follow-up questions that maintain conversation history
|
||||
- Fresh fuzzy search for each follow-up to discover newly relevant tasks
|
||||
- Cumulative context building across the conversation
|
||||
- Clean visual separation between exchanges
|
||||
|
||||
The research command integrates with the existing AI service layer and supports all configured AI providers. MCP integration provides the same functionality for programmatic access without interactive features.
|
||||
13
.changeset/cold-pears-poke.md
Normal file
13
.changeset/cold-pears-poke.md
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix critical bugs in task move functionality:
|
||||
|
||||
- **Fixed moving tasks to become subtasks of empty parents**: When moving a task to become a subtask of a parent that had no existing subtasks (e.g., task 89 → task 98.1), the operation would fail with validation errors.
|
||||
|
||||
- **Fixed moving subtasks between parents**: Subtasks can now be properly moved between different parent tasks, including to parents that previously had no subtasks.
|
||||
|
||||
- **Improved comma-separated batch moves**: Multiple tasks can now be moved simultaneously using comma-separated IDs (e.g., "88,90" → "92,93") with proper error handling and atomic operations.
|
||||
|
||||
These fixes enables proper task hierarchy reorganization for corner cases that were previously broken.
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix CLI --force flag for parse-prd command
|
||||
|
||||
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
|
||||
|
||||
- Fixes #477
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
.taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
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.
|
||||
5
.changeset/hungry-geese-work.md
Normal file
5
.changeset/hungry-geese-work.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add AWS bedrock support
|
||||
13
.changeset/itchy-taxes-sip.md
Normal file
13
.changeset/itchy-taxes-sip.md
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
# Add Google Vertex AI Provider Integration
|
||||
|
||||
- Implemented `VertexAIProvider` class extending BaseAIProvider
|
||||
- Added authentication and configuration handling for Vertex AI
|
||||
- Updated configuration manager with Vertex-specific getters
|
||||
- Modified AI services unified system to integrate the provider
|
||||
- Added documentation for Vertex AI setup and configuration
|
||||
- Updated environment variable examples for Vertex AI support
|
||||
- Implemented specialized error handling for Vertex-specific issues
|
||||
5
.changeset/lemon-apes-sort.md
Normal file
5
.changeset/lemon-apes-sort.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add support for Azure
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Task Master no longer tells you to update when you're already up to date
|
||||
17
.changeset/moody-results-clean.md
Normal file
17
.changeset/moody-results-clean.md
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add comprehensive `research` MCP tool for AI-powered research queries
|
||||
|
||||
- **New MCP Tool**: `research` tool enables AI-powered research with project context
|
||||
- **Context Integration**: Supports task IDs, file paths, custom context, and project tree
|
||||
- **Fuzzy Task Discovery**: Automatically finds relevant tasks using semantic search
|
||||
- **Token Management**: Detailed token counting and breakdown by context type
|
||||
- **Multiple Detail Levels**: Support for low, medium, and high detail research responses
|
||||
- **Telemetry Integration**: Full cost tracking and usage analytics
|
||||
- **Direct Function**: `researchDirect` with comprehensive parameter validation
|
||||
- **Silent Mode**: Prevents console output interference with MCP JSON responses
|
||||
- **Error Handling**: Robust error handling with proper MCP response formatting
|
||||
|
||||
This completes subtasks 94.5 (Direct Function) and 94.6 (MCP Tool) for the research command implementation, providing a powerful research interface for integrated development environments like Cursor.
|
||||
5
.changeset/new-colts-flow.md
Normal file
5
.changeset/new-colts-flow.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"task-master-ai": minor
|
||||
---
|
||||
|
||||
Increased minimum required node version to > 18 (was > 14)
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Adds costs information to AI commands using input/output tokens and model costs.
|
||||
5
.changeset/plain-bottles-stand.md
Normal file
5
.changeset/plain-bottles-stand.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Renamed baseUrl to baseURL
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"mode": "exit",
|
||||
"tag": "rc",
|
||||
"initialVersions": {
|
||||
"task-master-ai": "0.13.2"
|
||||
},
|
||||
"changesets": [
|
||||
"beige-doodles-type",
|
||||
"floppy-plants-marry",
|
||||
"forty-plums-stay",
|
||||
"many-wasps-sell",
|
||||
"red-oranges-attend",
|
||||
"red-suns-wash",
|
||||
"sharp-dingos-melt",
|
||||
"six-cloths-happen",
|
||||
"slow-singers-swim",
|
||||
"social-masks-fold",
|
||||
"soft-zoos-flow",
|
||||
"ten-ways-mate",
|
||||
"tricky-wombats-spend",
|
||||
"wide-eyes-relax"
|
||||
]
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Add src directory to exports
|
||||
5
.changeset/shaggy-rice-exist.md
Normal file
5
.changeset/shaggy-rice-exist.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix max_tokens error when trying to use claude-sonnet-4 and claude-opus-4
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix the error handling of task status settings
|
||||
7
.changeset/sharp-flies-call.md
Normal file
7
.changeset/sharp-flies-call.md
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add TASK_MASTER_PROJECT_ROOT env variable supported in mcp.json and .env for project root resolution
|
||||
|
||||
- Some users were having issues where the MCP wasn't able to detect the location of their project root, you can now set the `TASK_MASTER_PROJECT_ROOT` environment variable to the root of your project.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Remove caching layer from MCP direct functions for task listing, next task, and complexity report
|
||||
|
||||
- Fixes issues users where having where they were getting stale data
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix for issue #409 LOG_LEVEL Pydantic validation error
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
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
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Display task complexity scores in task lists, next task, and task details views.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix initial .env.example to work out of the box
|
||||
|
||||
- Closes #419
|
||||
19
.changeset/stale-bats-sin.md
Normal file
19
.changeset/stale-bats-sin.md
Normal file
@@ -0,0 +1,19 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Enhanced get-task/show command to support comma-separated task IDs for efficient batch operations
|
||||
|
||||
**New Features:**
|
||||
- **Multiple Task Retrieval**: Pass comma-separated IDs to get/show multiple tasks at once (e.g., `task-master show 1,3,5` or MCP `get_task` with `id: "1,3,5"`)
|
||||
- **Smart Display Logic**: Single ID shows detailed view, multiple IDs show compact summary table with interactive options
|
||||
- **Batch Action Menu**: Interactive menu for multiple tasks with copy-paste ready commands for common operations (mark as done/in-progress, expand all, view dependencies, etc.)
|
||||
- **MCP Array Response**: MCP tool returns structured array of task objects for efficient AI agent context gathering
|
||||
|
||||
**Benefits:**
|
||||
- **Faster Context Gathering**: AI agents can collect multiple tasks/subtasks in one call instead of iterating
|
||||
- **Improved Workflow**: Interactive batch operations reduce repetitive command execution
|
||||
- **Better UX**: Responsive layout adapts to terminal width, maintains consistency with existing UI patterns
|
||||
- **API Efficiency**: RESTful array responses in MCP format enable more sophisticated integrations
|
||||
|
||||
This enhancement maintains full backward compatibility while significantly improving efficiency for both human users and AI agents working with multiple tasks.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix default fallback model and maxTokens in Taskmaster initialization
|
||||
5
.changeset/tidy-seals-rule.md
Normal file
5
.changeset/tidy-seals-rule.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix add-task MCP command causing an error
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix bug when updating tasks on the MCP server (#412)
|
||||
@@ -1,11 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix duplicate output on CLI help screen
|
||||
|
||||
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
|
||||
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
|
||||
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
|
||||
- Ensures a clean, branded help experience with no repeated content.
|
||||
- Fixes #339
|
||||
@@ -1,19 +1,44 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"task-master-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"
|
||||
}
|
||||
}
|
||||
}
|
||||
"mcpServers": {
|
||||
"task-master-ai-tm": {
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"task-master-ai": {
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"--package=task-master-ai",
|
||||
"task-master-ai"
|
||||
],
|
||||
"env": {
|
||||
"ANTHROPIC_API_KEY": "ANTHROPIC_API_KEY_HERE",
|
||||
"PERPLEXITY_API_KEY": "PERPLEXITY_API_KEY_HERE",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
},
|
||||
"env": {
|
||||
"TASKMASTER_TELEMETRY_API_KEY": "339a81c9-5b9c-4d60-92d8-cba2ee2a8cc3",
|
||||
"TASKMASTER_TELEMETRY_USER_EMAIL": "user_1748640077834@taskmaster.dev"
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ This rule guides AI assistants on how to view, configure, and interact with the
|
||||
- **Key Locations** (See [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) - Configuration Management):
|
||||
- **MCP/Cursor:** Set keys in the `env` section of `.cursor/mcp.json`.
|
||||
- **CLI:** Set keys in a `.env` file in the project root.
|
||||
- As the AI agent, you do not have access to read the .env -- but do not attempt to recreate it!
|
||||
- **Provider List & Keys:**
|
||||
- **`anthropic`**: Requires `ANTHROPIC_API_KEY`.
|
||||
- **`google`**: Requires `GOOGLE_API_KEY`.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
description: Guidelines for interacting with the unified AI service layer.
|
||||
globs: scripts/modules/ai-services-unified.js, scripts/modules/task-manager/*.js, scripts/modules/commands.js
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# AI Services Layer Guidelines
|
||||
@@ -91,7 +92,7 @@ This document outlines the architecture and usage patterns for interacting with
|
||||
* ✅ **DO**: Centralize **all** LLM calls through `generateTextService` or `generateObjectService`.
|
||||
* ✅ **DO**: Determine the appropriate `role` (`main`, `research`, `fallback`) in your core logic and pass it to the service.
|
||||
* ✅ **DO**: Pass the `session` object (received in the `context` parameter, especially from direct function wrappers) to the service call when in MCP context.
|
||||
* ✅ **DO**: Ensure API keys are correctly configured in `.env` (for CLI) or `.cursor/mcp.json` (for MCP).
|
||||
* ✅ **DO**: Ensure API keys are correctly configured in `.env` (for CLI) or `.cursor/mcp.json` (for MCP). FYI: As the AI agent, you do not have access to read the .env -- so do not attempt to recreate it!
|
||||
* ✅ **DO**: Ensure `.taskmasterconfig` exists and has valid provider/model IDs for the roles you intend to use (manage via `task-master models --setup`).
|
||||
* ✅ **DO**: Use `generateTextService` and implement robust manual JSON parsing (with Zod validation *after* parsing) when structured output is needed, as `generateObjectService` has shown unreliability with some providers/schemas.
|
||||
* ❌ **DON'T**: Import or call anything from the old `ai-services.js`, `ai-client-factory.js`, or `ai-client-utils.js` files.
|
||||
|
||||
@@ -39,12 +39,12 @@ alwaysApply: false
|
||||
- **Responsibilities** (See also: [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc)):
|
||||
- Exports `generateTextService`, `generateObjectService`.
|
||||
- Handles provider/model selection based on `role` and `.taskmasterconfig`.
|
||||
- Resolves API keys (from `.env` or `session.env`).
|
||||
- Resolves API keys (from `.env` or `session.env`). As the AI agent, you do not have access to read the .env -- but do not attempt to recreate it!
|
||||
- Implements fallback and retry logic.
|
||||
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
|
||||
- Telemetry data generated by the AI service layer is propagated upwards through core logic, direct functions, and MCP tools. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the detailed integration pattern.
|
||||
|
||||
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
|
||||
- **[`src/ai-providers/*.js`](mdc:src/ai-providers): Provider-Specific Implementations**
|
||||
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.
|
||||
- **Responsibilities**: Interact directly with Vercel AI SDK adapters.
|
||||
|
||||
@@ -63,7 +63,7 @@ alwaysApply: false
|
||||
- API Key Resolution (`resolveEnvVariable`).
|
||||
- Silent Mode Control (`enableSilentMode`, `disableSilentMode`).
|
||||
|
||||
- **[`mcp-server/`](mdc:mcp-server/): MCP Server Integration**
|
||||
- **[`mcp-server/`](mdc:mcp-server): MCP Server Integration**
|
||||
- **Purpose**: Provides MCP interface using FastMCP.
|
||||
- **Responsibilities** (See also: [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)):
|
||||
- Registers tools (`mcp-server/src/tools/*.js`). Tool `execute` methods **should be wrapped** with the `withNormalizedProjectRoot` HOF (from `tools/utils.js`) to ensure consistent path handling.
|
||||
|
||||
@@ -329,6 +329,60 @@ When implementing commands that delete or remove data (like `remove-task` or `re
|
||||
};
|
||||
```
|
||||
|
||||
## Context-Aware Command Pattern
|
||||
|
||||
For AI-powered commands that benefit from project context, follow the research command pattern:
|
||||
|
||||
- **Context Integration**:
|
||||
- ✅ DO: Use `ContextGatherer` utility for multi-source context extraction
|
||||
- ✅ DO: Support task IDs, file paths, custom context, and project tree
|
||||
- ✅ DO: Implement fuzzy search for automatic task discovery
|
||||
- ✅ DO: Display detailed token breakdown for transparency
|
||||
|
||||
```javascript
|
||||
// ✅ DO: Follow this pattern for context-aware commands
|
||||
programInstance
|
||||
.command('research')
|
||||
.description('Perform AI-powered research queries with project context')
|
||||
.argument('<prompt>', 'Research prompt to investigate')
|
||||
.option('-i, --id <ids>', 'Comma-separated task/subtask IDs to include as context')
|
||||
.option('-f, --files <paths>', 'Comma-separated file paths to include as context')
|
||||
.option('-c, --context <text>', 'Additional custom context')
|
||||
.option('--tree', 'Include project file tree structure')
|
||||
.option('-d, --detail <level>', 'Output detail level: low, medium, high', 'medium')
|
||||
.action(async (prompt, options) => {
|
||||
// 1. Parameter validation and parsing
|
||||
const taskIds = options.id ? parseTaskIds(options.id) : [];
|
||||
const filePaths = options.files ? parseFilePaths(options.files) : [];
|
||||
|
||||
// 2. Initialize context gatherer
|
||||
const projectRoot = findProjectRoot() || '.';
|
||||
const gatherer = new ContextGatherer(projectRoot, tasksPath);
|
||||
|
||||
// 3. Auto-discover relevant tasks if none specified
|
||||
if (taskIds.length === 0) {
|
||||
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
|
||||
const discoveredIds = fuzzySearch.getTaskIds(
|
||||
fuzzySearch.findRelevantTasks(prompt)
|
||||
);
|
||||
taskIds.push(...discoveredIds);
|
||||
}
|
||||
|
||||
// 4. Gather context with token breakdown
|
||||
const contextResult = await gatherer.gather({
|
||||
tasks: taskIds,
|
||||
files: filePaths,
|
||||
customContext: options.context,
|
||||
includeProjectTree: options.projectTree,
|
||||
format: 'research',
|
||||
includeTokenCounts: true
|
||||
});
|
||||
|
||||
// 5. Display token breakdown and execute AI call
|
||||
// Implementation continues...
|
||||
});
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
- **Exception Management**:
|
||||
|
||||
268
.cursor/rules/context_gathering.mdc
Normal file
268
.cursor/rules/context_gathering.mdc
Normal file
@@ -0,0 +1,268 @@
|
||||
---
|
||||
description: Standardized patterns for gathering and processing context from multiple sources in Task Master commands, particularly for AI-powered features.
|
||||
globs:
|
||||
alwaysApply: false
|
||||
---
|
||||
# Context Gathering Patterns and Utilities
|
||||
|
||||
This document outlines the standardized patterns for gathering and processing context from multiple sources in Task Master commands, particularly for AI-powered features.
|
||||
|
||||
## Core Context Gathering Utility
|
||||
|
||||
The `ContextGatherer` class (`scripts/modules/utils/contextGatherer.js`) provides a centralized, reusable utility for extracting context from multiple sources:
|
||||
|
||||
### **Key Features**
|
||||
- **Multi-source Context**: Tasks, files, custom text, project file tree
|
||||
- **Token Counting**: Detailed breakdown using `gpt-tokens` library
|
||||
- **Format Support**: Different output formats (research, chat, system-prompt)
|
||||
- **Error Handling**: Graceful handling of missing files, invalid task IDs
|
||||
- **Performance**: File size limits, depth limits for tree generation
|
||||
|
||||
### **Usage Pattern**
|
||||
```javascript
|
||||
import { ContextGatherer } from '../utils/contextGatherer.js';
|
||||
|
||||
// Initialize with project paths
|
||||
const gatherer = new ContextGatherer(projectRoot, tasksPath);
|
||||
|
||||
// Gather context with detailed token breakdown
|
||||
const result = await gatherer.gather({
|
||||
tasks: ['15', '16.2'], // Task and subtask IDs
|
||||
files: ['src/api.js', 'README.md'], // File paths
|
||||
customContext: 'Additional context text',
|
||||
includeProjectTree: true, // Include file tree
|
||||
format: 'research', // Output format
|
||||
includeTokenCounts: true // Get detailed token breakdown
|
||||
});
|
||||
|
||||
// Access results
|
||||
const contextString = result.context;
|
||||
const tokenBreakdown = result.tokenBreakdown;
|
||||
```
|
||||
|
||||
### **Token Breakdown Structure**
|
||||
```javascript
|
||||
{
|
||||
customContext: { tokens: 150, characters: 800 },
|
||||
tasks: [
|
||||
{ id: '15', type: 'task', title: 'Task Title', tokens: 245, characters: 1200 },
|
||||
{ id: '16.2', type: 'subtask', title: 'Subtask Title', tokens: 180, characters: 900 }
|
||||
],
|
||||
files: [
|
||||
{ path: 'src/api.js', tokens: 890, characters: 4500, size: '4.5 KB' }
|
||||
],
|
||||
projectTree: { tokens: 320, characters: 1600 },
|
||||
total: { tokens: 1785, characters: 8000 }
|
||||
}
|
||||
```
|
||||
|
||||
## Fuzzy Search Integration
|
||||
|
||||
The `FuzzyTaskSearch` class (`scripts/modules/utils/fuzzyTaskSearch.js`) provides intelligent task discovery:
|
||||
|
||||
### **Key Features**
|
||||
- **Semantic Matching**: Uses Fuse.js for similarity scoring
|
||||
- **Purpose Categories**: Pattern-based task categorization
|
||||
- **Relevance Scoring**: High/medium/low relevance thresholds
|
||||
- **Context-Aware**: Different search configurations for different use cases
|
||||
|
||||
### **Usage Pattern**
|
||||
```javascript
|
||||
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
|
||||
|
||||
// Initialize with tasks data and context
|
||||
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
|
||||
|
||||
// Find relevant tasks
|
||||
const searchResults = fuzzySearch.findRelevantTasks(query, {
|
||||
maxResults: 8,
|
||||
includeRecent: true,
|
||||
includeCategoryMatches: true
|
||||
});
|
||||
|
||||
// Get task IDs for context gathering
|
||||
const taskIds = fuzzySearch.getTaskIds(searchResults);
|
||||
```
|
||||
|
||||
## Implementation Patterns for Commands
|
||||
|
||||
### **1. Context-Aware Command Structure**
|
||||
```javascript
|
||||
// In command action handler
|
||||
async function commandAction(prompt, options) {
|
||||
// 1. Parameter validation and parsing
|
||||
const taskIds = options.id ? parseTaskIds(options.id) : [];
|
||||
const filePaths = options.files ? parseFilePaths(options.files) : [];
|
||||
|
||||
// 2. Initialize context gatherer
|
||||
const projectRoot = findProjectRoot() || '.';
|
||||
const tasksPath = path.join(projectRoot, 'tasks', 'tasks.json');
|
||||
const gatherer = new ContextGatherer(projectRoot, tasksPath);
|
||||
|
||||
// 3. Auto-discover relevant tasks if none specified
|
||||
if (taskIds.length === 0) {
|
||||
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
|
||||
const discoveredIds = fuzzySearch.getTaskIds(
|
||||
fuzzySearch.findRelevantTasks(prompt)
|
||||
);
|
||||
taskIds.push(...discoveredIds);
|
||||
}
|
||||
|
||||
// 4. Gather context with token breakdown
|
||||
const contextResult = await gatherer.gather({
|
||||
tasks: taskIds,
|
||||
files: filePaths,
|
||||
customContext: options.context,
|
||||
includeProjectTree: options.projectTree,
|
||||
format: 'research',
|
||||
includeTokenCounts: true
|
||||
});
|
||||
|
||||
// 5. Display token breakdown (for CLI)
|
||||
if (outputFormat === 'text') {
|
||||
displayDetailedTokenBreakdown(contextResult.tokenBreakdown);
|
||||
}
|
||||
|
||||
// 6. Use context in AI call
|
||||
const aiResult = await generateTextService(role, session, systemPrompt, userPrompt);
|
||||
|
||||
// 7. Display results with enhanced formatting
|
||||
displayResults(aiResult, contextResult.tokenBreakdown);
|
||||
}
|
||||
```
|
||||
|
||||
### **2. Token Display Pattern**
|
||||
```javascript
|
||||
function displayDetailedTokenBreakdown(tokenBreakdown, systemTokens, userTokens) {
|
||||
const sections = [];
|
||||
|
||||
// Build context breakdown
|
||||
if (tokenBreakdown.tasks?.length > 0) {
|
||||
const taskDetails = tokenBreakdown.tasks.map(task =>
|
||||
`${task.type === 'subtask' ? ' ' : ''}${task.id}: ${task.tokens.toLocaleString()}`
|
||||
).join('\n');
|
||||
sections.push(`Tasks (${tokenBreakdown.tasks.reduce((sum, t) => sum + t.tokens, 0).toLocaleString()}):\n${taskDetails}`);
|
||||
}
|
||||
|
||||
if (tokenBreakdown.files?.length > 0) {
|
||||
const fileDetails = tokenBreakdown.files.map(file =>
|
||||
` ${file.path}: ${file.tokens.toLocaleString()} (${file.size})`
|
||||
).join('\n');
|
||||
sections.push(`Files (${tokenBreakdown.files.reduce((sum, f) => sum + f.tokens, 0).toLocaleString()}):\n${fileDetails}`);
|
||||
}
|
||||
|
||||
// Add prompts breakdown
|
||||
sections.push(`Prompts: system ${systemTokens.toLocaleString()}, user ${userTokens.toLocaleString()}`);
|
||||
|
||||
// Display in clean box
|
||||
const content = sections.join('\n\n');
|
||||
console.log(boxen(content, {
|
||||
title: chalk.cyan('Token Usage'),
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
borderStyle: 'round',
|
||||
borderColor: 'cyan'
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
### **3. Enhanced Result Display Pattern**
|
||||
```javascript
|
||||
function displayResults(result, query, detailLevel, tokenBreakdown) {
|
||||
// Header with query info
|
||||
const header = boxen(
|
||||
chalk.green.bold('Research Results') + '\n\n' +
|
||||
chalk.gray('Query: ') + chalk.white(query) + '\n' +
|
||||
chalk.gray('Detail Level: ') + chalk.cyan(detailLevel),
|
||||
{
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
margin: { top: 1, bottom: 0 },
|
||||
borderStyle: 'round',
|
||||
borderColor: 'green'
|
||||
}
|
||||
);
|
||||
console.log(header);
|
||||
|
||||
// Process and highlight code blocks
|
||||
const processedResult = processCodeBlocks(result);
|
||||
|
||||
// Main content in clean box
|
||||
const contentBox = boxen(processedResult, {
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
margin: { top: 0, bottom: 1 },
|
||||
borderStyle: 'single',
|
||||
borderColor: 'gray'
|
||||
});
|
||||
console.log(contentBox);
|
||||
|
||||
console.log(chalk.green('✓ Research complete'));
|
||||
}
|
||||
```
|
||||
|
||||
## Code Block Enhancement
|
||||
|
||||
### **Syntax Highlighting Pattern**
|
||||
```javascript
|
||||
import { highlight } from 'cli-highlight';
|
||||
|
||||
function processCodeBlocks(text) {
|
||||
return text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
|
||||
try {
|
||||
const highlighted = highlight(code.trim(), {
|
||||
language: language || 'javascript',
|
||||
theme: 'default'
|
||||
});
|
||||
return `\n${highlighted}\n`;
|
||||
} catch (error) {
|
||||
return `\n${code.trim()}\n`;
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Integration Guidelines
|
||||
|
||||
### **When to Use Context Gathering**
|
||||
- ✅ **DO**: Use for AI-powered commands that benefit from project context
|
||||
- ✅ **DO**: Use when users might want to reference specific tasks or files
|
||||
- ✅ **DO**: Use for research, analysis, or generation commands
|
||||
- ❌ **DON'T**: Use for simple CRUD operations that don't need AI context
|
||||
|
||||
### **Performance Considerations**
|
||||
- ✅ **DO**: Set reasonable file size limits (50KB default)
|
||||
- ✅ **DO**: Limit project tree depth (3-5 levels)
|
||||
- ✅ **DO**: Provide token counts to help users understand context size
|
||||
- ✅ **DO**: Allow users to control what context is included
|
||||
|
||||
### **Error Handling**
|
||||
- ✅ **DO**: Gracefully handle missing files with warnings
|
||||
- ✅ **DO**: Validate task IDs and provide helpful error messages
|
||||
- ✅ **DO**: Continue processing even if some context sources fail
|
||||
- ✅ **DO**: Provide fallback behavior when context gathering fails
|
||||
|
||||
### **Future Command Integration**
|
||||
Commands that should consider adopting this pattern:
|
||||
- `analyze-complexity` - Could benefit from file context
|
||||
- `expand-task` - Could use related task context
|
||||
- `update-task` - Could reference similar tasks for consistency
|
||||
- `add-task` - Could use project context for better task generation
|
||||
|
||||
## Export Patterns
|
||||
|
||||
### **Context Gatherer Module**
|
||||
```javascript
|
||||
export {
|
||||
ContextGatherer,
|
||||
createContextGatherer // Factory function
|
||||
};
|
||||
```
|
||||
|
||||
### **Fuzzy Search Module**
|
||||
```javascript
|
||||
export {
|
||||
FuzzyTaskSearch,
|
||||
PURPOSE_CATEGORIES,
|
||||
RELEVANCE_THRESHOLDS
|
||||
};
|
||||
```
|
||||
|
||||
This context gathering system provides a foundation for building more intelligent, context-aware commands that can leverage project knowledge to provide better AI-powered assistance.
|
||||
@@ -49,6 +49,7 @@ Task Master offers two primary ways to interact:
|
||||
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
|
||||
- Respect dependency chains and task priorities when selecting work
|
||||
- Report progress regularly using `get_tasks` / `task-master list`
|
||||
- Reorganize tasks as needed using `move_task` / `task-master move --from=<id> --to=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to change task hierarchy or ordering
|
||||
|
||||
## Task Complexity Analysis
|
||||
|
||||
@@ -154,6 +155,25 @@ Taskmaster configuration is managed through two main mechanisms:
|
||||
- Task files are automatically regenerated after dependency changes
|
||||
- Dependencies are visualized with status indicators in task listings and files
|
||||
|
||||
## Task Reorganization
|
||||
|
||||
- Use `move_task` / `task-master move --from=<id> --to=<id>` to move tasks or subtasks within the hierarchy
|
||||
- This command supports several use cases:
|
||||
- Moving a standalone task to become a subtask (e.g., `--from=5 --to=7`)
|
||||
- Moving a subtask to become a standalone task (e.g., `--from=5.2 --to=7`)
|
||||
- Moving a subtask to a different parent (e.g., `--from=5.2 --to=7.3`)
|
||||
- Reordering subtasks within the same parent (e.g., `--from=5.2 --to=5.4`)
|
||||
- Moving a task to a new, non-existent ID position (e.g., `--from=5 --to=25`)
|
||||
- Moving multiple tasks at once using comma-separated IDs (e.g., `--from=10,11,12 --to=16,17,18`)
|
||||
- The system includes validation to prevent data loss:
|
||||
- Allows moving to non-existent IDs by creating placeholder tasks
|
||||
- Prevents moving to existing task IDs that have content (to avoid overwriting)
|
||||
- Validates source tasks exist before attempting to move them
|
||||
- The system maintains proper parent-child relationships and dependency integrity
|
||||
- Task files are automatically regenerated after the move operation
|
||||
- This provides greater flexibility in organizing and refining your task structure as project understanding evolves
|
||||
- This is especially useful when dealing with potential merge conflicts arising from teams creating tasks on separate branches. Solve these conflicts very easily by moving your tasks and keeping theirs.
|
||||
|
||||
## Iterative Subtask Implementation
|
||||
|
||||
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:
|
||||
|
||||
367
.cursor/rules/git_workflow.mdc
Normal file
367
.cursor/rules/git_workflow.mdc
Normal file
@@ -0,0 +1,367 @@
|
||||
---
|
||||
description: Git workflow integrated with Task Master for feature development and collaboration
|
||||
globs: "**/*"
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Git Workflow with Task Master Integration
|
||||
|
||||
## **Branch Strategy**
|
||||
|
||||
### **Main Branch Protection**
|
||||
- **main** branch contains production-ready code
|
||||
- All feature development happens on task-specific branches
|
||||
- Direct commits to main are prohibited
|
||||
- All changes merge via Pull Requests
|
||||
|
||||
### **Task Branch Naming**
|
||||
```bash
|
||||
# ✅ DO: Use consistent task branch naming
|
||||
task-001 # For Task 1
|
||||
task-004 # For Task 4
|
||||
task-015 # For Task 15
|
||||
|
||||
# ❌ DON'T: Use inconsistent naming
|
||||
feature/user-auth
|
||||
fix-database-issue
|
||||
random-branch-name
|
||||
```
|
||||
|
||||
## **Workflow Overview**
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[Start: On main branch] --> B[Pull latest changes]
|
||||
B --> C[Create task branch<br/>git checkout -b task-XXX]
|
||||
C --> D[Set task status: in-progress]
|
||||
D --> E[Get task context & expand if needed]
|
||||
E --> F[Identify next subtask]
|
||||
|
||||
F --> G[Set subtask: in-progress]
|
||||
G --> H[Research & collect context<br/>update_subtask with findings]
|
||||
H --> I[Implement subtask]
|
||||
I --> J[Update subtask with completion]
|
||||
J --> K[Set subtask: done]
|
||||
K --> L[Git commit subtask]
|
||||
|
||||
L --> M{More subtasks?}
|
||||
M -->|Yes| F
|
||||
M -->|No| N[Run final tests]
|
||||
|
||||
N --> O[Commit tests if added]
|
||||
O --> P[Push task branch]
|
||||
P --> Q[Create Pull Request]
|
||||
Q --> R[Human review & merge]
|
||||
R --> S[Switch to main & pull]
|
||||
S --> T[Delete task branch]
|
||||
T --> U[Ready for next task]
|
||||
|
||||
style A fill:#e1f5fe
|
||||
style C fill:#f3e5f5
|
||||
style G fill:#fff3e0
|
||||
style L fill:#e8f5e8
|
||||
style Q fill:#fce4ec
|
||||
style R fill:#f1f8e9
|
||||
style U fill:#e1f5fe
|
||||
```
|
||||
|
||||
## **Complete Task Development Workflow**
|
||||
|
||||
### **Phase 1: Task Preparation**
|
||||
```bash
|
||||
# 1. Ensure you're on main branch and pull latest
|
||||
git checkout main
|
||||
git pull origin main
|
||||
|
||||
# 2. Check current branch status
|
||||
git branch # Verify you're on main
|
||||
|
||||
# 3. Create task-specific branch
|
||||
git checkout -b task-004 # For Task 4
|
||||
|
||||
# 4. Set task status in Task Master
|
||||
# Use: set_task_status tool or `task-master set-status --id=4 --status=in-progress`
|
||||
```
|
||||
|
||||
### **Phase 2: Task Analysis & Planning**
|
||||
```bash
|
||||
# 5. Get task context and expand if needed
|
||||
# Use: get_task tool or `task-master show 4`
|
||||
# Use: expand_task tool or `task-master expand --id=4 --research --force` (if complex)
|
||||
|
||||
# 6. Identify next subtask to work on
|
||||
# Use: next_task tool or `task-master next`
|
||||
```
|
||||
|
||||
### **Phase 3: Subtask Implementation Loop**
|
||||
For each subtask, follow this pattern:
|
||||
|
||||
```bash
|
||||
# 7. Mark subtask as in-progress
|
||||
# Use: set_task_status tool or `task-master set-status --id=4.1 --status=in-progress`
|
||||
|
||||
# 8. Gather context and research (if needed)
|
||||
# Use: update_subtask tool with research flag or:
|
||||
# `task-master update-subtask --id=4.1 --prompt="Research findings..." --research`
|
||||
|
||||
# 9. Collect code context through AI exploration
|
||||
# Document findings in subtask using update_subtask
|
||||
|
||||
# 10. Implement the subtask
|
||||
# Write code, tests, documentation
|
||||
|
||||
# 11. Update subtask with completion details
|
||||
# Use: update_subtask tool or:
|
||||
# `task-master update-subtask --id=4.1 --prompt="Implementation complete..."`
|
||||
|
||||
# 12. Mark subtask as done
|
||||
# Use: set_task_status tool or `task-master set-status --id=4.1 --status=done`
|
||||
|
||||
# 13. Commit the subtask implementation
|
||||
git add .
|
||||
git commit -m "feat(task-4): Complete subtask 4.1 - [Subtask Title]
|
||||
|
||||
- Implementation details
|
||||
- Key changes made
|
||||
- Any important notes
|
||||
|
||||
Subtask 4.1: [Brief description of what was accomplished]
|
||||
Relates to Task 4: [Main task title]"
|
||||
```
|
||||
|
||||
### **Phase 4: Task Completion**
|
||||
```bash
|
||||
# 14. When all subtasks are complete, run final testing
|
||||
# Create test file if needed, ensure all tests pass
|
||||
npm test # or jest, or manual testing
|
||||
|
||||
# 15. If tests were added/modified, commit them
|
||||
git add .
|
||||
git commit -m "test(task-4): Add comprehensive tests for Task 4
|
||||
|
||||
- Unit tests for core functionality
|
||||
- Integration tests for API endpoints
|
||||
- All tests passing
|
||||
|
||||
Task 4: [Main task title] - Testing complete"
|
||||
|
||||
# 16. Push the task branch
|
||||
git push origin task-004
|
||||
|
||||
# 17. Create Pull Request
|
||||
# Title: "Task 4: [Task Title]"
|
||||
# Description should include:
|
||||
# - Task overview
|
||||
# - Subtasks completed
|
||||
# - Testing approach
|
||||
# - Any breaking changes or considerations
|
||||
```
|
||||
|
||||
### **Phase 5: PR Merge & Cleanup**
|
||||
```bash
|
||||
# 18. Human reviews and merges PR into main
|
||||
|
||||
# 19. Switch back to main and pull merged changes
|
||||
git checkout main
|
||||
git pull origin main
|
||||
|
||||
# 20. Delete the feature branch (optional cleanup)
|
||||
git branch -d task-004
|
||||
git push origin --delete task-004
|
||||
```
|
||||
|
||||
## **Commit Message Standards**
|
||||
|
||||
### **Subtask Commits**
|
||||
```bash
|
||||
# ✅ DO: Consistent subtask commit format
|
||||
git commit -m "feat(task-4): Complete subtask 4.1 - Initialize Express server
|
||||
|
||||
- Set up Express.js with TypeScript configuration
|
||||
- Added CORS and body parsing middleware
|
||||
- Implemented health check endpoints
|
||||
- Basic error handling middleware
|
||||
|
||||
Subtask 4.1: Initialize project with npm and install dependencies
|
||||
Relates to Task 4: Setup Express.js Server Project"
|
||||
|
||||
# ❌ DON'T: Vague or inconsistent commits
|
||||
git commit -m "fixed stuff"
|
||||
git commit -m "working on task"
|
||||
```
|
||||
|
||||
### **Test Commits**
|
||||
```bash
|
||||
# ✅ DO: Separate test commits when substantial
|
||||
git commit -m "test(task-4): Add comprehensive tests for Express server setup
|
||||
|
||||
- Unit tests for middleware configuration
|
||||
- Integration tests for health check endpoints
|
||||
- Mock tests for database connection
|
||||
- All tests passing with 95% coverage
|
||||
|
||||
Task 4: Setup Express.js Server Project - Testing complete"
|
||||
```
|
||||
|
||||
### **Commit Type Prefixes**
|
||||
- `feat(task-X):` - New feature implementation
|
||||
- `fix(task-X):` - Bug fixes
|
||||
- `test(task-X):` - Test additions/modifications
|
||||
- `docs(task-X):` - Documentation updates
|
||||
- `refactor(task-X):` - Code refactoring
|
||||
- `chore(task-X):` - Build/tooling changes
|
||||
|
||||
## **Task Master Commands Integration**
|
||||
|
||||
### **Essential Commands for Git Workflow**
|
||||
```bash
|
||||
# Task management
|
||||
task-master show <id> # Get task/subtask details
|
||||
task-master next # Find next task to work on
|
||||
task-master set-status --id=<id> --status=<status>
|
||||
task-master update-subtask --id=<id> --prompt="..." --research
|
||||
|
||||
# Task expansion (for complex tasks)
|
||||
task-master expand --id=<id> --research --force
|
||||
|
||||
# Progress tracking
|
||||
task-master list # View all tasks and status
|
||||
task-master list --status=in-progress # View active tasks
|
||||
```
|
||||
|
||||
### **MCP Tool Equivalents**
|
||||
When using Cursor or other MCP-integrated tools:
|
||||
- `get_task` instead of `task-master show`
|
||||
- `next_task` instead of `task-master next`
|
||||
- `set_task_status` instead of `task-master set-status`
|
||||
- `update_subtask` instead of `task-master update-subtask`
|
||||
|
||||
## **Branch Management Rules**
|
||||
|
||||
### **Branch Protection**
|
||||
```bash
|
||||
# ✅ DO: Always work on task branches
|
||||
git checkout -b task-005
|
||||
# Make changes
|
||||
git commit -m "..."
|
||||
git push origin task-005
|
||||
|
||||
# ❌ DON'T: Commit directly to main
|
||||
git checkout main
|
||||
git commit -m "..." # NEVER do this
|
||||
```
|
||||
|
||||
### **Keeping Branches Updated**
|
||||
```bash
|
||||
# ✅ DO: Regularly sync with main (for long-running tasks)
|
||||
git checkout task-005
|
||||
git fetch origin
|
||||
git rebase origin/main # or merge if preferred
|
||||
|
||||
# Resolve any conflicts and continue
|
||||
```
|
||||
|
||||
## **Pull Request Guidelines**
|
||||
|
||||
### **PR Title Format**
|
||||
```
|
||||
Task <ID>: <Task Title>
|
||||
|
||||
Examples:
|
||||
Task 4: Setup Express.js Server Project
|
||||
Task 7: Implement User Authentication
|
||||
Task 12: Add Stripe Payment Integration
|
||||
```
|
||||
|
||||
### **PR Description Template**
|
||||
```markdown
|
||||
## Task Overview
|
||||
Brief description of the main task objective.
|
||||
|
||||
## Subtasks Completed
|
||||
- [x] 4.1: Initialize project with npm and install dependencies
|
||||
- [x] 4.2: Configure TypeScript, ESLint and Prettier
|
||||
- [x] 4.3: Create basic Express app with middleware and health check route
|
||||
|
||||
## Implementation Details
|
||||
- Key architectural decisions made
|
||||
- Important code changes
|
||||
- Any deviations from original plan
|
||||
|
||||
## Testing
|
||||
- [ ] Unit tests added/updated
|
||||
- [ ] Integration tests passing
|
||||
- [ ] Manual testing completed
|
||||
|
||||
## Breaking Changes
|
||||
List any breaking changes or migration requirements.
|
||||
|
||||
## Related Tasks
|
||||
Mention any dependent tasks or follow-up work needed.
|
||||
```
|
||||
|
||||
## **Conflict Resolution**
|
||||
|
||||
### **Task Conflicts**
|
||||
```bash
|
||||
# If multiple people work on overlapping tasks:
|
||||
# 1. Use Task Master's move functionality to reorganize
|
||||
task-master move --from=5 --to=25 # Move conflicting task
|
||||
|
||||
# 2. Update task dependencies
|
||||
task-master add-dependency --id=6 --depends-on=5
|
||||
|
||||
# 3. Coordinate through PR comments and task updates
|
||||
```
|
||||
|
||||
### **Code Conflicts**
|
||||
```bash
|
||||
# Standard Git conflict resolution
|
||||
git fetch origin
|
||||
git rebase origin/main
|
||||
# Resolve conflicts in files
|
||||
git add .
|
||||
git rebase --continue
|
||||
```
|
||||
|
||||
## **Emergency Procedures**
|
||||
|
||||
### **Hotfixes**
|
||||
```bash
|
||||
# For urgent production fixes:
|
||||
git checkout main
|
||||
git pull origin main
|
||||
git checkout -b hotfix-urgent-issue
|
||||
|
||||
# Make minimal fix
|
||||
git commit -m "hotfix: Fix critical production issue
|
||||
|
||||
- Specific fix description
|
||||
- Minimal impact change
|
||||
- Requires immediate deployment"
|
||||
|
||||
git push origin hotfix-urgent-issue
|
||||
# Create emergency PR for immediate review
|
||||
```
|
||||
|
||||
### **Task Abandonment**
|
||||
```bash
|
||||
# If task needs to be abandoned or significantly changed:
|
||||
# 1. Update task status
|
||||
task-master set-status --id=<id> --status=cancelled
|
||||
|
||||
# 2. Clean up branch
|
||||
git checkout main
|
||||
git branch -D task-<id>
|
||||
git push origin --delete task-<id>
|
||||
|
||||
# 3. Document reasoning in task
|
||||
task-master update-task --id=<id> --prompt="Task cancelled due to..."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**References:**
|
||||
- [Task Master Workflow](mdc:.cursor/rules/dev_workflow.mdc)
|
||||
- [Architecture Guidelines](mdc:.cursor/rules/architecture.mdc)
|
||||
- [Task Master Commands](mdc:.cursor/rules/taskmaster.mdc)
|
||||
@@ -24,17 +24,22 @@ alwaysApply: false
|
||||
The standard pattern for adding a feature follows this workflow:
|
||||
|
||||
1. **Core Logic**: Implement the business logic in the appropriate module (e.g., [`task-manager.js`](mdc:scripts/modules/task-manager.js)).
|
||||
2. **AI Integration (If Applicable)**:
|
||||
2. **Context Gathering (If Applicable)**:
|
||||
- For AI-powered commands that benefit from project context, use the standardized context gathering patterns from [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc).
|
||||
- Import `ContextGatherer` and `FuzzyTaskSearch` utilities for reusable context extraction.
|
||||
- Support multiple context types: tasks, files, custom text, project tree.
|
||||
- Implement detailed token breakdown display for transparency.
|
||||
3. **AI Integration (If Applicable)**:
|
||||
- Import necessary service functions (e.g., `generateTextService`, `streamTextService`) from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
|
||||
- Prepare parameters (`role`, `session`, `systemPrompt`, `prompt`).
|
||||
- Call the service function.
|
||||
- Handle the response (direct text or stream object).
|
||||
- **Important**: Prefer `generateTextService` for calls sending large context (like stringified JSON) where incremental display is not needed. See [`ai_services.mdc`](mdc:.cursor/rules/ai_services.mdc) for detailed usage patterns and cautions.
|
||||
3. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc).
|
||||
4. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
|
||||
5. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
|
||||
6. **Configuration**: Update configuration settings or add new ones in [`config-manager.js`](mdc:scripts/modules/config-manager.js) and ensure getters/setters are appropriate. Update documentation in [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc). Update the `.taskmasterconfig` structure if needed.
|
||||
7. **Documentation**: Update help text and documentation in [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc).
|
||||
4. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js) following [`ui.mdc`](mdc:.cursor/rules/ui.mdc). Consider enhanced formatting with syntax highlighting for code blocks.
|
||||
5. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js) following [`commands.mdc`](mdc:.cursor/rules/commands.mdc).
|
||||
6. **Testing**: Write tests for all components of the feature (following [`tests.mdc`](mdc:.cursor/rules/tests.mdc))
|
||||
7. **Configuration**: Update configuration settings or add new ones in [`config-manager.js`](mdc:scripts/modules/config-manager.js) and ensure getters/setters are appropriate. Update documentation in [`utilities.mdc`](mdc:.cursor/rules/utilities.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc). Update the `.taskmasterconfig` structure if needed.
|
||||
8. **Documentation**: Update help text and documentation in [`dev_workflow.mdc`](mdc:.cursor/rules/dev_workflow.mdc) and [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc).
|
||||
|
||||
## Critical Checklist for New Features
|
||||
|
||||
|
||||
@@ -112,9 +112,10 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* **CLI Command:** `task-master show [id] [options]`
|
||||
* **Description:** `Display detailed information for a specific Taskmaster task or subtask by its ID.`
|
||||
* **Key Parameters/Options:**
|
||||
* `id`: `Required. The ID of the Taskmaster task, e.g., '15', or subtask, e.g., '15.2', you want to view.` (CLI: `[id]` positional or `-i, --id <id>`)
|
||||
* `id`: `Required. The ID of the Taskmaster task, e.g., '15', or subtask, e.g., '15.2', you want to view.` (CLI: `[id]. Supports comma-separated list of tasks to get multiple tasks at once.` positional or `-i, --id <id>`)
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Understand the full details, implementation notes, and test strategy for a specific task before starting work.
|
||||
* **CRITICAL INFORMATION** If you need to collect information from multiple tasks, use comma-separated IDs (i.e. 1,2,3) to receive an array of tasks. Do not needlessly get tasks one at a time if you need to get many as that is wasteful.
|
||||
|
||||
---
|
||||
|
||||
@@ -269,11 +270,36 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Delete unnecessary subtasks or promote a subtask to a top-level task.
|
||||
|
||||
### 17. Move Task (`move_task`)
|
||||
|
||||
* **MCP Tool:** `move_task`
|
||||
* **CLI Command:** `task-master move [options]`
|
||||
* **Description:** `Move a task or subtask to a new position within the task hierarchy.`
|
||||
* **Key Parameters/Options:**
|
||||
* `from`: `Required. ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated for multiple tasks.` (CLI: `--from <id>`)
|
||||
* `to`: `Required. ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated.` (CLI: `--to <id>`)
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Reorganize tasks by moving them within the hierarchy. Supports various scenarios like:
|
||||
* Moving a task to become a subtask
|
||||
* Moving a subtask to become a standalone task
|
||||
* Moving a subtask to a different parent
|
||||
* Reordering subtasks within the same parent
|
||||
* Moving a task to a new, non-existent ID (automatically creates placeholders)
|
||||
* Moving multiple tasks at once with comma-separated IDs
|
||||
* **Validation Features:**
|
||||
* Allows moving tasks to non-existent destination IDs (creates placeholder tasks)
|
||||
* Prevents moving to existing task IDs that already have content (to avoid overwriting)
|
||||
* Validates that source tasks exist before attempting to move them
|
||||
* Maintains proper parent-child relationships
|
||||
* **Example CLI:** `task-master move --from=5.2 --to=7.3` to move subtask 5.2 to become subtask 7.3.
|
||||
* **Example Multi-Move:** `task-master move --from=10,11,12 --to=16,17,18` to move multiple tasks to new positions.
|
||||
* **Common Use:** Resolving merge conflicts in tasks.json when multiple team members create tasks on different branches.
|
||||
|
||||
---
|
||||
|
||||
## Dependency Management
|
||||
|
||||
### 17. Add Dependency (`add_dependency`)
|
||||
### 18. Add Dependency (`add_dependency`)
|
||||
|
||||
* **MCP Tool:** `add_dependency`
|
||||
* **CLI Command:** `task-master add-dependency [options]`
|
||||
@@ -284,7 +310,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`)
|
||||
* **Usage:** Establish the correct order of execution between tasks.
|
||||
|
||||
### 18. Remove Dependency (`remove_dependency`)
|
||||
### 19. Remove Dependency (`remove_dependency`)
|
||||
|
||||
* **MCP Tool:** `remove_dependency`
|
||||
* **CLI Command:** `task-master remove-dependency [options]`
|
||||
@@ -295,7 +321,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Update task relationships when the order of execution changes.
|
||||
|
||||
### 19. Validate Dependencies (`validate_dependencies`)
|
||||
### 20. Validate Dependencies (`validate_dependencies`)
|
||||
|
||||
* **MCP Tool:** `validate_dependencies`
|
||||
* **CLI Command:** `task-master validate-dependencies [options]`
|
||||
@@ -304,7 +330,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Audit the integrity of your task dependencies.
|
||||
|
||||
### 20. Fix Dependencies (`fix_dependencies`)
|
||||
### 21. Fix Dependencies (`fix_dependencies`)
|
||||
|
||||
* **MCP Tool:** `fix_dependencies`
|
||||
* **CLI Command:** `task-master fix-dependencies [options]`
|
||||
@@ -317,7 +343,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
|
||||
## Analysis & Reporting
|
||||
|
||||
### 21. Analyze Project Complexity (`analyze_project_complexity`)
|
||||
### 22. Analyze Project Complexity (`analyze_project_complexity`)
|
||||
|
||||
* **MCP Tool:** `analyze_project_complexity`
|
||||
* **CLI Command:** `task-master analyze-complexity [options]`
|
||||
@@ -330,7 +356,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* **Usage:** Used before breaking down tasks to identify which ones need the most attention.
|
||||
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||
|
||||
### 22. View Complexity Report (`complexity_report`)
|
||||
### 23. View Complexity Report (`complexity_report`)
|
||||
|
||||
* **MCP Tool:** `complexity_report`
|
||||
* **CLI Command:** `task-master complexity-report [options]`
|
||||
@@ -341,9 +367,46 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
|
||||
---
|
||||
|
||||
## AI-Powered Research
|
||||
|
||||
### 25. Research (`research`)
|
||||
|
||||
* **MCP Tool:** `research`
|
||||
* **CLI Command:** `task-master research [options]`
|
||||
* **Description:** `Perform AI-powered research queries with project context to get fresh, up-to-date information beyond the AI's knowledge cutoff.`
|
||||
* **Key Parameters/Options:**
|
||||
* `query`: `Required. Research query/prompt (e.g., "What are the latest best practices for React Query v5?").` (CLI: `[query]` positional or `-q, --query <text>`)
|
||||
* `taskIds`: `Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17").` (CLI: `-i, --id <ids>`)
|
||||
* `filePaths`: `Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md").` (CLI: `-f, --files <paths>`)
|
||||
* `customContext`: `Additional custom context text to include in the research.` (CLI: `-c, --context <text>`)
|
||||
* `includeProjectTree`: `Include project file tree structure in context (default: false).` (CLI: `--tree`)
|
||||
* `detailLevel`: `Detail level for the research response: 'low', 'medium', 'high' (default: medium).` (CLI: `--detail <level>`)
|
||||
* `projectRoot`: `The directory of the project. Must be an absolute path.` (CLI: Determined automatically)
|
||||
* **Usage:** **This is a POWERFUL tool that agents should use FREQUENTLY** to:
|
||||
* Get fresh information beyond knowledge cutoff dates
|
||||
* Research latest best practices, library updates, security patches
|
||||
* Find implementation examples for specific technologies
|
||||
* Validate approaches against current industry standards
|
||||
* Get contextual advice based on project files and tasks
|
||||
* **When to Consider Using Research:**
|
||||
* **Before implementing any task** - Research current best practices
|
||||
* **When encountering new technologies** - Get up-to-date implementation guidance (libraries, apis, etc)
|
||||
* **For security-related tasks** - Find latest security recommendations
|
||||
* **When updating dependencies** - Research breaking changes and migration guides
|
||||
* **For performance optimization** - Get current performance best practices
|
||||
* **When debugging complex issues** - Research known solutions and workarounds
|
||||
* **Research + Action Pattern:**
|
||||
* Use `research` to gather fresh information
|
||||
* Use `update_subtask` to commit findings with timestamps
|
||||
* Use `update_task` to incorporate research into task details
|
||||
* Use `add_task` with research flag for informed task creation
|
||||
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. The research provides FRESH data beyond the AI's training cutoff, making it invaluable for current best practices and recent developments.
|
||||
|
||||
---
|
||||
|
||||
## File Management
|
||||
|
||||
### 23. Generate Task Files (`generate`)
|
||||
### 24. Generate Task Files (`generate`)
|
||||
|
||||
* **MCP Tool:** `generate`
|
||||
* **CLI Command:** `task-master generate [options]`
|
||||
|
||||
408
.cursor/rules/tdd_workflow.mdc
Normal file
408
.cursor/rules/tdd_workflow.mdc
Normal file
@@ -0,0 +1,408 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: true
|
||||
---
|
||||
# Test Workflow & Development Process
|
||||
|
||||
## **Test-Driven Development (TDD) Integration**
|
||||
|
||||
### **Core TDD Cycle with Jest**
|
||||
```bash
|
||||
# 1. Start development with watch mode
|
||||
npm run test:watch
|
||||
|
||||
# 2. Write failing test first
|
||||
# Create test file: src/utils/newFeature.test.ts
|
||||
# Write test that describes expected behavior
|
||||
|
||||
# 3. Implement minimum code to make test pass
|
||||
# 4. Refactor while keeping tests green
|
||||
# 5. Add edge cases and error scenarios
|
||||
```
|
||||
|
||||
### **TDD Workflow Per Subtask**
|
||||
```bash
|
||||
# When starting a new subtask:
|
||||
task-master set-status --id=4.1 --status=in-progress
|
||||
|
||||
# Begin TDD cycle:
|
||||
npm run test:watch # Keep running during development
|
||||
|
||||
# Document TDD progress in subtask:
|
||||
task-master update-subtask --id=4.1 --prompt="TDD Progress:
|
||||
- Written 3 failing tests for core functionality
|
||||
- Implemented basic feature, tests now passing
|
||||
- Adding edge case tests for error handling"
|
||||
|
||||
# Complete subtask with test summary:
|
||||
task-master update-subtask --id=4.1 --prompt="Implementation complete:
|
||||
- Feature implemented with 8 unit tests
|
||||
- Coverage: 95% statements, 88% branches
|
||||
- All tests passing, TDD cycle complete"
|
||||
```
|
||||
|
||||
## **Testing Commands & Usage**
|
||||
|
||||
### **Development Commands**
|
||||
```bash
|
||||
# Primary development command - use during coding
|
||||
npm run test:watch # Watch mode with Jest
|
||||
npm run test:watch -- --testNamePattern="auth" # Watch specific tests
|
||||
|
||||
# Targeted testing during development
|
||||
npm run test:unit # Run only unit tests
|
||||
npm run test:unit -- --coverage # Unit tests with coverage
|
||||
|
||||
# Integration testing when APIs are ready
|
||||
npm run test:integration # Run integration tests
|
||||
npm run test:integration -- --detectOpenHandles # Debug hanging tests
|
||||
|
||||
# End-to-end testing for workflows
|
||||
npm run test:e2e # Run E2E tests
|
||||
npm run test:e2e -- --timeout=30000 # Extended timeout for E2E
|
||||
```
|
||||
|
||||
### **Quality Assurance Commands**
|
||||
```bash
|
||||
# Full test suite with coverage (before commits)
|
||||
npm run test:coverage # Complete coverage analysis
|
||||
|
||||
# All tests (CI/CD pipeline)
|
||||
npm test # Run all test projects
|
||||
|
||||
# Specific test file execution
|
||||
npm test -- auth.test.ts # Run specific test file
|
||||
npm test -- --testNamePattern="should handle errors" # Run specific tests
|
||||
```
|
||||
|
||||
## **Test Implementation Patterns**
|
||||
|
||||
### **Unit Test Development**
|
||||
```typescript
|
||||
// ✅ DO: Follow established patterns from auth.test.ts
|
||||
describe('FeatureName', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
// Setup mocks with proper typing
|
||||
});
|
||||
|
||||
describe('functionName', () => {
|
||||
it('should handle normal case', () => {
|
||||
// Test implementation with specific assertions
|
||||
});
|
||||
|
||||
it('should throw error for invalid input', async () => {
|
||||
// Error scenario testing
|
||||
await expect(functionName(invalidInput))
|
||||
.rejects.toThrow('Specific error message');
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### **Integration Test Development**
|
||||
```typescript
|
||||
// ✅ DO: Use supertest for API endpoint testing
|
||||
import request from 'supertest';
|
||||
import { app } from '../../src/app';
|
||||
|
||||
describe('POST /api/auth/register', () => {
|
||||
beforeEach(async () => {
|
||||
await integrationTestUtils.cleanupTestData();
|
||||
});
|
||||
|
||||
it('should register user successfully', async () => {
|
||||
const userData = createTestUser();
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/auth/register')
|
||||
.send(userData)
|
||||
.expect(201);
|
||||
|
||||
expect(response.body).toMatchObject({
|
||||
id: expect.any(String),
|
||||
email: userData.email
|
||||
});
|
||||
|
||||
// Verify database state
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: userData.email }
|
||||
});
|
||||
expect(user).toBeTruthy();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### **E2E Test Development**
|
||||
```typescript
|
||||
// ✅ DO: Test complete user workflows
|
||||
describe('User Authentication Flow', () => {
|
||||
it('should complete registration → login → protected access', async () => {
|
||||
// Step 1: Register
|
||||
const userData = createTestUser();
|
||||
await request(app)
|
||||
.post('/api/auth/register')
|
||||
.send(userData)
|
||||
.expect(201);
|
||||
|
||||
// Step 2: Login
|
||||
const loginResponse = await request(app)
|
||||
.post('/api/auth/login')
|
||||
.send({ email: userData.email, password: userData.password })
|
||||
.expect(200);
|
||||
|
||||
const { token } = loginResponse.body;
|
||||
|
||||
// Step 3: Access protected resource
|
||||
await request(app)
|
||||
.get('/api/profile')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
}, 30000); // Extended timeout for E2E
|
||||
});
|
||||
```
|
||||
|
||||
## **Mocking & Test Utilities**
|
||||
|
||||
### **Established Mocking Patterns**
|
||||
```typescript
|
||||
// ✅ DO: Use established bcrypt mocking pattern
|
||||
jest.mock('bcrypt');
|
||||
import bcrypt from 'bcrypt';
|
||||
const mockHash = bcrypt.hash as jest.MockedFunction<typeof bcrypt.hash>;
|
||||
const mockCompare = bcrypt.compare as jest.MockedFunction<typeof bcrypt.compare>;
|
||||
|
||||
// ✅ DO: Use Prisma mocking for unit tests
|
||||
jest.mock('@prisma/client', () => ({
|
||||
PrismaClient: jest.fn().mockImplementation(() => ({
|
||||
user: {
|
||||
create: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
$connect: jest.fn(),
|
||||
$disconnect: jest.fn(),
|
||||
})),
|
||||
}));
|
||||
```
|
||||
|
||||
### **Test Fixtures Usage**
|
||||
```typescript
|
||||
// ✅ DO: Use centralized test fixtures
|
||||
import { createTestUser, adminUser, invalidUser } from '../fixtures/users';
|
||||
|
||||
describe('User Service', () => {
|
||||
it('should handle admin user creation', async () => {
|
||||
const userData = createTestUser(adminUser);
|
||||
// Test implementation
|
||||
});
|
||||
|
||||
it('should reject invalid user data', async () => {
|
||||
const userData = createTestUser(invalidUser);
|
||||
// Error testing
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## **Coverage Standards & Monitoring**
|
||||
|
||||
### **Coverage Thresholds**
|
||||
- **Global Standards**: 80% lines/functions, 70% branches
|
||||
- **Critical Code**: 90% utils, 85% middleware
|
||||
- **New Features**: Must meet or exceed global thresholds
|
||||
- **Legacy Code**: Gradual improvement with each change
|
||||
|
||||
### **Coverage Reporting & Analysis**
|
||||
```bash
|
||||
# Generate coverage reports
|
||||
npm run test:coverage
|
||||
|
||||
# View detailed HTML report
|
||||
open coverage/lcov-report/index.html
|
||||
|
||||
# Coverage files generated:
|
||||
# - coverage/lcov-report/index.html # Detailed HTML report
|
||||
# - coverage/lcov.info # LCOV format for IDE integration
|
||||
# - coverage/coverage-final.json # JSON format for tooling
|
||||
```
|
||||
|
||||
### **Coverage Quality Checks**
|
||||
```typescript
|
||||
// ✅ DO: Test all code paths
|
||||
describe('validateInput', () => {
|
||||
it('should return true for valid input', () => {
|
||||
expect(validateInput('valid')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for various invalid inputs', () => {
|
||||
expect(validateInput('')).toBe(false); // Empty string
|
||||
expect(validateInput(null)).toBe(false); // Null value
|
||||
expect(validateInput(undefined)).toBe(false); // Undefined
|
||||
});
|
||||
|
||||
it('should throw for unexpected input types', () => {
|
||||
expect(() => validateInput(123)).toThrow('Invalid input type');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## **Testing During Development Phases**
|
||||
|
||||
### **Feature Development Phase**
|
||||
```bash
|
||||
# 1. Start feature development
|
||||
task-master set-status --id=X.Y --status=in-progress
|
||||
|
||||
# 2. Begin TDD cycle
|
||||
npm run test:watch
|
||||
|
||||
# 3. Document test progress in subtask
|
||||
task-master update-subtask --id=X.Y --prompt="Test development:
|
||||
- Created test file with 5 failing tests
|
||||
- Implemented core functionality
|
||||
- Tests passing, adding error scenarios"
|
||||
|
||||
# 4. Verify coverage before completion
|
||||
npm run test:coverage
|
||||
|
||||
# 5. Update subtask with final test status
|
||||
task-master update-subtask --id=X.Y --prompt="Testing complete:
|
||||
- 12 unit tests with full coverage
|
||||
- All edge cases and error scenarios covered
|
||||
- Ready for integration testing"
|
||||
```
|
||||
|
||||
### **Integration Testing Phase**
|
||||
```bash
|
||||
# After API endpoints are implemented
|
||||
npm run test:integration
|
||||
|
||||
# Update integration test templates
|
||||
# Replace placeholder tests with real endpoint calls
|
||||
|
||||
# Document integration test results
|
||||
task-master update-subtask --id=X.Y --prompt="Integration tests:
|
||||
- Updated auth endpoint tests
|
||||
- Database integration verified
|
||||
- All HTTP status codes and responses tested"
|
||||
```
|
||||
|
||||
### **Pre-Commit Testing Phase**
|
||||
```bash
|
||||
# Before committing code
|
||||
npm run test:coverage # Verify all tests pass with coverage
|
||||
npm run test:unit # Quick unit test verification
|
||||
npm run test:integration # Integration test verification (if applicable)
|
||||
|
||||
# Commit pattern for test updates
|
||||
git add tests/ src/**/*.test.ts
|
||||
git commit -m "test(task-X): Add comprehensive tests for Feature Y
|
||||
|
||||
- Unit tests with 95% coverage (exceeds 90% threshold)
|
||||
- Integration tests for API endpoints
|
||||
- Test fixtures for data generation
|
||||
- Proper mocking patterns established
|
||||
|
||||
Task X: Feature Y - Testing complete"
|
||||
```
|
||||
|
||||
## **Error Handling & Debugging**
|
||||
|
||||
### **Test Debugging Techniques**
|
||||
```typescript
|
||||
// ✅ DO: Use test utilities for debugging
|
||||
import { testUtils } from '../setup';
|
||||
|
||||
it('should debug complex operation', () => {
|
||||
testUtils.withConsole(() => {
|
||||
// Console output visible only for this test
|
||||
console.log('Debug info:', complexData);
|
||||
service.complexOperation();
|
||||
});
|
||||
});
|
||||
|
||||
// ✅ DO: Use proper async debugging
|
||||
it('should handle async operations', async () => {
|
||||
const promise = service.asyncOperation();
|
||||
|
||||
// Test intermediate state
|
||||
expect(service.isProcessing()).toBe(true);
|
||||
|
||||
const result = await promise;
|
||||
expect(result).toBe('expected');
|
||||
expect(service.isProcessing()).toBe(false);
|
||||
});
|
||||
```
|
||||
|
||||
### **Common Test Issues & Solutions**
|
||||
```bash
|
||||
# Hanging tests (common with database connections)
|
||||
npm run test:integration -- --detectOpenHandles
|
||||
|
||||
# Memory leaks in tests
|
||||
npm run test:unit -- --logHeapUsage
|
||||
|
||||
# Slow tests identification
|
||||
npm run test:coverage -- --verbose
|
||||
|
||||
# Mock not working properly
|
||||
# Check: mock is declared before imports
|
||||
# Check: jest.clearAllMocks() in beforeEach
|
||||
# Check: TypeScript typing is correct
|
||||
```
|
||||
|
||||
## **Continuous Integration Integration**
|
||||
|
||||
### **CI/CD Pipeline Testing**
|
||||
```yaml
|
||||
# Example GitHub Actions integration
|
||||
- name: Run tests
|
||||
run: |
|
||||
npm ci
|
||||
npm run test:coverage
|
||||
|
||||
- name: Upload coverage reports
|
||||
uses: codecov/codecov-action@v3
|
||||
with:
|
||||
file: ./coverage/lcov.info
|
||||
```
|
||||
|
||||
### **Pre-commit Hooks**
|
||||
```bash
|
||||
# Setup pre-commit testing (recommended)
|
||||
# In package.json scripts:
|
||||
"pre-commit": "npm run test:unit && npm run test:integration"
|
||||
|
||||
# Husky integration example:
|
||||
npx husky add .husky/pre-commit "npm run test:unit"
|
||||
```
|
||||
|
||||
## **Test Maintenance & Evolution**
|
||||
|
||||
### **Adding Tests for New Features**
|
||||
1. **Create test file** alongside source code or in `tests/unit/`
|
||||
2. **Follow established patterns** from `src/utils/auth.test.ts`
|
||||
3. **Use existing fixtures** from `tests/fixtures/`
|
||||
4. **Apply proper mocking** patterns for dependencies
|
||||
5. **Meet coverage thresholds** for the module
|
||||
|
||||
### **Updating Integration/E2E Tests**
|
||||
1. **Update templates** in `tests/integration/` when APIs change
|
||||
2. **Modify E2E workflows** in `tests/e2e/` for new user journeys
|
||||
3. **Update test fixtures** for new data requirements
|
||||
4. **Maintain database cleanup** utilities
|
||||
|
||||
### **Test Performance Optimization**
|
||||
- **Parallel execution**: Jest runs tests in parallel by default
|
||||
- **Test isolation**: Use proper setup/teardown for independence
|
||||
- **Mock optimization**: Mock heavy dependencies appropriately
|
||||
- **Database efficiency**: Use transaction rollbacks where possible
|
||||
|
||||
---
|
||||
|
||||
**Key References:**
|
||||
- [Testing Standards](mdc:.cursor/rules/tests.mdc)
|
||||
- [Git Workflow](mdc:.cursor/rules/git_workflow.mdc)
|
||||
- [Development Workflow](mdc:.cursor/rules/dev_workflow.mdc)
|
||||
- [Jest Configuration](mdc:jest.config.js)
|
||||
- [Auth Test Example](mdc:src/utils/auth.test.ts)
|
||||
@@ -150,4 +150,91 @@ alwaysApply: false
|
||||
));
|
||||
```
|
||||
|
||||
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.
|
||||
## Enhanced Display Patterns
|
||||
|
||||
### **Token Breakdown Display**
|
||||
- Use detailed, granular token breakdowns for AI-powered commands
|
||||
- Display context sources with individual token counts
|
||||
- Show both token count and character count for transparency
|
||||
|
||||
```javascript
|
||||
// ✅ DO: Display detailed token breakdown
|
||||
function displayDetailedTokenBreakdown(tokenBreakdown, systemTokens, userTokens) {
|
||||
const sections = [];
|
||||
|
||||
if (tokenBreakdown.tasks?.length > 0) {
|
||||
const taskDetails = tokenBreakdown.tasks.map(task =>
|
||||
`${task.type === 'subtask' ? ' ' : ''}${task.id}: ${task.tokens.toLocaleString()}`
|
||||
).join('\n');
|
||||
sections.push(`Tasks (${tokenBreakdown.tasks.reduce((sum, t) => sum + t.tokens, 0).toLocaleString()}):\n${taskDetails}`);
|
||||
}
|
||||
|
||||
const content = sections.join('\n\n');
|
||||
console.log(boxen(content, {
|
||||
title: chalk.cyan('Token Usage'),
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
borderStyle: 'round',
|
||||
borderColor: 'cyan'
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
### **Code Block Syntax Highlighting**
|
||||
- Use `cli-highlight` library for syntax highlighting in terminal output
|
||||
- Process code blocks in AI responses for better readability
|
||||
|
||||
```javascript
|
||||
// ✅ DO: Enhance code blocks with syntax highlighting
|
||||
import { highlight } from 'cli-highlight';
|
||||
|
||||
function processCodeBlocks(text) {
|
||||
return text.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, language, code) => {
|
||||
try {
|
||||
const highlighted = highlight(code.trim(), {
|
||||
language: language || 'javascript',
|
||||
theme: 'default'
|
||||
});
|
||||
return `\n${highlighted}\n`;
|
||||
} catch (error) {
|
||||
return `\n${code.trim()}\n`;
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### **Multi-Section Result Display**
|
||||
- Use separate boxes for headers, content, and metadata
|
||||
- Maintain consistent styling across different result types
|
||||
|
||||
```javascript
|
||||
// ✅ DO: Use structured result display
|
||||
function displayResults(result, query, detailLevel) {
|
||||
// Header with query info
|
||||
const header = boxen(
|
||||
chalk.green.bold('Research Results') + '\n\n' +
|
||||
chalk.gray('Query: ') + chalk.white(query) + '\n' +
|
||||
chalk.gray('Detail Level: ') + chalk.cyan(detailLevel),
|
||||
{
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
margin: { top: 1, bottom: 0 },
|
||||
borderStyle: 'round',
|
||||
borderColor: 'green'
|
||||
}
|
||||
);
|
||||
console.log(header);
|
||||
|
||||
// Process and display main content
|
||||
const processedResult = processCodeBlocks(result);
|
||||
const contentBox = boxen(processedResult, {
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
margin: { top: 0, bottom: 1 },
|
||||
borderStyle: 'single',
|
||||
borderColor: 'gray'
|
||||
});
|
||||
console.log(contentBox);
|
||||
|
||||
console.log(chalk.green('✓ Operation complete'));
|
||||
}
|
||||
```
|
||||
|
||||
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples, [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc) for context display patterns, and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.
|
||||
@@ -46,7 +46,7 @@ alwaysApply: false
|
||||
- **Location**:
|
||||
- **Core CLI Utilities**: Place utilities used primarily by the core `task-master` CLI logic and command modules (`scripts/modules/*`) into [`scripts/modules/utils.js`](mdc:scripts/modules/utils.js).
|
||||
- **MCP Server Utilities**: Place utilities specifically designed to support the MCP server implementation into the appropriate subdirectories within `mcp-server/src/`.
|
||||
- Path/Core Logic Helpers: [`mcp-server/src/core/utils/`](mdc:mcp-server/src/core/utils/) (e.g., `path-utils.js`).
|
||||
- Path/Core Logic Helpers: [`mcp-server/src/core/utils/`](mdc:mcp-server/src/core/utils) (e.g., `path-utils.js`).
|
||||
- Tool Execution/Response Helpers: [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
|
||||
|
||||
## Documentation Standards
|
||||
@@ -110,7 +110,7 @@ Taskmaster configuration (excluding API keys) is primarily managed through the `
|
||||
- ✅ DO: Use appropriate icons for different log levels
|
||||
- ✅ DO: Respect the configured log level
|
||||
- ❌ DON'T: Add direct console.log calls outside the logging utility
|
||||
- **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions.
|
||||
- **Note on Passed Loggers**: When a logger object (like the FastMCP `log` object) is passed *as a parameter* (e.g., as `mcpLog`) into core Task Master functions, the receiving function often expects specific methods (`.info`, `.warn`, `.error`, etc.) to be directly callable on that object (e.g., `mcpLog[level](mdc:...)`). If the passed logger doesn't have this exact structure, a wrapper object may be needed. See the **Handling Logging Context (`mcpLog`)** section in [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) for the standard pattern used in direct functions.
|
||||
|
||||
- **Logger Wrapper Pattern**:
|
||||
- ✅ DO: Use the logger wrapper pattern when passing loggers to prevent `mcpLog[level] is not a function` errors:
|
||||
@@ -548,4 +548,56 @@ export {
|
||||
};
|
||||
```
|
||||
|
||||
Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for more context on MCP server architecture and integration.
|
||||
## Context Gathering Utilities
|
||||
|
||||
### **ContextGatherer** (`scripts/modules/utils/contextGatherer.js`)
|
||||
|
||||
- **Multi-Source Context Extraction**:
|
||||
- ✅ DO: Use for AI-powered commands that need project context
|
||||
- ✅ DO: Support tasks, files, custom text, and project tree context
|
||||
- ✅ DO: Implement detailed token counting with `gpt-tokens` library
|
||||
- ✅ DO: Provide multiple output formats (research, chat, system-prompt)
|
||||
|
||||
```javascript
|
||||
// ✅ DO: Use ContextGatherer for consistent context extraction
|
||||
import { ContextGatherer } from '../utils/contextGatherer.js';
|
||||
|
||||
const gatherer = new ContextGatherer(projectRoot, tasksPath);
|
||||
const result = await gatherer.gather({
|
||||
tasks: ['15', '16.2'],
|
||||
files: ['src/api.js'],
|
||||
customContext: 'Additional context',
|
||||
includeProjectTree: true,
|
||||
format: 'research',
|
||||
includeTokenCounts: true
|
||||
});
|
||||
```
|
||||
|
||||
### **FuzzyTaskSearch** (`scripts/modules/utils/fuzzyTaskSearch.js`)
|
||||
|
||||
- **Intelligent Task Discovery**:
|
||||
- ✅ DO: Use for automatic task relevance detection
|
||||
- ✅ DO: Configure search parameters based on use case context
|
||||
- ✅ DO: Implement purpose-based categorization for better matching
|
||||
- ✅ DO: Sort results by relevance score and task ID
|
||||
|
||||
```javascript
|
||||
// ✅ DO: Use FuzzyTaskSearch for intelligent task discovery
|
||||
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
|
||||
|
||||
const fuzzySearch = new FuzzyTaskSearch(tasksData.tasks, 'research');
|
||||
const searchResults = fuzzySearch.findRelevantTasks(query, {
|
||||
maxResults: 8,
|
||||
includeRecent: true,
|
||||
includeCategoryMatches: true
|
||||
});
|
||||
const taskIds = fuzzySearch.getTaskIds(searchResults);
|
||||
```
|
||||
|
||||
- **Integration Guidelines**:
|
||||
- ✅ DO: Use fuzzy search to supplement user-provided task IDs
|
||||
- ✅ DO: Display discovered task IDs to users for transparency
|
||||
- ✅ DO: Sort discovered task IDs numerically for better readability
|
||||
- ❌ DON'T: Replace explicit user task selections with fuzzy results
|
||||
|
||||
Refer to [`context_gathering.mdc`](mdc:.cursor/rules/context_gathering.mdc) for detailed implementation patterns, [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc) and [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for more context on MCP server architecture and integration.
|
||||
@@ -7,3 +7,9 @@ MISTRAL_API_KEY=YOUR_MISTRAL_KEY_HERE
|
||||
OPENROUTER_API_KEY=YOUR_OPENROUTER_KEY_HERE
|
||||
XAI_API_KEY=YOUR_XAI_KEY_HERE
|
||||
AZURE_OPENAI_API_KEY=YOUR_AZURE_KEY_HERE
|
||||
|
||||
# Google Vertex AI Configuration
|
||||
VERTEX_PROJECT_ID=your-gcp-project-id
|
||||
VERTEX_LOCATION=us-central1
|
||||
# Optional: Path to service account credentials JSON file (alternative to API key)
|
||||
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json
|
||||
|
||||
40
.github/workflows/update-models-md.yml
vendored
Normal file
40
.github/workflows/update-models-md.yml
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
name: Update models.md from supported-models.json
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- next
|
||||
paths:
|
||||
- 'scripts/modules/supported-models.json'
|
||||
- 'docs/scripts/models-json-to-markdown.js'
|
||||
|
||||
jobs:
|
||||
update_markdown:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
|
||||
- name: Run transformation script
|
||||
run: node docs/scripts/models-json-to-markdown.js
|
||||
|
||||
- name: Format Markdown with Prettier
|
||||
run: npx prettier --write docs/models.md
|
||||
|
||||
- name: Stage docs/models.md
|
||||
run: git add docs/models.md
|
||||
|
||||
- name: Commit & Push docs/models.md
|
||||
uses: actions-js/push@master
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: ${{ github.ref_name }}
|
||||
message: 'docs: Auto-update and format models.md'
|
||||
author_name: 'github-actions[bot]'
|
||||
author_email: 'github-actions[bot]@users.noreply.github.com'
|
||||
33
.gitignore
vendored
33
.gitignore
vendored
@@ -19,13 +19,26 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
tests/e2e/_runs/
|
||||
tests/e2e/log/
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
coverage/
|
||||
*.lcov
|
||||
|
||||
# Jest cache
|
||||
.jest/
|
||||
|
||||
# Test temporary files and directories
|
||||
tests/temp/
|
||||
tests/e2e/_runs/
|
||||
tests/e2e/log/
|
||||
tests/**/*.log
|
||||
tests/**/coverage/
|
||||
|
||||
# Test database files (if any)
|
||||
tests/**/*.db
|
||||
tests/**/*.sqlite
|
||||
tests/**/*.sqlite3
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
@@ -64,3 +77,17 @@ dev-debug.log
|
||||
|
||||
# NPMRC
|
||||
.npmrc
|
||||
|
||||
# Added by Claude Task Master
|
||||
# Editor directories and files
|
||||
.idea
|
||||
.vscode
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
# OS specific
|
||||
# Task files
|
||||
tasks.json
|
||||
tasks/
|
||||
@@ -1,7 +0,0 @@
|
||||
# Ignore artifacts:
|
||||
build
|
||||
coverage
|
||||
.changeset
|
||||
tasks
|
||||
package-lock.json
|
||||
tests/fixture/*.json
|
||||
11
.prettierrc
11
.prettierrc
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"printWidth": 80,
|
||||
"tabWidth": 2,
|
||||
"useTabs": true,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"bracketSpacing": true,
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
@@ -1,32 +1,37 @@
|
||||
{
|
||||
"models": {
|
||||
"main": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 100000,
|
||||
"temperature": 0.2
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 8192,
|
||||
"temperature": 0.2
|
||||
}
|
||||
},
|
||||
"global": {
|
||||
"logLevel": "info",
|
||||
"debug": false,
|
||||
"defaultSubtasks": 5,
|
||||
"defaultPriority": "medium",
|
||||
"projectName": "Taskmaster",
|
||||
"ollamaBaseUrl": "http://localhost:11434/api",
|
||||
"userId": "1234567890",
|
||||
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
|
||||
}
|
||||
"models": {
|
||||
"main": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-sonnet-4-20250514",
|
||||
"maxTokens": 64000,
|
||||
"temperature": 0.2
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-5-sonnet-20241022",
|
||||
"maxTokens": 64000,
|
||||
"temperature": 0.2
|
||||
}
|
||||
},
|
||||
"global": {
|
||||
"logLevel": "info",
|
||||
"debug": false,
|
||||
"defaultSubtasks": 5,
|
||||
"defaultPriority": "medium",
|
||||
"projectName": "Taskmaster",
|
||||
"ollamaBaseURL": "http://localhost:11434/api",
|
||||
"azureBaseURL": "https://your-endpoint.azure.com/"
|
||||
},
|
||||
"account": {
|
||||
"userId": "1234567890",
|
||||
"email": "",
|
||||
"mode": "byok",
|
||||
"telemetryEnabled": true
|
||||
}
|
||||
}
|
||||
252
CHANGELOG.md
252
CHANGELOG.md
@@ -1,5 +1,257 @@
|
||||
# task-master-ai
|
||||
|
||||
## 0.15.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
|
||||
|
||||
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
|
||||
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
|
||||
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
|
||||
- **Robust Error Handling**:
|
||||
- Detects when Ollama server is not running and provides clear error messages
|
||||
- Validates model existence and lists available alternatives when model not found
|
||||
- Graceful fallback behavior for connection issues
|
||||
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
|
||||
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
|
||||
|
||||
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
|
||||
- Added Mistral models: Devstral Small, Mistral Nemo
|
||||
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
|
||||
- Updated Gemini model to latest 2.5 Flash preview version
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
|
||||
|
||||
- Research current technologies and best practices relevant to the project
|
||||
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
|
||||
- Include specific library recommendations with version numbers
|
||||
- Provide more detailed implementation guidance based on industry standards
|
||||
- Create more accurate dependency relationships between tasks
|
||||
|
||||
This results in higher quality, more actionable tasks with minimal additional effort.
|
||||
|
||||
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
|
||||
|
||||
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
|
||||
|
||||
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
|
||||
Status: DONE
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
|
||||
|
||||
**Usage:**
|
||||
|
||||
- CLI command: `task-master move --from=<id> --to=<id>`
|
||||
- MCP tool: `move_task` with parameters:
|
||||
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
|
||||
- `to`: ID of destination (e.g., "7" or "7.3")
|
||||
- `file` (optional): Custom path to tasks.json
|
||||
|
||||
**Example scenarios:**
|
||||
|
||||
- Move task to become subtask: `--from="5" --to="7"`
|
||||
- Move subtask to standalone task: `--from="5.2" --to="7"`
|
||||
- Move subtask to different parent: `--from="5.2" --to="7.3"`
|
||||
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
|
||||
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
|
||||
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
|
||||
|
||||
**Multiple Task Support:**
|
||||
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
|
||||
|
||||
**Validation Features:**
|
||||
|
||||
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
|
||||
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
|
||||
- Validates source tasks exist before attempting to move them
|
||||
- Ensures proper parent-child relationships are maintained
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
|
||||
|
||||
## 0.15.0-rc.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
|
||||
|
||||
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
|
||||
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
|
||||
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
|
||||
- **Robust Error Handling**:
|
||||
- Detects when Ollama server is not running and provides clear error messages
|
||||
- Validates model existence and lists available alternatives when model not found
|
||||
- Graceful fallback behavior for connection issues
|
||||
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
|
||||
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
|
||||
|
||||
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
|
||||
- Added Mistral models: Devstral Small, Mistral Nemo
|
||||
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
|
||||
- Updated Gemini model to latest 2.5 Flash preview version
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
|
||||
|
||||
- Research current technologies and best practices relevant to the project
|
||||
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
|
||||
- Include specific library recommendations with version numbers
|
||||
- Provide more detailed implementation guidance based on industry standards
|
||||
- Create more accurate dependency relationships between tasks
|
||||
|
||||
This results in higher quality, more actionable tasks with minimal additional effort.
|
||||
|
||||
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
|
||||
|
||||
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
|
||||
|
||||
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
|
||||
Status: DONE
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
|
||||
|
||||
**Usage:**
|
||||
|
||||
- CLI command: `task-master move --from=<id> --to=<id>`
|
||||
- MCP tool: `move_task` with parameters:
|
||||
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
|
||||
- `to`: ID of destination (e.g., "7" or "7.3")
|
||||
- `file` (optional): Custom path to tasks.json
|
||||
|
||||
**Example scenarios:**
|
||||
|
||||
- Move task to become subtask: `--from="5" --to="7"`
|
||||
- Move subtask to standalone task: `--from="5.2" --to="7"`
|
||||
- Move subtask to different parent: `--from="5.2" --to="7.3"`
|
||||
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
|
||||
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
|
||||
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
|
||||
|
||||
**Multiple Task Support:**
|
||||
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
|
||||
|
||||
**Validation Features:**
|
||||
|
||||
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
|
||||
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
|
||||
- Validates source tasks exist before attempting to move them
|
||||
- Ensures proper parent-child relationships are maintained
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
|
||||
|
||||
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
|
||||
|
||||
## 0.14.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
|
||||
|
||||
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
|
||||
|
||||
- You can now add it by running `task-master models --setup` and selecting it.
|
||||
- Ollama is a local model provider, so no API key is required.
|
||||
- Ollama models are available at `http://localhost:11434/api` by default.
|
||||
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
|
||||
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
|
||||
|
||||
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Resolve all issues related to MCP
|
||||
|
||||
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
|
||||
|
||||
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
|
||||
|
||||
- Fixes #477
|
||||
|
||||
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
|
||||
|
||||
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
|
||||
|
||||
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
|
||||
|
||||
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add src directory to exports
|
||||
|
||||
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
|
||||
|
||||
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
|
||||
|
||||
- Fixes issues users where having where they were getting stale data
|
||||
|
||||
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
|
||||
|
||||
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
|
||||
|
||||
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
|
||||
|
||||
- Closes #419
|
||||
|
||||
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
|
||||
|
||||
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
|
||||
|
||||
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
|
||||
|
||||
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
|
||||
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
|
||||
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
|
||||
- Ensures a clean, branded help experience with no repeated content.
|
||||
- Fixes #339
|
||||
|
||||
## 0.14.0-rc.1
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
|
||||
|
||||
- You can now add it by running `task-master models --setup` and selecting it.
|
||||
- Ollama is a local model provider, so no API key is required.
|
||||
- Ollama models are available at `http://localhost:11434/api` by default.
|
||||
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
|
||||
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
|
||||
|
||||
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
|
||||
|
||||
## 0.14.0-rc.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
335
CONTRIBUTING.md
Normal file
335
CONTRIBUTING.md
Normal file
@@ -0,0 +1,335 @@
|
||||
# Contributing to Task Master
|
||||
|
||||
Thank you for your interest in contributing to Task Master! We're excited to work with you and appreciate your help in making this project better. 🚀
|
||||
|
||||
## 🤝 Our Collaborative Approach
|
||||
|
||||
We're a **PR-friendly team** that values collaboration:
|
||||
|
||||
- ✅ **We review PRs quickly** - Usually within hours, not days
|
||||
- ✅ **We're super reactive** - Expect fast feedback and engagement
|
||||
- ✅ **We sometimes take over PRs** - If your contribution is valuable but needs cleanup, we might jump in to help finish it
|
||||
- ✅ **We're open to all contributions** - From bug fixes to major features
|
||||
|
||||
**We don't mind AI-generated code**, but we do expect you to:
|
||||
|
||||
- ✅ **Review and understand** what the AI generated
|
||||
- ✅ **Test the code thoroughly** before submitting
|
||||
- ✅ **Ensure it's well-written** and follows our patterns
|
||||
- ❌ **Don't submit "AI slop"** - untested, unreviewed AI output
|
||||
|
||||
> **Why this matters**: We spend significant time reviewing PRs. Help us help you by submitting quality contributions that save everyone time!
|
||||
|
||||
## 🚀 Quick Start for Contributors
|
||||
|
||||
### 1. Fork and Clone
|
||||
|
||||
```bash
|
||||
git clone https://github.com/YOUR_USERNAME/claude-task-master.git
|
||||
cd claude-task-master
|
||||
npm install
|
||||
```
|
||||
|
||||
### 2. Create a Feature Branch
|
||||
|
||||
**Important**: Always target the `next` branch, not `main`:
|
||||
|
||||
```bash
|
||||
git checkout next
|
||||
git pull origin next
|
||||
git checkout -b feature/your-feature-name
|
||||
```
|
||||
|
||||
### 3. Make Your Changes
|
||||
|
||||
Follow our development guidelines below.
|
||||
|
||||
### 4. Test Everything Yourself
|
||||
|
||||
**Before submitting your PR**, ensure:
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
npm test
|
||||
|
||||
# Check formatting
|
||||
npm run format-check
|
||||
|
||||
# Fix formatting if needed
|
||||
npm run format
|
||||
```
|
||||
|
||||
### 5. Create a Changeset
|
||||
|
||||
**Required for most changes**:
|
||||
|
||||
```bash
|
||||
npm run changeset
|
||||
```
|
||||
|
||||
See the [Changeset Guidelines](#changeset-guidelines) below for details.
|
||||
|
||||
### 6. Submit Your PR
|
||||
|
||||
- Target the `next` branch
|
||||
- Write a clear description
|
||||
- Reference any related issues
|
||||
|
||||
## 📋 Development Guidelines
|
||||
|
||||
### Branch Strategy
|
||||
|
||||
- **`main`**: Production-ready code
|
||||
- **`next`**: Development branch - **target this for PRs**
|
||||
- **Feature branches**: `feature/description` or `fix/description`
|
||||
|
||||
### Code Quality Standards
|
||||
|
||||
1. **Write tests** for new functionality
|
||||
2. **Follow existing patterns** in the codebase
|
||||
3. **Add JSDoc comments** for functions
|
||||
4. **Keep functions focused** and single-purpose
|
||||
|
||||
### Testing Requirements
|
||||
|
||||
Your PR **must pass all CI checks**:
|
||||
|
||||
- ✅ **Unit tests**: `npm test`
|
||||
- ✅ **Format check**: `npm run format-check`
|
||||
|
||||
**Test your changes locally first** - this saves review time and shows you care about quality.
|
||||
|
||||
## 📦 Changeset Guidelines
|
||||
|
||||
We use [Changesets](https://github.com/changesets/changesets) to manage versioning and generate changelogs.
|
||||
|
||||
### When to Create a Changeset
|
||||
|
||||
**Always create a changeset for**:
|
||||
|
||||
- ✅ New features
|
||||
- ✅ Bug fixes
|
||||
- ✅ Breaking changes
|
||||
- ✅ Performance improvements
|
||||
- ✅ User-facing documentation updates
|
||||
- ✅ Dependency updates that affect functionality
|
||||
|
||||
**Skip changesets for**:
|
||||
|
||||
- ❌ Internal documentation only
|
||||
- ❌ Test-only changes
|
||||
- ❌ Code formatting/linting
|
||||
- ❌ Development tooling that doesn't affect users
|
||||
|
||||
### How to Create a Changeset
|
||||
|
||||
1. **After making your changes**:
|
||||
|
||||
```bash
|
||||
npm run changeset
|
||||
```
|
||||
|
||||
2. **Choose the bump type**:
|
||||
|
||||
- **Major**: Breaking changes
|
||||
- **Minor**: New features
|
||||
- **Patch**: Bug fixes, docs, performance improvements
|
||||
|
||||
3. **Write a clear summary**:
|
||||
|
||||
```
|
||||
Add support for custom AI models in MCP configuration
|
||||
```
|
||||
|
||||
4. **Commit the changeset file** with your changes:
|
||||
```bash
|
||||
git add .changeset/*.md
|
||||
git commit -m "feat: add custom AI model support"
|
||||
```
|
||||
|
||||
### Changeset vs Git Commit Messages
|
||||
|
||||
- **Changeset summary**: User-facing, goes in CHANGELOG.md
|
||||
- **Git commit**: Developer-facing, explains the technical change
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
# Changeset summary (user-facing)
|
||||
"Add support for custom Ollama models"
|
||||
|
||||
# Git commit message (developer-facing)
|
||||
"feat(models): implement custom Ollama model validation
|
||||
|
||||
- Add model validation for custom Ollama endpoints
|
||||
- Update configuration schema to support custom models
|
||||
- Add tests for new validation logic"
|
||||
```
|
||||
|
||||
## 🔧 Development Setup
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 14+
|
||||
- npm or yarn
|
||||
|
||||
### Environment Setup
|
||||
|
||||
1. **Copy environment template**:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
2. **Add your API keys** (for testing AI features):
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=your_key_here
|
||||
OPENAI_API_KEY=your_key_here
|
||||
# Add others as needed
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
npm test
|
||||
|
||||
# Run tests in watch mode
|
||||
npm run test:watch
|
||||
|
||||
# Run with coverage
|
||||
npm run test:coverage
|
||||
|
||||
# Run E2E tests
|
||||
npm run test:e2e
|
||||
```
|
||||
|
||||
### Code Formatting
|
||||
|
||||
We use Prettier for consistent formatting:
|
||||
|
||||
```bash
|
||||
# Check formatting
|
||||
npm run format-check
|
||||
|
||||
# Fix formatting
|
||||
npm run format
|
||||
```
|
||||
|
||||
## 📝 PR Guidelines
|
||||
|
||||
### Before Submitting
|
||||
|
||||
- [ ] **Target the `next` branch**
|
||||
- [ ] **Test everything locally**
|
||||
- [ ] **Run the full test suite**
|
||||
- [ ] **Check code formatting**
|
||||
- [ ] **Create a changeset** (if needed)
|
||||
- [ ] **Re-read your changes** - ensure they're clean and well-thought-out
|
||||
|
||||
### PR Description Template
|
||||
|
||||
```markdown
|
||||
## Description
|
||||
|
||||
Brief description of what this PR does.
|
||||
|
||||
## Type of Change
|
||||
|
||||
- [ ] Bug fix
|
||||
- [ ] New feature
|
||||
- [ ] Breaking change
|
||||
- [ ] Documentation update
|
||||
|
||||
## Testing
|
||||
|
||||
- [ ] I have tested this locally
|
||||
- [ ] All existing tests pass
|
||||
- [ ] I have added tests for new functionality
|
||||
|
||||
## Changeset
|
||||
|
||||
- [ ] I have created a changeset (or this change doesn't need one)
|
||||
|
||||
## Additional Notes
|
||||
|
||||
Any additional context or notes for reviewers.
|
||||
```
|
||||
|
||||
### What We Look For
|
||||
|
||||
✅ **Good PRs**:
|
||||
|
||||
- Clear, focused changes
|
||||
- Comprehensive testing
|
||||
- Good commit messages
|
||||
- Proper changeset (when needed)
|
||||
- Self-reviewed code
|
||||
|
||||
❌ **Avoid**:
|
||||
|
||||
- Massive PRs that change everything
|
||||
- Untested code
|
||||
- Formatting issues
|
||||
- Missing changesets for user-facing changes
|
||||
- AI-generated code that wasn't reviewed
|
||||
|
||||
## 🏗️ Project Structure
|
||||
|
||||
```
|
||||
claude-task-master/
|
||||
├── bin/ # CLI executables
|
||||
├── mcp-server/ # MCP server implementation
|
||||
├── scripts/ # Core task management logic
|
||||
├── src/ # Shared utilities and providers and well refactored code (we are slowly moving everything here)
|
||||
├── tests/ # Test files
|
||||
├── docs/ # Documentation
|
||||
└── .cursor/ # Cursor IDE rules and configuration
|
||||
└── assets/ # Assets like rules and configuration for all IDEs
|
||||
```
|
||||
|
||||
### Key Areas for Contribution
|
||||
|
||||
- **CLI Commands**: `scripts/modules/commands.js`
|
||||
- **MCP Tools**: `mcp-server/src/tools/`
|
||||
- **Core Logic**: `scripts/modules/task-manager/`
|
||||
- **AI Providers**: `src/ai-providers/`
|
||||
- **Tests**: `tests/`
|
||||
|
||||
## 🐛 Reporting Issues
|
||||
|
||||
### Bug Reports
|
||||
|
||||
Include:
|
||||
|
||||
- Task Master version
|
||||
- Node.js version
|
||||
- Operating system
|
||||
- Steps to reproduce
|
||||
- Expected vs actual behavior
|
||||
- Error messages/logs
|
||||
|
||||
### Feature Requests
|
||||
|
||||
Include:
|
||||
|
||||
- Clear description of the feature
|
||||
- Use case/motivation
|
||||
- Proposed implementation (if you have ideas)
|
||||
- Willingness to contribute
|
||||
|
||||
## 💬 Getting Help
|
||||
|
||||
- **Discord**: [Join our community](https://discord.gg/taskmasterai)
|
||||
- **Issues**: [GitHub Issues](https://github.com/eyaltoledano/claude-task-master/issues)
|
||||
- **Discussions**: [GitHub Discussions](https://github.com/eyaltoledano/claude-task-master/discussions)
|
||||
|
||||
## 📄 License
|
||||
|
||||
By contributing, you agree that your contributions will be licensed under the same license as the project (MIT with Commons Clause).
|
||||
|
||||
---
|
||||
|
||||
**Thank you for contributing to Task Master!** 🎉
|
||||
|
||||
Your contributions help make AI-driven development more accessible and efficient for everyone.
|
||||
96
README.md
96
README.md
@@ -28,13 +28,22 @@ Using the research model is optional but highly recommended. You will need at le
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Option 1 | MCP (Recommended):
|
||||
### Option 1: MCP (Recommended)
|
||||
|
||||
MCP (Model Control Protocol) provides the easiest way to get started with Task Master directly in your editor.
|
||||
MCP (Model Control Protocol) lets you run Task Master directly from your editor.
|
||||
|
||||
1. **Add the MCP config to your editor** (Cursor recommended, but it works with other text editors):
|
||||
#### 1. Add your MCP config at the following path depending on your editor
|
||||
|
||||
```json
|
||||
| Editor | Scope | Linux/macOS Path | Windows Path | Key |
|
||||
| ------------ | ------- | ------------------------------------- | ------------------------------------------------- | ------------ |
|
||||
| **Cursor** | Global | `~/.cursor/mcp.json` | `%USERPROFILE%\.cursor\mcp.json` | `mcpServers` |
|
||||
| | Project | `<project_folder>/.cursor/mcp.json` | `<project_folder>\.cursor\mcp.json` | `mcpServers` |
|
||||
| **Windsurf** | Global | `~/.codeium/windsurf/mcp_config.json` | `%USERPROFILE%\.codeium\windsurf\mcp_config.json` | `mcpServers` |
|
||||
| **VS Code** | Project | `<project_folder>/.vscode/mcp.json` | `<project_folder>\.vscode\mcp.json` | `servers` |
|
||||
|
||||
##### Cursor & Windsurf (`mcpServers`)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"mcpServers": {
|
||||
"taskmaster-ai": {
|
||||
@@ -56,23 +65,78 @@ MCP (Model Control Protocol) provides the easiest way to get started with Task M
|
||||
}
|
||||
```
|
||||
|
||||
2. **Enable the MCP** in your editor
|
||||
> 🔑 Replace `YOUR_…_KEY_HERE` with your real API keys. You can remove keys you don't use.
|
||||
|
||||
3. **Prompt the AI** to initialize Task Master:
|
||||
##### VS Code (`servers` + `type`)
|
||||
|
||||
```
|
||||
Can you please initialize taskmaster-ai into my project?
|
||||
```jsonc
|
||||
{
|
||||
"servers": {
|
||||
"taskmaster-ai": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
|
||||
"env": {
|
||||
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
||||
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
||||
"OPENAI_API_KEY": "YOUR_OPENAI_KEY_HERE",
|
||||
"GOOGLE_API_KEY": "YOUR_GOOGLE_KEY_HERE",
|
||||
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
|
||||
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
|
||||
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
|
||||
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE"
|
||||
},
|
||||
"type": "stdio"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
4. **Use common commands** directly through your AI assistant:
|
||||
> 🔑 Replace `YOUR_…_KEY_HERE` with your real API keys. You can remove keys you don't use.
|
||||
|
||||
#### 2. (Cursor-only) Enable Taskmaster MCP
|
||||
|
||||
Open Cursor Settings (Ctrl+Shift+J) ➡ Click on MCP tab on the left ➡ Enable task-master-ai with the toggle
|
||||
|
||||
#### 3. (Optional) Configure the models you want to use
|
||||
|
||||
In your editor’s AI chat pane, say:
|
||||
|
||||
```txt
|
||||
Can you parse my PRD at scripts/prd.txt?
|
||||
What's the next task I should work on?
|
||||
Can you help me implement task 3?
|
||||
Can you help me expand task 4?
|
||||
Change the main, research and fallback models to <model_name>, <model_name> and <model_name> respectively.
|
||||
```
|
||||
|
||||
[Table of available models](docs/models.md)
|
||||
|
||||
#### 4. Initialize Task Master
|
||||
|
||||
In your editor’s AI chat pane, say:
|
||||
|
||||
```txt
|
||||
Initialize taskmaster-ai in my project
|
||||
```
|
||||
|
||||
#### 5. Make sure you have a PRD in `<project_folder>/scripts/prd.txt`
|
||||
|
||||
An example of a PRD is located into `<project_folder>/scripts/example_prd.txt`.
|
||||
|
||||
**Always start with a detailed PRD.**
|
||||
|
||||
The more detailed your PRD, the better the generated tasks will be.
|
||||
|
||||
#### 6. Common Commands
|
||||
|
||||
Use your AI assistant to:
|
||||
|
||||
- Parse requirements: `Can you parse my PRD at scripts/prd.txt?`
|
||||
- Plan next step: `What’s the next task I should work on?`
|
||||
- Implement a task: `Can you help me implement task 3?`
|
||||
- View multiple tasks: `Can you show me tasks 1, 3, and 5?`
|
||||
- Expand a task: `Can you help me expand task 4?`
|
||||
- **Research fresh information**: `Research the latest best practices for implementing JWT authentication with Node.js`
|
||||
- **Research with context**: `Research React Query v5 migration strategies for our current API implementation in src/api.js`
|
||||
|
||||
[More examples on how to use Task Master in chat](docs/examples.md)
|
||||
|
||||
### Option 2: Using Command Line
|
||||
|
||||
#### Installation
|
||||
@@ -112,6 +176,12 @@ task-master list
|
||||
# Show the next task to work on
|
||||
task-master next
|
||||
|
||||
# Show specific task(s) - supports comma-separated IDs
|
||||
task-master show 1,3,5
|
||||
|
||||
# Research fresh information with project context
|
||||
task-master research "What are the latest best practices for JWT authentication?"
|
||||
|
||||
# Generate task files
|
||||
task-master generate
|
||||
```
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"models": {
|
||||
"main": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 120000,
|
||||
"temperature": 0.2
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-5-sonnet-20240620",
|
||||
"maxTokens": 8192,
|
||||
"temperature": 0.1
|
||||
}
|
||||
},
|
||||
"global": {
|
||||
"logLevel": "info",
|
||||
"debug": false,
|
||||
"defaultSubtasks": 5,
|
||||
"defaultPriority": "medium",
|
||||
"projectName": "Taskmaster",
|
||||
"ollamaBaseUrl": "http://localhost:11434/api",
|
||||
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
|
||||
}
|
||||
}
|
||||
413
assets/AGENTS.md
Normal file
413
assets/AGENTS.md
Normal file
@@ -0,0 +1,413 @@
|
||||
# Task Master AI - Claude Code Integration Guide
|
||||
|
||||
## Essential Commands
|
||||
|
||||
### Core Workflow Commands
|
||||
|
||||
```bash
|
||||
# Project Setup
|
||||
task-master init # Initialize Task Master in current project
|
||||
task-master parse-prd scripts/prd.txt # Generate tasks from PRD document
|
||||
task-master models --setup # Configure AI models interactively
|
||||
|
||||
# Daily Development Workflow
|
||||
task-master list # Show all tasks with status
|
||||
task-master next # Get next available task to work on
|
||||
task-master show <id> # View detailed task information (e.g., task-master show 1.2)
|
||||
task-master set-status --id=<id> --status=done # Mark task complete
|
||||
|
||||
# Task Management
|
||||
task-master add-task --prompt="description" --research # Add new task with AI assistance
|
||||
task-master expand --id=<id> --research --force # Break task into subtasks
|
||||
task-master update-task --id=<id> --prompt="changes" # Update specific task
|
||||
task-master update --from=<id> --prompt="changes" # Update multiple tasks from ID onwards
|
||||
task-master update-subtask --id=<id> --prompt="notes" # Add implementation notes to subtask
|
||||
|
||||
# Analysis & Planning
|
||||
task-master analyze-complexity --research # Analyze task complexity
|
||||
task-master complexity-report # View complexity analysis
|
||||
task-master expand --all --research # Expand all eligible tasks
|
||||
|
||||
# Dependencies & Organization
|
||||
task-master add-dependency --id=<id> --depends-on=<id> # Add task dependency
|
||||
task-master move --from=<id> --to=<id> # Reorganize task hierarchy
|
||||
task-master validate-dependencies # Check for dependency issues
|
||||
task-master generate # Update task markdown files (usually auto-called)
|
||||
```
|
||||
|
||||
## Key Files & Project Structure
|
||||
|
||||
### Core Files
|
||||
|
||||
- `tasks/tasks.json` - Main task data file (auto-managed)
|
||||
- `.taskmasterconfig` - AI model configuration (use `task-master models` to modify)
|
||||
- `scripts/prd.txt` - Product Requirements Document for parsing
|
||||
- `tasks/*.txt` - Individual task files (auto-generated from tasks.json)
|
||||
- `.env` - API keys for CLI usage
|
||||
|
||||
### Claude Code Integration Files
|
||||
|
||||
- `CLAUDE.md` - Auto-loaded context for Claude Code (this file)
|
||||
- `.claude/settings.json` - Claude Code tool allowlist and preferences
|
||||
- `.claude/commands/` - Custom slash commands for repeated workflows
|
||||
- `.mcp.json` - MCP server configuration (project-specific)
|
||||
|
||||
### Directory Structure
|
||||
|
||||
```
|
||||
project/
|
||||
├── tasks/
|
||||
│ ├── tasks.json # Main task database
|
||||
│ ├── task-1.md # Individual task files
|
||||
│ └── task-2.md
|
||||
├── scripts/
|
||||
│ ├── prd.txt # Product requirements
|
||||
│ └── task-complexity-report.json
|
||||
├── .claude/
|
||||
│ ├── settings.json # Claude Code configuration
|
||||
│ └── commands/ # Custom slash commands
|
||||
├── .taskmasterconfig # AI models & settings
|
||||
├── .env # API keys
|
||||
├── .mcp.json # MCP configuration
|
||||
└── CLAUDE.md # This file - auto-loaded by Claude Code
|
||||
```
|
||||
|
||||
## MCP Integration
|
||||
|
||||
Task Master provides an MCP server that Claude Code can connect to. Configure in `.mcp.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"task-master-ai": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
|
||||
"env": {
|
||||
"ANTHROPIC_API_KEY": "your_key_here",
|
||||
"PERPLEXITY_API_KEY": "your_key_here",
|
||||
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
|
||||
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
|
||||
"XAI_API_KEY": "XAI_API_KEY_HERE",
|
||||
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
|
||||
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
|
||||
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
|
||||
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Essential MCP Tools
|
||||
|
||||
```javascript
|
||||
help; // = shows available taskmaster commands
|
||||
// Project setup
|
||||
initialize_project; // = task-master init
|
||||
parse_prd; // = task-master parse-prd
|
||||
|
||||
// Daily workflow
|
||||
get_tasks; // = task-master list
|
||||
next_task; // = task-master next
|
||||
get_task; // = task-master show <id>
|
||||
set_task_status; // = task-master set-status
|
||||
|
||||
// Task management
|
||||
add_task; // = task-master add-task
|
||||
expand_task; // = task-master expand
|
||||
update_task; // = task-master update-task
|
||||
update_subtask; // = task-master update-subtask
|
||||
update; // = task-master update
|
||||
|
||||
// Analysis
|
||||
analyze_project_complexity; // = task-master analyze-complexity
|
||||
complexity_report; // = task-master complexity-report
|
||||
```
|
||||
|
||||
## Claude Code Workflow Integration
|
||||
|
||||
### Standard Development Workflow
|
||||
|
||||
#### 1. Project Initialization
|
||||
|
||||
```bash
|
||||
# Initialize Task Master
|
||||
task-master init
|
||||
|
||||
# Create or obtain PRD, then parse it
|
||||
task-master parse-prd scripts/prd.txt
|
||||
|
||||
# Analyze complexity and expand tasks
|
||||
task-master analyze-complexity --research
|
||||
task-master expand --all --research
|
||||
```
|
||||
|
||||
If tasks already exist, another PRD can be parsed (with new information only!) using parse-prd with --append flag. This will add the generated tasks to the existing list of tasks..
|
||||
|
||||
#### 2. Daily Development Loop
|
||||
|
||||
```bash
|
||||
# Start each session
|
||||
task-master next # Find next available task
|
||||
task-master show <id> # Review task details
|
||||
|
||||
# During implementation, check in code context into the tasks and subtasks
|
||||
task-master update-subtask --id=<id> --prompt="implementation notes..."
|
||||
|
||||
# Complete tasks
|
||||
task-master set-status --id=<id> --status=done
|
||||
```
|
||||
|
||||
#### 3. Multi-Claude Workflows
|
||||
|
||||
For complex projects, use multiple Claude Code sessions:
|
||||
|
||||
```bash
|
||||
# Terminal 1: Main implementation
|
||||
cd project && claude
|
||||
|
||||
# Terminal 2: Testing and validation
|
||||
cd project-test-worktree && claude
|
||||
|
||||
# Terminal 3: Documentation updates
|
||||
cd project-docs-worktree && claude
|
||||
```
|
||||
|
||||
### Custom Slash Commands
|
||||
|
||||
Create `.claude/commands/taskmaster-next.md`:
|
||||
|
||||
```markdown
|
||||
Find the next available Task Master task and show its details.
|
||||
|
||||
Steps:
|
||||
|
||||
1. Run `task-master next` to get the next task
|
||||
2. If a task is available, run `task-master show <id>` for full details
|
||||
3. Provide a summary of what needs to be implemented
|
||||
4. Suggest the first implementation step
|
||||
```
|
||||
|
||||
Create `.claude/commands/taskmaster-complete.md`:
|
||||
|
||||
```markdown
|
||||
Complete a Task Master task: $ARGUMENTS
|
||||
|
||||
Steps:
|
||||
|
||||
1. Review the current task with `task-master show $ARGUMENTS`
|
||||
2. Verify all implementation is complete
|
||||
3. Run any tests related to this task
|
||||
4. Mark as complete: `task-master set-status --id=$ARGUMENTS --status=done`
|
||||
5. Show the next available task with `task-master next`
|
||||
```
|
||||
|
||||
## Tool Allowlist Recommendations
|
||||
|
||||
Add to `.claude/settings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"allowedTools": [
|
||||
"Edit",
|
||||
"Bash(task-master *)",
|
||||
"Bash(git commit:*)",
|
||||
"Bash(git add:*)",
|
||||
"Bash(npm run *)",
|
||||
"mcp__task_master_ai__*"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration & Setup
|
||||
|
||||
### API Keys Required
|
||||
|
||||
At least **one** of these API keys must be configured:
|
||||
|
||||
- `ANTHROPIC_API_KEY` (Claude models) - **Recommended**
|
||||
- `PERPLEXITY_API_KEY` (Research features) - **Highly recommended**
|
||||
- `OPENAI_API_KEY` (GPT models)
|
||||
- `GOOGLE_API_KEY` (Gemini models)
|
||||
- `MISTRAL_API_KEY` (Mistral models)
|
||||
- `OPENROUTER_API_KEY` (Multiple models)
|
||||
- `XAI_API_KEY` (Grok models)
|
||||
|
||||
An API key is required for any provider used across any of the 3 roles defined in the `models` command.
|
||||
|
||||
### Model Configuration
|
||||
|
||||
```bash
|
||||
# Interactive setup (recommended)
|
||||
task-master models --setup
|
||||
|
||||
# Set specific models
|
||||
task-master models --set-main claude-3-5-sonnet-20241022
|
||||
task-master models --set-research perplexity-llama-3.1-sonar-large-128k-online
|
||||
task-master models --set-fallback gpt-4o-mini
|
||||
```
|
||||
|
||||
## Task Structure & IDs
|
||||
|
||||
### Task ID Format
|
||||
|
||||
- Main tasks: `1`, `2`, `3`, etc.
|
||||
- Subtasks: `1.1`, `1.2`, `2.1`, etc.
|
||||
- Sub-subtasks: `1.1.1`, `1.1.2`, etc.
|
||||
|
||||
### Task Status Values
|
||||
|
||||
- `pending` - Ready to work on
|
||||
- `in-progress` - Currently being worked on
|
||||
- `done` - Completed and verified
|
||||
- `deferred` - Postponed
|
||||
- `cancelled` - No longer needed
|
||||
- `blocked` - Waiting on external factors
|
||||
|
||||
### Task Fields
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "1.2",
|
||||
"title": "Implement user authentication",
|
||||
"description": "Set up JWT-based auth system",
|
||||
"status": "pending",
|
||||
"priority": "high",
|
||||
"dependencies": ["1.1"],
|
||||
"details": "Use bcrypt for hashing, JWT for tokens...",
|
||||
"testStrategy": "Unit tests for auth functions, integration tests for login flow",
|
||||
"subtasks": []
|
||||
}
|
||||
```
|
||||
|
||||
## Claude Code Best Practices with Task Master
|
||||
|
||||
### Context Management
|
||||
|
||||
- Use `/clear` between different tasks to maintain focus
|
||||
- This CLAUDE.md file is automatically loaded for context
|
||||
- Use `task-master show <id>` to pull specific task context when needed
|
||||
|
||||
### Iterative Implementation
|
||||
|
||||
1. `task-master show <subtask-id>` - Understand requirements
|
||||
2. Explore codebase and plan implementation
|
||||
3. `task-master update-subtask --id=<id> --prompt="detailed plan"` - Log plan
|
||||
4. `task-master set-status --id=<id> --status=in-progress` - Start work
|
||||
5. Implement code following logged plan
|
||||
6. `task-master update-subtask --id=<id> --prompt="what worked/didn't work"` - Log progress
|
||||
7. `task-master set-status --id=<id> --status=done` - Complete task
|
||||
|
||||
### Complex Workflows with Checklists
|
||||
|
||||
For large migrations or multi-step processes:
|
||||
|
||||
1. Create a markdown PRD file describing the new changes: `touch task-migration-checklist.md` (prds can be .txt or .md)
|
||||
2. Use Taskmaster to parse the new prd with `task-master parse-prd --append` (also available in MCP)
|
||||
3. Use Taskmaster to expand the newly generated tasks into subtasks. Consdier using `analyze-complexity` with the correct --to and --from IDs (the new ids) to identify the ideal subtask amounts for each task. Then expand them.
|
||||
4. Work through items systematically, checking them off as completed
|
||||
5. Use `task-master update-subtask` to log progress on each task/subtask and/or updating/researching them before/during implementation if getting stuck
|
||||
|
||||
### Git Integration
|
||||
|
||||
Task Master works well with `gh` CLI:
|
||||
|
||||
```bash
|
||||
# Create PR for completed task
|
||||
gh pr create --title "Complete task 1.2: User authentication" --body "Implements JWT auth system as specified in task 1.2"
|
||||
|
||||
# Reference task in commits
|
||||
git commit -m "feat: implement JWT auth (task 1.2)"
|
||||
```
|
||||
|
||||
### Parallel Development with Git Worktrees
|
||||
|
||||
```bash
|
||||
# Create worktrees for parallel task development
|
||||
git worktree add ../project-auth feature/auth-system
|
||||
git worktree add ../project-api feature/api-refactor
|
||||
|
||||
# Run Claude Code in each worktree
|
||||
cd ../project-auth && claude # Terminal 1: Auth work
|
||||
cd ../project-api && claude # Terminal 2: API work
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### AI Commands Failing
|
||||
|
||||
```bash
|
||||
# Check API keys are configured
|
||||
cat .env # For CLI usage
|
||||
|
||||
# Verify model configuration
|
||||
task-master models
|
||||
|
||||
# Test with different model
|
||||
task-master models --set-fallback gpt-4o-mini
|
||||
```
|
||||
|
||||
### MCP Connection Issues
|
||||
|
||||
- Check `.mcp.json` configuration
|
||||
- Verify Node.js installation
|
||||
- Use `--mcp-debug` flag when starting Claude Code
|
||||
- Use CLI as fallback if MCP unavailable
|
||||
|
||||
### Task File Sync Issues
|
||||
|
||||
```bash
|
||||
# Regenerate task files from tasks.json
|
||||
task-master generate
|
||||
|
||||
# Fix dependency issues
|
||||
task-master fix-dependencies
|
||||
```
|
||||
|
||||
DO NOT RE-INITIALIZE. That will not do anything beyond re-adding the same Taskmaster core files.
|
||||
|
||||
## Important Notes
|
||||
|
||||
### AI-Powered Operations
|
||||
|
||||
These commands make AI calls and may take up to a minute:
|
||||
|
||||
- `parse_prd` / `task-master parse-prd`
|
||||
- `analyze_project_complexity` / `task-master analyze-complexity`
|
||||
- `expand_task` / `task-master expand`
|
||||
- `expand_all` / `task-master expand --all`
|
||||
- `add_task` / `task-master add-task`
|
||||
- `update` / `task-master update`
|
||||
- `update_task` / `task-master update-task`
|
||||
- `update_subtask` / `task-master update-subtask`
|
||||
|
||||
### File Management
|
||||
|
||||
- Never manually edit `tasks.json` - use commands instead
|
||||
- Never manually edit `.taskmasterconfig` - use `task-master models`
|
||||
- Task markdown files in `tasks/` are auto-generated
|
||||
- Run `task-master generate` after manual changes to tasks.json
|
||||
|
||||
### Claude Code Session Management
|
||||
|
||||
- Use `/clear` frequently to maintain focused context
|
||||
- Create custom slash commands for repeated Task Master workflows
|
||||
- Configure tool allowlist to streamline permissions
|
||||
- Use headless mode for automation: `claude -p "task-master next"`
|
||||
|
||||
### Multi-Task Updates
|
||||
|
||||
- Use `update --from=<id>` to update multiple future tasks
|
||||
- Use `update-task --id=<id>` for single task updates
|
||||
- Use `update-subtask --id=<id>` for implementation logging
|
||||
|
||||
### Research Mode
|
||||
|
||||
- Add `--research` flag for research-based AI enhancement
|
||||
- Requires a research model API key like Perplexity (`PERPLEXITY_API_KEY`) in environment
|
||||
- Provides more informed task creation and updates
|
||||
- Recommended for complex technical tasks
|
||||
|
||||
---
|
||||
|
||||
_This guide ensures Claude Code has immediate access to Task Master's essential functionality for agentic development workflows._
|
||||
@@ -39,7 +39,7 @@
|
||||
{
|
||||
"slug": "debug",
|
||||
"name": "Debug",
|
||||
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mdode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
|
||||
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
|
||||
"customInstructions": "Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.",
|
||||
"groups": [
|
||||
"read",
|
||||
|
||||
47
biome.json
Normal file
47
biome.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"files": {
|
||||
"ignore": [
|
||||
"build",
|
||||
"coverage",
|
||||
".changeset",
|
||||
"tasks",
|
||||
"package-lock.json",
|
||||
"tests/fixture/*.json"
|
||||
]
|
||||
},
|
||||
"formatter": {
|
||||
"bracketSpacing": true,
|
||||
"enabled": true,
|
||||
"indentStyle": "tab",
|
||||
"lineWidth": 80
|
||||
},
|
||||
"javascript": {
|
||||
"formatter": {
|
||||
"arrowParentheses": "always",
|
||||
"quoteStyle": "single",
|
||||
"trailingCommas": "none"
|
||||
}
|
||||
},
|
||||
"linter": {
|
||||
"rules": {
|
||||
"complexity": {
|
||||
"noForEach": "off",
|
||||
"useOptionalChain": "off"
|
||||
},
|
||||
"correctness": {
|
||||
"noConstantCondition": "off",
|
||||
"noUnreachable": "off"
|
||||
},
|
||||
"suspicious": {
|
||||
"noDuplicateTestHooks": "off",
|
||||
"noPrototypeBuiltins": "off"
|
||||
},
|
||||
"style": {
|
||||
"noUselessElse": "off",
|
||||
"useNodejsImportProtocol": "off",
|
||||
"useNumberNamespace": "off",
|
||||
"noParameterAssign": "off"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
1798
context/chats/add-task-dependencies-1.md
Normal file
1798
context/chats/add-task-dependencies-1.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,7 @@ Welcome to the Task Master documentation. Use the links below to navigate to the
|
||||
|
||||
## Reference
|
||||
|
||||
- [Command Reference](command-reference.md) - Complete list of all available commands
|
||||
- [Command Reference](command-reference.md) - Complete list of all available commands (including research and multi-task viewing)
|
||||
- [Task Structure](task-structure.md) - Understanding the task format and features
|
||||
|
||||
## Examples & Licensing
|
||||
|
||||
@@ -43,10 +43,28 @@ task-master show <id>
|
||||
# or
|
||||
task-master show --id=<id>
|
||||
|
||||
# View multiple tasks with comma-separated IDs
|
||||
task-master show 1,3,5
|
||||
task-master show 44,55
|
||||
|
||||
# View a specific subtask (e.g., subtask 2 of task 1)
|
||||
task-master show 1.2
|
||||
|
||||
# Mix parent tasks and subtasks
|
||||
task-master show 44,44.1,55,55.2
|
||||
```
|
||||
|
||||
**Multiple Task Display:**
|
||||
|
||||
- **Single ID**: Shows detailed task view with full implementation details
|
||||
- **Multiple IDs**: Shows compact summary table with interactive action menu
|
||||
- **Action Menu**: Provides copy-paste ready commands for batch operations:
|
||||
- Mark all as in-progress/done
|
||||
- Show next available task
|
||||
- Expand all tasks (generate subtasks)
|
||||
- View dependency relationships
|
||||
- Generate task files
|
||||
|
||||
## Update Tasks
|
||||
|
||||
```bash
|
||||
@@ -187,6 +205,32 @@ task-master validate-dependencies
|
||||
task-master fix-dependencies
|
||||
```
|
||||
|
||||
## Move Tasks
|
||||
|
||||
```bash
|
||||
# Move a task or subtask to a new position
|
||||
task-master move --from=<id> --to=<id>
|
||||
|
||||
# Examples:
|
||||
# Move task to become a subtask
|
||||
task-master move --from=5 --to=7
|
||||
|
||||
# Move subtask to become a standalone task
|
||||
task-master move --from=5.2 --to=7
|
||||
|
||||
# Move subtask to a different parent
|
||||
task-master move --from=5.2 --to=7.3
|
||||
|
||||
# Reorder subtasks within the same parent
|
||||
task-master move --from=5.2 --to=5.4
|
||||
|
||||
# Move a task to a new ID position (creates placeholder if doesn't exist)
|
||||
task-master move --from=5 --to=25
|
||||
|
||||
# Move multiple tasks at once (must have the same number of IDs)
|
||||
task-master move --from=10,11,12 --to=16,17,18
|
||||
```
|
||||
|
||||
## Add a New Task
|
||||
|
||||
```bash
|
||||
@@ -236,3 +280,42 @@ task-master models --setup
|
||||
```
|
||||
|
||||
Configuration is stored in `.taskmasterconfig` in your project root. API keys are still managed via `.env` or MCP configuration. Use `task-master models` without flags to see available built-in models. Use `--setup` for a guided experience.
|
||||
|
||||
## Research Fresh Information
|
||||
|
||||
```bash
|
||||
# Perform AI-powered research with fresh, up-to-date information
|
||||
task-master research "What are the latest best practices for JWT authentication in Node.js?"
|
||||
|
||||
# Research with specific task context
|
||||
task-master research "How to implement OAuth 2.0?" --id=15,16
|
||||
|
||||
# Research with file context for code-aware suggestions
|
||||
task-master research "How can I optimize this API implementation?" --files=src/api.js,src/auth.js
|
||||
|
||||
# Research with custom context and project tree
|
||||
task-master research "Best practices for error handling" --context="We're using Express.js" --tree
|
||||
|
||||
# Research with different detail levels
|
||||
task-master research "React Query v5 migration guide" --detail=high
|
||||
|
||||
# Save research results to a file
|
||||
task-master research "Database optimization techniques" --save=research/db-optimization.md
|
||||
```
|
||||
|
||||
**The research command is a powerful tool that provides:**
|
||||
|
||||
- **Fresh information beyond AI knowledge cutoffs**
|
||||
- **Project-aware context** from your tasks and files
|
||||
- **Automatic task discovery** using fuzzy search
|
||||
- **Multiple detail levels** (low, medium, high)
|
||||
- **Token counting and cost tracking**
|
||||
- **Interactive follow-up questions**
|
||||
|
||||
**Use research frequently to:**
|
||||
|
||||
- Get current best practices before implementing features
|
||||
- Research new technologies and libraries
|
||||
- Find solutions to complex problems
|
||||
- Validate your implementation approaches
|
||||
- Stay updated with latest security recommendations
|
||||
|
||||
@@ -16,14 +16,14 @@ Taskmaster uses two primary methods for configuration:
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 64000,
|
||||
"temperature": 0.2,
|
||||
"baseUrl": "https://api.anthropic.com/v1"
|
||||
"baseURL": "https://api.anthropic.com/v1"
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1,
|
||||
"baseUrl": "https://api.perplexity.ai/v1"
|
||||
"baseURL": "https://api.perplexity.ai/v1"
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
@@ -38,8 +38,10 @@ Taskmaster uses two primary methods for configuration:
|
||||
"defaultSubtasks": 5,
|
||||
"defaultPriority": "medium",
|
||||
"projectName": "Your Project Name",
|
||||
"ollamaBaseUrl": "http://localhost:11434/api",
|
||||
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
|
||||
"ollamaBaseURL": "http://localhost:11434/api",
|
||||
"azureBaseURL": "https://your-endpoint.azure.com/",
|
||||
"vertexProjectId": "your-gcp-project-id",
|
||||
"vertexLocation": "us-central1"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -53,15 +55,18 @@ Taskmaster uses two primary methods for configuration:
|
||||
- `ANTHROPIC_API_KEY`: Your Anthropic API key.
|
||||
- `PERPLEXITY_API_KEY`: Your Perplexity API key.
|
||||
- `OPENAI_API_KEY`: Your OpenAI API key.
|
||||
- `GOOGLE_API_KEY`: Your Google API key.
|
||||
- `GOOGLE_API_KEY`: Your Google API key (also used for Vertex AI provider).
|
||||
- `MISTRAL_API_KEY`: Your Mistral API key.
|
||||
- `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key (also requires `AZURE_OPENAI_ENDPOINT`).
|
||||
- `OPENROUTER_API_KEY`: Your OpenRouter API key.
|
||||
- `XAI_API_KEY`: Your X-AI API key.
|
||||
- **Optional Endpoint Overrides:**
|
||||
- **Per-role `baseUrl` in `.taskmasterconfig`:** You can add a `baseUrl` property to any model role (`main`, `research`, `fallback`) to override the default API endpoint for that provider. If omitted, the provider's standard endpoint is used.
|
||||
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key (can also be set as `baseUrl` for the Azure model role).
|
||||
- **Per-role `baseURL` in `.taskmasterconfig`:** You can add a `baseURL` property to any model role (`main`, `research`, `fallback`) to override the default API endpoint for that provider. If omitted, the provider's standard endpoint is used.
|
||||
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key (can also be set as `baseURL` for the Azure model role).
|
||||
- `OLLAMA_BASE_URL`: Override the default Ollama API URL (Default: `http://localhost:11434/api`).
|
||||
- `VERTEX_PROJECT_ID`: Your Google Cloud project ID for Vertex AI. Required when using the 'vertex' provider.
|
||||
- `VERTEX_LOCATION`: Google Cloud region for Vertex AI (e.g., 'us-central1'). Default is 'us-central1'.
|
||||
- `GOOGLE_APPLICATION_CREDENTIALS`: Path to service account credentials JSON file for Google Cloud auth (alternative to API key for Vertex AI).
|
||||
|
||||
**Important:** Settings like model ID selections (`main`, `research`, `fallback`), `maxTokens`, `temperature`, `logLevel`, `defaultSubtasks`, `defaultPriority`, and `projectName` are **managed in `.taskmasterconfig`**, not environment variables.
|
||||
|
||||
@@ -78,6 +83,11 @@ PERPLEXITY_API_KEY=pplx-your-key-here
|
||||
# Optional Endpoint Overrides
|
||||
# AZURE_OPENAI_ENDPOINT=https://your-azure-endpoint.openai.azure.com/
|
||||
# OLLAMA_BASE_URL=http://custom-ollama-host:11434/api
|
||||
|
||||
# Google Vertex AI Configuration (Required if using 'vertex' provider)
|
||||
# VERTEX_PROJECT_ID=your-gcp-project-id
|
||||
# VERTEX_LOCATION=us-central1
|
||||
# GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
@@ -102,3 +112,45 @@ git clone https://github.com/eyaltoledano/claude-task-master.git
|
||||
cd claude-task-master
|
||||
node scripts/init.js
|
||||
```
|
||||
|
||||
## Provider-Specific Configuration
|
||||
|
||||
### Google Vertex AI Configuration
|
||||
|
||||
Google Vertex AI is Google Cloud's enterprise AI platform and requires specific configuration:
|
||||
|
||||
1. **Prerequisites**:
|
||||
- A Google Cloud account with Vertex AI API enabled
|
||||
- Either a Google API key with Vertex AI permissions OR a service account with appropriate roles
|
||||
- A Google Cloud project ID
|
||||
2. **Authentication Options**:
|
||||
- **API Key**: Set the `GOOGLE_API_KEY` environment variable
|
||||
- **Service Account**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to your service account JSON file
|
||||
3. **Required Configuration**:
|
||||
- Set `VERTEX_PROJECT_ID` to your Google Cloud project ID
|
||||
- Set `VERTEX_LOCATION` to your preferred Google Cloud region (default: us-central1)
|
||||
4. **Example Setup**:
|
||||
|
||||
```bash
|
||||
# In .env file
|
||||
GOOGLE_API_KEY=AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
VERTEX_PROJECT_ID=my-gcp-project-123
|
||||
VERTEX_LOCATION=us-central1
|
||||
```
|
||||
|
||||
Or using service account:
|
||||
|
||||
```bash
|
||||
# In .env file
|
||||
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
|
||||
VERTEX_PROJECT_ID=my-gcp-project-123
|
||||
VERTEX_LOCATION=us-central1
|
||||
```
|
||||
|
||||
5. **In .taskmasterconfig**:
|
||||
```json
|
||||
"global": {
|
||||
"vertexProjectId": "my-gcp-project-123",
|
||||
"vertexLocation": "us-central1"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -21,6 +21,20 @@ What's the next task I should work on? Please consider dependencies and prioriti
|
||||
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
|
||||
```
|
||||
|
||||
## Viewing multiple tasks
|
||||
|
||||
```
|
||||
Can you show me tasks 1, 3, and 5 so I can understand their relationship?
|
||||
```
|
||||
|
||||
```
|
||||
I need to see the status of tasks 44, 55, and their subtasks. Can you show me those?
|
||||
```
|
||||
|
||||
```
|
||||
Show me tasks 10, 12, and 15 and give me some batch actions I can perform on them.
|
||||
```
|
||||
|
||||
## Managing subtasks
|
||||
|
||||
```
|
||||
@@ -30,7 +44,7 @@ I need to regenerate the subtasks for task 3 with a different approach. Can you
|
||||
## Handling changes
|
||||
|
||||
```
|
||||
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||
I've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||
```
|
||||
|
||||
## Completing work
|
||||
@@ -40,6 +54,34 @@ I've finished implementing the authentication system described in task 2. All te
|
||||
Please mark it as complete and tell me what I should work on next.
|
||||
```
|
||||
|
||||
## Reorganizing tasks
|
||||
|
||||
```
|
||||
I think subtask 5.2 would fit better as part of task 7. Can you move it there?
|
||||
```
|
||||
|
||||
(Agent runs: `task-master move --from=5.2 --to=7.3`)
|
||||
|
||||
```
|
||||
Task 8 should actually be a subtask of task 4. Can you reorganize this?
|
||||
```
|
||||
|
||||
(Agent runs: `task-master move --from=8 --to=4.1`)
|
||||
|
||||
```
|
||||
I just merged the main branch and there's a conflict in tasks.json. My teammates created tasks 10-15 on their branch while I created tasks 10-12 on my branch. Can you help me resolve this by moving my tasks?
|
||||
```
|
||||
|
||||
(Agent runs:
|
||||
|
||||
```bash
|
||||
task-master move --from=10 --to=16
|
||||
task-master move --from=11 --to=17
|
||||
task-master move --from=12 --to=18
|
||||
```
|
||||
|
||||
)
|
||||
|
||||
## Analyzing complexity
|
||||
|
||||
```
|
||||
@@ -81,3 +123,56 @@ Please add a new task to implement user profile image uploads using Cloudinary,
|
||||
```
|
||||
|
||||
(Agent runs: `task-master add-task --prompt="Implement user profile image uploads using Cloudinary" --research`)
|
||||
|
||||
## Research-Driven Development
|
||||
|
||||
### Getting Fresh Information
|
||||
|
||||
```
|
||||
Research the latest best practices for implementing JWT authentication in Node.js applications.
|
||||
```
|
||||
|
||||
(Agent runs: `task-master research "Latest best practices for JWT authentication in Node.js"`)
|
||||
|
||||
### Research with Project Context
|
||||
|
||||
```
|
||||
I'm working on task 15 which involves API optimization. Can you research current best practices for our specific implementation?
|
||||
```
|
||||
|
||||
(Agent runs: `task-master research "API optimization best practices" --id=15 --files=src/api.js`)
|
||||
|
||||
### Research Before Implementation
|
||||
|
||||
```
|
||||
Before I implement task 8 (React Query integration), can you research the latest React Query v5 patterns and any breaking changes?
|
||||
```
|
||||
|
||||
(Agent runs: `task-master research "React Query v5 patterns and breaking changes" --id=8`)
|
||||
|
||||
### Research and Update Pattern
|
||||
|
||||
```
|
||||
Research the latest security recommendations for Express.js applications and update our authentication task with the findings.
|
||||
```
|
||||
|
||||
(Agent runs:
|
||||
|
||||
1. `task-master research "Latest Express.js security recommendations" --id=12`
|
||||
2. `task-master update-subtask --id=12.3 --prompt="Updated with latest security findings: [research results]"`)
|
||||
|
||||
### Research for Debugging
|
||||
|
||||
```
|
||||
I'm having issues with our WebSocket implementation in task 20. Can you research common WebSocket problems and solutions?
|
||||
```
|
||||
|
||||
(Agent runs: `task-master research "Common WebSocket implementation problems and solutions" --id=20 --files=src/websocket.js`)
|
||||
|
||||
### Research Technology Comparisons
|
||||
|
||||
```
|
||||
We need to choose between Redis and Memcached for caching. Can you research the current recommendations for our use case?
|
||||
```
|
||||
|
||||
(Agent runs: `task-master research "Redis vs Memcached 2024 comparison for session caching" --tree`)
|
||||
|
||||
125
docs/models.md
Normal file
125
docs/models.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# Available Models as of May 27, 2025
|
||||
|
||||
## Main Models
|
||||
|
||||
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
|
||||
| ---------- | ---------------------------------------------- | --------- | ---------- | ----------- |
|
||||
| anthropic | claude-sonnet-4-20250514 | 0.727 | 3 | 15 |
|
||||
| anthropic | claude-opus-4-20250514 | 0.725 | 15 | 75 |
|
||||
| anthropic | claude-3-7-sonnet-20250219 | 0.623 | 3 | 15 |
|
||||
| anthropic | claude-3-5-sonnet-20241022 | 0.49 | 3 | 15 |
|
||||
| openai | gpt-4o | 0.332 | 2.5 | 10 |
|
||||
| openai | o1 | 0.489 | 15 | 60 |
|
||||
| openai | o3 | 0.5 | 10 | 40 |
|
||||
| openai | o3-mini | 0.493 | 1.1 | 4.4 |
|
||||
| openai | o4-mini | 0.45 | 1.1 | 4.4 |
|
||||
| openai | o1-mini | 0.4 | 1.1 | 4.4 |
|
||||
| openai | o1-pro | — | 150 | 600 |
|
||||
| openai | gpt-4-5-preview | 0.38 | 75 | 150 |
|
||||
| openai | gpt-4-1-mini | — | 0.4 | 1.6 |
|
||||
| openai | gpt-4-1-nano | — | 0.1 | 0.4 |
|
||||
| openai | gpt-4o-mini | 0.3 | 0.15 | 0.6 |
|
||||
| google | gemini-2.5-pro-preview-05-06 | 0.638 | — | — |
|
||||
| google | gemini-2.5-pro-preview-03-25 | 0.638 | — | — |
|
||||
| google | gemini-2.5-flash-preview-04-17 | — | — | — |
|
||||
| google | gemini-2.0-flash | 0.754 | 0.15 | 0.6 |
|
||||
| google | gemini-2.0-flash-lite | — | — | — |
|
||||
| perplexity | sonar-reasoning-pro | 0.211 | 2 | 8 |
|
||||
| perplexity | sonar-reasoning | 0.211 | 1 | 5 |
|
||||
| xai | grok-3 | — | 3 | 15 |
|
||||
| xai | grok-3-fast | — | 5 | 25 |
|
||||
| ollama | devstral:latest | — | 0 | 0 |
|
||||
| ollama | qwen3:latest | — | 0 | 0 |
|
||||
| ollama | qwen3:14b | — | 0 | 0 |
|
||||
| ollama | qwen3:32b | — | 0 | 0 |
|
||||
| ollama | mistral-small3.1:latest | — | 0 | 0 |
|
||||
| ollama | llama3.3:latest | — | 0 | 0 |
|
||||
| ollama | phi4:latest | — | 0 | 0 |
|
||||
| openrouter | google/gemini-2.5-flash-preview-05-20 | — | 0.15 | 0.6 |
|
||||
| openrouter | google/gemini-2.5-flash-preview-05-20:thinking | — | 0.15 | 3.5 |
|
||||
| openrouter | google/gemini-2.5-pro-exp-03-25 | — | 0 | 0 |
|
||||
| openrouter | deepseek/deepseek-chat-v3-0324:free | — | 0 | 0 |
|
||||
| openrouter | deepseek/deepseek-chat-v3-0324 | — | 0.27 | 1.1 |
|
||||
| openrouter | openai/gpt-4.1 | — | 2 | 8 |
|
||||
| openrouter | openai/gpt-4.1-mini | — | 0.4 | 1.6 |
|
||||
| openrouter | openai/gpt-4.1-nano | — | 0.1 | 0.4 |
|
||||
| openrouter | openai/o3 | — | 10 | 40 |
|
||||
| openrouter | openai/codex-mini | — | 1.5 | 6 |
|
||||
| openrouter | openai/gpt-4o-mini | — | 0.15 | 0.6 |
|
||||
| openrouter | openai/o4-mini | 0.45 | 1.1 | 4.4 |
|
||||
| openrouter | openai/o4-mini-high | — | 1.1 | 4.4 |
|
||||
| openrouter | openai/o1-pro | — | 150 | 600 |
|
||||
| openrouter | meta-llama/llama-3.3-70b-instruct | — | 120 | 600 |
|
||||
| openrouter | meta-llama/llama-4-maverick | — | 0.18 | 0.6 |
|
||||
| openrouter | meta-llama/llama-4-scout | — | 0.08 | 0.3 |
|
||||
| openrouter | qwen/qwen-max | — | 1.6 | 6.4 |
|
||||
| openrouter | qwen/qwen-turbo | — | 0.05 | 0.2 |
|
||||
| openrouter | qwen/qwen3-235b-a22b | — | 0.14 | 2 |
|
||||
| openrouter | mistralai/mistral-small-3.1-24b-instruct:free | — | 0 | 0 |
|
||||
| openrouter | mistralai/mistral-small-3.1-24b-instruct | — | 0.1 | 0.3 |
|
||||
| openrouter | mistralai/devstral-small | — | 0.1 | 0.3 |
|
||||
| openrouter | mistralai/mistral-nemo | — | 0.03 | 0.07 |
|
||||
| openrouter | thudm/glm-4-32b:free | — | 0 | 0 |
|
||||
|
||||
## Research Models
|
||||
|
||||
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
|
||||
| ---------- | -------------------------- | --------- | ---------- | ----------- |
|
||||
| openai | gpt-4o-search-preview | 0.33 | 2.5 | 10 |
|
||||
| openai | gpt-4o-mini-search-preview | 0.3 | 0.15 | 0.6 |
|
||||
| perplexity | sonar-pro | — | 3 | 15 |
|
||||
| perplexity | sonar | — | 1 | 1 |
|
||||
| perplexity | deep-research | 0.211 | 2 | 8 |
|
||||
| xai | grok-3 | — | 3 | 15 |
|
||||
| xai | grok-3-fast | — | 5 | 25 |
|
||||
|
||||
## Fallback Models
|
||||
|
||||
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
|
||||
| ---------- | ---------------------------------------------- | --------- | ---------- | ----------- |
|
||||
| anthropic | claude-sonnet-4-20250514 | 0.727 | 3 | 15 |
|
||||
| anthropic | claude-opus-4-20250514 | 0.725 | 15 | 75 |
|
||||
| anthropic | claude-3-7-sonnet-20250219 | 0.623 | 3 | 15 |
|
||||
| anthropic | claude-3-5-sonnet-20241022 | 0.49 | 3 | 15 |
|
||||
| openai | gpt-4o | 0.332 | 2.5 | 10 |
|
||||
| openai | o3 | 0.5 | 10 | 40 |
|
||||
| openai | o4-mini | 0.45 | 1.1 | 4.4 |
|
||||
| google | gemini-2.5-pro-preview-05-06 | 0.638 | — | — |
|
||||
| google | gemini-2.5-pro-preview-03-25 | 0.638 | — | — |
|
||||
| google | gemini-2.5-flash-preview-04-17 | — | — | — |
|
||||
| google | gemini-2.0-flash | 0.754 | 0.15 | 0.6 |
|
||||
| google | gemini-2.0-flash-lite | — | — | — |
|
||||
| perplexity | sonar-reasoning-pro | 0.211 | 2 | 8 |
|
||||
| perplexity | sonar-reasoning | 0.211 | 1 | 5 |
|
||||
| xai | grok-3 | — | 3 | 15 |
|
||||
| xai | grok-3-fast | — | 5 | 25 |
|
||||
| ollama | devstral:latest | — | 0 | 0 |
|
||||
| ollama | qwen3:latest | — | 0 | 0 |
|
||||
| ollama | qwen3:14b | — | 0 | 0 |
|
||||
| ollama | qwen3:32b | — | 0 | 0 |
|
||||
| ollama | mistral-small3.1:latest | — | 0 | 0 |
|
||||
| ollama | llama3.3:latest | — | 0 | 0 |
|
||||
| ollama | phi4:latest | — | 0 | 0 |
|
||||
| openrouter | google/gemini-2.5-flash-preview-05-20 | — | 0.15 | 0.6 |
|
||||
| openrouter | google/gemini-2.5-flash-preview-05-20:thinking | — | 0.15 | 3.5 |
|
||||
| openrouter | google/gemini-2.5-pro-exp-03-25 | — | 0 | 0 |
|
||||
| openrouter | deepseek/deepseek-chat-v3-0324:free | — | 0 | 0 |
|
||||
| openrouter | openai/gpt-4.1 | — | 2 | 8 |
|
||||
| openrouter | openai/gpt-4.1-mini | — | 0.4 | 1.6 |
|
||||
| openrouter | openai/gpt-4.1-nano | — | 0.1 | 0.4 |
|
||||
| openrouter | openai/o3 | — | 10 | 40 |
|
||||
| openrouter | openai/codex-mini | — | 1.5 | 6 |
|
||||
| openrouter | openai/gpt-4o-mini | — | 0.15 | 0.6 |
|
||||
| openrouter | openai/o4-mini | 0.45 | 1.1 | 4.4 |
|
||||
| openrouter | openai/o4-mini-high | — | 1.1 | 4.4 |
|
||||
| openrouter | openai/o1-pro | — | 150 | 600 |
|
||||
| openrouter | meta-llama/llama-3.3-70b-instruct | — | 120 | 600 |
|
||||
| openrouter | meta-llama/llama-4-maverick | — | 0.18 | 0.6 |
|
||||
| openrouter | meta-llama/llama-4-scout | — | 0.08 | 0.3 |
|
||||
| openrouter | qwen/qwen-max | — | 1.6 | 6.4 |
|
||||
| openrouter | qwen/qwen-turbo | — | 0.05 | 0.2 |
|
||||
| openrouter | qwen/qwen3-235b-a22b | — | 0.14 | 2 |
|
||||
| openrouter | mistralai/mistral-small-3.1-24b-instruct:free | — | 0 | 0 |
|
||||
| openrouter | mistralai/mistral-small-3.1-24b-instruct | — | 0.1 | 0.3 |
|
||||
| openrouter | mistralai/mistral-nemo | — | 0.03 | 0.07 |
|
||||
| openrouter | thudm/glm-4-32b:free | — | 0 | 0 |
|
||||
131
docs/scripts/models-json-to-markdown.js
Normal file
131
docs/scripts/models-json-to-markdown.js
Normal file
@@ -0,0 +1,131 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const supportedModelsPath = path.join(
|
||||
__dirname,
|
||||
'..',
|
||||
'modules',
|
||||
'supported-models.json'
|
||||
);
|
||||
const outputMarkdownPath = path.join(
|
||||
__dirname,
|
||||
'..',
|
||||
'..',
|
||||
'docs',
|
||||
'models.md'
|
||||
);
|
||||
|
||||
function formatCost(cost) {
|
||||
if (cost === null || cost === undefined) {
|
||||
return '—';
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
|
||||
function formatSweScore(score) {
|
||||
if (score === null || score === undefined || score === 0) {
|
||||
return '—';
|
||||
}
|
||||
return score.toString();
|
||||
}
|
||||
|
||||
function generateMarkdownTable(title, models) {
|
||||
if (!models || models.length === 0) {
|
||||
return `## ${title}\n\nNo models in this category.\n\n`;
|
||||
}
|
||||
let table = `## ${title}\n\n`;
|
||||
table += '| Provider | Model Name | SWE Score | Input Cost | Output Cost |\n';
|
||||
table += '|---|---|---|---|---|\n';
|
||||
models.forEach((model) => {
|
||||
table += `| ${model.provider} | ${model.modelName} | ${formatSweScore(model.sweScore)} | ${formatCost(model.inputCost)} | ${formatCost(model.outputCost)} |\n`;
|
||||
});
|
||||
table += '\n';
|
||||
return table;
|
||||
}
|
||||
|
||||
function main() {
|
||||
try {
|
||||
const correctSupportedModelsPath = path.join(
|
||||
__dirname,
|
||||
'..',
|
||||
'..',
|
||||
'scripts',
|
||||
'modules',
|
||||
'supported-models.json'
|
||||
);
|
||||
const correctOutputMarkdownPath = path.join(__dirname, '..', 'models.md');
|
||||
|
||||
const supportedModelsContent = fs.readFileSync(
|
||||
correctSupportedModelsPath,
|
||||
'utf8'
|
||||
);
|
||||
const supportedModels = JSON.parse(supportedModelsContent);
|
||||
|
||||
const mainModels = [];
|
||||
const researchModels = [];
|
||||
const fallbackModels = [];
|
||||
|
||||
for (const provider in supportedModels) {
|
||||
if (Object.hasOwnProperty.call(supportedModels, provider)) {
|
||||
const models = supportedModels[provider];
|
||||
models.forEach((model) => {
|
||||
const modelEntry = {
|
||||
provider: provider,
|
||||
modelName: model.id,
|
||||
sweScore: model.swe_score,
|
||||
inputCost: model.cost_per_1m_tokens
|
||||
? model.cost_per_1m_tokens.input
|
||||
: null,
|
||||
outputCost: model.cost_per_1m_tokens
|
||||
? model.cost_per_1m_tokens.output
|
||||
: null
|
||||
};
|
||||
|
||||
if (model.allowed_roles.includes('main')) {
|
||||
mainModels.push(modelEntry);
|
||||
}
|
||||
if (model.allowed_roles.includes('research')) {
|
||||
researchModels.push(modelEntry);
|
||||
}
|
||||
if (model.allowed_roles.includes('fallback')) {
|
||||
fallbackModels.push(modelEntry);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const date = new Date();
|
||||
const monthNames = [
|
||||
'January',
|
||||
'February',
|
||||
'March',
|
||||
'April',
|
||||
'May',
|
||||
'June',
|
||||
'July',
|
||||
'August',
|
||||
'September',
|
||||
'October',
|
||||
'November',
|
||||
'December'
|
||||
];
|
||||
const formattedDate = `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
|
||||
|
||||
let markdownContent = `# Available Models as of ${formattedDate}\n\n`;
|
||||
markdownContent += generateMarkdownTable('Main Models', mainModels);
|
||||
markdownContent += generateMarkdownTable('Research Models', researchModels);
|
||||
markdownContent += generateMarkdownTable('Fallback Models', fallbackModels);
|
||||
|
||||
fs.writeFileSync(correctOutputMarkdownPath, markdownContent, 'utf8');
|
||||
console.log(`Successfully updated ${correctOutputMarkdownPath}`);
|
||||
} catch (error) {
|
||||
console.error('Error transforming models.json to models.md:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
128
docs/tutorial.md
128
docs/tutorial.md
@@ -198,10 +198,15 @@ Ask the agent to list available tasks:
|
||||
What tasks are available to work on next?
|
||||
```
|
||||
|
||||
```
|
||||
Can you show me tasks 1, 3, and 5 to understand their current status?
|
||||
```
|
||||
|
||||
The agent will:
|
||||
|
||||
- Run `task-master list` to see all tasks
|
||||
- Run `task-master next` to determine the next task to work on
|
||||
- Run `task-master show 1,3,5` to display multiple tasks with interactive options
|
||||
- Analyze dependencies to determine which tasks are ready to be worked on
|
||||
- Prioritize tasks based on priority level and ID order
|
||||
- Suggest the next task(s) to implement
|
||||
@@ -221,6 +226,21 @@ You can ask:
|
||||
Let's implement task 3. What does it involve?
|
||||
```
|
||||
|
||||
### 2.1. Viewing Multiple Tasks
|
||||
|
||||
For efficient context gathering and batch operations:
|
||||
|
||||
```
|
||||
Show me tasks 5, 7, and 9 so I can plan my implementation approach.
|
||||
```
|
||||
|
||||
The agent will:
|
||||
|
||||
- Run `task-master show 5,7,9` to display a compact summary table
|
||||
- Show task status, priority, and progress indicators
|
||||
- Provide an interactive action menu with batch operations
|
||||
- Allow you to perform group actions like marking multiple tasks as in-progress
|
||||
|
||||
### 3. Task Verification
|
||||
|
||||
Before marking a task as complete, verify it according to:
|
||||
@@ -268,7 +288,61 @@ task-master update --from=4 --prompt="Update to use MongoDB, researching best pr
|
||||
|
||||
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
|
||||
|
||||
### 6. Breaking Down Complex Tasks
|
||||
### 6. Reorganizing Tasks
|
||||
|
||||
If you need to reorganize your task structure:
|
||||
|
||||
```
|
||||
I think subtask 5.2 would fit better as part of task 7 instead. Can you move it there?
|
||||
```
|
||||
|
||||
The agent will execute:
|
||||
|
||||
```bash
|
||||
task-master move --from=5.2 --to=7.3
|
||||
```
|
||||
|
||||
You can reorganize tasks in various ways:
|
||||
|
||||
- Moving a standalone task to become a subtask: `--from=5 --to=7`
|
||||
- Moving a subtask to become a standalone task: `--from=5.2 --to=7`
|
||||
- Moving a subtask to a different parent: `--from=5.2 --to=7.3`
|
||||
- Reordering subtasks within the same parent: `--from=5.2 --to=5.4`
|
||||
- Moving a task to a new ID position: `--from=5 --to=25` (even if task 25 doesn't exist yet)
|
||||
- Moving multiple tasks at once: `--from=10,11,12 --to=16,17,18` (must have same number of IDs, Taskmaster will look through each position)
|
||||
|
||||
When moving tasks to new IDs:
|
||||
|
||||
- The system automatically creates placeholder tasks for non-existent destination IDs
|
||||
- This prevents accidental data loss during reorganization
|
||||
- Any tasks that depend on moved tasks will have their dependencies updated
|
||||
- When moving a parent task, all its subtasks are automatically moved with it and renumbered
|
||||
|
||||
This is particularly useful as your project understanding evolves and you need to refine your task structure.
|
||||
|
||||
### 7. Resolving Merge Conflicts with Tasks
|
||||
|
||||
When working with a team, you might encounter merge conflicts in your tasks.json file if multiple team members create tasks on different branches. The move command makes resolving these conflicts straightforward:
|
||||
|
||||
```
|
||||
I just merged the main branch and there's a conflict with tasks.json. My teammates created tasks 10-15 while I created tasks 10-12 on my branch. Can you help me resolve this?
|
||||
```
|
||||
|
||||
The agent will help you:
|
||||
|
||||
1. Keep your teammates' tasks (10-15)
|
||||
2. Move your tasks to new positions to avoid conflicts:
|
||||
|
||||
```bash
|
||||
# Move your tasks to new positions (e.g., 16-18)
|
||||
task-master move --from=10 --to=16
|
||||
task-master move --from=11 --to=17
|
||||
task-master move --from=12 --to=18
|
||||
```
|
||||
|
||||
This approach preserves everyone's work while maintaining a clean task structure, making it much easier to handle task conflicts than trying to manually merge JSON files.
|
||||
|
||||
### 8. Breaking Down Complex Tasks
|
||||
|
||||
For complex tasks that need more granularity:
|
||||
|
||||
@@ -369,3 +443,55 @@ Can you analyze the complexity of our tasks to help me understand which ones nee
|
||||
```
|
||||
Can you show me the complexity report in a more readable format?
|
||||
```
|
||||
|
||||
### Research-Driven Development
|
||||
|
||||
Task Master includes a powerful research tool that provides fresh, up-to-date information beyond the AI's knowledge cutoff. This is particularly valuable for:
|
||||
|
||||
#### Getting Current Best Practices
|
||||
|
||||
```
|
||||
Before implementing task 5 (authentication), research the latest JWT security recommendations.
|
||||
```
|
||||
|
||||
The agent will execute:
|
||||
|
||||
```bash
|
||||
task-master research "Latest JWT security recommendations 2024" --id=5
|
||||
```
|
||||
|
||||
#### Research with Project Context
|
||||
|
||||
```
|
||||
Research React Query v5 migration strategies for our current API implementation.
|
||||
```
|
||||
|
||||
The agent will execute:
|
||||
|
||||
```bash
|
||||
task-master research "React Query v5 migration strategies" --files=src/api.js,src/hooks.js
|
||||
```
|
||||
|
||||
#### Research and Update Pattern
|
||||
|
||||
A powerful workflow is to research first, then update tasks with findings:
|
||||
|
||||
```
|
||||
Research the latest Node.js performance optimization techniques and update task 12 with the findings.
|
||||
```
|
||||
|
||||
The agent will:
|
||||
|
||||
1. Run research: `task-master research "Node.js performance optimization 2024" --id=12`
|
||||
2. Update the task: `task-master update-subtask --id=12.2 --prompt="Updated with latest performance findings: [research results]"`
|
||||
|
||||
#### When to Use Research
|
||||
|
||||
- **Before implementing any new technology**
|
||||
- **When encountering security-related tasks**
|
||||
- **For performance optimization tasks**
|
||||
- **When debugging complex issues**
|
||||
- **Before making architectural decisions**
|
||||
- **When updating dependencies**
|
||||
|
||||
The research tool automatically includes relevant project context and provides fresh information that can significantly improve implementation quality.
|
||||
|
||||
@@ -1,52 +1,52 @@
|
||||
export default {
|
||||
// Use Node.js environment for testing
|
||||
testEnvironment: 'node',
|
||||
// Use Node.js environment for testing
|
||||
testEnvironment: "node",
|
||||
|
||||
// Automatically clear mock calls between every test
|
||||
clearMocks: true,
|
||||
// Automatically clear mock calls between every test
|
||||
clearMocks: true,
|
||||
|
||||
// Indicates whether the coverage information should be collected while executing the test
|
||||
collectCoverage: false,
|
||||
// Indicates whether the coverage information should be collected while executing the test
|
||||
collectCoverage: false,
|
||||
|
||||
// The directory where Jest should output its coverage files
|
||||
coverageDirectory: 'coverage',
|
||||
// The directory where Jest should output its coverage files
|
||||
coverageDirectory: "coverage",
|
||||
|
||||
// A list of paths to directories that Jest should use to search for files in
|
||||
roots: ['<rootDir>/tests'],
|
||||
// A list of paths to directories that Jest should use to search for files in
|
||||
roots: ["<rootDir>/tests"],
|
||||
|
||||
// The glob patterns Jest uses to detect test files
|
||||
testMatch: ['**/__tests__/**/*.js', '**/?(*.)+(spec|test).js'],
|
||||
// The glob patterns Jest uses to detect test files
|
||||
testMatch: ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
|
||||
|
||||
// Transform files
|
||||
transform: {},
|
||||
// Transform files
|
||||
transform: {},
|
||||
|
||||
// Disable transformations for node_modules
|
||||
transformIgnorePatterns: ['/node_modules/'],
|
||||
// Disable transformations for node_modules
|
||||
transformIgnorePatterns: ["/node_modules/"],
|
||||
|
||||
// Set moduleNameMapper for absolute paths
|
||||
moduleNameMapper: {
|
||||
'^@/(.*)$': '<rootDir>/$1'
|
||||
},
|
||||
// Set moduleNameMapper for absolute paths
|
||||
moduleNameMapper: {
|
||||
"^@/(.*)$": "<rootDir>/$1",
|
||||
},
|
||||
|
||||
// Setup module aliases
|
||||
moduleDirectories: ['node_modules', '<rootDir>'],
|
||||
// Setup module aliases
|
||||
moduleDirectories: ["node_modules", "<rootDir>"],
|
||||
|
||||
// Configure test coverage thresholds
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
branches: 80,
|
||||
functions: 80,
|
||||
lines: 80,
|
||||
statements: 80
|
||||
}
|
||||
},
|
||||
// Configure test coverage thresholds
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
branches: 80,
|
||||
functions: 80,
|
||||
lines: 80,
|
||||
statements: 80,
|
||||
},
|
||||
},
|
||||
|
||||
// Generate coverage report in these formats
|
||||
coverageReporters: ['text', 'lcov'],
|
||||
// Generate coverage report in these formats
|
||||
coverageReporters: ["text", "lcov"],
|
||||
|
||||
// Verbose output
|
||||
verbose: true,
|
||||
// Verbose output
|
||||
verbose: true,
|
||||
|
||||
// Setup file
|
||||
setupFilesAfterEnv: ['<rootDir>/tests/setup.js']
|
||||
// Setup file
|
||||
setupFilesAfterEnv: ["<rootDir>/tests/setup.js"],
|
||||
};
|
||||
|
||||
131
llms-install.md
Normal file
131
llms-install.md
Normal file
@@ -0,0 +1,131 @@
|
||||
``# Taskmaster AI Installation Guide
|
||||
|
||||
This guide helps AI assistants install and configure Taskmaster for users in their development projects.
|
||||
|
||||
## What is Taskmaster?
|
||||
|
||||
Taskmaster is an AI-driven task management system designed for development workflows. It helps break down projects into manageable tasks, track dependencies, and maintain development momentum through structured, AI-enhanced planning.
|
||||
|
||||
## Installation Steps
|
||||
|
||||
### Step 1: Add MCP Configuration
|
||||
|
||||
Add the following configuration to the user's MCP settings file (`.cursor/mcp.json` for Cursor, or equivalent for other editors):
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"taskmaster-ai": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
|
||||
"env": {
|
||||
"ANTHROPIC_API_KEY": "user_will_add_their_key_here",
|
||||
"PERPLEXITY_API_KEY": "user_will_add_their_key_here",
|
||||
"OPENAI_API_KEY": "user_will_add_their_key_here",
|
||||
"GOOGLE_API_KEY": "user_will_add_their_key_here",
|
||||
"MISTRAL_API_KEY": "user_will_add_their_key_here",
|
||||
"OPENROUTER_API_KEY": "user_will_add_their_key_here",
|
||||
"XAI_API_KEY": "user_will_add_their_key_here"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: API Key Requirements
|
||||
|
||||
Inform the user they need **at least one** API key from the following providers:
|
||||
|
||||
- **Anthropic** (for Claude models) - Recommended
|
||||
- **OpenAI** (for GPT models)
|
||||
- **Google** (for Gemini models)
|
||||
- **Perplexity** (for research features) - Highly recommended
|
||||
- **Mistral** (for Mistral models)
|
||||
- **OpenRouter** (access to multiple models)
|
||||
- **xAI** (for Grok models)
|
||||
|
||||
The user will be able to define 3 separate roles (can be the same provider or separate providers) for main AI operations, research operations (research providers/models only), and a fallback model in case of errors.
|
||||
|
||||
### Step 3: Initialize Project
|
||||
|
||||
Once the MCP server is configured and API keys are added, initialize Taskmaster in the user's project:
|
||||
|
||||
> Can you initialize Task Master in my project?
|
||||
|
||||
This will run the `initialize_project` tool to set up the basic file structure.
|
||||
|
||||
### Step 4: Create Initial Tasks
|
||||
|
||||
Users have two options for creating initial tasks:
|
||||
|
||||
**Option A: Parse a PRD (Recommended)**
|
||||
If they have a Product Requirements Document:
|
||||
|
||||
> Can you parse my PRD file at [path/to/prd.txt] to generate initial tasks?
|
||||
|
||||
If the user does not have a PRD, the AI agent can help them create one and store it in scripts/prd.txt for parsing.
|
||||
|
||||
**Option B: Start from scratch**
|
||||
|
||||
> Can you help me add my first task: [describe the task]
|
||||
|
||||
## Common Usage Patterns
|
||||
|
||||
### Daily Workflow
|
||||
|
||||
> What's the next task I should work on?
|
||||
> Can you show me the details for task [ID]?
|
||||
> Can you mark task [ID] as done?
|
||||
|
||||
### Task Management
|
||||
|
||||
> Can you break down task [ID] into subtasks?
|
||||
> Can you add a new task: [description]
|
||||
> Can you analyze the complexity of my tasks?
|
||||
|
||||
### Project Organization
|
||||
|
||||
> Can you show me all my pending tasks?
|
||||
> Can you move task [ID] to become a subtask of [parent ID]?
|
||||
> Can you update task [ID] with this new information: [details]
|
||||
|
||||
## Verification Steps
|
||||
|
||||
After installation, verify everything is working:
|
||||
|
||||
1. **Check MCP Connection**: The AI should be able to access Task Master tools
|
||||
2. **Test Basic Commands**: Try `get_tasks` to list current tasks
|
||||
3. **Verify API Keys**: Ensure AI-powered commands work (like `add_task`)
|
||||
|
||||
Note: An API key fallback exists that allows the MCP server to read API keys from `.env` instead of the MCP JSON config. It is recommended to have keys in both places in case the MCP server is unable to read keys from its environment for whatever reason.
|
||||
|
||||
When adding keys to `.env` only, the `models` tool will explain that the keys are not OK for MCP. Despite this, the fallback should kick in and the API keys will be read from the `.env` file.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**If MCP server doesn't start:**
|
||||
|
||||
- Verify the JSON configuration is valid
|
||||
- Check that Node.js is installed
|
||||
- Ensure API keys are properly formatted
|
||||
|
||||
**If AI commands fail:**
|
||||
|
||||
- Verify at least one API key is configured
|
||||
- Check API key permissions and quotas
|
||||
- Try using a different model via the `models` tool
|
||||
|
||||
## CLI Fallback
|
||||
|
||||
Taskmaster is also available via CLI commands, by installing with `npm install task-master-ai@latest` in a terminal. Running `task-master help` will show all available commands, which offer a 1:1 experience with the MCP server. As the AI agent, you should refer to the system prompts and rules provided to you to identify Taskmaster-specific rules that help you understand how and when to use it.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Once installed, users can:
|
||||
|
||||
- Create new tasks with `add-task` or parse a PRD (scripts/prd.txt) into tasks with `parse-prd`
|
||||
- Set up model preferences with `models` tool
|
||||
- Expand tasks into subtasks with `expand-all` and `expand-task`
|
||||
- Explore advanced features like research mode and complexity analysis
|
||||
|
||||
For detailed documentation, refer to the Task Master docs directory.``
|
||||
@@ -18,6 +18,9 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
|
||||
* @param {string} args.outputPath - Explicit absolute path to save the report.
|
||||
* @param {string|number} [args.threshold] - Minimum complexity score to recommend expansion (1-10)
|
||||
* @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis
|
||||
* @param {string} [args.ids] - Comma-separated list of task IDs to analyze
|
||||
* @param {number} [args.from] - Starting task ID in a range to analyze
|
||||
* @param {number} [args.to] - Ending task ID in a range to analyze
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} log - Logger object
|
||||
* @param {Object} [context={}] - Context object containing session data
|
||||
@@ -26,7 +29,16 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
|
||||
*/
|
||||
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
const { tasksJsonPath, outputPath, threshold, research, projectRoot } = args;
|
||||
const {
|
||||
tasksJsonPath,
|
||||
outputPath,
|
||||
threshold,
|
||||
research,
|
||||
projectRoot,
|
||||
ids,
|
||||
from,
|
||||
to
|
||||
} = args;
|
||||
|
||||
const logWrapper = createLogWrapper(log);
|
||||
|
||||
@@ -58,6 +70,14 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
log.info(`Analyzing task complexity from: ${tasksPath}`);
|
||||
log.info(`Output report will be saved to: ${resolvedOutputPath}`);
|
||||
|
||||
if (ids) {
|
||||
log.info(`Analyzing specific task IDs: ${ids}`);
|
||||
} else if (from || to) {
|
||||
const fromStr = from !== undefined ? from : 'first';
|
||||
const toStr = to !== undefined ? to : 'last';
|
||||
log.info(`Analyzing tasks in range: ${fromStr} to ${toStr}`);
|
||||
}
|
||||
|
||||
if (research) {
|
||||
log.info('Using research role for complexity analysis');
|
||||
}
|
||||
@@ -68,7 +88,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
output: outputPath,
|
||||
threshold: threshold,
|
||||
research: research === true, // Ensure boolean
|
||||
projectRoot: projectRoot // Pass projectRoot here
|
||||
projectRoot: projectRoot, // Pass projectRoot here
|
||||
id: ids, // Pass the ids parameter to the core function as 'id'
|
||||
from: from, // Pass from parameter
|
||||
to: to // Pass to parameter
|
||||
};
|
||||
// --- End Initial Checks ---
|
||||
|
||||
|
||||
101
mcp-server/src/core/direct-functions/move-task.js
Normal file
101
mcp-server/src/core/direct-functions/move-task.js
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Direct function wrapper for moveTask
|
||||
*/
|
||||
|
||||
import { moveTask } from '../../../../scripts/modules/task-manager.js';
|
||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
|
||||
/**
|
||||
* Move a task or subtask to a new position
|
||||
* @param {Object} args - Function arguments
|
||||
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file
|
||||
* @param {string} args.sourceId - ID of the task/subtask to move (e.g., '5' or '5.2' or '5,6,7')
|
||||
* @param {string} args.destinationId - ID of the destination (e.g., '7' or '7.3' or '7,8,9')
|
||||
* @param {string} args.file - Alternative path to the tasks.json file
|
||||
* @param {string} args.projectRoot - Project root directory
|
||||
* @param {boolean} args.generateFiles - Whether to regenerate task files after moving (default: true)
|
||||
* @param {Object} log - Logger object
|
||||
* @returns {Promise<{success: boolean, data?: Object, error?: Object}>}
|
||||
*/
|
||||
export async function moveTaskDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
|
||||
// Validate required parameters
|
||||
if (!args.sourceId) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Source ID is required',
|
||||
code: 'MISSING_SOURCE_ID'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (!args.destinationId) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Destination ID is required',
|
||||
code: 'MISSING_DESTINATION_ID'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
// Find tasks.json path if not provided
|
||||
let tasksPath = args.tasksJsonPath || args.file;
|
||||
if (!tasksPath) {
|
||||
if (!args.projectRoot) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
message:
|
||||
'Project root is required if tasksJsonPath is not provided',
|
||||
code: 'MISSING_PROJECT_ROOT'
|
||||
}
|
||||
};
|
||||
}
|
||||
tasksPath = findTasksJsonPath(args, log);
|
||||
}
|
||||
|
||||
// Enable silent mode to prevent console output during MCP operation
|
||||
enableSilentMode();
|
||||
|
||||
// Call the core moveTask function with file generation control
|
||||
const generateFiles = args.generateFiles !== false; // Default to true
|
||||
const result = await moveTask(
|
||||
tasksPath,
|
||||
args.sourceId,
|
||||
args.destinationId,
|
||||
generateFiles
|
||||
);
|
||||
|
||||
// Restore console output
|
||||
disableSilentMode();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
...result,
|
||||
message: `Successfully moved task/subtask ${args.sourceId} to ${args.destinationId}`
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
// Restore console output in case of error
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Failed to move task: ${error.message}`);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
message: error.message,
|
||||
code: 'MOVE_TASK_ERROR'
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ export async function parsePRDDirect(args, log, context = {}) {
|
||||
numTasks: numTasksArg,
|
||||
force,
|
||||
append,
|
||||
research,
|
||||
projectRoot
|
||||
} = args;
|
||||
|
||||
@@ -114,8 +115,14 @@ export async function parsePRDDirect(args, log, context = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
if (research) {
|
||||
logWrapper.info(
|
||||
'Research mode enabled. Using Perplexity AI for enhanced PRD analysis.'
|
||||
);
|
||||
}
|
||||
|
||||
logWrapper.info(
|
||||
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, ProjectRoot: ${projectRoot}`
|
||||
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, Research: ${research}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
|
||||
const wasSilent = isSilentMode();
|
||||
@@ -135,6 +142,7 @@ export async function parsePRDDirect(args, log, context = {}) {
|
||||
projectRoot,
|
||||
force,
|
||||
append,
|
||||
research,
|
||||
commandName: 'parse-prd',
|
||||
outputType: 'mcp'
|
||||
},
|
||||
|
||||
159
mcp-server/src/core/direct-functions/research.js
Normal file
159
mcp-server/src/core/direct-functions/research.js
Normal file
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* research.js
|
||||
* Direct function implementation for AI-powered research queries
|
||||
*/
|
||||
|
||||
import { performResearch } from '../../../../scripts/modules/task-manager.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for performing AI-powered research with project context.
|
||||
*
|
||||
* @param {Object} args - Command arguments
|
||||
* @param {string} args.query - Research query/prompt (required)
|
||||
* @param {string} [args.taskIds] - Comma-separated list of task/subtask IDs for context
|
||||
* @param {string} [args.filePaths] - Comma-separated list of file paths for context
|
||||
* @param {string} [args.customContext] - Additional custom context text
|
||||
* @param {boolean} [args.includeProjectTree=false] - Include project file tree in context
|
||||
* @param {string} [args.detailLevel='medium'] - Detail level: 'low', 'medium', 'high'
|
||||
* @param {string} [args.projectRoot] - Project root path
|
||||
* @param {Object} log - Logger object
|
||||
* @param {Object} context - Additional context (session)
|
||||
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
|
||||
*/
|
||||
export async function researchDirect(args, log, context = {}) {
|
||||
// Destructure expected args
|
||||
const {
|
||||
query,
|
||||
taskIds,
|
||||
filePaths,
|
||||
customContext,
|
||||
includeProjectTree = false,
|
||||
detailLevel = 'medium',
|
||||
projectRoot
|
||||
} = args;
|
||||
const { session } = context; // Destructure session from context
|
||||
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
enableSilentMode();
|
||||
|
||||
// Create logger wrapper using the utility
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
try {
|
||||
// Check required parameters
|
||||
if (!query || typeof query !== 'string' || query.trim().length === 0) {
|
||||
log.error('Missing or invalid required parameter: query');
|
||||
disableSilentMode();
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'MISSING_PARAMETER',
|
||||
message:
|
||||
'The query parameter is required and must be a non-empty string'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Parse comma-separated task IDs if provided
|
||||
const parsedTaskIds = taskIds
|
||||
? taskIds
|
||||
.split(',')
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0)
|
||||
: [];
|
||||
|
||||
// Parse comma-separated file paths if provided
|
||||
const parsedFilePaths = filePaths
|
||||
? filePaths
|
||||
.split(',')
|
||||
.map((path) => path.trim())
|
||||
.filter((path) => path.length > 0)
|
||||
: [];
|
||||
|
||||
// Validate detail level
|
||||
const validDetailLevels = ['low', 'medium', 'high'];
|
||||
if (!validDetailLevels.includes(detailLevel)) {
|
||||
log.error(`Invalid detail level: ${detailLevel}`);
|
||||
disableSilentMode();
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'INVALID_PARAMETER',
|
||||
message: `Detail level must be one of: ${validDetailLevels.join(', ')}`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
log.info(
|
||||
`Performing research query: "${query.substring(0, 100)}${query.length > 100 ? '...' : ''}", ` +
|
||||
`taskIds: [${parsedTaskIds.join(', ')}], ` +
|
||||
`filePaths: [${parsedFilePaths.join(', ')}], ` +
|
||||
`detailLevel: ${detailLevel}, ` +
|
||||
`includeProjectTree: ${includeProjectTree}, ` +
|
||||
`projectRoot: ${projectRoot}`
|
||||
);
|
||||
|
||||
// Prepare options for the research function
|
||||
const researchOptions = {
|
||||
taskIds: parsedTaskIds,
|
||||
filePaths: parsedFilePaths,
|
||||
customContext: customContext || '',
|
||||
includeProjectTree,
|
||||
detailLevel,
|
||||
projectRoot
|
||||
};
|
||||
|
||||
// Prepare context for the research function
|
||||
const researchContext = {
|
||||
session,
|
||||
mcpLog,
|
||||
commandName: 'research',
|
||||
outputType: 'mcp'
|
||||
};
|
||||
|
||||
// Call the performResearch function
|
||||
const result = await performResearch(
|
||||
query.trim(),
|
||||
researchOptions,
|
||||
researchContext,
|
||||
'json', // outputFormat - use 'json' to suppress CLI UI
|
||||
false // allowFollowUp - disable for MCP calls
|
||||
);
|
||||
|
||||
// Restore normal logging
|
||||
disableSilentMode();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
query: result.query,
|
||||
result: result.result,
|
||||
contextSize: result.contextSize,
|
||||
contextTokens: result.contextTokens,
|
||||
tokenBreakdown: result.tokenBreakdown,
|
||||
systemPromptTokens: result.systemPromptTokens,
|
||||
userPromptTokens: result.userPromptTokens,
|
||||
totalInputTokens: result.totalInputTokens,
|
||||
detailLevel: result.detailLevel,
|
||||
telemetryData: result.telemetryData
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
// Make sure to restore normal logging even if there's an error
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Error in researchDirect: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: error.code || 'RESEARCH_ERROR',
|
||||
message: error.message
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
|
||||
import { nextTaskDirect } from './next-task.js';
|
||||
/**
|
||||
* Direct function wrapper for setTaskStatus with error handling.
|
||||
*
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
*/
|
||||
export async function setTaskStatusDirect(args, log) {
|
||||
// Destructure expected args, including the resolved tasksJsonPath
|
||||
const { tasksJsonPath, id, status } = args;
|
||||
const { tasksJsonPath, id, status, complexityReportPath } = args;
|
||||
try {
|
||||
log.info(`Setting task status with args: ${JSON.stringify(args)}`);
|
||||
|
||||
@@ -85,6 +85,39 @@ export async function setTaskStatusDirect(args, log) {
|
||||
},
|
||||
fromCache: false // This operation always modifies state and should never be cached
|
||||
};
|
||||
|
||||
// If the task was completed, attempt to fetch the next task
|
||||
if (result.data.status === 'done') {
|
||||
try {
|
||||
log.info(`Attempting to fetch next task for task ${taskId}`);
|
||||
const nextResult = await nextTaskDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
reportPath: complexityReportPath
|
||||
},
|
||||
log
|
||||
);
|
||||
|
||||
if (nextResult.success) {
|
||||
log.info(
|
||||
`Successfully retrieved next task: ${nextResult.data.nextTask}`
|
||||
);
|
||||
result.data = {
|
||||
...result.data,
|
||||
nextTask: nextResult.data.nextTask,
|
||||
isNextSubtask: nextResult.data.isSubtask,
|
||||
nextSteps: nextResult.data.nextSteps
|
||||
};
|
||||
} else {
|
||||
log.warn(
|
||||
`Failed to retrieve next task: ${nextResult.error?.message || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
} catch (nextErr) {
|
||||
log.error(`Error retrieving next task: ${nextErr.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
log.error(`Error setting task status: ${error.message}`);
|
||||
|
||||
@@ -66,32 +66,91 @@ export async function showTaskDirect(args, log) {
|
||||
|
||||
const complexityReport = readComplexityReport(reportPath);
|
||||
|
||||
const { task, originalSubtaskCount } = findTaskById(
|
||||
tasksData.tasks,
|
||||
id,
|
||||
complexityReport,
|
||||
status
|
||||
);
|
||||
// Parse comma-separated IDs
|
||||
const taskIds = id
|
||||
.split(',')
|
||||
.map((taskId) => taskId.trim())
|
||||
.filter((taskId) => taskId.length > 0);
|
||||
|
||||
if (!task) {
|
||||
if (taskIds.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'TASK_NOT_FOUND',
|
||||
message: `Task or subtask with ID ${id} not found`
|
||||
code: 'INVALID_TASK_ID',
|
||||
message: 'No valid task IDs provided'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
log.info(`Successfully retrieved task ${id}.`);
|
||||
// Handle single task ID (existing behavior)
|
||||
if (taskIds.length === 1) {
|
||||
const { task, originalSubtaskCount } = findTaskById(
|
||||
tasksData.tasks,
|
||||
taskIds[0],
|
||||
complexityReport,
|
||||
status
|
||||
);
|
||||
|
||||
const returnData = { ...task };
|
||||
if (originalSubtaskCount !== null) {
|
||||
returnData._originalSubtaskCount = originalSubtaskCount;
|
||||
returnData._subtaskFilter = status;
|
||||
if (!task) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'TASK_NOT_FOUND',
|
||||
message: `Task or subtask with ID ${taskIds[0]} not found`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
log.info(`Successfully retrieved task ${taskIds[0]}.`);
|
||||
|
||||
const returnData = { ...task };
|
||||
if (originalSubtaskCount !== null) {
|
||||
returnData._originalSubtaskCount = originalSubtaskCount;
|
||||
returnData._subtaskFilter = status;
|
||||
}
|
||||
|
||||
return { success: true, data: returnData };
|
||||
}
|
||||
|
||||
return { success: true, data: returnData };
|
||||
// Handle multiple task IDs
|
||||
const foundTasks = [];
|
||||
const notFoundIds = [];
|
||||
|
||||
taskIds.forEach((taskId) => {
|
||||
const { task, originalSubtaskCount } = findTaskById(
|
||||
tasksData.tasks,
|
||||
taskId,
|
||||
complexityReport,
|
||||
status
|
||||
);
|
||||
|
||||
if (task) {
|
||||
const taskData = { ...task };
|
||||
if (originalSubtaskCount !== null) {
|
||||
taskData._originalSubtaskCount = originalSubtaskCount;
|
||||
taskData._subtaskFilter = status;
|
||||
}
|
||||
foundTasks.push(taskData);
|
||||
} else {
|
||||
notFoundIds.push(taskId);
|
||||
}
|
||||
});
|
||||
|
||||
log.info(
|
||||
`Successfully retrieved ${foundTasks.length} of ${taskIds.length} requested tasks.`
|
||||
);
|
||||
|
||||
// Return multiple tasks with metadata
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
tasks: foundTasks,
|
||||
requestedIds: taskIds,
|
||||
foundCount: foundTasks.length,
|
||||
notFoundIds: notFoundIds,
|
||||
isMultiple: true
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
log.error(`Error showing task ${id}: ${error.message}`);
|
||||
return {
|
||||
|
||||
@@ -30,6 +30,8 @@ import { addDependencyDirect } from './direct-functions/add-dependency.js';
|
||||
import { removeTaskDirect } from './direct-functions/remove-task.js';
|
||||
import { initializeProjectDirect } from './direct-functions/initialize-project.js';
|
||||
import { modelsDirect } from './direct-functions/models.js';
|
||||
import { moveTaskDirect } from './direct-functions/move-task.js';
|
||||
import { researchDirect } from './direct-functions/research.js';
|
||||
|
||||
// Re-export utility functions
|
||||
export { findTasksJsonPath } from './utils/path-utils.js';
|
||||
@@ -60,7 +62,9 @@ export const directFunctions = new Map([
|
||||
['addDependencyDirect', addDependencyDirect],
|
||||
['removeTaskDirect', removeTaskDirect],
|
||||
['initializeProjectDirect', initializeProjectDirect],
|
||||
['modelsDirect', modelsDirect]
|
||||
['modelsDirect', modelsDirect],
|
||||
['moveTaskDirect', moveTaskDirect],
|
||||
['researchDirect', researchDirect]
|
||||
]);
|
||||
|
||||
// Re-export all direct function implementations
|
||||
@@ -89,5 +93,7 @@ export {
|
||||
addDependencyDirect,
|
||||
removeTaskDirect,
|
||||
initializeProjectDirect,
|
||||
modelsDirect
|
||||
modelsDirect,
|
||||
moveTaskDirect,
|
||||
researchDirect
|
||||
};
|
||||
|
||||
@@ -49,6 +49,24 @@ export function registerAnalyzeProjectComplexityTool(server) {
|
||||
.describe(
|
||||
'Path to the tasks file relative to project root (default: tasks/tasks.json).'
|
||||
),
|
||||
ids: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").'
|
||||
),
|
||||
from: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe('Starting task ID in a range to analyze.'),
|
||||
to: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe('Ending task ID in a range to analyze.'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
@@ -107,7 +125,10 @@ export function registerAnalyzeProjectComplexityTool(server) {
|
||||
outputPath: outputPath,
|
||||
threshold: args.threshold,
|
||||
research: args.research,
|
||||
projectRoot: args.projectRoot
|
||||
projectRoot: args.projectRoot,
|
||||
ids: args.ids,
|
||||
from: args.from,
|
||||
to: args.to
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
|
||||
@@ -44,7 +44,11 @@ export function registerShowTaskTool(server) {
|
||||
name: 'get_task',
|
||||
description: 'Get detailed information about a specific task',
|
||||
parameters: z.object({
|
||||
id: z.string().describe('Task ID to get'),
|
||||
id: z
|
||||
.string()
|
||||
.describe(
|
||||
'Task ID(s) to get (can be comma-separated for multiple tasks)'
|
||||
),
|
||||
status: z
|
||||
.string()
|
||||
.optional()
|
||||
@@ -66,7 +70,7 @@ export function registerShowTaskTool(server) {
|
||||
'Absolute path to the project root directory (Optional, usually from session)'
|
||||
)
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log }) => {
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
const { id, file, status, projectRoot } = args;
|
||||
|
||||
try {
|
||||
@@ -110,7 +114,8 @@ export function registerShowTaskTool(server) {
|
||||
status: status,
|
||||
projectRoot: projectRoot
|
||||
},
|
||||
log
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
|
||||
@@ -28,6 +28,8 @@ import { registerAddDependencyTool } from './add-dependency.js';
|
||||
import { registerRemoveTaskTool } from './remove-task.js';
|
||||
import { registerInitializeProjectTool } from './initialize-project.js';
|
||||
import { registerModelsTool } from './models.js';
|
||||
import { registerMoveTaskTool } from './move-task.js';
|
||||
import { registerResearchTool } from './research.js';
|
||||
|
||||
/**
|
||||
* Register all Task Master tools with the MCP server
|
||||
@@ -61,6 +63,7 @@ export function registerTaskMasterTools(server) {
|
||||
registerRemoveTaskTool(server);
|
||||
registerRemoveSubtaskTool(server);
|
||||
registerClearSubtasksTool(server);
|
||||
registerMoveTaskTool(server);
|
||||
|
||||
// Group 5: Task Analysis & Expansion
|
||||
registerAnalyzeProjectComplexityTool(server);
|
||||
@@ -72,6 +75,9 @@ export function registerTaskMasterTools(server) {
|
||||
registerRemoveDependencyTool(server);
|
||||
registerValidateDependenciesTool(server);
|
||||
registerFixDependenciesTool(server);
|
||||
|
||||
// Group 7: AI-Powered Features
|
||||
registerResearchTool(server);
|
||||
} catch (error) {
|
||||
logger.error(`Error registering Task Master tools: ${error.message}`);
|
||||
throw error;
|
||||
|
||||
66
mcp-server/src/tools/move-task.js
Normal file
66
mcp-server/src/tools/move-task.js
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* tools/move-task.js
|
||||
* Tool for moving tasks or subtasks to a new position
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
} from './utils.js';
|
||||
import { moveTaskDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Register the moveTask tool with the MCP server
|
||||
* @param {Object} server - FastMCP server instance
|
||||
*/
|
||||
export function registerMoveTaskTool(server) {
|
||||
server.addTool({
|
||||
name: 'move_task',
|
||||
description: 'Move a task or subtask to a new position',
|
||||
parameters: z.object({
|
||||
from: z
|
||||
.string()
|
||||
.describe(
|
||||
'ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")'
|
||||
),
|
||||
to: z
|
||||
.string()
|
||||
.describe(
|
||||
'ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated'
|
||||
),
|
||||
file: z.string().optional().describe('Custom path to tasks.json file'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Root directory of the project (typically derived from session)'
|
||||
)
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
try {
|
||||
// Let the core logic handle comma-separated IDs and validation
|
||||
const result = await moveTaskDirect(
|
||||
{
|
||||
sourceId: args.from,
|
||||
destinationId: args.to,
|
||||
file: args.file,
|
||||
projectRoot: args.projectRoot,
|
||||
generateFiles: true // Always generate files for MCP operations
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
return handleApiResult(result, log);
|
||||
} catch (error) {
|
||||
return createErrorResponse(
|
||||
`Failed to move task: ${error.message}`,
|
||||
'MOVE_TASK_ERROR'
|
||||
);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -49,6 +49,13 @@ export function registerParsePRDTool(server) {
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe('Append generated tasks to existing file.'),
|
||||
research: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe(
|
||||
'Use the research model for research-backed task generation, providing more comprehensive, accurate and up-to-date task details.'
|
||||
),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
@@ -68,6 +75,7 @@ export function registerParsePRDTool(server) {
|
||||
numTasks: args.numTasks,
|
||||
force: args.force,
|
||||
append: args.append,
|
||||
research: args.research,
|
||||
projectRoot: args.projectRoot
|
||||
},
|
||||
log,
|
||||
|
||||
82
mcp-server/src/tools/research.js
Normal file
82
mcp-server/src/tools/research.js
Normal file
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* tools/research.js
|
||||
* Tool to perform AI-powered research queries with project context
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
createErrorResponse,
|
||||
handleApiResult,
|
||||
withNormalizedProjectRoot
|
||||
} from './utils.js';
|
||||
import { researchDirect } from '../core/task-master-core.js';
|
||||
|
||||
/**
|
||||
* Register the research tool with the MCP server
|
||||
* @param {Object} server - FastMCP server instance
|
||||
*/
|
||||
export function registerResearchTool(server) {
|
||||
server.addTool({
|
||||
name: 'research',
|
||||
description: 'Perform AI-powered research queries with project context',
|
||||
parameters: z.object({
|
||||
query: z.string().describe('Research query/prompt (required)'),
|
||||
taskIds: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Comma-separated list of task/subtask IDs for context (e.g., "15,16.2,17")'
|
||||
),
|
||||
filePaths: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Comma-separated list of file paths for context (e.g., "src/api.js,docs/readme.md")'
|
||||
),
|
||||
customContext: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Additional custom context text to include in the research'),
|
||||
includeProjectTree: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
'Include project file tree structure in context (default: false)'
|
||||
),
|
||||
detailLevel: z
|
||||
.enum(['low', 'medium', 'high'])
|
||||
.optional()
|
||||
.describe('Detail level for the research response (default: medium)'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Starting research with query: "${args.query.substring(0, 100)}${args.query.length > 100 ? '...' : ''}"`
|
||||
);
|
||||
|
||||
// Call the direct function
|
||||
const result = await researchDirect(
|
||||
{
|
||||
query: args.query,
|
||||
taskIds: args.taskIds,
|
||||
filePaths: args.filePaths,
|
||||
customContext: args.customContext,
|
||||
includeProjectTree: args.includeProjectTree || false,
|
||||
detailLevel: args.detailLevel || 'medium',
|
||||
projectRoot: args.projectRoot
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
return handleApiResult(result, log);
|
||||
} catch (error) {
|
||||
log.error(`Error in research tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -9,8 +9,14 @@ import {
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
} from './utils.js';
|
||||
import { setTaskStatusDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
import {
|
||||
setTaskStatusDirect,
|
||||
nextTaskDirect
|
||||
} from '../core/task-master-core.js';
|
||||
import {
|
||||
findTasksJsonPath,
|
||||
findComplexityReportPath
|
||||
} from '../core/utils/path-utils.js';
|
||||
import { TASK_STATUS_OPTIONS } from '../../../src/constants/task-status.js';
|
||||
|
||||
/**
|
||||
@@ -33,6 +39,12 @@ export function registerSetTaskStatusTool(server) {
|
||||
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
|
||||
),
|
||||
file: z.string().optional().describe('Absolute path to the tasks file'),
|
||||
complexityReport: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Path to the complexity report file (relative to project root or absolute)'
|
||||
),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
@@ -55,11 +67,23 @@ export function registerSetTaskStatusTool(server) {
|
||||
);
|
||||
}
|
||||
|
||||
let complexityReportPath;
|
||||
try {
|
||||
complexityReportPath = findComplexityReportPath(
|
||||
args.projectRoot,
|
||||
args.complexityReport,
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Error finding complexity report: ${error.message}`);
|
||||
}
|
||||
|
||||
const result = await setTaskStatusDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
id: args.id,
|
||||
status: args.status
|
||||
status: args.status,
|
||||
complexityReportPath
|
||||
},
|
||||
log
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
2427
package-lock.json
generated
2427
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
24
package.json
24
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "task-master-ai",
|
||||
"version": "0.14.0-rc.0",
|
||||
"version": "0.15.0",
|
||||
"description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
|
||||
"main": "index.js",
|
||||
"type": "module",
|
||||
@@ -21,8 +21,8 @@
|
||||
"release": "changeset publish",
|
||||
"inspector": "npx @modelcontextprotocol/inspector node mcp-server/server.js",
|
||||
"mcp-server": "node mcp-server/server.js",
|
||||
"format-check": "prettier --check .",
|
||||
"format": "prettier --write ."
|
||||
"format-check": "biome format .",
|
||||
"format": "biome format . --write"
|
||||
},
|
||||
"keywords": [
|
||||
"claude",
|
||||
@@ -39,18 +39,22 @@
|
||||
"author": "Eyal Toledano",
|
||||
"license": "MIT WITH Commons-Clause",
|
||||
"dependencies": {
|
||||
"@ai-sdk/amazon-bedrock": "^2.2.9",
|
||||
"@ai-sdk/anthropic": "^1.2.10",
|
||||
"@ai-sdk/azure": "^1.3.17",
|
||||
"@ai-sdk/google": "^1.2.13",
|
||||
"@ai-sdk/google-vertex": "^2.2.23",
|
||||
"@ai-sdk/mistral": "^1.2.7",
|
||||
"@ai-sdk/openai": "^1.3.20",
|
||||
"@ai-sdk/perplexity": "^1.1.7",
|
||||
"@ai-sdk/xai": "^1.2.15",
|
||||
"@anthropic-ai/sdk": "^0.39.0",
|
||||
"@aws-sdk/credential-providers": "^3.817.0",
|
||||
"@openrouter/ai-sdk-provider": "^0.4.5",
|
||||
"ai": "^4.3.10",
|
||||
"boxen": "^8.0.1",
|
||||
"chalk": "^5.4.1",
|
||||
"cli-highlight": "^2.1.11",
|
||||
"cli-table3": "^0.6.5",
|
||||
"commander": "^11.1.0",
|
||||
"cors": "^2.8.5",
|
||||
@@ -58,20 +62,24 @@
|
||||
"express": "^4.21.2",
|
||||
"fastmcp": "^1.20.5",
|
||||
"figlet": "^1.8.0",
|
||||
"fuse.js": "^7.0.0",
|
||||
"fuse.js": "^7.1.0",
|
||||
"gpt-tokens": "^1.3.14",
|
||||
"gradient-string": "^3.0.0",
|
||||
"helmet": "^8.1.0",
|
||||
"inquirer": "^12.5.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"lru-cache": "^10.2.0",
|
||||
"ollama-ai-provider": "^1.2.0",
|
||||
"open": "^10.1.2",
|
||||
"openai": "^4.89.0",
|
||||
"ora": "^8.2.0",
|
||||
"task-master-ai": "^0.15.0",
|
||||
"uuid": "^11.1.0",
|
||||
"zod": "^3.23.8"
|
||||
"zod": "^3.23.8",
|
||||
"zod-to-json-schema": "^3.24.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -92,10 +100,11 @@
|
||||
"src/**"
|
||||
],
|
||||
"overrides": {
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-fetch": "^2.6.12",
|
||||
"whatwg-url": "^11.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^1.9.4",
|
||||
"@changesets/changelog-github": "^0.5.1",
|
||||
"@changesets/cli": "^2.28.1",
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -104,7 +113,6 @@
|
||||
"jest": "^29.7.0",
|
||||
"jest-environment-node": "^29.7.0",
|
||||
"mock-fs": "^5.5.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"prettier": "^3.5.3",
|
||||
"react": "^18.3.1",
|
||||
"supertest": "^7.1.0",
|
||||
|
||||
1869
scripts/init.js
1869
scripts/init.js
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,19 @@
|
||||
{
|
||||
"anthropic": [
|
||||
{
|
||||
"id": "claude-sonnet-4-20250514",
|
||||
"swe_score": 0.727,
|
||||
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 64000
|
||||
},
|
||||
{
|
||||
"id": "claude-opus-4-20250514",
|
||||
"swe_score": 0.725,
|
||||
"cost_per_1m_tokens": { "input": 15.0, "output": 75.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 32000
|
||||
},
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
"swe_score": 0.623,
|
||||
@@ -191,43 +205,43 @@
|
||||
],
|
||||
"ollama": [
|
||||
{
|
||||
"id": "gemma3:27b",
|
||||
"id": "devstral:latest",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"]
|
||||
},
|
||||
{
|
||||
"id": "gemma3:12b",
|
||||
"id": "qwen3:latest",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"]
|
||||
},
|
||||
{
|
||||
"id": "qwq",
|
||||
"id": "qwen3:14b",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"]
|
||||
},
|
||||
{
|
||||
"id": "deepseek-r1",
|
||||
"id": "qwen3:32b",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"]
|
||||
},
|
||||
{
|
||||
"id": "mistral-small3.1",
|
||||
"id": "mistral-small3.1:latest",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"]
|
||||
},
|
||||
{
|
||||
"id": "llama3.3",
|
||||
"id": "llama3.3:latest",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"]
|
||||
},
|
||||
{
|
||||
"id": "phi4",
|
||||
"id": "phi4:latest",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"]
|
||||
@@ -235,9 +249,16 @@
|
||||
],
|
||||
"openrouter": [
|
||||
{
|
||||
"id": "google/gemini-2.0-flash-001",
|
||||
"id": "google/gemini-2.5-flash-preview-05-20",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
|
||||
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 1048576
|
||||
},
|
||||
{
|
||||
"id": "google/gemini-2.5-flash-preview-05-20:thinking",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 1048576
|
||||
},
|
||||
@@ -263,40 +284,25 @@
|
||||
"max_tokens": 64000
|
||||
},
|
||||
{
|
||||
"id": "deepseek/deepseek-r1:free",
|
||||
"id": "openai/gpt-4.1",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"cost_per_1m_tokens": { "input": 2, "output": 8 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 163840
|
||||
"max_tokens": 1000000
|
||||
},
|
||||
|
||||
{
|
||||
"id": "microsoft/mai-ds-r1:free",
|
||||
"id": "openai/gpt-4.1-mini",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"cost_per_1m_tokens": { "input": 0.4, "output": 1.6 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 163840
|
||||
"max_tokens": 1000000
|
||||
},
|
||||
{
|
||||
"id": "google/gemini-2.5-pro-preview-03-25",
|
||||
"id": "openai/gpt-4.1-nano",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 1.25, "output": 10 },
|
||||
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 65535
|
||||
},
|
||||
{
|
||||
"id": "google/gemini-2.5-flash-preview",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
||||
"allowed_roles": ["main"],
|
||||
"max_tokens": 65535
|
||||
},
|
||||
{
|
||||
"id": "google/gemini-2.5-flash-preview:thinking",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
|
||||
"allowed_roles": ["main"],
|
||||
"max_tokens": 65535
|
||||
"max_tokens": 1000000
|
||||
},
|
||||
{
|
||||
"id": "openai/o3",
|
||||
@@ -305,6 +311,20 @@
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 200000
|
||||
},
|
||||
{
|
||||
"id": "openai/codex-mini",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 1.5, "output": 6 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 100000
|
||||
},
|
||||
{
|
||||
"id": "openai/gpt-4o-mini",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 100000
|
||||
},
|
||||
{
|
||||
"id": "openai/o4-mini",
|
||||
"swe_score": 0.45,
|
||||
@@ -334,46 +354,18 @@
|
||||
"max_tokens": 1048576
|
||||
},
|
||||
{
|
||||
"id": "google/gemma-3-12b-it:free",
|
||||
"id": "meta-llama/llama-4-maverick",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"cost_per_1m_tokens": { "input": 0.18, "output": 0.6 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 131072
|
||||
"max_tokens": 1000000
|
||||
},
|
||||
{
|
||||
"id": "google/gemma-3-12b-it",
|
||||
"id": "meta-llama/llama-4-scout",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 50, "output": 100 },
|
||||
"cost_per_1m_tokens": { "input": 0.08, "output": 0.3 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 131072
|
||||
},
|
||||
{
|
||||
"id": "google/gemma-3-27b-it:free",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 96000
|
||||
},
|
||||
{
|
||||
"id": "google/gemma-3-27b-it",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 100, "output": 200 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 131072
|
||||
},
|
||||
{
|
||||
"id": "qwen/qwq-32b:free",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 40000
|
||||
},
|
||||
{
|
||||
"id": "qwen/qwq-32b",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 150, "output": 200 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 131072
|
||||
"max_tokens": 1000000
|
||||
},
|
||||
{
|
||||
"id": "qwen/qwen-max",
|
||||
@@ -389,6 +381,13 @@
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 1000000
|
||||
},
|
||||
{
|
||||
"id": "qwen/qwen3-235b-a22b",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0.14, "output": 2 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 24000
|
||||
},
|
||||
{
|
||||
"id": "mistralai/mistral-small-3.1-24b-instruct:free",
|
||||
"swe_score": 0,
|
||||
@@ -403,6 +402,20 @@
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 128000
|
||||
},
|
||||
{
|
||||
"id": "mistralai/devstral-small",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0.1, "output": 0.3 },
|
||||
"allowed_roles": ["main"],
|
||||
"max_tokens": 110000
|
||||
},
|
||||
{
|
||||
"id": "mistralai/mistral-nemo",
|
||||
"swe_score": 0,
|
||||
"cost_per_1m_tokens": { "input": 0.03, "output": 0.07 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"max_tokens": 100000
|
||||
},
|
||||
{
|
||||
"id": "thudm/glm-4-32b:free",
|
||||
"swe_score": 0,
|
||||
|
||||
@@ -23,6 +23,8 @@ import updateSubtaskById from './task-manager/update-subtask-by-id.js';
|
||||
import removeTask from './task-manager/remove-task.js';
|
||||
import taskExists from './task-manager/task-exists.js';
|
||||
import isTaskDependentOn from './task-manager/is-task-dependent.js';
|
||||
import moveTask from './task-manager/move-task.js';
|
||||
import { performResearch } from './task-manager/research.js';
|
||||
import { readComplexityReport } from './utils.js';
|
||||
// Export task manager functions
|
||||
export {
|
||||
@@ -46,5 +48,7 @@ export {
|
||||
findTaskById,
|
||||
taskExists,
|
||||
isTaskDependentOn,
|
||||
moveTask,
|
||||
performResearch,
|
||||
readComplexityReport
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
||||
import chalk from 'chalk';
|
||||
import boxen from 'boxen';
|
||||
import readline from 'readline';
|
||||
import fs from 'fs';
|
||||
|
||||
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
|
||||
|
||||
@@ -51,6 +52,9 @@ Do not include any explanatory text, markdown formatting, or code block markers
|
||||
* @param {string|number} [options.threshold] - Complexity threshold
|
||||
* @param {boolean} [options.research] - Use research role
|
||||
* @param {string} [options.projectRoot] - Project root path (for MCP/env fallback).
|
||||
* @param {string} [options.id] - Comma-separated list of task IDs to analyze specifically
|
||||
* @param {number} [options.from] - Starting task ID in a range to analyze
|
||||
* @param {number} [options.to] - Ending task ID in a range to analyze
|
||||
* @param {Object} [options._filteredTasksData] - Pre-filtered task data (internal use)
|
||||
* @param {number} [options._originalTaskCount] - Original task count (internal use)
|
||||
* @param {Object} context - Context object, potentially containing session and mcpLog
|
||||
@@ -65,6 +69,15 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
const thresholdScore = parseFloat(options.threshold || '5');
|
||||
const useResearch = options.research || false;
|
||||
const projectRoot = options.projectRoot;
|
||||
// New parameters for task ID filtering
|
||||
const specificIds = options.id
|
||||
? options.id
|
||||
.split(',')
|
||||
.map((id) => parseInt(id.trim(), 10))
|
||||
.filter((id) => !isNaN(id))
|
||||
: null;
|
||||
const fromId = options.from !== undefined ? parseInt(options.from, 10) : null;
|
||||
const toId = options.to !== undefined ? parseInt(options.to, 10) : null;
|
||||
|
||||
const outputFormat = mcpLog ? 'json' : 'text';
|
||||
|
||||
@@ -88,13 +101,14 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
reportLog(`Reading tasks from ${tasksPath}...`, 'info');
|
||||
let tasksData;
|
||||
let originalTaskCount = 0;
|
||||
let originalData = null;
|
||||
|
||||
if (options._filteredTasksData) {
|
||||
tasksData = options._filteredTasksData;
|
||||
originalTaskCount = options._originalTaskCount || tasksData.tasks.length;
|
||||
if (!options._originalTaskCount) {
|
||||
try {
|
||||
const originalData = readJSON(tasksPath);
|
||||
originalData = readJSON(tasksPath);
|
||||
if (originalData && originalData.tasks) {
|
||||
originalTaskCount = originalData.tasks.length;
|
||||
}
|
||||
@@ -103,22 +117,80 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tasksData = readJSON(tasksPath);
|
||||
originalData = readJSON(tasksPath);
|
||||
if (
|
||||
!tasksData ||
|
||||
!tasksData.tasks ||
|
||||
!Array.isArray(tasksData.tasks) ||
|
||||
tasksData.tasks.length === 0
|
||||
!originalData ||
|
||||
!originalData.tasks ||
|
||||
!Array.isArray(originalData.tasks) ||
|
||||
originalData.tasks.length === 0
|
||||
) {
|
||||
throw new Error('No tasks found in the tasks file');
|
||||
}
|
||||
originalTaskCount = tasksData.tasks.length;
|
||||
originalTaskCount = originalData.tasks.length;
|
||||
|
||||
// Filter tasks based on active status
|
||||
const activeStatuses = ['pending', 'blocked', 'in-progress'];
|
||||
const filteredTasks = tasksData.tasks.filter((task) =>
|
||||
let filteredTasks = originalData.tasks.filter((task) =>
|
||||
activeStatuses.includes(task.status?.toLowerCase() || 'pending')
|
||||
);
|
||||
|
||||
// Apply ID filtering if specified
|
||||
if (specificIds && specificIds.length > 0) {
|
||||
reportLog(
|
||||
`Filtering tasks by specific IDs: ${specificIds.join(', ')}`,
|
||||
'info'
|
||||
);
|
||||
filteredTasks = filteredTasks.filter((task) =>
|
||||
specificIds.includes(task.id)
|
||||
);
|
||||
|
||||
if (outputFormat === 'text') {
|
||||
if (filteredTasks.length === 0 && specificIds.length > 0) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
`Warning: No active tasks found with IDs: ${specificIds.join(', ')}`
|
||||
)
|
||||
);
|
||||
} else if (filteredTasks.length < specificIds.length) {
|
||||
const foundIds = filteredTasks.map((t) => t.id);
|
||||
const missingIds = specificIds.filter(
|
||||
(id) => !foundIds.includes(id)
|
||||
);
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
`Warning: Some requested task IDs were not found or are not active: ${missingIds.join(', ')}`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Apply range filtering if specified
|
||||
else if (fromId !== null || toId !== null) {
|
||||
const effectiveFromId = fromId !== null ? fromId : 1;
|
||||
const effectiveToId =
|
||||
toId !== null
|
||||
? toId
|
||||
: Math.max(...originalData.tasks.map((t) => t.id));
|
||||
|
||||
reportLog(
|
||||
`Filtering tasks by ID range: ${effectiveFromId} to ${effectiveToId}`,
|
||||
'info'
|
||||
);
|
||||
filteredTasks = filteredTasks.filter(
|
||||
(task) => task.id >= effectiveFromId && task.id <= effectiveToId
|
||||
);
|
||||
|
||||
if (outputFormat === 'text' && filteredTasks.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
`Warning: No active tasks found in range: ${effectiveFromId}-${effectiveToId}`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
tasksData = {
|
||||
...tasksData,
|
||||
...originalData,
|
||||
tasks: filteredTasks,
|
||||
_originalTaskCount: originalTaskCount
|
||||
};
|
||||
@@ -129,7 +201,18 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
`Found ${originalTaskCount} total tasks in the task file.`,
|
||||
'info'
|
||||
);
|
||||
if (skippedCount > 0) {
|
||||
|
||||
// Updated messaging to reflect filtering logic
|
||||
if (specificIds || fromId !== null || toId !== null) {
|
||||
const filterMsg = specificIds
|
||||
? `Analyzing ${tasksData.tasks.length} tasks with specific IDs: ${specificIds.join(', ')}`
|
||||
: `Analyzing ${tasksData.tasks.length} tasks in range: ${fromId || 1} to ${toId || 'end'}`;
|
||||
|
||||
reportLog(filterMsg, 'info');
|
||||
if (outputFormat === 'text') {
|
||||
console.log(chalk.blue(filterMsg));
|
||||
}
|
||||
} else if (skippedCount > 0) {
|
||||
const skipMessage = `Skipping ${skippedCount} tasks marked as done/cancelled/deferred. Analyzing ${tasksData.tasks.length} active tasks.`;
|
||||
reportLog(skipMessage, 'info');
|
||||
if (outputFormat === 'text') {
|
||||
@@ -137,7 +220,59 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Check for existing report before doing analysis
|
||||
let existingReport = null;
|
||||
let existingAnalysisMap = new Map(); // For quick lookups by task ID
|
||||
try {
|
||||
if (fs.existsSync(outputPath)) {
|
||||
existingReport = readJSON(outputPath);
|
||||
reportLog(`Found existing complexity report at ${outputPath}`, 'info');
|
||||
|
||||
if (
|
||||
existingReport &&
|
||||
existingReport.complexityAnalysis &&
|
||||
Array.isArray(existingReport.complexityAnalysis)
|
||||
) {
|
||||
// Create lookup map of existing analysis entries
|
||||
existingReport.complexityAnalysis.forEach((item) => {
|
||||
existingAnalysisMap.set(item.taskId, item);
|
||||
});
|
||||
reportLog(
|
||||
`Existing report contains ${existingReport.complexityAnalysis.length} task analyses`,
|
||||
'info'
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (readError) {
|
||||
reportLog(
|
||||
`Warning: Could not read existing report: ${readError.message}`,
|
||||
'warn'
|
||||
);
|
||||
existingReport = null;
|
||||
existingAnalysisMap.clear();
|
||||
}
|
||||
|
||||
if (tasksData.tasks.length === 0) {
|
||||
// If using ID filtering but no matching tasks, return existing report or empty
|
||||
if (existingReport && (specificIds || fromId !== null || toId !== null)) {
|
||||
reportLog(
|
||||
`No matching tasks found for analysis. Keeping existing report.`,
|
||||
'info'
|
||||
);
|
||||
if (outputFormat === 'text') {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
`No matching tasks found for analysis. Keeping existing report.`
|
||||
)
|
||||
);
|
||||
}
|
||||
return {
|
||||
report: existingReport,
|
||||
telemetryData: null
|
||||
};
|
||||
}
|
||||
|
||||
// Otherwise create empty report
|
||||
const emptyReport = {
|
||||
meta: {
|
||||
generatedAt: new Date().toISOString(),
|
||||
@@ -146,9 +281,9 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
projectName: getProjectName(session),
|
||||
usedResearch: useResearch
|
||||
},
|
||||
complexityAnalysis: []
|
||||
complexityAnalysis: existingReport?.complexityAnalysis || []
|
||||
};
|
||||
reportLog(`Writing empty complexity report to ${outputPath}...`, 'info');
|
||||
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
|
||||
writeJSON(outputPath, emptyReport);
|
||||
reportLog(
|
||||
`Task complexity analysis complete. Report written to ${outputPath}`,
|
||||
@@ -196,9 +331,13 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
)
|
||||
);
|
||||
}
|
||||
return emptyReport;
|
||||
return {
|
||||
report: emptyReport,
|
||||
telemetryData: null
|
||||
};
|
||||
}
|
||||
|
||||
// Continue with regular analysis path
|
||||
const prompt = generateInternalComplexityAnalysisPrompt(tasksData);
|
||||
const systemPrompt =
|
||||
'You are an expert software architect and project manager analyzing task complexity. Respond only with the requested valid JSON array.';
|
||||
@@ -326,15 +465,47 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// Merge with existing report
|
||||
let finalComplexityAnalysis = [];
|
||||
|
||||
if (existingReport && Array.isArray(existingReport.complexityAnalysis)) {
|
||||
// Create a map of task IDs that we just analyzed
|
||||
const analyzedTaskIds = new Set(
|
||||
complexityAnalysis.map((item) => item.taskId)
|
||||
);
|
||||
|
||||
// Keep existing entries that weren't in this analysis run
|
||||
const existingEntriesNotAnalyzed =
|
||||
existingReport.complexityAnalysis.filter(
|
||||
(item) => !analyzedTaskIds.has(item.taskId)
|
||||
);
|
||||
|
||||
// Combine with new analysis
|
||||
finalComplexityAnalysis = [
|
||||
...existingEntriesNotAnalyzed,
|
||||
...complexityAnalysis
|
||||
];
|
||||
|
||||
reportLog(
|
||||
`Merged ${complexityAnalysis.length} new analyses with ${existingEntriesNotAnalyzed.length} existing entries`,
|
||||
'info'
|
||||
);
|
||||
} else {
|
||||
// No existing report or invalid format, just use the new analysis
|
||||
finalComplexityAnalysis = complexityAnalysis;
|
||||
}
|
||||
|
||||
const report = {
|
||||
meta: {
|
||||
generatedAt: new Date().toISOString(),
|
||||
tasksAnalyzed: tasksData.tasks.length,
|
||||
totalTasks: originalTaskCount,
|
||||
analysisCount: finalComplexityAnalysis.length,
|
||||
thresholdScore: thresholdScore,
|
||||
projectName: getProjectName(session),
|
||||
usedResearch: useResearch
|
||||
},
|
||||
complexityAnalysis: complexityAnalysis
|
||||
complexityAnalysis: finalComplexityAnalysis
|
||||
};
|
||||
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
|
||||
writeJSON(outputPath, report);
|
||||
@@ -350,6 +521,7 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
`Task complexity analysis complete. Report written to ${outputPath}`
|
||||
)
|
||||
);
|
||||
// Calculate statistics specifically for this analysis run
|
||||
const highComplexity = complexityAnalysis.filter(
|
||||
(t) => t.complexityScore >= 8
|
||||
).length;
|
||||
@@ -361,18 +533,25 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
).length;
|
||||
const totalAnalyzed = complexityAnalysis.length;
|
||||
|
||||
console.log('\nComplexity Analysis Summary:');
|
||||
console.log('\nCurrent Analysis Summary:');
|
||||
console.log('----------------------------');
|
||||
console.log(
|
||||
`Active tasks sent for analysis: ${tasksData.tasks.length}`
|
||||
);
|
||||
console.log(`Tasks successfully analyzed: ${totalAnalyzed}`);
|
||||
console.log(`Tasks analyzed in this run: ${totalAnalyzed}`);
|
||||
console.log(`High complexity tasks: ${highComplexity}`);
|
||||
console.log(`Medium complexity tasks: ${mediumComplexity}`);
|
||||
console.log(`Low complexity tasks: ${lowComplexity}`);
|
||||
console.log(
|
||||
`Sum verification: ${highComplexity + mediumComplexity + lowComplexity} (should equal ${totalAnalyzed})`
|
||||
);
|
||||
|
||||
if (existingReport) {
|
||||
console.log('\nUpdated Report Summary:');
|
||||
console.log('----------------------------');
|
||||
console.log(
|
||||
`Total analyses in report: ${finalComplexityAnalysis.length}`
|
||||
);
|
||||
console.log(
|
||||
`Analyses from previous runs: ${finalComplexityAnalysis.length - totalAnalyzed}`
|
||||
);
|
||||
console.log(`New/updated analyses: ${totalAnalyzed}`);
|
||||
}
|
||||
|
||||
console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`);
|
||||
console.log(
|
||||
`\nSee ${outputPath} for the full report and expansion commands.`
|
||||
|
||||
@@ -308,7 +308,8 @@ function parseSubtasksFromText(
|
||||
logger.error(
|
||||
`Advanced extraction: Problematic JSON string for parse (first 500 chars): ${jsonToParse.substring(0, 500)}`
|
||||
);
|
||||
throw new Error( // Re-throw a more specific error if advanced also fails
|
||||
throw new Error(
|
||||
// Re-throw a more specific error if advanced also fails
|
||||
`Failed to parse JSON response object after both simple and advanced attempts: ${parseError.message}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,6 +35,53 @@ function generateTaskFiles(tasksPath, outputDir, options = {}) {
|
||||
log('info', `Validating and fixing dependencies`);
|
||||
validateAndFixDependencies(data, tasksPath);
|
||||
|
||||
// Get valid task IDs from tasks.json
|
||||
const validTaskIds = data.tasks.map((task) => task.id);
|
||||
|
||||
// Cleanup orphaned task files
|
||||
log('info', 'Checking for orphaned task files to clean up...');
|
||||
try {
|
||||
// Get all task files in the output directory
|
||||
const files = fs.readdirSync(outputDir);
|
||||
const taskFilePattern = /^task_(\d+)\.txt$/;
|
||||
|
||||
// Filter for task files and check if they match a valid task ID
|
||||
const orphanedFiles = files.filter((file) => {
|
||||
const match = file.match(taskFilePattern);
|
||||
if (match) {
|
||||
const fileTaskId = parseInt(match[1], 10);
|
||||
return !validTaskIds.includes(fileTaskId);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
// Delete orphaned files
|
||||
if (orphanedFiles.length > 0) {
|
||||
log(
|
||||
'info',
|
||||
`Found ${orphanedFiles.length} orphaned task files to remove`
|
||||
);
|
||||
|
||||
orphanedFiles.forEach((file) => {
|
||||
const filePath = path.join(outputDir, file);
|
||||
try {
|
||||
fs.unlinkSync(filePath);
|
||||
log('info', `Removed orphaned task file: ${file}`);
|
||||
} catch (err) {
|
||||
log(
|
||||
'warn',
|
||||
`Failed to remove orphaned task file ${file}: ${err.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
log('info', 'No orphaned task files found');
|
||||
}
|
||||
} catch (err) {
|
||||
log('warn', `Error cleaning up orphaned task files: ${err.message}`);
|
||||
// Continue with file generation even if cleanup fails
|
||||
}
|
||||
|
||||
// Generate task files
|
||||
log('info', 'Generating individual task files...');
|
||||
data.tasks.forEach((task) => {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import https from 'https';
|
||||
import http from 'http';
|
||||
import {
|
||||
getMainModelId,
|
||||
getResearchModelId,
|
||||
@@ -19,7 +20,8 @@ import {
|
||||
getConfig,
|
||||
writeConfig,
|
||||
isConfigFilePresent,
|
||||
getAllProviders
|
||||
getAllProviders,
|
||||
getBaseUrlForRole
|
||||
} from '../config-manager.js';
|
||||
|
||||
/**
|
||||
@@ -68,6 +70,68 @@ function fetchOpenRouterModels() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the list of models from Ollama instance.
|
||||
* @param {string} baseURL - The base URL for the Ollama API (e.g., "http://localhost:11434/api")
|
||||
* @returns {Promise<Array|null>} A promise that resolves with the list of model objects or null if fetch fails.
|
||||
*/
|
||||
function fetchOllamaModels(baseURL = 'http://localhost:11434/api') {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
// Parse the base URL to extract hostname, port, and base path
|
||||
const url = new URL(baseURL);
|
||||
const isHttps = url.protocol === 'https:';
|
||||
const port = url.port || (isHttps ? 443 : 80);
|
||||
const basePath = url.pathname.endsWith('/')
|
||||
? url.pathname.slice(0, -1)
|
||||
: url.pathname;
|
||||
|
||||
const options = {
|
||||
hostname: url.hostname,
|
||||
port: parseInt(port, 10),
|
||||
path: `${basePath}/tags`,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json'
|
||||
}
|
||||
};
|
||||
|
||||
const requestLib = isHttps ? https : http;
|
||||
const req = requestLib.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on('end', () => {
|
||||
if (res.statusCode === 200) {
|
||||
try {
|
||||
const parsedData = JSON.parse(data);
|
||||
resolve(parsedData.models || []); // Return the array of models
|
||||
} catch (e) {
|
||||
console.error('Error parsing Ollama response:', e);
|
||||
resolve(null); // Indicate failure
|
||||
}
|
||||
} else {
|
||||
console.error(
|
||||
`Ollama API request failed with status code: ${res.statusCode}`
|
||||
);
|
||||
resolve(null); // Indicate failure
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (e) => {
|
||||
console.error('Error fetching Ollama models:', e);
|
||||
resolve(null); // Indicate failure
|
||||
});
|
||||
req.end();
|
||||
} catch (e) {
|
||||
console.error('Error parsing Ollama base URL:', e);
|
||||
resolve(null); // Indicate failure
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current model configuration
|
||||
* @param {Object} [options] - Options for the operation
|
||||
@@ -416,10 +480,29 @@ async function setModel(role, modelId, options = {}) {
|
||||
);
|
||||
}
|
||||
} else if (providerHint === 'ollama') {
|
||||
// Hinted as Ollama - set provider directly WITHOUT checking OpenRouter
|
||||
determinedProvider = 'ollama';
|
||||
warningMessage = `Warning: Custom Ollama model '${modelId}' set. Ensure your Ollama server is running and has pulled this model. Taskmaster cannot guarantee compatibility.`;
|
||||
report('warn', warningMessage);
|
||||
// Check Ollama ONLY because hint was ollama
|
||||
report('info', `Checking Ollama for ${modelId} (as hinted)...`);
|
||||
|
||||
// Get the Ollama base URL from config
|
||||
const ollamaBaseURL = getBaseUrlForRole(role, projectRoot);
|
||||
const ollamaModels = await fetchOllamaModels(ollamaBaseURL);
|
||||
|
||||
if (ollamaModels === null) {
|
||||
// Connection failed - server probably not running
|
||||
throw new Error(
|
||||
`Unable to connect to Ollama server at ${ollamaBaseURL}. Please ensure Ollama is running and try again.`
|
||||
);
|
||||
} else if (ollamaModels.some((m) => m.model === modelId)) {
|
||||
determinedProvider = 'ollama';
|
||||
warningMessage = `Warning: Custom Ollama model '${modelId}' set. Ensure your Ollama server is running and has pulled this model. Taskmaster cannot guarantee compatibility.`;
|
||||
report('warn', warningMessage);
|
||||
} else {
|
||||
// Server is running but model not found
|
||||
const tagsUrl = `${ollamaBaseURL}/tags`;
|
||||
throw new Error(
|
||||
`Model ID "${modelId}" not found in the Ollama instance. Please verify the model is pulled and available. You can check available models with: curl ${tagsUrl}`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Invalid provider hint - should not happen
|
||||
throw new Error(`Invalid provider hint received: ${providerHint}`);
|
||||
|
||||
657
scripts/modules/task-manager/move-task.js
Normal file
657
scripts/modules/task-manager/move-task.js
Normal file
@@ -0,0 +1,657 @@
|
||||
import path from "path";
|
||||
import { log, readJSON, writeJSON } from "../utils.js";
|
||||
import { isTaskDependentOn } from "../task-manager.js";
|
||||
import generateTaskFiles from "./generate-task-files.js";
|
||||
|
||||
/**
|
||||
* Move one or more tasks/subtasks to new positions
|
||||
* @param {string} tasksPath - Path to tasks.json file
|
||||
* @param {string} sourceId - ID(s) of the task/subtask to move (e.g., '5' or '5.2' or '5,6,7')
|
||||
* @param {string} destinationId - ID(s) of the destination (e.g., '7' or '7.3' or '7,8,9')
|
||||
* @param {boolean} generateFiles - Whether to regenerate task files after moving
|
||||
* @returns {Object} Result object with moved task details
|
||||
*/
|
||||
async function moveTask(
|
||||
tasksPath,
|
||||
sourceId,
|
||||
destinationId,
|
||||
generateFiles = true
|
||||
) {
|
||||
// Check if we have comma-separated IDs (multiple moves)
|
||||
const sourceIds = sourceId.split(",").map((id) => id.trim());
|
||||
const destinationIds = destinationId.split(",").map((id) => id.trim());
|
||||
|
||||
// If multiple IDs, validate they match in count
|
||||
if (sourceIds.length > 1 || destinationIds.length > 1) {
|
||||
if (sourceIds.length !== destinationIds.length) {
|
||||
throw new Error(
|
||||
`Number of source IDs (${sourceIds.length}) must match number of destination IDs (${destinationIds.length})`
|
||||
);
|
||||
}
|
||||
|
||||
// Perform multiple moves
|
||||
return await moveMultipleTasks(
|
||||
tasksPath,
|
||||
sourceIds,
|
||||
destinationIds,
|
||||
generateFiles
|
||||
);
|
||||
}
|
||||
|
||||
// Single move - use existing logic
|
||||
return await moveSingleTask(
|
||||
tasksPath,
|
||||
sourceId,
|
||||
destinationId,
|
||||
generateFiles
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move multiple tasks/subtasks to new positions
|
||||
* @param {string} tasksPath - Path to tasks.json file
|
||||
* @param {string[]} sourceIds - Array of source IDs
|
||||
* @param {string[]} destinationIds - Array of destination IDs
|
||||
* @param {boolean} generateFiles - Whether to regenerate task files after moving
|
||||
* @returns {Object} Result object with moved task details
|
||||
*/
|
||||
async function moveMultipleTasks(
|
||||
tasksPath,
|
||||
sourceIds,
|
||||
destinationIds,
|
||||
generateFiles = true
|
||||
) {
|
||||
try {
|
||||
log(
|
||||
"info",
|
||||
`Moving multiple tasks/subtasks: ${sourceIds.join(", ")} to ${destinationIds.join(", ")}...`
|
||||
);
|
||||
|
||||
const results = [];
|
||||
|
||||
// Perform moves one by one, but don't regenerate files until the end
|
||||
for (let i = 0; i < sourceIds.length; i++) {
|
||||
const result = await moveSingleTask(
|
||||
tasksPath,
|
||||
sourceIds[i],
|
||||
destinationIds[i],
|
||||
false
|
||||
);
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
// Generate task files once at the end if requested
|
||||
if (generateFiles) {
|
||||
log("info", "Regenerating task files...");
|
||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||
}
|
||||
|
||||
return {
|
||||
message: `Successfully moved ${sourceIds.length} tasks/subtasks`,
|
||||
moves: results,
|
||||
};
|
||||
} catch (error) {
|
||||
log("error", `Error moving multiple tasks/subtasks: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a single task or subtask to a new position
|
||||
* @param {string} tasksPath - Path to tasks.json file
|
||||
* @param {string} sourceId - ID of the task/subtask to move (e.g., '5' or '5.2')
|
||||
* @param {string} destinationId - ID of the destination (e.g., '7' or '7.3')
|
||||
* @param {boolean} generateFiles - Whether to regenerate task files after moving
|
||||
* @returns {Object} Result object with moved task details
|
||||
*/
|
||||
async function moveSingleTask(
|
||||
tasksPath,
|
||||
sourceId,
|
||||
destinationId,
|
||||
generateFiles = true
|
||||
) {
|
||||
try {
|
||||
log("info", `Moving task/subtask ${sourceId} to ${destinationId}...`);
|
||||
|
||||
// Read the existing tasks
|
||||
const data = readJSON(tasksPath);
|
||||
if (!data || !data.tasks) {
|
||||
throw new Error(`Invalid or missing tasks file at ${tasksPath}`);
|
||||
}
|
||||
|
||||
// Parse source ID to determine if it's a task or subtask
|
||||
const isSourceSubtask = sourceId.includes(".");
|
||||
let sourceTask,
|
||||
sourceParentTask,
|
||||
sourceSubtask,
|
||||
sourceTaskIndex,
|
||||
sourceSubtaskIndex;
|
||||
|
||||
// Parse destination ID to determine the target
|
||||
const isDestinationSubtask = destinationId.includes(".");
|
||||
let destTask, destParentTask, destSubtask, destTaskIndex, destSubtaskIndex;
|
||||
|
||||
// Validate source exists
|
||||
if (isSourceSubtask) {
|
||||
// Source is a subtask
|
||||
const [parentIdStr, subtaskIdStr] = sourceId.split(".");
|
||||
const parentIdNum = parseInt(parentIdStr, 10);
|
||||
const subtaskIdNum = parseInt(subtaskIdStr, 10);
|
||||
|
||||
sourceParentTask = data.tasks.find((t) => t.id === parentIdNum);
|
||||
if (!sourceParentTask) {
|
||||
throw new Error(`Source parent task with ID ${parentIdNum} not found`);
|
||||
}
|
||||
|
||||
if (
|
||||
!sourceParentTask.subtasks ||
|
||||
sourceParentTask.subtasks.length === 0
|
||||
) {
|
||||
throw new Error(`Source parent task ${parentIdNum} has no subtasks`);
|
||||
}
|
||||
|
||||
sourceSubtaskIndex = sourceParentTask.subtasks.findIndex(
|
||||
(st) => st.id === subtaskIdNum
|
||||
);
|
||||
if (sourceSubtaskIndex === -1) {
|
||||
throw new Error(`Source subtask ${sourceId} not found`);
|
||||
}
|
||||
|
||||
sourceSubtask = { ...sourceParentTask.subtasks[sourceSubtaskIndex] };
|
||||
} else {
|
||||
// Source is a task
|
||||
const sourceIdNum = parseInt(sourceId, 10);
|
||||
sourceTaskIndex = data.tasks.findIndex((t) => t.id === sourceIdNum);
|
||||
if (sourceTaskIndex === -1) {
|
||||
throw new Error(`Source task with ID ${sourceIdNum} not found`);
|
||||
}
|
||||
|
||||
sourceTask = { ...data.tasks[sourceTaskIndex] };
|
||||
}
|
||||
|
||||
// Validate destination exists
|
||||
if (isDestinationSubtask) {
|
||||
// Destination is a subtask (target will be the parent of this subtask)
|
||||
const [parentIdStr, subtaskIdStr] = destinationId.split(".");
|
||||
const parentIdNum = parseInt(parentIdStr, 10);
|
||||
const subtaskIdNum = parseInt(subtaskIdStr, 10);
|
||||
|
||||
destParentTask = data.tasks.find((t) => t.id === parentIdNum);
|
||||
if (!destParentTask) {
|
||||
throw new Error(
|
||||
`Destination parent task with ID ${parentIdNum} not found`
|
||||
);
|
||||
}
|
||||
|
||||
// Initialize subtasks array if it doesn't exist
|
||||
if (!destParentTask.subtasks) {
|
||||
destParentTask.subtasks = [];
|
||||
}
|
||||
|
||||
// If there are existing subtasks, try to find the specific destination subtask
|
||||
if (destParentTask.subtasks.length > 0) {
|
||||
destSubtaskIndex = destParentTask.subtasks.findIndex(
|
||||
(st) => st.id === subtaskIdNum
|
||||
);
|
||||
if (destSubtaskIndex !== -1) {
|
||||
destSubtask = destParentTask.subtasks[destSubtaskIndex];
|
||||
} else {
|
||||
// Subtask doesn't exist, we'll insert at the end
|
||||
destSubtaskIndex = destParentTask.subtasks.length - 1;
|
||||
}
|
||||
} else {
|
||||
// No existing subtasks, this will be the first one
|
||||
destSubtaskIndex = -1; // Will insert at position 0
|
||||
}
|
||||
} else {
|
||||
// Destination is a task
|
||||
const destIdNum = parseInt(destinationId, 10);
|
||||
destTaskIndex = data.tasks.findIndex((t) => t.id === destIdNum);
|
||||
|
||||
if (destTaskIndex === -1) {
|
||||
// Create placeholder for destination if it doesn't exist
|
||||
log("info", `Creating placeholder for destination task ${destIdNum}`);
|
||||
const newTask = {
|
||||
id: destIdNum,
|
||||
title: `Task ${destIdNum}`,
|
||||
description: "",
|
||||
status: "pending",
|
||||
priority: "medium",
|
||||
details: "",
|
||||
testStrategy: "",
|
||||
};
|
||||
|
||||
// Find correct position to insert the new task
|
||||
let insertIndex = 0;
|
||||
while (
|
||||
insertIndex < data.tasks.length &&
|
||||
data.tasks[insertIndex].id < destIdNum
|
||||
) {
|
||||
insertIndex++;
|
||||
}
|
||||
|
||||
// Insert the new task at the appropriate position
|
||||
data.tasks.splice(insertIndex, 0, newTask);
|
||||
destTaskIndex = insertIndex;
|
||||
destTask = data.tasks[destTaskIndex];
|
||||
} else {
|
||||
destTask = data.tasks[destTaskIndex];
|
||||
}
|
||||
}
|
||||
|
||||
// Validate that we aren't trying to move a task to itself
|
||||
if (sourceId === destinationId) {
|
||||
throw new Error("Cannot move a task/subtask to itself");
|
||||
}
|
||||
|
||||
// Prevent moving a parent to its own subtask
|
||||
if (!isSourceSubtask && isDestinationSubtask) {
|
||||
const destParentId = parseInt(destinationId.split(".")[0], 10);
|
||||
if (parseInt(sourceId, 10) === destParentId) {
|
||||
throw new Error("Cannot move a parent task to one of its own subtasks");
|
||||
}
|
||||
}
|
||||
|
||||
// Check for circular dependency when moving tasks
|
||||
if (!isSourceSubtask && !isDestinationSubtask) {
|
||||
const sourceIdNum = parseInt(sourceId, 10);
|
||||
const destIdNum = parseInt(destinationId, 10);
|
||||
|
||||
// Check if destination is dependent on source
|
||||
if (isTaskDependentOn(data.tasks, destTask, sourceIdNum)) {
|
||||
throw new Error(
|
||||
`Cannot move task ${sourceId} to task ${destinationId} as it would create a circular dependency`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let movedTask;
|
||||
|
||||
// Handle different move scenarios
|
||||
if (!isSourceSubtask && !isDestinationSubtask) {
|
||||
// Case: Moving task to task position
|
||||
// Always treat this as a task replacement/move to new ID
|
||||
// The destination task will be replaced by the source task
|
||||
movedTask = moveTaskToNewId(
|
||||
data,
|
||||
sourceTask,
|
||||
sourceTaskIndex,
|
||||
destTask,
|
||||
destTaskIndex
|
||||
);
|
||||
} else if (!isSourceSubtask && isDestinationSubtask) {
|
||||
// Case 2: Move standalone task to become a subtask at a specific position
|
||||
movedTask = moveTaskToSubtaskPosition(
|
||||
data,
|
||||
sourceTask,
|
||||
sourceTaskIndex,
|
||||
destParentTask,
|
||||
destSubtaskIndex
|
||||
);
|
||||
} else if (isSourceSubtask && !isDestinationSubtask) {
|
||||
// Case 3: Move subtask to become a standalone task
|
||||
movedTask = moveSubtaskToTask(
|
||||
data,
|
||||
sourceSubtask,
|
||||
sourceParentTask,
|
||||
sourceSubtaskIndex,
|
||||
destTask
|
||||
);
|
||||
} else if (isSourceSubtask && isDestinationSubtask) {
|
||||
// Case 4: Move subtask to another parent or position
|
||||
// First check if it's the same parent
|
||||
const sourceParentId = parseInt(sourceId.split(".")[0], 10);
|
||||
const destParentId = parseInt(destinationId.split(".")[0], 10);
|
||||
|
||||
if (sourceParentId === destParentId) {
|
||||
// Case 4a: Move subtask within the same parent (reordering)
|
||||
movedTask = reorderSubtask(
|
||||
sourceParentTask,
|
||||
sourceSubtaskIndex,
|
||||
destSubtaskIndex
|
||||
);
|
||||
} else {
|
||||
// Case 4b: Move subtask to a different parent
|
||||
movedTask = moveSubtaskToAnotherParent(
|
||||
sourceSubtask,
|
||||
sourceParentTask,
|
||||
sourceSubtaskIndex,
|
||||
destParentTask,
|
||||
destSubtaskIndex
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Write the updated tasks back to the file
|
||||
writeJSON(tasksPath, data);
|
||||
|
||||
// Generate task files if requested
|
||||
if (generateFiles) {
|
||||
log("info", "Regenerating task files...");
|
||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||
}
|
||||
|
||||
return movedTask;
|
||||
} catch (error) {
|
||||
log("error", `Error moving task/subtask: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a standalone task to become a subtask of another task
|
||||
* @param {Object} data - Tasks data object
|
||||
* @param {Object} sourceTask - Source task to move
|
||||
* @param {number} sourceTaskIndex - Index of source task in data.tasks
|
||||
* @param {Object} destTask - Destination task
|
||||
* @returns {Object} Moved task object
|
||||
*/
|
||||
function moveTaskToTask(data, sourceTask, sourceTaskIndex, destTask) {
|
||||
// Initialize subtasks array if it doesn't exist
|
||||
if (!destTask.subtasks) {
|
||||
destTask.subtasks = [];
|
||||
}
|
||||
|
||||
// Find the highest subtask ID to determine the next ID
|
||||
const highestSubtaskId =
|
||||
destTask.subtasks.length > 0
|
||||
? Math.max(...destTask.subtasks.map((st) => st.id))
|
||||
: 0;
|
||||
const newSubtaskId = highestSubtaskId + 1;
|
||||
|
||||
// Create the new subtask from the source task
|
||||
const newSubtask = {
|
||||
...sourceTask,
|
||||
id: newSubtaskId,
|
||||
parentTaskId: destTask.id,
|
||||
};
|
||||
|
||||
// Add to destination's subtasks
|
||||
destTask.subtasks.push(newSubtask);
|
||||
|
||||
// Remove the original task from the tasks array
|
||||
data.tasks.splice(sourceTaskIndex, 1);
|
||||
|
||||
log(
|
||||
"info",
|
||||
`Moved task ${sourceTask.id} to become subtask ${destTask.id}.${newSubtaskId}`
|
||||
);
|
||||
|
||||
return newSubtask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a standalone task to become a subtask at a specific position
|
||||
* @param {Object} data - Tasks data object
|
||||
* @param {Object} sourceTask - Source task to move
|
||||
* @param {number} sourceTaskIndex - Index of source task in data.tasks
|
||||
* @param {Object} destParentTask - Destination parent task
|
||||
* @param {number} destSubtaskIndex - Index of the subtask before which to insert
|
||||
* @returns {Object} Moved task object
|
||||
*/
|
||||
function moveTaskToSubtaskPosition(
|
||||
data,
|
||||
sourceTask,
|
||||
sourceTaskIndex,
|
||||
destParentTask,
|
||||
destSubtaskIndex
|
||||
) {
|
||||
// Initialize subtasks array if it doesn't exist
|
||||
if (!destParentTask.subtasks) {
|
||||
destParentTask.subtasks = [];
|
||||
}
|
||||
|
||||
// Find the highest subtask ID to determine the next ID
|
||||
const highestSubtaskId =
|
||||
destParentTask.subtasks.length > 0
|
||||
? Math.max(...destParentTask.subtasks.map((st) => st.id))
|
||||
: 0;
|
||||
const newSubtaskId = highestSubtaskId + 1;
|
||||
|
||||
// Create the new subtask from the source task
|
||||
const newSubtask = {
|
||||
...sourceTask,
|
||||
id: newSubtaskId,
|
||||
parentTaskId: destParentTask.id,
|
||||
};
|
||||
|
||||
// Insert at specific position
|
||||
// If destSubtaskIndex is -1, insert at the beginning (position 0)
|
||||
// Otherwise, insert after the specified subtask
|
||||
const insertPosition = destSubtaskIndex === -1 ? 0 : destSubtaskIndex + 1;
|
||||
destParentTask.subtasks.splice(insertPosition, 0, newSubtask);
|
||||
|
||||
// Remove the original task from the tasks array
|
||||
data.tasks.splice(sourceTaskIndex, 1);
|
||||
|
||||
log(
|
||||
"info",
|
||||
`Moved task ${sourceTask.id} to become subtask ${destParentTask.id}.${newSubtaskId}`
|
||||
);
|
||||
|
||||
return newSubtask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a subtask to become a standalone task
|
||||
* @param {Object} data - Tasks data object
|
||||
* @param {Object} sourceSubtask - Source subtask to move
|
||||
* @param {Object} sourceParentTask - Parent task of the source subtask
|
||||
* @param {number} sourceSubtaskIndex - Index of source subtask in parent's subtasks
|
||||
* @param {Object} destTask - Destination task (will be replaced)
|
||||
* @returns {Object} Moved task object
|
||||
*/
|
||||
function moveSubtaskToTask(
|
||||
data,
|
||||
sourceSubtask,
|
||||
sourceParentTask,
|
||||
sourceSubtaskIndex,
|
||||
destTask
|
||||
) {
|
||||
// Use the destination task's ID instead of generating a new one
|
||||
const newTaskId = destTask.id;
|
||||
|
||||
// Create the new task from the subtask, using the destination task's ID
|
||||
const newTask = {
|
||||
...sourceSubtask,
|
||||
id: newTaskId,
|
||||
priority: sourceParentTask.priority || "medium", // Inherit priority from parent
|
||||
};
|
||||
delete newTask.parentTaskId;
|
||||
|
||||
// Add the parent task as a dependency if not already present
|
||||
if (!newTask.dependencies) {
|
||||
newTask.dependencies = [];
|
||||
}
|
||||
if (!newTask.dependencies.includes(sourceParentTask.id)) {
|
||||
newTask.dependencies.push(sourceParentTask.id);
|
||||
}
|
||||
|
||||
// Find the destination index to replace the destination task
|
||||
const destTaskIndex = data.tasks.findIndex((t) => t.id === destTask.id);
|
||||
|
||||
// Replace the destination task with the new task
|
||||
data.tasks[destTaskIndex] = newTask;
|
||||
|
||||
// Remove the subtask from the parent
|
||||
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
|
||||
|
||||
// If parent has no more subtasks, remove the subtasks array
|
||||
if (sourceParentTask.subtasks.length === 0) {
|
||||
delete sourceParentTask.subtasks;
|
||||
}
|
||||
|
||||
log(
|
||||
"info",
|
||||
`Moved subtask ${sourceParentTask.id}.${sourceSubtask.id} to become task ${newTaskId}`
|
||||
);
|
||||
|
||||
return newTask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reorder a subtask within the same parent
|
||||
* @param {Object} parentTask - Parent task containing the subtask
|
||||
* @param {number} sourceIndex - Current index of the subtask
|
||||
* @param {number} destIndex - Destination index for the subtask
|
||||
* @returns {Object} Moved subtask object
|
||||
*/
|
||||
function reorderSubtask(parentTask, sourceIndex, destIndex) {
|
||||
// Get the subtask to move
|
||||
const subtask = parentTask.subtasks[sourceIndex];
|
||||
|
||||
// Remove the subtask from its current position
|
||||
parentTask.subtasks.splice(sourceIndex, 1);
|
||||
|
||||
// Insert the subtask at the new position
|
||||
// If destIndex was after sourceIndex, it's now one less because we removed an item
|
||||
const adjustedDestIndex = sourceIndex < destIndex ? destIndex - 1 : destIndex;
|
||||
parentTask.subtasks.splice(adjustedDestIndex, 0, subtask);
|
||||
|
||||
log(
|
||||
"info",
|
||||
`Reordered subtask ${parentTask.id}.${subtask.id} within parent task ${parentTask.id}`
|
||||
);
|
||||
|
||||
return subtask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a subtask to a different parent
|
||||
* @param {Object} sourceSubtask - Source subtask to move
|
||||
* @param {Object} sourceParentTask - Parent task of the source subtask
|
||||
* @param {number} sourceSubtaskIndex - Index of source subtask in parent's subtasks
|
||||
* @param {Object} destParentTask - Destination parent task
|
||||
* @param {number} destSubtaskIndex - Index of the subtask before which to insert
|
||||
* @returns {Object} Moved subtask object
|
||||
*/
|
||||
function moveSubtaskToAnotherParent(
|
||||
sourceSubtask,
|
||||
sourceParentTask,
|
||||
sourceSubtaskIndex,
|
||||
destParentTask,
|
||||
destSubtaskIndex
|
||||
) {
|
||||
// Find the highest subtask ID in the destination parent
|
||||
const highestSubtaskId =
|
||||
destParentTask.subtasks.length > 0
|
||||
? Math.max(...destParentTask.subtasks.map((st) => st.id))
|
||||
: 0;
|
||||
const newSubtaskId = highestSubtaskId + 1;
|
||||
|
||||
// Create the new subtask with updated parent reference
|
||||
const newSubtask = {
|
||||
...sourceSubtask,
|
||||
id: newSubtaskId,
|
||||
parentTaskId: destParentTask.id,
|
||||
};
|
||||
|
||||
// If the subtask depends on its original parent, keep that dependency
|
||||
if (!newSubtask.dependencies) {
|
||||
newSubtask.dependencies = [];
|
||||
}
|
||||
if (!newSubtask.dependencies.includes(sourceParentTask.id)) {
|
||||
newSubtask.dependencies.push(sourceParentTask.id);
|
||||
}
|
||||
|
||||
// Insert at the destination position
|
||||
// If destSubtaskIndex is -1, insert at the beginning (position 0)
|
||||
// Otherwise, insert after the specified subtask
|
||||
const insertPosition = destSubtaskIndex === -1 ? 0 : destSubtaskIndex + 1;
|
||||
destParentTask.subtasks.splice(insertPosition, 0, newSubtask);
|
||||
|
||||
// Remove the subtask from the original parent
|
||||
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
|
||||
|
||||
// If original parent has no more subtasks, remove the subtasks array
|
||||
if (sourceParentTask.subtasks.length === 0) {
|
||||
delete sourceParentTask.subtasks;
|
||||
}
|
||||
|
||||
log(
|
||||
"info",
|
||||
`Moved subtask ${sourceParentTask.id}.${sourceSubtask.id} to become subtask ${destParentTask.id}.${newSubtaskId}`
|
||||
);
|
||||
|
||||
return newSubtask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a standalone task to a new ID position
|
||||
* @param {Object} data - Tasks data object
|
||||
* @param {Object} sourceTask - Source task to move
|
||||
* @param {number} sourceTaskIndex - Index of source task in data.tasks
|
||||
* @param {Object} destTask - Destination task (will be replaced)
|
||||
* @param {number} destTaskIndex - Index of destination task in data.tasks
|
||||
* @returns {Object} Moved task object
|
||||
*/
|
||||
function moveTaskToNewId(
|
||||
data,
|
||||
sourceTask,
|
||||
sourceTaskIndex,
|
||||
destTask,
|
||||
destTaskIndex
|
||||
) {
|
||||
// Create a copy of the source task with the new ID
|
||||
const movedTask = {
|
||||
...sourceTask,
|
||||
id: destTask.id,
|
||||
};
|
||||
|
||||
// Get numeric IDs for comparison
|
||||
const sourceIdNum = parseInt(sourceTask.id, 10);
|
||||
const destIdNum = parseInt(destTask.id, 10);
|
||||
|
||||
// Handle subtasks if present
|
||||
if (sourceTask.subtasks && sourceTask.subtasks.length > 0) {
|
||||
// Update subtasks to reference the new parent ID if needed
|
||||
movedTask.subtasks = sourceTask.subtasks.map((subtask) => ({
|
||||
...subtask,
|
||||
parentTaskId: destIdNum,
|
||||
}));
|
||||
}
|
||||
|
||||
// Update any dependencies in other tasks that referenced the old source ID
|
||||
data.tasks.forEach((task) => {
|
||||
if (task.dependencies && task.dependencies.includes(sourceIdNum)) {
|
||||
// Replace the old source ID with the new destination ID
|
||||
const depIndex = task.dependencies.indexOf(sourceIdNum);
|
||||
task.dependencies[depIndex] = destIdNum;
|
||||
}
|
||||
|
||||
// Also check for subtask dependencies that might reference the source task
|
||||
if (task.subtasks && task.subtasks.length > 0) {
|
||||
task.subtasks.forEach((subtask) => {
|
||||
if (
|
||||
subtask.dependencies &&
|
||||
subtask.dependencies.includes(sourceIdNum)
|
||||
) {
|
||||
const depIndex = subtask.dependencies.indexOf(sourceIdNum);
|
||||
subtask.dependencies[depIndex] = destIdNum;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Remove tasks in the correct order to avoid index shifting issues
|
||||
// Always remove the higher index first to avoid shifting the lower index
|
||||
if (sourceTaskIndex > destTaskIndex) {
|
||||
// Remove source first (higher index), then destination
|
||||
data.tasks.splice(sourceTaskIndex, 1);
|
||||
data.tasks.splice(destTaskIndex, 1);
|
||||
// Insert the moved task at the destination position
|
||||
data.tasks.splice(destTaskIndex, 0, movedTask);
|
||||
} else {
|
||||
// Remove destination first (higher index), then source
|
||||
data.tasks.splice(destTaskIndex, 1);
|
||||
data.tasks.splice(sourceTaskIndex, 1);
|
||||
// Insert the moved task at the original destination position (now shifted down by 1)
|
||||
data.tasks.splice(sourceTaskIndex, 0, movedTask);
|
||||
}
|
||||
|
||||
log("info", `Moved task ${sourceIdNum} to replace task ${destIdNum}`);
|
||||
|
||||
return movedTask;
|
||||
}
|
||||
|
||||
export default moveTask;
|
||||
@@ -50,6 +50,7 @@ const prdResponseSchema = z.object({
|
||||
* @param {Object} options - Additional options
|
||||
* @param {boolean} [options.force=false] - Whether to overwrite existing tasks.json.
|
||||
* @param {boolean} [options.append=false] - Append to existing tasks file.
|
||||
* @param {boolean} [options.research=false] - Use research model for enhanced PRD analysis.
|
||||
* @param {Object} [options.reportProgress] - Function to report progress (optional, likely unused).
|
||||
* @param {Object} [options.mcpLog] - MCP logger object (optional).
|
||||
* @param {Object} [options.session] - Session object from MCP server (optional).
|
||||
@@ -63,7 +64,8 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
|
||||
session,
|
||||
projectRoot,
|
||||
force = false,
|
||||
append = false
|
||||
append = false,
|
||||
research = false
|
||||
} = options;
|
||||
const isMCP = !!mcpLog;
|
||||
const outputFormat = isMCP ? 'json' : 'text';
|
||||
@@ -90,7 +92,9 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
|
||||
}
|
||||
};
|
||||
|
||||
report(`Parsing PRD file: ${prdPath}, Force: ${force}, Append: ${append}`);
|
||||
report(
|
||||
`Parsing PRD file: ${prdPath}, Force: ${force}, Append: ${append}, Research: ${research}`
|
||||
);
|
||||
|
||||
let existingTasks = [];
|
||||
let nextId = 1;
|
||||
@@ -148,8 +152,22 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
|
||||
throw new Error(`Input file ${prdPath} is empty or could not be read.`);
|
||||
}
|
||||
|
||||
// Build system prompt for PRD parsing
|
||||
const systemPrompt = `You are an AI assistant specialized in analyzing Product Requirements Documents (PRDs) and generating a structured, logically ordered, dependency-aware and sequenced list of development tasks in JSON format.
|
||||
// Research-specific enhancements to the system prompt
|
||||
const researchPromptAddition = research
|
||||
? `\nBefore breaking down the PRD into tasks, you will:
|
||||
1. Research and analyze the latest technologies, libraries, frameworks, and best practices that would be appropriate for this project
|
||||
2. Identify any potential technical challenges, security concerns, or scalability issues not explicitly mentioned in the PRD without discarding any explicit requirements or going overboard with complexity -- always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches
|
||||
3. Consider current industry standards and evolving trends relevant to this project (this step aims to solve LLM hallucinations and out of date information due to training data cutoff dates)
|
||||
4. Evaluate alternative implementation approaches and recommend the most efficient path
|
||||
5. Include specific library versions, helpful APIs, and concrete implementation guidance based on your research
|
||||
6. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches
|
||||
|
||||
Your task breakdown should incorporate this research, resulting in more detailed implementation guidance, more accurate dependency mapping, and more precise technology recommendations than would be possible from the PRD text alone, while maintaining all explicit requirements and best practices and all details and nuances of the PRD.`
|
||||
: '';
|
||||
|
||||
// Base system prompt for PRD parsing
|
||||
const systemPrompt = `You are an AI assistant specialized in analyzing Product Requirements Documents (PRDs) and generating a structured, logically ordered, dependency-aware and sequenced list of development tasks in JSON format.${researchPromptAddition}
|
||||
|
||||
Analyze the provided PRD content and generate approximately ${numTasks} top-level development tasks. If the complexity or the level of detail of the PRD is high, generate more tasks relative to the complexity of the PRD
|
||||
Each task should represent a logical unit of work needed to implement the requirements and focus on the most direct and effective way to implement the requirements without unnecessary complexity or overengineering. Include pseudo-code, implementation details, and test strategy for each task. Find the most up to date information to implement each task.
|
||||
Assign sequential IDs starting from ${nextId}. Infer title, description, details, and test strategy for each task based *only* on the PRD content.
|
||||
@@ -176,13 +194,13 @@ Guidelines:
|
||||
5. Include clear validation/testing approach for each task
|
||||
6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs, potentially including existing tasks with IDs less than ${nextId} if applicable)
|
||||
7. Assign priority (high/medium/low) based on criticality and dependency order
|
||||
8. Include detailed implementation guidance in the "details" field
|
||||
8. Include detailed implementation guidance in the "details" field${research ? ', with specific libraries and version recommendations based on your research' : ''}
|
||||
9. If the PRD contains specific requirements for libraries, database schemas, frameworks, tech stacks, or any other implementation details, STRICTLY ADHERE to these requirements in your task breakdown and do not discard them under any circumstance
|
||||
10. Focus on filling in any gaps left by the PRD or areas that aren't fully specified, while preserving all explicit requirements
|
||||
11. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches`;
|
||||
11. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches${research ? '\n12. For each task, include specific, actionable guidance based on current industry standards and best practices discovered through research' : ''}`;
|
||||
|
||||
// Build user prompt with PRD content
|
||||
const userPrompt = `Here's the Product Requirements Document (PRD) to break down into approximately ${numTasks} tasks, starting IDs from ${nextId}:\n\n${prdContent}\n\n
|
||||
const userPrompt = `Here's the Product Requirements Document (PRD) to break down into approximately ${numTasks} tasks, starting IDs from ${nextId}:${research ? '\n\nRemember to thoroughly research current best practices and technologies before task breakdown to provide specific, actionable implementation details.' : ''}\n\n${prdContent}\n\n
|
||||
|
||||
Return your response in this format:
|
||||
{
|
||||
@@ -204,11 +222,14 @@ Guidelines:
|
||||
}`;
|
||||
|
||||
// Call the unified AI service
|
||||
report('Calling AI service to generate tasks from PRD...', 'info');
|
||||
report(
|
||||
`Calling AI service to generate tasks from PRD${research ? ' with research-backed analysis' : ''}...`,
|
||||
'info'
|
||||
);
|
||||
|
||||
// Call generateObjectService with the CORRECT schema and additional telemetry params
|
||||
aiServiceResponse = await generateObjectService({
|
||||
role: 'main',
|
||||
role: research ? 'research' : 'main', // Use research role if flag is set
|
||||
session: session,
|
||||
projectRoot: projectRoot,
|
||||
schema: prdResponseSchema,
|
||||
@@ -224,7 +245,9 @@ Guidelines:
|
||||
if (!fs.existsSync(tasksDir)) {
|
||||
fs.mkdirSync(tasksDir, { recursive: true });
|
||||
}
|
||||
logFn.success('Successfully parsed PRD via AI service.\n');
|
||||
logFn.success(
|
||||
`Successfully parsed PRD via AI service${research ? ' with research-backed analysis' : ''}.`
|
||||
);
|
||||
|
||||
// Validate and Process Tasks
|
||||
// const generatedData = aiServiceResponse?.mainResult?.object;
|
||||
@@ -294,7 +317,7 @@ Guidelines:
|
||||
// Write the final tasks to the file
|
||||
writeJSON(tasksPath, outputData);
|
||||
report(
|
||||
`Successfully ${append ? 'appended' : 'generated'} ${processedNewTasks.length} tasks in ${tasksPath}`,
|
||||
`Successfully ${append ? 'appended' : 'generated'} ${processedNewTasks.length} tasks in ${tasksPath}${research ? ' with research-backed analysis' : ''}`,
|
||||
'success'
|
||||
);
|
||||
|
||||
@@ -306,7 +329,7 @@ Guidelines:
|
||||
console.log(
|
||||
boxen(
|
||||
chalk.green(
|
||||
`Successfully generated ${processedNewTasks.length} new tasks. Total tasks in ${tasksPath}: ${finalTasks.length}`
|
||||
`Successfully generated ${processedNewTasks.length} new tasks${research ? ' with research-backed analysis' : ''}. Total tasks in ${tasksPath}: ${finalTasks.length}`
|
||||
),
|
||||
{ padding: 1, borderColor: 'green', borderStyle: 'round' }
|
||||
)
|
||||
|
||||
747
scripts/modules/task-manager/research.js
Normal file
747
scripts/modules/task-manager/research.js
Normal file
@@ -0,0 +1,747 @@
|
||||
/**
|
||||
* research.js
|
||||
* Core research functionality for AI-powered queries with project context
|
||||
*/
|
||||
|
||||
import path from 'path';
|
||||
import chalk from 'chalk';
|
||||
import boxen from 'boxen';
|
||||
import inquirer from 'inquirer';
|
||||
import { highlight } from 'cli-highlight';
|
||||
import { ContextGatherer } from '../utils/contextGatherer.js';
|
||||
import { FuzzyTaskSearch } from '../utils/fuzzyTaskSearch.js';
|
||||
import { generateTextService } from '../ai-services-unified.js';
|
||||
import { log as consoleLog, findProjectRoot, readJSON } from '../utils.js';
|
||||
import {
|
||||
displayAiUsageSummary,
|
||||
startLoadingIndicator,
|
||||
stopLoadingIndicator
|
||||
} from '../ui.js';
|
||||
|
||||
/**
|
||||
* Perform AI-powered research with project context
|
||||
* @param {string} query - Research query/prompt
|
||||
* @param {Object} options - Research options
|
||||
* @param {Array<string>} [options.taskIds] - Task/subtask IDs for context
|
||||
* @param {Array<string>} [options.filePaths] - File paths for context
|
||||
* @param {string} [options.customContext] - Additional custom context
|
||||
* @param {boolean} [options.includeProjectTree] - Include project file tree
|
||||
* @param {string} [options.detailLevel] - Detail level: 'low', 'medium', 'high'
|
||||
* @param {string} [options.projectRoot] - Project root directory
|
||||
* @param {Object} [context] - Execution context
|
||||
* @param {Object} [context.session] - MCP session object
|
||||
* @param {Object} [context.mcpLog] - MCP logger object
|
||||
* @param {string} [context.commandName] - Command name for telemetry
|
||||
* @param {string} [context.outputType] - Output type ('cli' or 'mcp')
|
||||
* @param {string} [outputFormat] - Output format ('text' or 'json')
|
||||
* @param {boolean} [allowFollowUp] - Whether to allow follow-up questions (default: true)
|
||||
* @returns {Promise<Object>} Research results with telemetry data
|
||||
*/
|
||||
async function performResearch(
|
||||
query,
|
||||
options = {},
|
||||
context = {},
|
||||
outputFormat = 'text',
|
||||
allowFollowUp = true
|
||||
) {
|
||||
const {
|
||||
taskIds = [],
|
||||
filePaths = [],
|
||||
customContext = '',
|
||||
includeProjectTree = false,
|
||||
detailLevel = 'medium',
|
||||
projectRoot: providedProjectRoot
|
||||
} = options;
|
||||
|
||||
const {
|
||||
session,
|
||||
mcpLog,
|
||||
commandName = 'research',
|
||||
outputType = 'cli'
|
||||
} = context;
|
||||
const isMCP = !!mcpLog;
|
||||
|
||||
// Determine project root
|
||||
const projectRoot = providedProjectRoot || findProjectRoot();
|
||||
if (!projectRoot) {
|
||||
throw new Error('Could not determine project root directory');
|
||||
}
|
||||
|
||||
// Create consistent logger
|
||||
const logFn = isMCP
|
||||
? mcpLog
|
||||
: {
|
||||
info: (...args) => consoleLog('info', ...args),
|
||||
warn: (...args) => consoleLog('warn', ...args),
|
||||
error: (...args) => consoleLog('error', ...args),
|
||||
debug: (...args) => consoleLog('debug', ...args),
|
||||
success: (...args) => consoleLog('success', ...args)
|
||||
};
|
||||
|
||||
// Show UI banner for CLI mode
|
||||
if (outputFormat === 'text') {
|
||||
console.log(
|
||||
boxen(chalk.cyan.bold(`🔍 AI Research Query`), {
|
||||
padding: 1,
|
||||
borderColor: 'cyan',
|
||||
borderStyle: 'round',
|
||||
margin: { top: 1, bottom: 1 }
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// Initialize context gatherer
|
||||
const contextGatherer = new ContextGatherer(projectRoot);
|
||||
|
||||
// Auto-discover relevant tasks using fuzzy search to supplement provided tasks
|
||||
let finalTaskIds = [...taskIds]; // Start with explicitly provided tasks
|
||||
let autoDiscoveredIds = [];
|
||||
|
||||
try {
|
||||
const tasksPath = path.join(projectRoot, 'tasks', 'tasks.json');
|
||||
const tasksData = await readJSON(tasksPath);
|
||||
|
||||
if (tasksData && tasksData.tasks && tasksData.tasks.length > 0) {
|
||||
// Flatten tasks to include subtasks for fuzzy search
|
||||
const flattenedTasks = flattenTasksWithSubtasks(tasksData.tasks);
|
||||
const fuzzySearch = new FuzzyTaskSearch(flattenedTasks, 'research');
|
||||
const searchResults = fuzzySearch.findRelevantTasks(query, {
|
||||
maxResults: 8,
|
||||
includeRecent: true,
|
||||
includeCategoryMatches: true
|
||||
});
|
||||
|
||||
autoDiscoveredIds = fuzzySearch.getTaskIds(searchResults);
|
||||
|
||||
// Remove any auto-discovered tasks that were already explicitly provided
|
||||
const uniqueAutoDiscovered = autoDiscoveredIds.filter(
|
||||
(id) => !finalTaskIds.includes(id)
|
||||
);
|
||||
|
||||
// Add unique auto-discovered tasks to the final list
|
||||
finalTaskIds = [...finalTaskIds, ...uniqueAutoDiscovered];
|
||||
|
||||
if (outputFormat === 'text' && finalTaskIds.length > 0) {
|
||||
// Sort task IDs numerically for better display
|
||||
const sortedTaskIds = finalTaskIds
|
||||
.map((id) => parseInt(id))
|
||||
.sort((a, b) => a - b)
|
||||
.map((id) => id.toString());
|
||||
|
||||
// Show different messages based on whether tasks were explicitly provided
|
||||
if (taskIds.length > 0) {
|
||||
const sortedProvidedIds = taskIds
|
||||
.map((id) => parseInt(id))
|
||||
.sort((a, b) => a - b)
|
||||
.map((id) => id.toString());
|
||||
|
||||
console.log(
|
||||
chalk.gray('Provided tasks: ') +
|
||||
chalk.cyan(sortedProvidedIds.join(', '))
|
||||
);
|
||||
|
||||
if (uniqueAutoDiscovered.length > 0) {
|
||||
const sortedAutoIds = uniqueAutoDiscovered
|
||||
.map((id) => parseInt(id))
|
||||
.sort((a, b) => a - b)
|
||||
.map((id) => id.toString());
|
||||
|
||||
console.log(
|
||||
chalk.gray('+ Auto-discovered related tasks: ') +
|
||||
chalk.cyan(sortedAutoIds.join(', '))
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.log(
|
||||
chalk.gray('Auto-discovered relevant tasks: ') +
|
||||
chalk.cyan(sortedTaskIds.join(', '))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Silently continue without auto-discovered tasks if there's an error
|
||||
logFn.debug(`Could not auto-discover tasks: ${error.message}`);
|
||||
}
|
||||
|
||||
const contextResult = await contextGatherer.gather({
|
||||
tasks: finalTaskIds,
|
||||
files: filePaths,
|
||||
customContext,
|
||||
includeProjectTree,
|
||||
format: 'research', // Use research format for AI consumption
|
||||
includeTokenCounts: true
|
||||
});
|
||||
|
||||
const gatheredContext = contextResult.context;
|
||||
const tokenBreakdown = contextResult.tokenBreakdown;
|
||||
|
||||
// Build system prompt based on detail level
|
||||
const systemPrompt = buildResearchSystemPrompt(detailLevel, projectRoot);
|
||||
|
||||
// Build user prompt with context
|
||||
const userPrompt = buildResearchUserPrompt(
|
||||
query,
|
||||
gatheredContext,
|
||||
detailLevel
|
||||
);
|
||||
|
||||
// Count tokens for system and user prompts
|
||||
const systemPromptTokens = contextGatherer.countTokens(systemPrompt);
|
||||
const userPromptTokens = contextGatherer.countTokens(userPrompt);
|
||||
const totalInputTokens = systemPromptTokens + userPromptTokens;
|
||||
|
||||
if (outputFormat === 'text') {
|
||||
// Display detailed token breakdown in a clean box
|
||||
displayDetailedTokenBreakdown(
|
||||
tokenBreakdown,
|
||||
systemPromptTokens,
|
||||
userPromptTokens
|
||||
);
|
||||
}
|
||||
|
||||
// Only log detailed info in debug mode or MCP
|
||||
if (outputFormat !== 'text') {
|
||||
logFn.info(
|
||||
`Calling AI service with research role, context size: ${tokenBreakdown.total} tokens (${gatheredContext.length} characters)`
|
||||
);
|
||||
}
|
||||
|
||||
// Start loading indicator for CLI mode
|
||||
let loadingIndicator = null;
|
||||
if (outputFormat === 'text') {
|
||||
loadingIndicator = startLoadingIndicator('Researching with AI...\n');
|
||||
}
|
||||
|
||||
let aiResult;
|
||||
try {
|
||||
// Call AI service with research role
|
||||
aiResult = await generateTextService({
|
||||
role: 'research', // Always use research role for research command
|
||||
session,
|
||||
projectRoot,
|
||||
systemPrompt,
|
||||
prompt: userPrompt,
|
||||
commandName,
|
||||
outputType
|
||||
});
|
||||
} catch (error) {
|
||||
if (loadingIndicator) {
|
||||
stopLoadingIndicator(loadingIndicator);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
if (loadingIndicator) {
|
||||
stopLoadingIndicator(loadingIndicator);
|
||||
}
|
||||
}
|
||||
|
||||
const researchResult = aiResult.mainResult;
|
||||
const telemetryData = aiResult.telemetryData;
|
||||
|
||||
// Format and display results
|
||||
if (outputFormat === 'text') {
|
||||
displayResearchResults(
|
||||
researchResult,
|
||||
query,
|
||||
detailLevel,
|
||||
tokenBreakdown
|
||||
);
|
||||
|
||||
// Display AI usage telemetry for CLI users
|
||||
if (telemetryData) {
|
||||
displayAiUsageSummary(telemetryData, 'cli');
|
||||
}
|
||||
|
||||
// Offer follow-up question option (only for initial CLI queries, not MCP)
|
||||
if (allowFollowUp && !isMCP) {
|
||||
await handleFollowUpQuestions(
|
||||
options,
|
||||
context,
|
||||
outputFormat,
|
||||
projectRoot,
|
||||
logFn,
|
||||
query,
|
||||
researchResult
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logFn.success('Research query completed successfully');
|
||||
|
||||
return {
|
||||
query,
|
||||
result: researchResult,
|
||||
contextSize: gatheredContext.length,
|
||||
contextTokens: tokenBreakdown.total,
|
||||
tokenBreakdown,
|
||||
systemPromptTokens,
|
||||
userPromptTokens,
|
||||
totalInputTokens,
|
||||
detailLevel,
|
||||
telemetryData
|
||||
};
|
||||
} catch (error) {
|
||||
logFn.error(`Research query failed: ${error.message}`);
|
||||
|
||||
if (outputFormat === 'text') {
|
||||
console.error(chalk.red(`\n❌ Research failed: ${error.message}`));
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build system prompt for research based on detail level
|
||||
* @param {string} detailLevel - Detail level: 'low', 'medium', 'high'
|
||||
* @param {string} projectRoot - Project root for context
|
||||
* @returns {string} System prompt
|
||||
*/
|
||||
function buildResearchSystemPrompt(detailLevel, projectRoot) {
|
||||
const basePrompt = `You are an expert AI research assistant helping with a software development project. You have access to project context including tasks, files, and project structure.
|
||||
|
||||
Your role is to provide comprehensive, accurate, and actionable research responses based on the user's query and the provided project context.`;
|
||||
|
||||
const detailInstructions = {
|
||||
low: `
|
||||
**Response Style: Concise & Direct**
|
||||
- Provide brief, focused answers (2-4 paragraphs maximum)
|
||||
- Focus on the most essential information
|
||||
- Use bullet points for key takeaways
|
||||
- Avoid lengthy explanations unless critical
|
||||
- Skip pleasantries, introductions, and conclusions
|
||||
- No phrases like "Based on your project context" or "I'll provide guidance"
|
||||
- No summary outros or alignment statements
|
||||
- Get straight to the actionable information
|
||||
- Use simple, direct language - users want info, not explanation`,
|
||||
|
||||
medium: `
|
||||
**Response Style: Balanced & Comprehensive**
|
||||
- Provide thorough but well-structured responses (4-8 paragraphs)
|
||||
- Include relevant examples and explanations
|
||||
- Balance depth with readability
|
||||
- Use headings and bullet points for organization`,
|
||||
|
||||
high: `
|
||||
**Response Style: Detailed & Exhaustive**
|
||||
- Provide comprehensive, in-depth analysis (8+ paragraphs)
|
||||
- Include multiple perspectives and approaches
|
||||
- Provide detailed examples, code snippets, and step-by-step guidance
|
||||
- Cover edge cases and potential pitfalls
|
||||
- Use clear structure with headings, subheadings, and lists`
|
||||
};
|
||||
|
||||
return `${basePrompt}
|
||||
|
||||
${detailInstructions[detailLevel]}
|
||||
|
||||
**Guidelines:**
|
||||
- Always consider the project context when formulating responses
|
||||
- Reference specific tasks, files, or project elements when relevant
|
||||
- Provide actionable insights that can be applied to the project
|
||||
- If the query relates to existing project tasks, suggest how the research applies to those tasks
|
||||
- Use markdown formatting for better readability
|
||||
- Be precise and avoid speculation unless clearly marked as such
|
||||
|
||||
**For LOW detail level specifically:**
|
||||
- Start immediately with the core information
|
||||
- No introductory phrases or context acknowledgments
|
||||
- No concluding summaries or project alignment statements
|
||||
- Focus purely on facts, steps, and actionable items`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build user prompt with query and context
|
||||
* @param {string} query - User's research query
|
||||
* @param {string} gatheredContext - Gathered project context
|
||||
* @param {string} detailLevel - Detail level for response guidance
|
||||
* @returns {string} Complete user prompt
|
||||
*/
|
||||
function buildResearchUserPrompt(query, gatheredContext, detailLevel) {
|
||||
let prompt = `# Research Query
|
||||
|
||||
${query}`;
|
||||
|
||||
if (gatheredContext && gatheredContext.trim()) {
|
||||
prompt += `
|
||||
|
||||
# Project Context
|
||||
|
||||
${gatheredContext}`;
|
||||
}
|
||||
|
||||
prompt += `
|
||||
|
||||
# Instructions
|
||||
|
||||
Please research and provide a ${detailLevel}-detail response to the query above. Consider the project context provided and make your response as relevant and actionable as possible for this specific project.`;
|
||||
|
||||
return prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display detailed token breakdown for context and prompts
|
||||
* @param {Object} tokenBreakdown - Token breakdown from context gatherer
|
||||
* @param {number} systemPromptTokens - System prompt token count
|
||||
* @param {number} userPromptTokens - User prompt token count
|
||||
*/
|
||||
function displayDetailedTokenBreakdown(
|
||||
tokenBreakdown,
|
||||
systemPromptTokens,
|
||||
userPromptTokens
|
||||
) {
|
||||
const parts = [];
|
||||
|
||||
// Custom context
|
||||
if (tokenBreakdown.customContext) {
|
||||
parts.push(
|
||||
chalk.cyan('Custom: ') +
|
||||
chalk.yellow(tokenBreakdown.customContext.tokens.toLocaleString())
|
||||
);
|
||||
}
|
||||
|
||||
// Tasks breakdown
|
||||
if (tokenBreakdown.tasks && tokenBreakdown.tasks.length > 0) {
|
||||
const totalTaskTokens = tokenBreakdown.tasks.reduce(
|
||||
(sum, task) => sum + task.tokens,
|
||||
0
|
||||
);
|
||||
const taskDetails = tokenBreakdown.tasks
|
||||
.map((task) => {
|
||||
const titleDisplay =
|
||||
task.title.length > 30
|
||||
? task.title.substring(0, 30) + '...'
|
||||
: task.title;
|
||||
return ` ${chalk.gray(task.id)} ${chalk.white(titleDisplay)} ${chalk.yellow(task.tokens.toLocaleString())} tokens`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
parts.push(
|
||||
chalk.cyan('Tasks: ') +
|
||||
chalk.yellow(totalTaskTokens.toLocaleString()) +
|
||||
chalk.gray(` (${tokenBreakdown.tasks.length} items)`) +
|
||||
'\n' +
|
||||
taskDetails
|
||||
);
|
||||
}
|
||||
|
||||
// Files breakdown
|
||||
if (tokenBreakdown.files && tokenBreakdown.files.length > 0) {
|
||||
const totalFileTokens = tokenBreakdown.files.reduce(
|
||||
(sum, file) => sum + file.tokens,
|
||||
0
|
||||
);
|
||||
const fileDetails = tokenBreakdown.files
|
||||
.map((file) => {
|
||||
const pathDisplay =
|
||||
file.path.length > 40
|
||||
? '...' + file.path.substring(file.path.length - 37)
|
||||
: file.path;
|
||||
return ` ${chalk.gray(pathDisplay)} ${chalk.yellow(file.tokens.toLocaleString())} tokens ${chalk.gray(`(${file.sizeKB}KB)`)}`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
parts.push(
|
||||
chalk.cyan('Files: ') +
|
||||
chalk.yellow(totalFileTokens.toLocaleString()) +
|
||||
chalk.gray(` (${tokenBreakdown.files.length} files)`) +
|
||||
'\n' +
|
||||
fileDetails
|
||||
);
|
||||
}
|
||||
|
||||
// Project tree
|
||||
if (tokenBreakdown.projectTree) {
|
||||
parts.push(
|
||||
chalk.cyan('Project Tree: ') +
|
||||
chalk.yellow(tokenBreakdown.projectTree.tokens.toLocaleString()) +
|
||||
chalk.gray(
|
||||
` (${tokenBreakdown.projectTree.fileCount} files, ${tokenBreakdown.projectTree.dirCount} dirs)`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Prompts breakdown
|
||||
const totalPromptTokens = systemPromptTokens + userPromptTokens;
|
||||
const promptDetails = [
|
||||
` ${chalk.gray('System:')} ${chalk.yellow(systemPromptTokens.toLocaleString())} tokens`,
|
||||
` ${chalk.gray('User:')} ${chalk.yellow(userPromptTokens.toLocaleString())} tokens`
|
||||
].join('\n');
|
||||
|
||||
parts.push(
|
||||
chalk.cyan('Prompts: ') +
|
||||
chalk.yellow(totalPromptTokens.toLocaleString()) +
|
||||
chalk.gray(' (generated)') +
|
||||
'\n' +
|
||||
promptDetails
|
||||
);
|
||||
|
||||
// Display the breakdown in a clean box
|
||||
if (parts.length > 0) {
|
||||
const content = parts.join('\n\n');
|
||||
const tokenBox = boxen(content, {
|
||||
title: chalk.blue.bold('Context Analysis'),
|
||||
titleAlignment: 'left',
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
margin: { top: 0, bottom: 1 },
|
||||
borderStyle: 'single',
|
||||
borderColor: 'blue'
|
||||
});
|
||||
console.log(tokenBox);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process research result text to highlight code blocks
|
||||
* @param {string} text - Raw research result text
|
||||
* @returns {string} Processed text with highlighted code blocks
|
||||
*/
|
||||
function processCodeBlocks(text) {
|
||||
// Regex to match code blocks with optional language specification
|
||||
const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
|
||||
|
||||
return text.replace(codeBlockRegex, (match, language, code) => {
|
||||
try {
|
||||
// Default to javascript if no language specified
|
||||
const lang = language || 'javascript';
|
||||
|
||||
// Highlight the code using cli-highlight
|
||||
const highlightedCode = highlight(code.trim(), {
|
||||
language: lang,
|
||||
ignoreIllegals: true // Don't fail on unrecognized syntax
|
||||
});
|
||||
|
||||
// Add a subtle border around code blocks
|
||||
const codeBox = boxen(highlightedCode, {
|
||||
padding: { top: 0, bottom: 0, left: 1, right: 1 },
|
||||
margin: { top: 0, bottom: 0 },
|
||||
borderStyle: 'single',
|
||||
borderColor: 'dim'
|
||||
});
|
||||
|
||||
return '\n' + codeBox + '\n';
|
||||
} catch (error) {
|
||||
// If highlighting fails, return the original code block with basic formatting
|
||||
return (
|
||||
'\n' +
|
||||
chalk.gray('```' + (language || '')) +
|
||||
'\n' +
|
||||
chalk.white(code.trim()) +
|
||||
'\n' +
|
||||
chalk.gray('```') +
|
||||
'\n'
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Display research results in formatted output
|
||||
* @param {string} result - AI research result
|
||||
* @param {string} query - Original query
|
||||
* @param {string} detailLevel - Detail level used
|
||||
* @param {Object} tokenBreakdown - Detailed token usage
|
||||
*/
|
||||
function displayResearchResults(result, query, detailLevel, tokenBreakdown) {
|
||||
// Header with query info
|
||||
const header = boxen(
|
||||
chalk.green.bold('Research Results') +
|
||||
'\n\n' +
|
||||
chalk.gray('Query: ') +
|
||||
chalk.white(query) +
|
||||
'\n' +
|
||||
chalk.gray('Detail Level: ') +
|
||||
chalk.cyan(detailLevel),
|
||||
{
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
margin: { top: 1, bottom: 0 },
|
||||
borderStyle: 'round',
|
||||
borderColor: 'green'
|
||||
}
|
||||
);
|
||||
console.log(header);
|
||||
|
||||
// Process the result to highlight code blocks
|
||||
const processedResult = processCodeBlocks(result);
|
||||
|
||||
// Main research content in a clean box
|
||||
const contentBox = boxen(processedResult, {
|
||||
padding: { top: 1, bottom: 1, left: 2, right: 2 },
|
||||
margin: { top: 0, bottom: 1 },
|
||||
borderStyle: 'single',
|
||||
borderColor: 'gray'
|
||||
});
|
||||
console.log(contentBox);
|
||||
|
||||
// Success footer
|
||||
console.log(chalk.green('✅ Research completed'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Flatten tasks array to include subtasks as individual searchable items
|
||||
* @param {Array} tasks - Array of task objects
|
||||
* @returns {Array} Flattened array including both tasks and subtasks
|
||||
*/
|
||||
function flattenTasksWithSubtasks(tasks) {
|
||||
const flattened = [];
|
||||
|
||||
for (const task of tasks) {
|
||||
// Add the main task
|
||||
flattened.push({
|
||||
...task,
|
||||
searchableId: task.id.toString(), // For consistent ID handling
|
||||
isSubtask: false
|
||||
});
|
||||
|
||||
// Add subtasks if they exist
|
||||
if (task.subtasks && task.subtasks.length > 0) {
|
||||
for (const subtask of task.subtasks) {
|
||||
flattened.push({
|
||||
...subtask,
|
||||
searchableId: `${task.id}.${subtask.id}`, // Format: "15.2"
|
||||
isSubtask: true,
|
||||
parentId: task.id,
|
||||
parentTitle: task.title,
|
||||
// Enhance subtask context with parent information
|
||||
title: `${subtask.title} (subtask of: ${task.title})`,
|
||||
description: `${subtask.description} [Parent: ${task.description}]`
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return flattened;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle follow-up questions in interactive mode
|
||||
* @param {Object} originalOptions - Original research options
|
||||
* @param {Object} context - Execution context
|
||||
* @param {string} outputFormat - Output format
|
||||
* @param {string} projectRoot - Project root directory
|
||||
* @param {Object} logFn - Logger function
|
||||
* @param {string} initialQuery - Initial query for context
|
||||
* @param {string} initialResult - Initial AI result for context
|
||||
*/
|
||||
async function handleFollowUpQuestions(
|
||||
originalOptions,
|
||||
context,
|
||||
outputFormat,
|
||||
projectRoot,
|
||||
logFn,
|
||||
initialQuery,
|
||||
initialResult
|
||||
) {
|
||||
try {
|
||||
// Initialize conversation history with the initial Q&A
|
||||
const conversationHistory = [
|
||||
{
|
||||
question: initialQuery,
|
||||
answer: initialResult,
|
||||
type: 'initial'
|
||||
}
|
||||
];
|
||||
|
||||
while (true) {
|
||||
// Ask if user wants to ask a follow-up question
|
||||
const { wantFollowUp } = await inquirer.prompt([
|
||||
{
|
||||
type: 'confirm',
|
||||
name: 'wantFollowUp',
|
||||
message: 'Would you like to ask a follow-up question?',
|
||||
default: false // Default to 'n' as requested
|
||||
}
|
||||
]);
|
||||
|
||||
if (!wantFollowUp) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Get the follow-up question
|
||||
const { followUpQuery } = await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'followUpQuery',
|
||||
message: 'Enter your follow-up question:',
|
||||
validate: (input) => {
|
||||
if (!input || input.trim().length === 0) {
|
||||
return 'Please enter a valid question.';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
if (!followUpQuery || followUpQuery.trim().length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
console.log('\n' + chalk.gray('─'.repeat(60)) + '\n');
|
||||
|
||||
// Build cumulative conversation context from all previous exchanges
|
||||
const conversationContext = buildConversationContext(conversationHistory);
|
||||
|
||||
// Create enhanced options for follow-up with full conversation context
|
||||
// Remove explicit task IDs to allow fresh fuzzy search based on new question
|
||||
const followUpOptions = {
|
||||
...originalOptions,
|
||||
taskIds: [], // Clear task IDs to allow fresh fuzzy search
|
||||
customContext:
|
||||
conversationContext +
|
||||
(originalOptions.customContext
|
||||
? `\n\n--- Original Context ---\n${originalOptions.customContext}`
|
||||
: '')
|
||||
};
|
||||
|
||||
// Perform follow-up research with fresh fuzzy search and conversation context
|
||||
// Disable follow-up prompts for nested calls to prevent infinite recursion
|
||||
const followUpResult = await performResearch(
|
||||
followUpQuery.trim(),
|
||||
followUpOptions,
|
||||
context,
|
||||
outputFormat,
|
||||
false // allowFollowUp = false for nested calls
|
||||
);
|
||||
|
||||
// Add this exchange to the conversation history
|
||||
conversationHistory.push({
|
||||
question: followUpQuery.trim(),
|
||||
answer: followUpResult.result,
|
||||
type: 'followup'
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// If there's an error with inquirer (e.g., non-interactive terminal),
|
||||
// silently continue without follow-up functionality
|
||||
logFn.debug(`Follow-up questions not available: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build conversation context string from conversation history
|
||||
* @param {Array} conversationHistory - Array of conversation exchanges
|
||||
* @returns {string} Formatted conversation context
|
||||
*/
|
||||
function buildConversationContext(conversationHistory) {
|
||||
if (conversationHistory.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const contextParts = ['--- Conversation History ---'];
|
||||
|
||||
conversationHistory.forEach((exchange, index) => {
|
||||
const questionLabel =
|
||||
exchange.type === 'initial' ? 'Initial Question' : `Follow-up ${index}`;
|
||||
const answerLabel =
|
||||
exchange.type === 'initial' ? 'Initial Answer' : `Answer ${index}`;
|
||||
|
||||
contextParts.push(`\n${questionLabel}: ${exchange.question}`);
|
||||
contextParts.push(`${answerLabel}: ${exchange.answer}`);
|
||||
});
|
||||
|
||||
return contextParts.join('\n');
|
||||
}
|
||||
|
||||
export { performResearch };
|
||||
384
scripts/modules/telemetry-queue.js
Normal file
384
scripts/modules/telemetry-queue.js
Normal file
@@ -0,0 +1,384 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { submitTelemetryData } from "./telemetry-submission.js";
|
||||
import { getDebugFlag } from "./config-manager.js";
|
||||
import { log } from "./utils.js";
|
||||
|
||||
class TelemetryQueue {
|
||||
constructor() {
|
||||
this.queue = [];
|
||||
this.processing = false;
|
||||
this.backgroundInterval = null;
|
||||
this.stats = {
|
||||
pending: 0,
|
||||
processed: 0,
|
||||
failed: 0,
|
||||
lastProcessedAt: null,
|
||||
};
|
||||
this.logFile = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the queue with comprehensive logging file path
|
||||
* @param {string} projectRoot - Project root directory for log file
|
||||
*/
|
||||
initialize(projectRoot) {
|
||||
if (projectRoot) {
|
||||
this.logFile = path.join(projectRoot, ".taskmaster-activity.log");
|
||||
this.loadPersistedQueue();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add telemetry data to queue without blocking
|
||||
* @param {Object} telemetryData - Command telemetry data
|
||||
*/
|
||||
addToQueue(telemetryData) {
|
||||
const queueItem = {
|
||||
...telemetryData,
|
||||
queuedAt: new Date().toISOString(),
|
||||
attempts: 0,
|
||||
};
|
||||
|
||||
this.queue.push(queueItem);
|
||||
this.stats.pending = this.queue.length;
|
||||
|
||||
// Log the activity immediately to .log file
|
||||
this.logActivity("QUEUED", {
|
||||
commandName: telemetryData.commandName,
|
||||
queuedAt: queueItem.queuedAt,
|
||||
userId: telemetryData.userId,
|
||||
success: telemetryData.success,
|
||||
executionTimeMs: telemetryData.executionTimeMs,
|
||||
});
|
||||
|
||||
if (getDebugFlag()) {
|
||||
log("debug", `Added ${telemetryData.commandName} to telemetry queue`);
|
||||
}
|
||||
|
||||
// Persist queue state if file is configured
|
||||
this.persistQueue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Log activity to comprehensive .log file
|
||||
* @param {string} action - The action being logged (QUEUED, SUBMITTED, FAILED, etc.)
|
||||
* @param {Object} data - The data to log
|
||||
*/
|
||||
logActivity(action, data) {
|
||||
if (!this.logFile) return;
|
||||
|
||||
try {
|
||||
const timestamp = new Date().toISOString();
|
||||
const logEntry = `${timestamp} [${action}] ${JSON.stringify(data)}\n`;
|
||||
|
||||
fs.appendFileSync(this.logFile, logEntry);
|
||||
} catch (error) {
|
||||
if (getDebugFlag()) {
|
||||
log("error", `Failed to write to activity log: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process all queued telemetry items
|
||||
* @returns {Object} Processing result with stats
|
||||
*/
|
||||
async processQueue() {
|
||||
if (this.processing || this.queue.length === 0) {
|
||||
return { processed: 0, failed: 0, errors: [] };
|
||||
}
|
||||
|
||||
this.processing = true;
|
||||
const errors = [];
|
||||
let processed = 0;
|
||||
let failed = 0;
|
||||
|
||||
this.logActivity("PROCESSING_START", { queueSize: this.queue.length });
|
||||
|
||||
// Process items in batches to avoid overwhelming the gateway
|
||||
const batchSize = 5;
|
||||
const itemsToProcess = [...this.queue];
|
||||
|
||||
for (let i = 0; i < itemsToProcess.length; i += batchSize) {
|
||||
const batch = itemsToProcess.slice(i, i + batchSize);
|
||||
|
||||
for (const item of batch) {
|
||||
try {
|
||||
item.attempts++;
|
||||
const result = await submitTelemetryData(item);
|
||||
|
||||
if (result.success) {
|
||||
// Remove from queue on success
|
||||
const index = this.queue.findIndex(
|
||||
(q) => q.queuedAt === item.queuedAt
|
||||
);
|
||||
if (index > -1) {
|
||||
this.queue.splice(index, 1);
|
||||
}
|
||||
processed++;
|
||||
|
||||
// Log successful submission
|
||||
this.logActivity("SUBMITTED", {
|
||||
commandName: item.commandName,
|
||||
queuedAt: item.queuedAt,
|
||||
attempts: item.attempts,
|
||||
});
|
||||
} else {
|
||||
// Retry failed items up to 3 times
|
||||
if (item.attempts >= 3) {
|
||||
const index = this.queue.findIndex(
|
||||
(q) => q.queuedAt === item.queuedAt
|
||||
);
|
||||
if (index > -1) {
|
||||
this.queue.splice(index, 1);
|
||||
}
|
||||
failed++;
|
||||
const errorMsg = `Failed to submit ${item.commandName} after 3 attempts: ${result.error}`;
|
||||
errors.push(errorMsg);
|
||||
|
||||
// Log final failure
|
||||
this.logActivity("FAILED", {
|
||||
commandName: item.commandName,
|
||||
queuedAt: item.queuedAt,
|
||||
attempts: item.attempts,
|
||||
error: result.error,
|
||||
});
|
||||
} else {
|
||||
// Log retry attempt
|
||||
this.logActivity("RETRY", {
|
||||
commandName: item.commandName,
|
||||
queuedAt: item.queuedAt,
|
||||
attempts: item.attempts,
|
||||
error: result.error,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Network or unexpected errors
|
||||
if (item.attempts >= 3) {
|
||||
const index = this.queue.findIndex(
|
||||
(q) => q.queuedAt === item.queuedAt
|
||||
);
|
||||
if (index > -1) {
|
||||
this.queue.splice(index, 1);
|
||||
}
|
||||
failed++;
|
||||
const errorMsg = `Exception submitting ${item.commandName}: ${error.message}`;
|
||||
errors.push(errorMsg);
|
||||
|
||||
// Log exception failure
|
||||
this.logActivity("EXCEPTION", {
|
||||
commandName: item.commandName,
|
||||
queuedAt: item.queuedAt,
|
||||
attempts: item.attempts,
|
||||
error: error.message,
|
||||
});
|
||||
} else {
|
||||
// Log retry for exception
|
||||
this.logActivity("RETRY_EXCEPTION", {
|
||||
commandName: item.commandName,
|
||||
queuedAt: item.queuedAt,
|
||||
attempts: item.attempts,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Small delay between batches
|
||||
if (i + batchSize < itemsToProcess.length) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
this.stats.pending = this.queue.length;
|
||||
this.stats.processed += processed;
|
||||
this.stats.failed += failed;
|
||||
this.stats.lastProcessedAt = new Date().toISOString();
|
||||
|
||||
this.processing = false;
|
||||
this.persistQueue();
|
||||
|
||||
// Log processing completion
|
||||
this.logActivity("PROCESSING_COMPLETE", {
|
||||
processed,
|
||||
failed,
|
||||
remainingInQueue: this.queue.length,
|
||||
});
|
||||
|
||||
if (getDebugFlag() && (processed > 0 || failed > 0)) {
|
||||
log(
|
||||
"debug",
|
||||
`Telemetry queue processed: ${processed} success, ${failed} failed`
|
||||
);
|
||||
}
|
||||
|
||||
return { processed, failed, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Start background processing at specified interval
|
||||
* @param {number} intervalMs - Processing interval in milliseconds (default: 30000)
|
||||
*/
|
||||
startBackgroundProcessor(intervalMs = 30000) {
|
||||
if (this.backgroundInterval) {
|
||||
clearInterval(this.backgroundInterval);
|
||||
}
|
||||
|
||||
this.backgroundInterval = setInterval(async () => {
|
||||
try {
|
||||
await this.processQueue();
|
||||
} catch (error) {
|
||||
if (getDebugFlag()) {
|
||||
log(
|
||||
"error",
|
||||
`Background telemetry processing error: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}, intervalMs);
|
||||
|
||||
if (getDebugFlag()) {
|
||||
log(
|
||||
"debug",
|
||||
`Started telemetry background processor (${intervalMs}ms interval)`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop background processing
|
||||
*/
|
||||
stopBackgroundProcessor() {
|
||||
if (this.backgroundInterval) {
|
||||
clearInterval(this.backgroundInterval);
|
||||
this.backgroundInterval = null;
|
||||
|
||||
if (getDebugFlag()) {
|
||||
log("debug", "Stopped telemetry background processor");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queue statistics
|
||||
* @returns {Object} Queue stats
|
||||
*/
|
||||
getQueueStats() {
|
||||
return {
|
||||
...this.stats,
|
||||
pending: this.queue.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load persisted queue from file (now reads from .log file)
|
||||
*/
|
||||
loadPersistedQueue() {
|
||||
// For the .log file, we'll look for a companion .json file for queue state
|
||||
if (!this.logFile) return;
|
||||
|
||||
const stateFile = this.logFile.replace(".log", "-queue-state.json");
|
||||
if (!fs.existsSync(stateFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = fs.readFileSync(stateFile, "utf8");
|
||||
const persistedData = JSON.parse(data);
|
||||
|
||||
this.queue = persistedData.queue || [];
|
||||
this.stats = { ...this.stats, ...persistedData.stats };
|
||||
|
||||
if (getDebugFlag()) {
|
||||
log(
|
||||
"debug",
|
||||
`Loaded ${this.queue.length} items from telemetry queue state`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
if (getDebugFlag()) {
|
||||
log(
|
||||
"error",
|
||||
`Failed to load persisted telemetry queue: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist queue state to companion file
|
||||
*/
|
||||
persistQueue() {
|
||||
if (!this.logFile) return;
|
||||
|
||||
const stateFile = this.logFile.replace(".log", "-queue-state.json");
|
||||
|
||||
try {
|
||||
const data = {
|
||||
queue: this.queue,
|
||||
stats: this.stats,
|
||||
lastUpdated: new Date().toISOString(),
|
||||
};
|
||||
|
||||
fs.writeFileSync(stateFile, JSON.stringify(data, null, 2));
|
||||
} catch (error) {
|
||||
if (getDebugFlag()) {
|
||||
log("error", `Failed to persist telemetry queue: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Global instance
|
||||
const telemetryQueue = new TelemetryQueue();
|
||||
|
||||
/**
|
||||
* Add command telemetry to queue (non-blocking)
|
||||
* @param {Object} commandData - Command execution data
|
||||
*/
|
||||
export function queueCommandTelemetry(commandData) {
|
||||
telemetryQueue.addToQueue(commandData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize telemetry queue with project root
|
||||
* @param {string} projectRoot - Project root directory
|
||||
*/
|
||||
export function initializeTelemetryQueue(projectRoot) {
|
||||
telemetryQueue.initialize(projectRoot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start background telemetry processing
|
||||
* @param {number} intervalMs - Processing interval in milliseconds
|
||||
*/
|
||||
export function startTelemetryBackgroundProcessor(intervalMs = 30000) {
|
||||
telemetryQueue.startBackgroundProcessor(intervalMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop background telemetry processing
|
||||
*/
|
||||
export function stopTelemetryBackgroundProcessor() {
|
||||
telemetryQueue.stopBackgroundProcessor();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get telemetry queue statistics
|
||||
* @returns {Object} Queue statistics
|
||||
*/
|
||||
export function getTelemetryQueueStats() {
|
||||
return telemetryQueue.getQueueStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually process telemetry queue
|
||||
* @returns {Object} Processing result
|
||||
*/
|
||||
export function processTelemetryQueue() {
|
||||
return telemetryQueue.processQueue();
|
||||
}
|
||||
|
||||
export { telemetryQueue };
|
||||
238
scripts/modules/telemetry-submission.js
Normal file
238
scripts/modules/telemetry-submission.js
Normal file
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* Telemetry Submission Service
|
||||
* Handles sending telemetry data to remote gateway endpoint
|
||||
*/
|
||||
|
||||
import { z } from "zod";
|
||||
import { getConfig } from "./config-manager.js";
|
||||
import { getTelemetryEnabled } from "./config-manager.js";
|
||||
import { resolveEnvVariable } from "./utils.js";
|
||||
|
||||
// Telemetry data validation schema
|
||||
const TelemetryDataSchema = z.object({
|
||||
timestamp: z.string().datetime(),
|
||||
userId: z.string().min(1),
|
||||
commandName: z.string().min(1),
|
||||
modelUsed: z.string().optional(),
|
||||
providerName: z.string().optional(),
|
||||
inputTokens: z.number().optional(),
|
||||
outputTokens: z.number().optional(),
|
||||
totalTokens: z.number().optional(),
|
||||
totalCost: z.number().optional(),
|
||||
currency: z.string().optional(),
|
||||
commandArgs: z.any().optional(),
|
||||
fullOutput: z.any().optional(),
|
||||
});
|
||||
|
||||
// Hardcoded configuration for TaskMaster telemetry gateway
|
||||
const TASKMASTER_BASE_URL = "http://localhost:4444";
|
||||
const TASKMASTER_TELEMETRY_ENDPOINT = `${TASKMASTER_BASE_URL}/api/v1/telemetry`;
|
||||
const TASKMASTER_USER_REGISTRATION_ENDPOINT = `${TASKMASTER_BASE_URL}/auth/init`;
|
||||
const MAX_RETRIES = 3;
|
||||
const RETRY_DELAY = 1000; // 1 second
|
||||
|
||||
/**
|
||||
* Get telemetry configuration from hardcoded service ID, user token, and config
|
||||
* @returns {Object} Configuration object with serviceId, apiKey, userId, and email
|
||||
*/
|
||||
function getTelemetryConfig() {
|
||||
// Get the config which contains userId and email
|
||||
const config = getConfig();
|
||||
|
||||
// Hardcoded service ID for TaskMaster telemetry service
|
||||
const hardcodedServiceId = "98fb3198-2dfc-42d1-af53-07b99e4f3bde";
|
||||
|
||||
// Get user's API token from .env (managed by user-management.js)
|
||||
const userApiKey = resolveEnvVariable("TASKMASTER_API_KEY");
|
||||
|
||||
return {
|
||||
serviceId: hardcodedServiceId, // Hardcoded service identifier
|
||||
apiKey: userApiKey || null, // User's Bearer token from .env
|
||||
userId: config?.account?.userId || null, // From config
|
||||
email: config?.account?.email || null, // From config
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Register or lookup user with the TaskMaster telemetry gateway using /auth/init
|
||||
* @param {string} email - User's email address
|
||||
* @param {string} userId - User's ID
|
||||
* @returns {Promise<{success: boolean, apiKey?: string, userId?: string, email?: string, isNewUser?: boolean, error?: string}>}
|
||||
*/
|
||||
export async function registerUserWithGateway(email = null, userId = null) {
|
||||
try {
|
||||
const requestBody = {};
|
||||
if (email) requestBody.email = email;
|
||||
if (userId) requestBody.userId = userId;
|
||||
|
||||
const response = await fetch(TASKMASTER_USER_REGISTRATION_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Gateway registration failed: ${response.status} ${response.statusText}`,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// Handle the /auth/init response format
|
||||
if (result.success && result.data) {
|
||||
return {
|
||||
success: true,
|
||||
apiKey: result.data.token,
|
||||
userId: result.data.userId,
|
||||
email: email,
|
||||
isNewUser: result.data.isNewUser,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
error: result.error || result.message || "Unknown registration error",
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Gateway registration error: ${error.message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits telemetry data to the remote gateway endpoint
|
||||
* @param {Object} telemetryData - The telemetry data to submit
|
||||
* @returns {Promise<Object>} - Result object with success status and details
|
||||
*/
|
||||
export async function submitTelemetryData(telemetryData) {
|
||||
try {
|
||||
// Check user opt-out preferences first, but hosted mode always sends telemetry
|
||||
const config = getConfig();
|
||||
const isHostedMode = config?.account?.mode === "hosted";
|
||||
|
||||
if (!isHostedMode && !getTelemetryEnabled()) {
|
||||
return {
|
||||
success: true,
|
||||
skipped: true,
|
||||
reason: "Telemetry disabled by user preference",
|
||||
};
|
||||
}
|
||||
|
||||
// Get telemetry configuration
|
||||
const telemetryConfig = getTelemetryConfig();
|
||||
if (
|
||||
!telemetryConfig.apiKey ||
|
||||
!telemetryConfig.userId ||
|
||||
!telemetryConfig.email
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
"Telemetry configuration incomplete. Please ensure you have completed 'task-master init' to set up your user account.",
|
||||
};
|
||||
}
|
||||
|
||||
// Validate telemetry data
|
||||
try {
|
||||
TelemetryDataSchema.parse(telemetryData);
|
||||
} catch (validationError) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Telemetry data validation failed: ${validationError.message}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Send FULL telemetry data to gateway (including commandArgs and fullOutput)
|
||||
// Note: Sensitive data filtering is handled separately for user-facing responses
|
||||
const completeTelemetryData = {
|
||||
...telemetryData,
|
||||
userId: telemetryConfig.userId, // Ensure correct userId
|
||||
};
|
||||
|
||||
// Attempt submission with retry logic
|
||||
let lastError;
|
||||
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
const response = await fetch(TASKMASTER_TELEMETRY_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-taskmaster-service-id": telemetryConfig.serviceId, // Hardcoded service ID
|
||||
Authorization: `Bearer ${telemetryConfig.apiKey}`, // User's Bearer token
|
||||
"X-User-Email": telemetryConfig.email, // User's email from config
|
||||
},
|
||||
body: JSON.stringify(completeTelemetryData),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
return {
|
||||
success: true,
|
||||
id: result.id,
|
||||
attempt,
|
||||
};
|
||||
} else {
|
||||
// Handle HTTP error responses
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
const errorMessage = `HTTP ${response.status} ${response.statusText}`;
|
||||
|
||||
// Don't retry on certain status codes (rate limiting, auth errors, etc.)
|
||||
if (
|
||||
response.status === 429 ||
|
||||
response.status === 401 ||
|
||||
response.status === 403
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
statusCode: response.status,
|
||||
};
|
||||
}
|
||||
|
||||
// For other HTTP errors, continue retrying
|
||||
lastError = new Error(errorMessage);
|
||||
}
|
||||
} catch (networkError) {
|
||||
lastError = networkError;
|
||||
}
|
||||
|
||||
// Wait before retry (exponential backoff)
|
||||
if (attempt < MAX_RETRIES) {
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, RETRY_DELAY * Math.pow(2, attempt - 1))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// All retries failed
|
||||
return {
|
||||
success: false,
|
||||
error: lastError.message,
|
||||
attempts: MAX_RETRIES,
|
||||
};
|
||||
} catch (error) {
|
||||
// Graceful error handling - never throw
|
||||
return {
|
||||
success: false,
|
||||
error: `Telemetry submission failed: ${error.message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits telemetry data asynchronously without blocking execution
|
||||
* @param {Object} telemetryData - The telemetry data to submit
|
||||
*/
|
||||
export function submitTelemetryDataAsync(telemetryData) {
|
||||
// Fire and forget - don't block execution
|
||||
submitTelemetryData(telemetryData).catch((error) => {
|
||||
// Silently log errors without blocking
|
||||
console.debug("Telemetry submission failed:", error);
|
||||
});
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user