Compare commits
9 Commits
23.16-23.3
...
remove-pac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4641cff82 | ||
|
|
4386e74ed2 | ||
|
|
5d3d66ee64 | ||
|
|
bf38baf858 | ||
|
|
ab6746a0c0 | ||
|
|
c02483bc41 | ||
|
|
3148b57f1b | ||
|
|
47b79c0e29 | ||
|
|
0dfecec1b3 |
@@ -1,20 +1,18 @@
|
|||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"taskmaster-ai": {
|
"taskmaster-ai": {
|
||||||
"command": "node",
|
"command": "node",
|
||||||
"args": [
|
"args": ["./mcp-server/server.js"],
|
||||||
"./mcp-server/server.js"
|
"env": {
|
||||||
],
|
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
||||||
"env": {
|
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
||||||
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
"MODEL": "claude-3-7-sonnet-20250219",
|
||||||
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
"PERPLEXITY_MODEL": "sonar-pro",
|
||||||
"MODEL": "claude-3-7-sonnet-20250219",
|
"MAX_TOKENS": 128000,
|
||||||
"PERPLEXITY_MODEL": "sonar-pro",
|
"TEMPERATURE": 0.2,
|
||||||
"MAX_TOKENS": 128000,
|
"DEFAULT_SUBTASKS": 5,
|
||||||
"TEMPERATURE": 0.2,
|
"DEFAULT_PRIORITY": "medium"
|
||||||
"DEFAULT_SUBTASKS": 5,
|
}
|
||||||
"DEFAULT_PRIORITY": "medium"
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
60
.github/workflows/ci.yml
vendored
60
.github/workflows/ci.yml
vendored
@@ -14,7 +14,7 @@ permissions:
|
|||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
setup:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
@@ -24,21 +24,55 @@ jobs:
|
|||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 20
|
||||||
cache: "npm"
|
cache: 'npm'
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
id: install
|
||||||
|
run: npm ci
|
||||||
|
timeout-minutes: 2
|
||||||
|
|
||||||
- name: Cache node_modules
|
- name: Cache node_modules
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: node_modules
|
||||||
node_modules
|
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
|
||||||
*/*/node_modules
|
|
||||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-node-
|
|
||||||
|
|
||||||
- name: Install Dependencies
|
format-check:
|
||||||
run: npm ci
|
needs: setup
|
||||||
timeout-minutes: 2
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
|
||||||
|
- name: Restore node_modules
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: node_modules
|
||||||
|
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
|
||||||
|
|
||||||
|
- name: Format Check
|
||||||
|
run: npm run format-check
|
||||||
|
env:
|
||||||
|
FORCE_COLOR: 1
|
||||||
|
|
||||||
|
test:
|
||||||
|
needs: setup
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
|
||||||
|
- name: Restore node_modules
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: node_modules
|
||||||
|
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
|
||||||
|
|
||||||
- name: Run Tests
|
- name: Run Tests
|
||||||
run: |
|
run: |
|
||||||
@@ -47,13 +81,13 @@ jobs:
|
|||||||
NODE_ENV: test
|
NODE_ENV: test
|
||||||
CI: true
|
CI: true
|
||||||
FORCE_COLOR: 1
|
FORCE_COLOR: 1
|
||||||
timeout-minutes: 15
|
timeout-minutes: 10
|
||||||
|
|
||||||
- name: Upload Test Results
|
- name: Upload Test Results
|
||||||
if: always()
|
if: always()
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: test-results-node
|
name: test-results
|
||||||
path: |
|
path: |
|
||||||
test-results
|
test-results
|
||||||
coverage
|
coverage
|
||||||
|
|||||||
2
.github/workflows/release.yml
vendored
2
.github/workflows/release.yml
vendored
@@ -14,7 +14,7 @@ jobs:
|
|||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 20
|
||||||
cache: "npm"
|
cache: 'npm'
|
||||||
|
|
||||||
- name: Cache node_modules
|
- name: Cache node_modules
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
|
|||||||
6
.prettierignore
Normal file
6
.prettierignore
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
# Ignore artifacts:
|
||||||
|
build
|
||||||
|
coverage
|
||||||
|
.changeset
|
||||||
|
tasks
|
||||||
|
package-lock.json
|
||||||
11
.prettierrc
Normal file
11
.prettierrc
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"printWidth": 80,
|
||||||
|
"tabWidth": 2,
|
||||||
|
"useTabs": true,
|
||||||
|
"semi": true,
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "none",
|
||||||
|
"bracketSpacing": true,
|
||||||
|
"arrowParens": "always",
|
||||||
|
"endOfLine": "lf"
|
||||||
|
}
|
||||||
90
LICENSE.md
90
LICENSE.md
@@ -1,90 +0,0 @@
|
|||||||
# Dual License
|
|
||||||
|
|
||||||
This project is licensed under two separate licenses:
|
|
||||||
|
|
||||||
1. [Business Source License 1.1](#business-source-license-11) (BSL 1.1) for commercial use of Task Master itself
|
|
||||||
2. [Apache License 2.0](#apache-license-20) for all other uses
|
|
||||||
|
|
||||||
## Business Source License 1.1
|
|
||||||
|
|
||||||
Terms: https://mariadb.com/bsl11/
|
|
||||||
|
|
||||||
Licensed Work: Task Master AI
|
|
||||||
Additional Use Grant: You may use Task Master AI to create and commercialize your own projects and products.
|
|
||||||
|
|
||||||
Change Date: 2025-03-30
|
|
||||||
Change License: None
|
|
||||||
|
|
||||||
The Licensed Work is subject to the Business Source License 1.1. If you are interested in using the Licensed Work in a way that competes directly with Task Master, please contact the licensors.
|
|
||||||
|
|
||||||
### Licensor
|
|
||||||
|
|
||||||
- Eyal Toledano (GitHub: @eyaltoledano)
|
|
||||||
- Ralph (GitHub: @Crunchyman-ralph)
|
|
||||||
|
|
||||||
### Commercial Use Restrictions
|
|
||||||
|
|
||||||
This license explicitly restricts certain commercial uses of Task Master AI to the Licensors listed above. Restricted commercial uses include:
|
|
||||||
|
|
||||||
1. Creating commercial products or services that directly compete with Task Master AI
|
|
||||||
2. Selling Task Master AI itself as a service
|
|
||||||
3. Offering Task Master AI's functionality as a commercial managed service
|
|
||||||
4. Reselling or redistributing Task Master AI for a fee
|
|
||||||
|
|
||||||
### Explicitly Permitted Uses
|
|
||||||
|
|
||||||
The following uses are explicitly allowed under this license:
|
|
||||||
|
|
||||||
1. Using Task Master AI to create and commercialize your own projects
|
|
||||||
2. Using Task Master AI in commercial environments for internal development
|
|
||||||
3. Building and selling products or services that were created using Task Master AI
|
|
||||||
4. Using Task Master AI for commercial development as long as you're not selling Task Master AI itself
|
|
||||||
|
|
||||||
### Additional Terms
|
|
||||||
|
|
||||||
1. The right to commercialize Task Master AI itself is exclusively reserved for the Licensors
|
|
||||||
2. No party may create commercial products that directly compete with Task Master AI without explicit written permission
|
|
||||||
3. Forks of this repository are subject to the same restrictions regarding direct competition
|
|
||||||
4. Contributors agree that their contributions will be subject to this same dual licensing structure
|
|
||||||
|
|
||||||
## Apache License 2.0
|
|
||||||
|
|
||||||
For all uses other than those restricted above. See [APACHE-LICENSE](./APACHE-LICENSE) for the full license text.
|
|
||||||
|
|
||||||
### Permitted Use Definition
|
|
||||||
|
|
||||||
You may use Task Master AI for any purpose, including commercial purposes, as long as you are not:
|
|
||||||
|
|
||||||
1. Creating a direct competitor to Task Master AI
|
|
||||||
2. Selling Task Master AI itself as a service
|
|
||||||
3. Redistributing Task Master AI for a fee
|
|
||||||
|
|
||||||
### Requirements for Use
|
|
||||||
|
|
||||||
1. You must include appropriate copyright notices
|
|
||||||
2. You must state significant changes made to the software
|
|
||||||
3. You must preserve all license notices
|
|
||||||
|
|
||||||
## Questions and Commercial Licensing
|
|
||||||
|
|
||||||
For questions about licensing or to inquire about commercial use that may compete with Task Master, please contact:
|
|
||||||
|
|
||||||
- Eyal Toledano (GitHub: @eyaltoledano)
|
|
||||||
- Ralph (GitHub: @Crunchyman-ralph)
|
|
||||||
|
|
||||||
## Examples
|
|
||||||
|
|
||||||
### ✅ Allowed Uses
|
|
||||||
|
|
||||||
- Using Task Master to create a commercial SaaS product
|
|
||||||
- Using Task Master in your company for development
|
|
||||||
- Creating and selling products that were built using Task Master
|
|
||||||
- Using Task Master to generate code for commercial projects
|
|
||||||
- Offering consulting services where you use Task Master
|
|
||||||
|
|
||||||
### ❌ Restricted Uses
|
|
||||||
|
|
||||||
- Creating a competing AI task management tool
|
|
||||||
- Selling access to Task Master as a service
|
|
||||||
- Creating a hosted version of Task Master
|
|
||||||
- Reselling Task Master's functionality
|
|
||||||
@@ -58,6 +58,7 @@ This will prompt you for project details and set up a new project with the neces
|
|||||||
### Important Notes
|
### Important Notes
|
||||||
|
|
||||||
1. **ES Modules Configuration:**
|
1. **ES Modules Configuration:**
|
||||||
|
|
||||||
- This project uses ES Modules (ESM) instead of CommonJS.
|
- This project uses ES Modules (ESM) instead of CommonJS.
|
||||||
- This is set via `"type": "module"` in your package.json.
|
- This is set via `"type": "module"` in your package.json.
|
||||||
- Use `import/export` syntax instead of `require()`.
|
- Use `import/export` syntax instead of `require()`.
|
||||||
|
|||||||
693
README.md
693
README.md
@@ -1,62 +1,68 @@
|
|||||||
# Task Master
|
# Task Master [](https://github.com/eyaltoledano/claude-task-master/stargazers)
|
||||||
|
|
||||||
[](https://github.com/eyaltoledano/claude-task-master/actions/workflows/ci.yml)
|
[](https://github.com/eyaltoledano/claude-task-master/actions/workflows/ci.yml) [](https://badge.fury.io/js/task-master-ai)  [](LICENSE)
|
||||||
[](LICENSE)
|
|
||||||
[](https://badge.fury.io/js/task-master-ai)
|
|
||||||
|
|
||||||
### by [@eyaltoledano](https://x.com/eyaltoledano)
|
### By [@eyaltoledano](https://x.com/eyaltoledano) & [@RalphEcom](https://x.com/RalphEcom)
|
||||||
|
|
||||||
|
[](https://x.com/eyaltoledano)
|
||||||
|
[](https://x.com/RalphEcom)
|
||||||
|
|
||||||
A task management system for AI-driven development with Claude, designed to work seamlessly with Cursor AI.
|
A task management system for AI-driven development with Claude, designed to work seamlessly with Cursor AI.
|
||||||
|
|
||||||
## Licensing
|
|
||||||
|
|
||||||
Task Master is licensed under the MIT License with Commons Clause. This means you can:
|
|
||||||
|
|
||||||
✅ **Allowed**:
|
|
||||||
|
|
||||||
- Use Task Master for any purpose (personal, commercial, academic)
|
|
||||||
- Modify the code
|
|
||||||
- Distribute copies
|
|
||||||
- Create and sell products built using Task Master
|
|
||||||
|
|
||||||
❌ **Not Allowed**:
|
|
||||||
|
|
||||||
- Sell Task Master itself
|
|
||||||
- Offer Task Master as a hosted service
|
|
||||||
- Create competing products based on Task Master
|
|
||||||
|
|
||||||
See the [LICENSE](LICENSE) file for the complete license text.
|
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- Node.js 14.0.0 or higher
|
|
||||||
- Anthropic API key (Claude API)
|
- Anthropic API key (Claude API)
|
||||||
- Anthropic SDK version 0.39.0 or higher
|
|
||||||
- OpenAI SDK (for Perplexity API integration, optional)
|
- OpenAI SDK (for Perplexity API integration, optional)
|
||||||
|
|
||||||
## Configuration
|
## Quick Start
|
||||||
|
|
||||||
The script can be configured through environment variables in a `.env` file at the root of the project:
|
### Option 1 | MCP (Recommended):
|
||||||
|
|
||||||
### Required Configuration
|
MCP (Model Control Protocol) provides the easiest way to get started with Task Master directly in your editor.
|
||||||
|
|
||||||
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
|
1. **Add the MCP config to your editor** (Cursor recommended, but it works with other text editors):
|
||||||
|
|
||||||
### Optional Configuration
|
```json
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"taskmaster-ai": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "task-master-ai", "mcp-server"],
|
||||||
|
"env": {
|
||||||
|
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
||||||
|
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
||||||
|
"MODEL": "claude-3-7-sonnet-20250219",
|
||||||
|
"PERPLEXITY_MODEL": "sonar-pro",
|
||||||
|
"MAX_TOKENS": 128000,
|
||||||
|
"TEMPERATURE": 0.2,
|
||||||
|
"DEFAULT_SUBTASKS": 5,
|
||||||
|
"DEFAULT_PRIORITY": "medium"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
|
2. **Enable the MCP** in your editor
|
||||||
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
|
|
||||||
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
|
|
||||||
- `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subtask generation
|
|
||||||
- `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online")
|
|
||||||
- `DEBUG`: Enable debug logging (default: false)
|
|
||||||
- `LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
|
|
||||||
- `DEFAULT_SUBTASKS`: Default number of subtasks when expanding (default: 3)
|
|
||||||
- `DEFAULT_PRIORITY`: Default priority for generated tasks (default: medium)
|
|
||||||
- `PROJECT_NAME`: Override default project name in tasks.json
|
|
||||||
- `PROJECT_VERSION`: Override default version in tasks.json
|
|
||||||
|
|
||||||
## Installation
|
3. **Prompt the AI** to initialize Task Master:
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you please initialize taskmaster-ai into my project?
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Use common commands** directly through your AI assistant:
|
||||||
|
|
||||||
|
```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?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option 2: Using Command Line
|
||||||
|
|
||||||
|
#### Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install globally
|
# Install globally
|
||||||
@@ -66,7 +72,7 @@ npm install -g task-master-ai
|
|||||||
npm install task-master-ai
|
npm install task-master-ai
|
||||||
```
|
```
|
||||||
|
|
||||||
### Initialize a new project
|
#### Initialize a new project
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# If installed globally
|
# If installed globally
|
||||||
@@ -78,14 +84,7 @@ npx task-master-init
|
|||||||
|
|
||||||
This will prompt you for project details and set up a new project with the necessary files and structure.
|
This will prompt you for project details and set up a new project with the necessary files and structure.
|
||||||
|
|
||||||
### Important Notes
|
#### Common Commands
|
||||||
|
|
||||||
1. This package uses ES modules. Your package.json should include `"type": "module"`.
|
|
||||||
2. The Anthropic SDK version should be 0.39.0 or higher.
|
|
||||||
|
|
||||||
## Quick Start with Global Commands
|
|
||||||
|
|
||||||
After installing the package globally, you can use these CLI commands from any directory:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Initialize a new project
|
# Initialize a new project
|
||||||
@@ -104,6 +103,16 @@ task-master next
|
|||||||
task-master generate
|
task-master generate
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
For more detailed information, check out the documentation in the `docs` directory:
|
||||||
|
|
||||||
|
- [Configuration Guide](docs/configuration.md) - Set up environment variables and customize Task Master
|
||||||
|
- [Tutorial](docs/tutorial.md) - Step-by-step guide to getting started with Task Master
|
||||||
|
- [Command Reference](docs/command-reference.md) - Complete list of all available commands
|
||||||
|
- [Task Structure](docs/task-structure.md) - Understanding the task format and features
|
||||||
|
- [Example Interactions](docs/examples.md) - Common Cursor AI interaction examples
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
### If `task-master init` doesn't respond:
|
### If `task-master init` doesn't respond:
|
||||||
@@ -122,577 +131,25 @@ cd claude-task-master
|
|||||||
node scripts/init.js
|
node scripts/init.js
|
||||||
```
|
```
|
||||||
|
|
||||||
## Task Structure
|
## Star History
|
||||||
|
|
||||||
Tasks in tasks.json have the following structure:
|
[](https://www.star-history.com/#eyaltoledano/claude-task-master&Timeline)
|
||||||
|
|
||||||
- `id`: Unique identifier for the task (Example: `1`)
|
## Licensing
|
||||||
- `title`: Brief, descriptive title of the task (Example: `"Initialize Repo"`)
|
|
||||||
- `description`: Concise description of what the task involves (Example: `"Create a new repository, set up initial structure."`)
|
|
||||||
- `status`: Current state of the task (Example: `"pending"`, `"done"`, `"deferred"`)
|
|
||||||
- `dependencies`: IDs of tasks that must be completed before this task (Example: `[1, 2]`)
|
|
||||||
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending)
|
|
||||||
- This helps quickly identify which prerequisite tasks are blocking work
|
|
||||||
- `priority`: Importance level of the task (Example: `"high"`, `"medium"`, `"low"`)
|
|
||||||
- `details`: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
|
|
||||||
- `testStrategy`: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
|
|
||||||
- `subtasks`: List of smaller, more specific tasks that make up the main task (Example: `[{"id": 1, "title": "Configure OAuth", ...}]`)
|
|
||||||
|
|
||||||
## Integrating with Cursor AI
|
Task Master is licensed under the MIT License with Commons Clause. This means you can:
|
||||||
|
|
||||||
Claude Task Master is designed to work seamlessly with [Cursor AI](https://www.cursor.so/), providing a structured workflow for AI-driven development.
|
✅ **Allowed**:
|
||||||
|
|
||||||
### Setup with Cursor
|
- Use Task Master for any purpose (personal, commercial, academic)
|
||||||
|
- Modify the code
|
||||||
|
- Distribute copies
|
||||||
|
- Create and sell products built using Task Master
|
||||||
|
|
||||||
1. After initializing your project, open it in Cursor
|
❌ **Not Allowed**:
|
||||||
2. The `.cursor/rules/dev_workflow.mdc` file is automatically loaded by Cursor, providing the AI with knowledge about the task management system
|
|
||||||
3. Place your PRD document in the `scripts/` directory (e.g., `scripts/prd.txt`)
|
|
||||||
4. Open Cursor's AI chat and switch to Agent mode
|
|
||||||
|
|
||||||
### Setting up MCP in Cursor
|
- Sell Task Master itself
|
||||||
|
- Offer Task Master as a hosted service
|
||||||
|
- Create competing products based on Task Master
|
||||||
|
|
||||||
To enable enhanced task management capabilities directly within Cursor using the Model Control Protocol (MCP):
|
See the [LICENSE](LICENSE) file for the complete license text and [licensing details](docs/licensing.md) for more information.
|
||||||
|
|
||||||
1. Go to Cursor settings
|
|
||||||
2. Navigate to the MCP section
|
|
||||||
3. Click on "Add New MCP Server"
|
|
||||||
4. Configure with the following details:
|
|
||||||
- Name: "Task Master"
|
|
||||||
- Type: "Command"
|
|
||||||
- Command: "npx -y --package task-master-ai task-master-mcp"
|
|
||||||
5. Save the settings
|
|
||||||
|
|
||||||
Once configured, you can interact with Task Master's task management commands directly through Cursor's interface, providing a more integrated experience.
|
|
||||||
|
|
||||||
### Initial Task Generation
|
|
||||||
|
|
||||||
In Cursor's AI chat, instruct the agent to generate tasks from your PRD:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please use the task-master parse-prd command to generate tasks from my PRD. The PRD is located at scripts/prd.txt.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master parse-prd scripts/prd.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
This will:
|
|
||||||
|
|
||||||
- Parse your PRD document
|
|
||||||
- Generate a structured `tasks.json` file with tasks, dependencies, priorities, and test strategies
|
|
||||||
- The agent will understand this process due to the Cursor rules
|
|
||||||
|
|
||||||
### Generate Individual Task Files
|
|
||||||
|
|
||||||
Next, ask the agent to generate individual task files:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please generate individual task files from tasks.json
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master generate
|
|
||||||
```
|
|
||||||
|
|
||||||
This creates individual task files in the `tasks/` directory (e.g., `task_001.txt`, `task_002.txt`), making it easier to reference specific tasks.
|
|
||||||
|
|
||||||
## AI-Driven Development Workflow
|
|
||||||
|
|
||||||
The Cursor agent is pre-configured (via the rules file) to follow this workflow:
|
|
||||||
|
|
||||||
### 1. Task Discovery and Selection
|
|
||||||
|
|
||||||
Ask the agent to list available tasks:
|
|
||||||
|
|
||||||
```
|
|
||||||
What tasks are available to work on next?
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will:
|
|
||||||
|
|
||||||
- Run `task-master list` to see all tasks
|
|
||||||
- Run `task-master next` to determine the next task to work on
|
|
||||||
- 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
|
|
||||||
|
|
||||||
### 2. Task Implementation
|
|
||||||
|
|
||||||
When implementing a task, the agent will:
|
|
||||||
|
|
||||||
- Reference the task's details section for implementation specifics
|
|
||||||
- Consider dependencies on previous tasks
|
|
||||||
- Follow the project's coding standards
|
|
||||||
- Create appropriate tests based on the task's testStrategy
|
|
||||||
|
|
||||||
You can ask:
|
|
||||||
|
|
||||||
```
|
|
||||||
Let's implement task 3. What does it involve?
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Task Verification
|
|
||||||
|
|
||||||
Before marking a task as complete, verify it according to:
|
|
||||||
|
|
||||||
- The task's specified testStrategy
|
|
||||||
- Any automated tests in the codebase
|
|
||||||
- Manual verification if required
|
|
||||||
|
|
||||||
### 4. Task Completion
|
|
||||||
|
|
||||||
When a task is completed, tell the agent:
|
|
||||||
|
|
||||||
```
|
|
||||||
Task 3 is now complete. Please update its status.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master set-status --id=3 --status=done
|
|
||||||
```
|
|
||||||
|
|
||||||
### 5. Handling Implementation Drift
|
|
||||||
|
|
||||||
If during implementation, you discover that:
|
|
||||||
|
|
||||||
- The current approach differs significantly from what was planned
|
|
||||||
- Future tasks need to be modified due to current implementation choices
|
|
||||||
- New dependencies or requirements have emerged
|
|
||||||
|
|
||||||
Tell the agent:
|
|
||||||
|
|
||||||
```
|
|
||||||
We've changed our approach. We're now using Express instead of Fastify. Please update all future tasks to reflect this change.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master update --from=4 --prompt="Now we are using Express instead of Fastify."
|
|
||||||
```
|
|
||||||
|
|
||||||
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
|
|
||||||
|
|
||||||
### 6. Breaking Down Complex Tasks
|
|
||||||
|
|
||||||
For complex tasks that need more granularity:
|
|
||||||
|
|
||||||
```
|
|
||||||
Task 5 seems complex. Can you break it down into subtasks?
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master expand --id=5 --num=3
|
|
||||||
```
|
|
||||||
|
|
||||||
You can provide additional context:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please break down task 5 with a focus on security considerations.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master expand --id=5 --prompt="Focus on security aspects"
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also expand all pending tasks:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please break down all pending tasks into subtasks.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master expand --all
|
|
||||||
```
|
|
||||||
|
|
||||||
For research-backed subtask generation using Perplexity AI:
|
|
||||||
|
|
||||||
```
|
|
||||||
Please break down task 5 using research-backed generation.
|
|
||||||
```
|
|
||||||
|
|
||||||
The agent will execute:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task-master expand --id=5 --research
|
|
||||||
```
|
|
||||||
|
|
||||||
## Command Reference
|
|
||||||
|
|
||||||
Here's a comprehensive reference of all available commands:
|
|
||||||
|
|
||||||
### Parse PRD
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Parse a PRD file and generate tasks
|
|
||||||
task-master parse-prd <prd-file.txt>
|
|
||||||
|
|
||||||
# Limit the number of tasks generated
|
|
||||||
task-master parse-prd <prd-file.txt> --num-tasks=10
|
|
||||||
```
|
|
||||||
|
|
||||||
### List Tasks
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# List all tasks
|
|
||||||
task-master list
|
|
||||||
|
|
||||||
# List tasks with a specific status
|
|
||||||
task-master list --status=<status>
|
|
||||||
|
|
||||||
# List tasks with subtasks
|
|
||||||
task-master list --with-subtasks
|
|
||||||
|
|
||||||
# List tasks with a specific status and include subtasks
|
|
||||||
task-master list --status=<status> --with-subtasks
|
|
||||||
```
|
|
||||||
|
|
||||||
### Show Next Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Show the next task to work on based on dependencies and status
|
|
||||||
task-master next
|
|
||||||
```
|
|
||||||
|
|
||||||
### Show Specific Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Show details of a specific task
|
|
||||||
task-master show <id>
|
|
||||||
# or
|
|
||||||
task-master show --id=<id>
|
|
||||||
|
|
||||||
# View a specific subtask (e.g., subtask 2 of task 1)
|
|
||||||
task-master show 1.2
|
|
||||||
```
|
|
||||||
|
|
||||||
### Update Tasks
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Update tasks from a specific ID and provide context
|
|
||||||
task-master update --from=<id> --prompt="<prompt>"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Update a Specific Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Update a single task by ID with new information
|
|
||||||
task-master update-task --id=<id> --prompt="<prompt>"
|
|
||||||
|
|
||||||
# Use research-backed updates with Perplexity AI
|
|
||||||
task-master update-task --id=<id> --prompt="<prompt>" --research
|
|
||||||
```
|
|
||||||
|
|
||||||
### Update a Subtask
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Append additional information to a specific subtask
|
|
||||||
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>"
|
|
||||||
|
|
||||||
# Example: Add details about API rate limiting to subtask 2 of task 5
|
|
||||||
task-master update-subtask --id=5.2 --prompt="Add rate limiting of 100 requests per minute"
|
|
||||||
|
|
||||||
# Use research-backed updates with Perplexity AI
|
|
||||||
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>" --research
|
|
||||||
```
|
|
||||||
|
|
||||||
Unlike the `update-task` command which replaces task information, the `update-subtask` command _appends_ new information to the existing subtask details, marking it with a timestamp. This is useful for iteratively enhancing subtasks while preserving the original content.
|
|
||||||
|
|
||||||
### Remove Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Remove a task permanently
|
|
||||||
task-master remove-task --id=<id>
|
|
||||||
|
|
||||||
# Remove a subtask permanently
|
|
||||||
task-master remove-task --id=<parentId.subtaskId>
|
|
||||||
|
|
||||||
# Skip the confirmation prompt
|
|
||||||
task-master remove-task --id=<id> --yes
|
|
||||||
```
|
|
||||||
|
|
||||||
The `remove-task` command permanently deletes a task or subtask from `tasks.json`. It also automatically cleans up any references to the deleted task in other tasks' dependencies. Consider using 'blocked', 'cancelled', or 'deferred' status instead if you want to keep the task for reference.
|
|
||||||
|
|
||||||
### Generate Task Files
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Generate individual task files from tasks.json
|
|
||||||
task-master generate
|
|
||||||
```
|
|
||||||
|
|
||||||
### Set Task Status
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Set status of a single task
|
|
||||||
task-master set-status --id=<id> --status=<status>
|
|
||||||
|
|
||||||
# Set status for multiple tasks
|
|
||||||
task-master set-status --id=1,2,3 --status=<status>
|
|
||||||
|
|
||||||
# Set status for subtasks
|
|
||||||
task-master set-status --id=1.1,1.2 --status=<status>
|
|
||||||
```
|
|
||||||
|
|
||||||
When marking a task as "done", all of its subtasks will automatically be marked as "done" as well.
|
|
||||||
|
|
||||||
### Expand Tasks
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Expand a specific task with subtasks
|
|
||||||
task-master expand --id=<id> --num=<number>
|
|
||||||
|
|
||||||
# Expand with additional context
|
|
||||||
task-master expand --id=<id> --prompt="<context>"
|
|
||||||
|
|
||||||
# Expand all pending tasks
|
|
||||||
task-master expand --all
|
|
||||||
|
|
||||||
# Force regeneration of subtasks for tasks that already have them
|
|
||||||
task-master expand --all --force
|
|
||||||
|
|
||||||
# Research-backed subtask generation for a specific task
|
|
||||||
task-master expand --id=<id> --research
|
|
||||||
|
|
||||||
# Research-backed generation for all tasks
|
|
||||||
task-master expand --all --research
|
|
||||||
```
|
|
||||||
|
|
||||||
### Clear Subtasks
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Clear subtasks from a specific task
|
|
||||||
task-master clear-subtasks --id=<id>
|
|
||||||
|
|
||||||
# Clear subtasks from multiple tasks
|
|
||||||
task-master clear-subtasks --id=1,2,3
|
|
||||||
|
|
||||||
# Clear subtasks from all tasks
|
|
||||||
task-master clear-subtasks --all
|
|
||||||
```
|
|
||||||
|
|
||||||
### Analyze Task Complexity
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Analyze complexity of all tasks
|
|
||||||
task-master analyze-complexity
|
|
||||||
|
|
||||||
# Save report to a custom location
|
|
||||||
task-master analyze-complexity --output=my-report.json
|
|
||||||
|
|
||||||
# Use a specific LLM model
|
|
||||||
task-master analyze-complexity --model=claude-3-opus-20240229
|
|
||||||
|
|
||||||
# Set a custom complexity threshold (1-10)
|
|
||||||
task-master analyze-complexity --threshold=6
|
|
||||||
|
|
||||||
# Use an alternative tasks file
|
|
||||||
task-master analyze-complexity --file=custom-tasks.json
|
|
||||||
|
|
||||||
# Use Perplexity AI for research-backed complexity analysis
|
|
||||||
task-master analyze-complexity --research
|
|
||||||
```
|
|
||||||
|
|
||||||
### View Complexity Report
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Display the task complexity analysis report
|
|
||||||
task-master complexity-report
|
|
||||||
|
|
||||||
# View a report at a custom location
|
|
||||||
task-master complexity-report --file=my-report.json
|
|
||||||
```
|
|
||||||
|
|
||||||
### Managing Task Dependencies
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Add a dependency to a task
|
|
||||||
task-master add-dependency --id=<id> --depends-on=<id>
|
|
||||||
|
|
||||||
# Remove a dependency from a task
|
|
||||||
task-master remove-dependency --id=<id> --depends-on=<id>
|
|
||||||
|
|
||||||
# Validate dependencies without fixing them
|
|
||||||
task-master validate-dependencies
|
|
||||||
|
|
||||||
# Find and fix invalid dependencies automatically
|
|
||||||
task-master fix-dependencies
|
|
||||||
```
|
|
||||||
|
|
||||||
### Add a New Task
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Add a new task using AI
|
|
||||||
task-master add-task --prompt="Description of the new task"
|
|
||||||
|
|
||||||
# Add a task with dependencies
|
|
||||||
task-master add-task --prompt="Description" --dependencies=1,2,3
|
|
||||||
|
|
||||||
# Add a task with priority
|
|
||||||
task-master add-task --prompt="Description" --priority=high
|
|
||||||
```
|
|
||||||
|
|
||||||
## Feature Details
|
|
||||||
|
|
||||||
### Analyzing Task Complexity
|
|
||||||
|
|
||||||
The `analyze-complexity` command:
|
|
||||||
|
|
||||||
- Analyzes each task using AI to assess its complexity on a scale of 1-10
|
|
||||||
- Recommends optimal number of subtasks based on configured DEFAULT_SUBTASKS
|
|
||||||
- Generates tailored prompts for expanding each task
|
|
||||||
- Creates a comprehensive JSON report with ready-to-use commands
|
|
||||||
- Saves the report to scripts/task-complexity-report.json by default
|
|
||||||
|
|
||||||
The generated report contains:
|
|
||||||
|
|
||||||
- Complexity analysis for each task (scored 1-10)
|
|
||||||
- Recommended number of subtasks based on complexity
|
|
||||||
- AI-generated expansion prompts customized for each task
|
|
||||||
- Ready-to-run expansion commands directly within each task analysis
|
|
||||||
|
|
||||||
### Viewing Complexity Report
|
|
||||||
|
|
||||||
The `complexity-report` command:
|
|
||||||
|
|
||||||
- Displays a formatted, easy-to-read version of the complexity analysis report
|
|
||||||
- Shows tasks organized by complexity score (highest to lowest)
|
|
||||||
- Provides complexity distribution statistics (low, medium, high)
|
|
||||||
- Highlights tasks recommended for expansion based on threshold score
|
|
||||||
- Includes ready-to-use expansion commands for each complex task
|
|
||||||
- If no report exists, offers to generate one on the spot
|
|
||||||
|
|
||||||
### Smart Task Expansion
|
|
||||||
|
|
||||||
The `expand` command automatically checks for and uses the complexity report:
|
|
||||||
|
|
||||||
When a complexity report exists:
|
|
||||||
|
|
||||||
- Tasks are automatically expanded using the recommended subtask count and prompts
|
|
||||||
- When expanding all tasks, they're processed in order of complexity (highest first)
|
|
||||||
- Research-backed generation is preserved from the complexity analysis
|
|
||||||
- You can still override recommendations with explicit command-line options
|
|
||||||
|
|
||||||
Example workflow:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Generate the complexity analysis report with research capabilities
|
|
||||||
task-master analyze-complexity --research
|
|
||||||
|
|
||||||
# Review the report in a readable format
|
|
||||||
task-master complexity-report
|
|
||||||
|
|
||||||
# Expand tasks using the optimized recommendations
|
|
||||||
task-master expand --id=8
|
|
||||||
# or expand all tasks
|
|
||||||
task-master expand --all
|
|
||||||
```
|
|
||||||
|
|
||||||
### Finding the Next Task
|
|
||||||
|
|
||||||
The `next` command:
|
|
||||||
|
|
||||||
- Identifies tasks that are pending/in-progress and have all dependencies satisfied
|
|
||||||
- Prioritizes tasks by priority level, dependency count, and task ID
|
|
||||||
- Displays comprehensive information about the selected task:
|
|
||||||
- Basic task details (ID, title, priority, dependencies)
|
|
||||||
- Implementation details
|
|
||||||
- Subtasks (if they exist)
|
|
||||||
- Provides contextual suggested actions:
|
|
||||||
- Command to mark the task as in-progress
|
|
||||||
- Command to mark the task as done
|
|
||||||
- Commands for working with subtasks
|
|
||||||
|
|
||||||
### Viewing Specific Task Details
|
|
||||||
|
|
||||||
The `show` command:
|
|
||||||
|
|
||||||
- Displays comprehensive details about a specific task or subtask
|
|
||||||
- Shows task status, priority, dependencies, and detailed implementation notes
|
|
||||||
- For parent tasks, displays all subtasks and their status
|
|
||||||
- For subtasks, shows parent task relationship
|
|
||||||
- Provides contextual action suggestions based on the task's state
|
|
||||||
- Works with both regular tasks and subtasks (using the format taskId.subtaskId)
|
|
||||||
|
|
||||||
## Best Practices for AI-Driven Development
|
|
||||||
|
|
||||||
1. **Start with a detailed PRD**: The more detailed your PRD, the better the generated tasks will be.
|
|
||||||
|
|
||||||
2. **Review generated tasks**: After parsing the PRD, review the tasks to ensure they make sense and have appropriate dependencies.
|
|
||||||
|
|
||||||
3. **Analyze task complexity**: Use the complexity analysis feature to identify which tasks should be broken down further.
|
|
||||||
|
|
||||||
4. **Follow the dependency chain**: Always respect task dependencies - the Cursor agent will help with this.
|
|
||||||
|
|
||||||
5. **Update as you go**: If your implementation diverges from the plan, use the update command to keep future tasks aligned with your current approach.
|
|
||||||
|
|
||||||
6. **Break down complex tasks**: Use the expand command to break down complex tasks into manageable subtasks.
|
|
||||||
|
|
||||||
7. **Regenerate task files**: After any updates to tasks.json, regenerate the task files to keep them in sync.
|
|
||||||
|
|
||||||
8. **Communicate context to the agent**: When asking the Cursor agent to help with a task, provide context about what you're trying to achieve.
|
|
||||||
|
|
||||||
9. **Validate dependencies**: Periodically run the validate-dependencies command to check for invalid or circular dependencies.
|
|
||||||
|
|
||||||
## Example Cursor AI Interactions
|
|
||||||
|
|
||||||
### Starting a new project
|
|
||||||
|
|
||||||
```
|
|
||||||
I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
|
|
||||||
Can you help me parse it and set up the initial tasks?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Working on tasks
|
|
||||||
|
|
||||||
```
|
|
||||||
What's the next task I should work on? Please consider dependencies and priorities.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Implementing a specific task
|
|
||||||
|
|
||||||
```
|
|
||||||
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Managing subtasks
|
|
||||||
|
|
||||||
```
|
|
||||||
I need to regenerate the subtasks for task 3 with a different approach. Can you help me clear and regenerate them?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Handling changes
|
|
||||||
|
|
||||||
```
|
|
||||||
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Completing work
|
|
||||||
|
|
||||||
```
|
|
||||||
I've finished implementing the authentication system described in task 2. All tests are passing.
|
|
||||||
Please mark it as complete and tell me what I should work on next.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Analyzing complexity
|
|
||||||
|
|
||||||
```
|
|
||||||
Can you analyze the complexity of our tasks to help me understand which ones need to be broken down further?
|
|
||||||
```
|
|
||||||
|
|
||||||
### Viewing complexity report
|
|
||||||
|
|
||||||
```
|
|
||||||
Can you show me the complexity report in a more readable format?
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -21,9 +21,11 @@ In an AI-driven development process—particularly with tools like [Cursor](http
|
|||||||
The script can be configured through environment variables in a `.env` file at the root of the project:
|
The script can be configured through environment variables in a `.env` file at the root of the project:
|
||||||
|
|
||||||
### Required Configuration
|
### Required Configuration
|
||||||
|
|
||||||
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
|
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
|
||||||
|
|
||||||
### Optional Configuration
|
### Optional Configuration
|
||||||
|
|
||||||
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
|
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
|
||||||
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
|
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
|
||||||
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
|
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
|
||||||
@@ -39,6 +41,7 @@ The script can be configured through environment variables in a `.env` file at t
|
|||||||
## How It Works
|
## How It Works
|
||||||
|
|
||||||
1. **`tasks.json`**:
|
1. **`tasks.json`**:
|
||||||
|
|
||||||
- A JSON file at the project root containing an array of tasks (each with `id`, `title`, `description`, `status`, etc.).
|
- A JSON file at the project root containing an array of tasks (each with `id`, `title`, `description`, `status`, etc.).
|
||||||
- The `meta` field can store additional info like the project's name, version, or reference to the PRD.
|
- The `meta` field can store additional info like the project's name, version, or reference to the PRD.
|
||||||
- Tasks can have `subtasks` for more detailed implementation steps.
|
- Tasks can have `subtasks` for more detailed implementation steps.
|
||||||
@@ -111,6 +114,7 @@ task-master update --file=custom-tasks.json --from=5 --prompt="Change database f
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- The `--prompt` parameter is required and should explain the changes or new context
|
- The `--prompt` parameter is required and should explain the changes or new context
|
||||||
- Only tasks that aren't marked as 'done' will be updated
|
- Only tasks that aren't marked as 'done' will be updated
|
||||||
- Tasks with ID >= the specified --from value will be updated
|
- Tasks with ID >= the specified --from value will be updated
|
||||||
@@ -134,6 +138,7 @@ task-master set-status --id=1,2,3 --status=done
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- When marking a parent task as "done", all of its subtasks will automatically be marked as "done" as well
|
- When marking a parent task as "done", all of its subtasks will automatically be marked as "done" as well
|
||||||
- Common status values are 'done', 'pending', and 'deferred', but any string is accepted
|
- Common status values are 'done', 'pending', and 'deferred', but any string is accepted
|
||||||
- You can specify multiple task IDs by separating them with commas
|
- You can specify multiple task IDs by separating them with commas
|
||||||
@@ -183,6 +188,7 @@ task-master clear-subtasks --all
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- After clearing subtasks, task files are automatically regenerated
|
- After clearing subtasks, task files are automatically regenerated
|
||||||
- This is useful when you want to regenerate subtasks with a different approach
|
- This is useful when you want to regenerate subtasks with a different approach
|
||||||
- Can be combined with the `expand` command to immediately generate new subtasks
|
- Can be combined with the `expand` command to immediately generate new subtasks
|
||||||
@@ -198,6 +204,7 @@ The script integrates with two AI services:
|
|||||||
The Perplexity integration uses the OpenAI client to connect to Perplexity's API, which provides enhanced research capabilities for generating more informed subtasks. If the Perplexity API is unavailable or encounters an error, the script will automatically fall back to using Anthropic's Claude.
|
The Perplexity integration uses the OpenAI client to connect to Perplexity's API, which provides enhanced research capabilities for generating more informed subtasks. If the Perplexity API is unavailable or encounters an error, the script will automatically fall back to using Anthropic's Claude.
|
||||||
|
|
||||||
To use the Perplexity integration:
|
To use the Perplexity integration:
|
||||||
|
|
||||||
1. Obtain a Perplexity API key
|
1. Obtain a Perplexity API key
|
||||||
2. Add `PERPLEXITY_API_KEY` to your `.env` file
|
2. Add `PERPLEXITY_API_KEY` to your `.env` file
|
||||||
3. Optionally specify `PERPLEXITY_MODEL` in your `.env` file (default: "sonar-medium-online")
|
3. Optionally specify `PERPLEXITY_MODEL` in your `.env` file (default: "sonar-medium-online")
|
||||||
@@ -206,6 +213,7 @@ To use the Perplexity integration:
|
|||||||
## Logging
|
## Logging
|
||||||
|
|
||||||
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
|
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
|
||||||
|
|
||||||
- `debug`: Detailed information, typically useful for troubleshooting
|
- `debug`: Detailed information, typically useful for troubleshooting
|
||||||
- `info`: Confirmation that things are working as expected (default)
|
- `info`: Confirmation that things are working as expected (default)
|
||||||
- `warn`: Warning messages that don't prevent execution
|
- `warn`: Warning messages that don't prevent execution
|
||||||
@@ -228,17 +236,20 @@ task-master remove-dependency --id=<id> --depends-on=<id>
|
|||||||
These commands:
|
These commands:
|
||||||
|
|
||||||
1. **Allow precise dependency management**:
|
1. **Allow precise dependency management**:
|
||||||
|
|
||||||
- Add dependencies between tasks with automatic validation
|
- Add dependencies between tasks with automatic validation
|
||||||
- Remove dependencies when they're no longer needed
|
- Remove dependencies when they're no longer needed
|
||||||
- Update task files automatically after changes
|
- Update task files automatically after changes
|
||||||
|
|
||||||
2. **Include validation checks**:
|
2. **Include validation checks**:
|
||||||
|
|
||||||
- Prevent circular dependencies (a task depending on itself)
|
- Prevent circular dependencies (a task depending on itself)
|
||||||
- Prevent duplicate dependencies
|
- Prevent duplicate dependencies
|
||||||
- Verify that both tasks exist before adding/removing dependencies
|
- Verify that both tasks exist before adding/removing dependencies
|
||||||
- Check if dependencies exist before attempting to remove them
|
- Check if dependencies exist before attempting to remove them
|
||||||
|
|
||||||
3. **Provide clear feedback**:
|
3. **Provide clear feedback**:
|
||||||
|
|
||||||
- Success messages confirm when dependencies are added/removed
|
- Success messages confirm when dependencies are added/removed
|
||||||
- Error messages explain why operations failed (if applicable)
|
- Error messages explain why operations failed (if applicable)
|
||||||
|
|
||||||
@@ -263,6 +274,7 @@ task-master validate-dependencies --file=custom-tasks.json
|
|||||||
```
|
```
|
||||||
|
|
||||||
This command:
|
This command:
|
||||||
|
|
||||||
- Scans all tasks and subtasks for non-existent dependencies
|
- Scans all tasks and subtasks for non-existent dependencies
|
||||||
- Identifies potential self-dependencies (tasks referencing themselves)
|
- Identifies potential self-dependencies (tasks referencing themselves)
|
||||||
- Reports all found issues without modifying files
|
- Reports all found issues without modifying files
|
||||||
@@ -284,6 +296,7 @@ task-master fix-dependencies --file=custom-tasks.json
|
|||||||
```
|
```
|
||||||
|
|
||||||
This command:
|
This command:
|
||||||
|
|
||||||
1. **Validates all dependencies** across tasks and subtasks
|
1. **Validates all dependencies** across tasks and subtasks
|
||||||
2. **Automatically removes**:
|
2. **Automatically removes**:
|
||||||
- References to non-existent tasks and subtasks
|
- References to non-existent tasks and subtasks
|
||||||
@@ -321,6 +334,7 @@ task-master analyze-complexity --research
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- The command uses Claude to analyze each task's complexity (or Perplexity with --research flag)
|
- The command uses Claude to analyze each task's complexity (or Perplexity with --research flag)
|
||||||
- Tasks are scored on a scale of 1-10
|
- Tasks are scored on a scale of 1-10
|
||||||
- Each task receives a recommended number of subtasks based on DEFAULT_SUBTASKS configuration
|
- Each task receives a recommended number of subtasks based on DEFAULT_SUBTASKS configuration
|
||||||
@@ -345,33 +359,35 @@ task-master expand --id=8 --num=5 --prompt="Custom prompt"
|
|||||||
```
|
```
|
||||||
|
|
||||||
When a complexity report exists:
|
When a complexity report exists:
|
||||||
|
|
||||||
- The `expand` command will use the recommended subtask count from the report (unless overridden)
|
- The `expand` command will use the recommended subtask count from the report (unless overridden)
|
||||||
- It will use the tailored expansion prompt from the report (unless a custom prompt is provided)
|
- It will use the tailored expansion prompt from the report (unless a custom prompt is provided)
|
||||||
- When using `--all`, tasks are sorted by complexity score (highest first)
|
- When using `--all`, tasks are sorted by complexity score (highest first)
|
||||||
- The `--research` flag is preserved from the complexity analysis to expansion
|
- The `--research` flag is preserved from the complexity analysis to expansion
|
||||||
|
|
||||||
The output report structure is:
|
The output report structure is:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"meta": {
|
"meta": {
|
||||||
"generatedAt": "2023-06-15T12:34:56.789Z",
|
"generatedAt": "2023-06-15T12:34:56.789Z",
|
||||||
"tasksAnalyzed": 20,
|
"tasksAnalyzed": 20,
|
||||||
"thresholdScore": 5,
|
"thresholdScore": 5,
|
||||||
"projectName": "Your Project Name",
|
"projectName": "Your Project Name",
|
||||||
"usedResearch": true
|
"usedResearch": true
|
||||||
},
|
},
|
||||||
"complexityAnalysis": [
|
"complexityAnalysis": [
|
||||||
{
|
{
|
||||||
"taskId": 8,
|
"taskId": 8,
|
||||||
"taskTitle": "Develop Implementation Drift Handling",
|
"taskTitle": "Develop Implementation Drift Handling",
|
||||||
"complexityScore": 9.5,
|
"complexityScore": 9.5,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 6,
|
||||||
"expansionPrompt": "Create subtasks that handle detecting...",
|
"expansionPrompt": "Create subtasks that handle detecting...",
|
||||||
"reasoning": "This task requires sophisticated logic...",
|
"reasoning": "This task requires sophisticated logic...",
|
||||||
"expansionCommand": "task-master expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
|
"expansionCommand": "task-master expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
|
||||||
},
|
}
|
||||||
// More tasks sorted by complexity score (highest first)
|
// More tasks sorted by complexity score (highest first)
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -20,11 +20,11 @@ const args = process.argv.slice(2);
|
|||||||
|
|
||||||
// Spawn the init script with all arguments
|
// Spawn the init script with all arguments
|
||||||
const child = spawn('node', [initScriptPath, ...args], {
|
const child = spawn('node', [initScriptPath, ...args], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: process.cwd()
|
cwd: process.cwd()
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle exit
|
// Handle exit
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
process.exit(code);
|
process.exit(code);
|
||||||
});
|
});
|
||||||
@@ -44,30 +44,36 @@ const initScriptPath = resolve(__dirname, '../scripts/init.js');
|
|||||||
|
|
||||||
// Helper function to run dev.js with arguments
|
// Helper function to run dev.js with arguments
|
||||||
function runDevScript(args) {
|
function runDevScript(args) {
|
||||||
// Debug: Show the transformed arguments when DEBUG=1 is set
|
// Debug: Show the transformed arguments when DEBUG=1 is set
|
||||||
if (process.env.DEBUG === '1') {
|
if (process.env.DEBUG === '1') {
|
||||||
console.error('\nDEBUG - CLI Wrapper Analysis:');
|
console.error('\nDEBUG - CLI Wrapper Analysis:');
|
||||||
console.error('- Original command: ' + process.argv.join(' '));
|
console.error('- Original command: ' + process.argv.join(' '));
|
||||||
console.error('- Transformed args: ' + args.join(' '));
|
console.error('- Transformed args: ' + args.join(' '));
|
||||||
console.error('- dev.js will receive: node ' + devScriptPath + ' ' + args.join(' ') + '\n');
|
console.error(
|
||||||
}
|
'- dev.js will receive: node ' +
|
||||||
|
devScriptPath +
|
||||||
|
' ' +
|
||||||
|
args.join(' ') +
|
||||||
|
'\n'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// For testing: If TEST_MODE is set, just print args and exit
|
// For testing: If TEST_MODE is set, just print args and exit
|
||||||
if (process.env.TEST_MODE === '1') {
|
if (process.env.TEST_MODE === '1') {
|
||||||
console.log('Would execute:');
|
console.log('Would execute:');
|
||||||
console.log(`node ${devScriptPath} ${args.join(' ')}`);
|
console.log(`node ${devScriptPath} ${args.join(' ')}`);
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const child = spawn('node', [devScriptPath, ...args], {
|
const child = spawn('node', [devScriptPath, ...args], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: process.cwd()
|
cwd: process.cwd()
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
process.exit(code);
|
process.exit(code);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to detect camelCase and convert to kebab-case
|
// Helper function to detect camelCase and convert to kebab-case
|
||||||
@@ -79,228 +85,239 @@ const toKebabCase = (str) => str.replace(/([A-Z])/g, '-$1').toLowerCase();
|
|||||||
* @returns {Function} Wrapper action function
|
* @returns {Function} Wrapper action function
|
||||||
*/
|
*/
|
||||||
function createDevScriptAction(commandName) {
|
function createDevScriptAction(commandName) {
|
||||||
return (options, cmd) => {
|
return (options, cmd) => {
|
||||||
// Check for camelCase flags and error out with helpful message
|
// Check for camelCase flags and error out with helpful message
|
||||||
const camelCaseFlags = detectCamelCaseFlags(process.argv);
|
const camelCaseFlags = detectCamelCaseFlags(process.argv);
|
||||||
|
|
||||||
// If camelCase flags were found, show error and exit
|
// If camelCase flags were found, show error and exit
|
||||||
if (camelCaseFlags.length > 0) {
|
if (camelCaseFlags.length > 0) {
|
||||||
console.error('\nError: Please use kebab-case for CLI flags:');
|
console.error('\nError: Please use kebab-case for CLI flags:');
|
||||||
camelCaseFlags.forEach(flag => {
|
camelCaseFlags.forEach((flag) => {
|
||||||
console.error(` Instead of: --${flag.original}`);
|
console.error(` Instead of: --${flag.original}`);
|
||||||
console.error(` Use: --${flag.kebabCase}`);
|
console.error(` Use: --${flag.kebabCase}`);
|
||||||
});
|
});
|
||||||
console.error('\nExample: task-master parse-prd --num-tasks=5 instead of --numTasks=5\n');
|
console.error(
|
||||||
process.exit(1);
|
'\nExample: task-master parse-prd --num-tasks=5 instead of --numTasks=5\n'
|
||||||
}
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
// Since we've ensured no camelCase flags, we can now just:
|
// Since we've ensured no camelCase flags, we can now just:
|
||||||
// 1. Start with the command name
|
// 1. Start with the command name
|
||||||
const args = [commandName];
|
const args = [commandName];
|
||||||
|
|
||||||
// 3. Get positional arguments and explicit flags from the command line
|
// 3. Get positional arguments and explicit flags from the command line
|
||||||
const commandArgs = [];
|
const commandArgs = [];
|
||||||
const positionals = new Set(); // Track positional args we've seen
|
const positionals = new Set(); // Track positional args we've seen
|
||||||
|
|
||||||
// Find the command in raw process.argv to extract args
|
// Find the command in raw process.argv to extract args
|
||||||
const commandIndex = process.argv.indexOf(commandName);
|
const commandIndex = process.argv.indexOf(commandName);
|
||||||
if (commandIndex !== -1) {
|
if (commandIndex !== -1) {
|
||||||
// Process all args after the command name
|
// Process all args after the command name
|
||||||
for (let i = commandIndex + 1; i < process.argv.length; i++) {
|
for (let i = commandIndex + 1; i < process.argv.length; i++) {
|
||||||
const arg = process.argv[i];
|
const arg = process.argv[i];
|
||||||
|
|
||||||
if (arg.startsWith('--')) {
|
if (arg.startsWith('--')) {
|
||||||
// It's a flag - pass through as is
|
// It's a flag - pass through as is
|
||||||
commandArgs.push(arg);
|
commandArgs.push(arg);
|
||||||
// Skip the next arg if this is a flag with a value (not --flag=value format)
|
// Skip the next arg if this is a flag with a value (not --flag=value format)
|
||||||
if (!arg.includes('=') &&
|
if (
|
||||||
i + 1 < process.argv.length &&
|
!arg.includes('=') &&
|
||||||
!process.argv[i+1].startsWith('--')) {
|
i + 1 < process.argv.length &&
|
||||||
commandArgs.push(process.argv[++i]);
|
!process.argv[i + 1].startsWith('--')
|
||||||
}
|
) {
|
||||||
} else if (!positionals.has(arg)) {
|
commandArgs.push(process.argv[++i]);
|
||||||
// It's a positional argument we haven't seen
|
}
|
||||||
commandArgs.push(arg);
|
} else if (!positionals.has(arg)) {
|
||||||
positionals.add(arg);
|
// It's a positional argument we haven't seen
|
||||||
}
|
commandArgs.push(arg);
|
||||||
}
|
positionals.add(arg);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Add all command line args we collected
|
// Add all command line args we collected
|
||||||
args.push(...commandArgs);
|
args.push(...commandArgs);
|
||||||
|
|
||||||
// 4. Add default options from Commander if not specified on command line
|
// 4. Add default options from Commander if not specified on command line
|
||||||
// Track which options we've seen on the command line
|
// Track which options we've seen on the command line
|
||||||
const userOptions = new Set();
|
const userOptions = new Set();
|
||||||
for (const arg of commandArgs) {
|
for (const arg of commandArgs) {
|
||||||
if (arg.startsWith('--')) {
|
if (arg.startsWith('--')) {
|
||||||
// Extract option name (without -- and value)
|
// Extract option name (without -- and value)
|
||||||
const name = arg.split('=')[0].slice(2);
|
const name = arg.split('=')[0].slice(2);
|
||||||
userOptions.add(name);
|
userOptions.add(name);
|
||||||
|
|
||||||
// Add the kebab-case version too, to prevent duplicates
|
// Add the kebab-case version too, to prevent duplicates
|
||||||
const kebabName = name.replace(/([A-Z])/g, '-$1').toLowerCase();
|
const kebabName = name.replace(/([A-Z])/g, '-$1').toLowerCase();
|
||||||
userOptions.add(kebabName);
|
userOptions.add(kebabName);
|
||||||
|
|
||||||
// Add the camelCase version as well
|
// Add the camelCase version as well
|
||||||
const camelName = kebabName.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
const camelName = kebabName.replace(/-([a-z])/g, (_, letter) =>
|
||||||
userOptions.add(camelName);
|
letter.toUpperCase()
|
||||||
}
|
);
|
||||||
}
|
userOptions.add(camelName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Add Commander-provided defaults for options not specified by user
|
// Add Commander-provided defaults for options not specified by user
|
||||||
Object.entries(options).forEach(([key, value]) => {
|
Object.entries(options).forEach(([key, value]) => {
|
||||||
// Debug output to see what keys we're getting
|
// Debug output to see what keys we're getting
|
||||||
if (process.env.DEBUG === '1') {
|
if (process.env.DEBUG === '1') {
|
||||||
console.error(`DEBUG - Processing option: ${key} = ${value}`);
|
console.error(`DEBUG - Processing option: ${key} = ${value}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Special case for numTasks > num-tasks (a known problem case)
|
// Special case for numTasks > num-tasks (a known problem case)
|
||||||
if (key === 'numTasks') {
|
if (key === 'numTasks') {
|
||||||
if (process.env.DEBUG === '1') {
|
if (process.env.DEBUG === '1') {
|
||||||
console.error('DEBUG - Converting numTasks to num-tasks');
|
console.error('DEBUG - Converting numTasks to num-tasks');
|
||||||
}
|
}
|
||||||
if (!userOptions.has('num-tasks') && !userOptions.has('numTasks')) {
|
if (!userOptions.has('num-tasks') && !userOptions.has('numTasks')) {
|
||||||
args.push(`--num-tasks=${value}`);
|
args.push(`--num-tasks=${value}`);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip built-in Commander properties and options the user provided
|
// Skip built-in Commander properties and options the user provided
|
||||||
if (['parent', 'commands', 'options', 'rawArgs'].includes(key) || userOptions.has(key)) {
|
if (
|
||||||
return;
|
['parent', 'commands', 'options', 'rawArgs'].includes(key) ||
|
||||||
}
|
userOptions.has(key)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Also check the kebab-case version of this key
|
// Also check the kebab-case version of this key
|
||||||
const kebabKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
|
const kebabKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
|
||||||
if (userOptions.has(kebabKey)) {
|
if (userOptions.has(kebabKey)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add default values, using kebab-case for the parameter name
|
// Add default values, using kebab-case for the parameter name
|
||||||
if (value !== undefined) {
|
if (value !== undefined) {
|
||||||
if (typeof value === 'boolean') {
|
if (typeof value === 'boolean') {
|
||||||
if (value === true) {
|
if (value === true) {
|
||||||
args.push(`--${kebabKey}`);
|
args.push(`--${kebabKey}`);
|
||||||
} else if (value === false && key === 'generate') {
|
} else if (value === false && key === 'generate') {
|
||||||
args.push('--skip-generate');
|
args.push('--skip-generate');
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Always use kebab-case for option names
|
// Always use kebab-case for option names
|
||||||
args.push(`--${kebabKey}=${value}`);
|
args.push(`--${kebabKey}=${value}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Special handling for parent parameter (uses -p)
|
// Special handling for parent parameter (uses -p)
|
||||||
if (options.parent && !args.includes('-p') && !userOptions.has('parent')) {
|
if (options.parent && !args.includes('-p') && !userOptions.has('parent')) {
|
||||||
args.push('-p', options.parent);
|
args.push('-p', options.parent);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Debug output for troubleshooting
|
// Debug output for troubleshooting
|
||||||
if (process.env.DEBUG === '1') {
|
if (process.env.DEBUG === '1') {
|
||||||
console.error('DEBUG - Command args:', commandArgs);
|
console.error('DEBUG - Command args:', commandArgs);
|
||||||
console.error('DEBUG - User options:', Array.from(userOptions));
|
console.error('DEBUG - User options:', Array.from(userOptions));
|
||||||
console.error('DEBUG - Commander options:', options);
|
console.error('DEBUG - Commander options:', options);
|
||||||
console.error('DEBUG - Final args:', args);
|
console.error('DEBUG - Final args:', args);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run the script with our processed args
|
// Run the script with our processed args
|
||||||
runDevScript(args);
|
runDevScript(args);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Special case for the 'init' command which uses a different script
|
// Special case for the 'init' command which uses a different script
|
||||||
function registerInitCommand(program) {
|
function registerInitCommand(program) {
|
||||||
program
|
program
|
||||||
.command('init')
|
.command('init')
|
||||||
.description('Initialize a new project')
|
.description('Initialize a new project')
|
||||||
.option('-y, --yes', 'Skip prompts and use default values')
|
.option('-y, --yes', 'Skip prompts and use default values')
|
||||||
.option('-n, --name <name>', 'Project name')
|
.option('-n, --name <name>', 'Project name')
|
||||||
.option('-d, --description <description>', 'Project description')
|
.option('-d, --description <description>', 'Project description')
|
||||||
.option('-v, --version <version>', 'Project version')
|
.option('-v, --version <version>', 'Project version')
|
||||||
.option('-a, --author <author>', 'Author name')
|
.option('-a, --author <author>', 'Author name')
|
||||||
.option('--skip-install', 'Skip installing dependencies')
|
.option('--skip-install', 'Skip installing dependencies')
|
||||||
.option('--dry-run', 'Show what would be done without making changes')
|
.option('--dry-run', 'Show what would be done without making changes')
|
||||||
.action((options) => {
|
.action((options) => {
|
||||||
// Pass through any options to the init script
|
// Pass through any options to the init script
|
||||||
const args = ['--yes', 'name', 'description', 'version', 'author', 'skip-install', 'dry-run']
|
const args = [
|
||||||
.filter(opt => options[opt])
|
'--yes',
|
||||||
.map(opt => {
|
'name',
|
||||||
if (opt === 'yes' || opt === 'skip-install' || opt === 'dry-run') {
|
'description',
|
||||||
return `--${opt}`;
|
'version',
|
||||||
}
|
'author',
|
||||||
return `--${opt}=${options[opt]}`;
|
'skip-install',
|
||||||
});
|
'dry-run'
|
||||||
|
]
|
||||||
|
.filter((opt) => options[opt])
|
||||||
|
.map((opt) => {
|
||||||
|
if (opt === 'yes' || opt === 'skip-install' || opt === 'dry-run') {
|
||||||
|
return `--${opt}`;
|
||||||
|
}
|
||||||
|
return `--${opt}=${options[opt]}`;
|
||||||
|
});
|
||||||
|
|
||||||
const child = spawn('node', [initScriptPath, ...args], {
|
const child = spawn('node', [initScriptPath, ...args], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: process.cwd()
|
cwd: process.cwd()
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
process.exit(code);
|
process.exit(code);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set up the command-line interface
|
// Set up the command-line interface
|
||||||
const program = new Command();
|
const program = new Command();
|
||||||
|
|
||||||
program
|
program
|
||||||
.name('task-master')
|
.name('task-master')
|
||||||
.description('Claude Task Master CLI')
|
.description('Claude Task Master CLI')
|
||||||
.version(version)
|
.version(version)
|
||||||
.addHelpText('afterAll', () => {
|
.addHelpText('afterAll', () => {
|
||||||
// Use the same help display function as dev.js for consistency
|
// Use the same help display function as dev.js for consistency
|
||||||
displayHelp();
|
displayHelp();
|
||||||
return ''; // Return empty string to prevent commander's default help
|
return ''; // Return empty string to prevent commander's default help
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add custom help option to directly call our help display
|
// Add custom help option to directly call our help display
|
||||||
program.helpOption('-h, --help', 'Display help information');
|
program.helpOption('-h, --help', 'Display help information');
|
||||||
program.on('--help', () => {
|
program.on('--help', () => {
|
||||||
displayHelp();
|
displayHelp();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add special case commands
|
// Add special case commands
|
||||||
registerInitCommand(program);
|
registerInitCommand(program);
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('dev')
|
.command('dev')
|
||||||
.description('Run the dev.js script')
|
.description('Run the dev.js script')
|
||||||
.action(() => {
|
.action(() => {
|
||||||
const args = process.argv.slice(process.argv.indexOf('dev') + 1);
|
const args = process.argv.slice(process.argv.indexOf('dev') + 1);
|
||||||
runDevScript(args);
|
runDevScript(args);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Use a temporary Command instance to get all command definitions
|
// Use a temporary Command instance to get all command definitions
|
||||||
const tempProgram = new Command();
|
const tempProgram = new Command();
|
||||||
registerCommands(tempProgram);
|
registerCommands(tempProgram);
|
||||||
|
|
||||||
// For each command in the temp instance, add a modified version to our actual program
|
// For each command in the temp instance, add a modified version to our actual program
|
||||||
tempProgram.commands.forEach(cmd => {
|
tempProgram.commands.forEach((cmd) => {
|
||||||
if (['init', 'dev'].includes(cmd.name())) {
|
if (['init', 'dev'].includes(cmd.name())) {
|
||||||
// Skip commands we've already defined specially
|
// Skip commands we've already defined specially
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a new command with the same name and description
|
// Create a new command with the same name and description
|
||||||
const newCmd = program
|
const newCmd = program.command(cmd.name()).description(cmd.description());
|
||||||
.command(cmd.name())
|
|
||||||
.description(cmd.description());
|
|
||||||
|
|
||||||
// Copy all options
|
// Copy all options
|
||||||
cmd.options.forEach(opt => {
|
cmd.options.forEach((opt) => {
|
||||||
newCmd.option(
|
newCmd.option(opt.flags, opt.description, opt.defaultValue);
|
||||||
opt.flags,
|
});
|
||||||
opt.description,
|
|
||||||
opt.defaultValue
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Set the action to proxy to dev.js
|
// Set the action to proxy to dev.js
|
||||||
newCmd.action(createDevScriptAction(cmd.name()));
|
newCmd.action(createDevScriptAction(cmd.name()));
|
||||||
});
|
});
|
||||||
|
|
||||||
// Parse the command line arguments
|
// Parse the command line arguments
|
||||||
@@ -308,47 +325,56 @@ program.parse(process.argv);
|
|||||||
|
|
||||||
// Add global error handling for unknown commands and options
|
// Add global error handling for unknown commands and options
|
||||||
process.on('uncaughtException', (err) => {
|
process.on('uncaughtException', (err) => {
|
||||||
// Check if this is a commander.js unknown option error
|
// Check if this is a commander.js unknown option error
|
||||||
if (err.code === 'commander.unknownOption') {
|
if (err.code === 'commander.unknownOption') {
|
||||||
const option = err.message.match(/'([^']+)'/)?.[1];
|
const option = err.message.match(/'([^']+)'/)?.[1];
|
||||||
const commandArg = process.argv.find(arg => !arg.startsWith('-') &&
|
const commandArg = process.argv.find(
|
||||||
arg !== 'task-master' &&
|
(arg) =>
|
||||||
!arg.includes('/') &&
|
!arg.startsWith('-') &&
|
||||||
arg !== 'node');
|
arg !== 'task-master' &&
|
||||||
const command = commandArg || 'unknown';
|
!arg.includes('/') &&
|
||||||
|
arg !== 'node'
|
||||||
|
);
|
||||||
|
const command = commandArg || 'unknown';
|
||||||
|
|
||||||
console.error(chalk.red(`Error: Unknown option '${option}'`));
|
console.error(chalk.red(`Error: Unknown option '${option}'`));
|
||||||
console.error(chalk.yellow(`Run 'task-master ${command} --help' to see available options for this command`));
|
console.error(
|
||||||
process.exit(1);
|
chalk.yellow(
|
||||||
}
|
`Run 'task-master ${command} --help' to see available options for this command`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
// Check if this is a commander.js unknown command error
|
// Check if this is a commander.js unknown command error
|
||||||
if (err.code === 'commander.unknownCommand') {
|
if (err.code === 'commander.unknownCommand') {
|
||||||
const command = err.message.match(/'([^']+)'/)?.[1];
|
const command = err.message.match(/'([^']+)'/)?.[1];
|
||||||
|
|
||||||
console.error(chalk.red(`Error: Unknown command '${command}'`));
|
console.error(chalk.red(`Error: Unknown command '${command}'`));
|
||||||
console.error(chalk.yellow(`Run 'task-master --help' to see available commands`));
|
console.error(
|
||||||
process.exit(1);
|
chalk.yellow(`Run 'task-master --help' to see available commands`)
|
||||||
}
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
// Handle other uncaught exceptions
|
// Handle other uncaught exceptions
|
||||||
console.error(chalk.red(`Error: ${err.message}`));
|
console.error(chalk.red(`Error: ${err.message}`));
|
||||||
if (process.env.DEBUG === '1') {
|
if (process.env.DEBUG === '1') {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Show help if no command was provided (just 'task-master' with no args)
|
// Show help if no command was provided (just 'task-master' with no args)
|
||||||
if (process.argv.length <= 2) {
|
if (process.argv.length <= 2) {
|
||||||
displayBanner();
|
displayBanner();
|
||||||
displayHelp();
|
displayHelp();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add exports at the end of the file
|
// Add exports at the end of the file
|
||||||
if (typeof module !== 'undefined') {
|
if (typeof module !== 'undefined') {
|
||||||
module.exports = {
|
module.exports = {
|
||||||
detectCamelCaseFlags
|
detectCamelCaseFlags
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -41,39 +41,39 @@ Core functions should follow this pattern to support both CLI and MCP use:
|
|||||||
* @returns {Object|undefined} - Returns data when source is 'mcp'
|
* @returns {Object|undefined} - Returns data when source is 'mcp'
|
||||||
*/
|
*/
|
||||||
function exampleFunction(param1, param2, options = {}) {
|
function exampleFunction(param1, param2, options = {}) {
|
||||||
try {
|
try {
|
||||||
// Skip UI for MCP
|
// Skip UI for MCP
|
||||||
if (options.source !== 'mcp') {
|
if (options.source !== 'mcp') {
|
||||||
displayBanner();
|
displayBanner();
|
||||||
console.log(chalk.blue('Processing operation...'));
|
console.log(chalk.blue('Processing operation...'));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Do the core business logic
|
// Do the core business logic
|
||||||
const result = doSomething(param1, param2);
|
const result = doSomething(param1, param2);
|
||||||
|
|
||||||
// For MCP, return structured data
|
// For MCP, return structured data
|
||||||
if (options.source === 'mcp') {
|
if (options.source === 'mcp') {
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: result
|
data: result
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// For CLI, display output
|
// For CLI, display output
|
||||||
console.log(chalk.green('Operation completed successfully!'));
|
console.log(chalk.green('Operation completed successfully!'));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Handle errors based on source
|
// Handle errors based on source
|
||||||
if (options.source === 'mcp') {
|
if (options.source === 'mcp') {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message
|
error: error.message
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// CLI error handling
|
// CLI error handling
|
||||||
console.error(chalk.red(`Error: ${error.message}`));
|
console.error(chalk.red(`Error: ${error.message}`));
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -89,17 +89,17 @@ export const simpleFunction = adaptForMcp(originalFunction);
|
|||||||
|
|
||||||
// Split implementation - completely different code paths for CLI vs MCP
|
// Split implementation - completely different code paths for CLI vs MCP
|
||||||
export const complexFunction = sourceSplitFunction(
|
export const complexFunction = sourceSplitFunction(
|
||||||
// CLI version with UI
|
// CLI version with UI
|
||||||
function(param1, param2) {
|
function (param1, param2) {
|
||||||
displayBanner();
|
displayBanner();
|
||||||
console.log(`Processing ${param1}...`);
|
console.log(`Processing ${param1}...`);
|
||||||
// ... CLI implementation
|
// ... CLI implementation
|
||||||
},
|
},
|
||||||
// MCP version with structured return
|
// MCP version with structured return
|
||||||
function(param1, param2, options = {}) {
|
function (param1, param2, options = {}) {
|
||||||
// ... MCP implementation
|
// ... MCP implementation
|
||||||
return { success: true, data };
|
return { success: true, data };
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -119,39 +119,39 @@ When adding new features, follow these steps to ensure CLI and MCP compatibility
|
|||||||
```javascript
|
```javascript
|
||||||
// In scripts/modules/task-manager.js
|
// In scripts/modules/task-manager.js
|
||||||
export async function newFeature(param1, param2, options = {}) {
|
export async function newFeature(param1, param2, options = {}) {
|
||||||
try {
|
try {
|
||||||
// Source-specific UI
|
// Source-specific UI
|
||||||
if (options.source !== 'mcp') {
|
if (options.source !== 'mcp') {
|
||||||
displayBanner();
|
displayBanner();
|
||||||
console.log(chalk.blue('Running new feature...'));
|
console.log(chalk.blue('Running new feature...'));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shared core logic
|
// Shared core logic
|
||||||
const result = processFeature(param1, param2);
|
const result = processFeature(param1, param2);
|
||||||
|
|
||||||
// Source-specific return handling
|
// Source-specific return handling
|
||||||
if (options.source === 'mcp') {
|
if (options.source === 'mcp') {
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: result
|
data: result
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// CLI output
|
// CLI output
|
||||||
console.log(chalk.green('Feature completed successfully!'));
|
console.log(chalk.green('Feature completed successfully!'));
|
||||||
displayOutput(result);
|
displayOutput(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Error handling based on source
|
// Error handling based on source
|
||||||
if (options.source === 'mcp') {
|
if (options.source === 'mcp') {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message
|
error: error.message
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
console.error(chalk.red(`Error: ${error.message}`));
|
console.error(chalk.red(`Error: ${error.message}`));
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -163,12 +163,12 @@ import { newFeature } from '../../../scripts/modules/task-manager.js';
|
|||||||
|
|
||||||
// Add to exports
|
// Add to exports
|
||||||
export default {
|
export default {
|
||||||
// ... existing functions
|
// ... existing functions
|
||||||
|
|
||||||
async newFeature(args = {}, options = {}) {
|
async newFeature(args = {}, options = {}) {
|
||||||
const { param1, param2 } = args;
|
const { param1, param2 } = args;
|
||||||
return executeFunction(newFeature, [param1, param2], options);
|
return executeFunction(newFeature, [param1, param2], options);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -177,8 +177,8 @@ export default {
|
|||||||
```javascript
|
```javascript
|
||||||
// In mcp-server/src/tools/utils.js
|
// In mcp-server/src/tools/utils.js
|
||||||
const commandMap = {
|
const commandMap = {
|
||||||
// ... existing mappings
|
// ... existing mappings
|
||||||
'new-feature': 'newFeature'
|
'new-feature': 'newFeature'
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -186,53 +186,53 @@ const commandMap = {
|
|||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// In mcp-server/src/tools/newFeature.js
|
// In mcp-server/src/tools/newFeature.js
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
executeTaskMasterCommand,
|
executeTaskMasterCommand,
|
||||||
createContentResponse,
|
createContentResponse,
|
||||||
createErrorResponse,
|
createErrorResponse
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
|
|
||||||
export function registerNewFeatureTool(server) {
|
export function registerNewFeatureTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "newFeature",
|
name: 'newFeature',
|
||||||
description: "Run the new feature",
|
description: 'Run the new feature',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
param1: z.string().describe("First parameter"),
|
param1: z.string().describe('First parameter'),
|
||||||
param2: z.number().optional().describe("Second parameter"),
|
param2: z.number().optional().describe('Second parameter'),
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z.string().describe("Root directory of the project")
|
projectRoot: z.string().describe('Root directory of the project')
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log }) => {
|
execute: async (args, { log }) => {
|
||||||
try {
|
try {
|
||||||
log.info(`Running new feature with args: ${JSON.stringify(args)}`);
|
log.info(`Running new feature with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
const cmdArgs = [];
|
const cmdArgs = [];
|
||||||
if (args.param1) cmdArgs.push(`--param1=${args.param1}`);
|
if (args.param1) cmdArgs.push(`--param1=${args.param1}`);
|
||||||
if (args.param2) cmdArgs.push(`--param2=${args.param2}`);
|
if (args.param2) cmdArgs.push(`--param2=${args.param2}`);
|
||||||
if (args.file) cmdArgs.push(`--file=${args.file}`);
|
if (args.file) cmdArgs.push(`--file=${args.file}`);
|
||||||
|
|
||||||
const projectRoot = args.projectRoot;
|
const projectRoot = args.projectRoot;
|
||||||
|
|
||||||
// Execute the command
|
// Execute the command
|
||||||
const result = await executeTaskMasterCommand(
|
const result = await executeTaskMasterCommand(
|
||||||
"new-feature",
|
'new-feature',
|
||||||
log,
|
log,
|
||||||
cmdArgs,
|
cmdArgs,
|
||||||
projectRoot
|
projectRoot
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
throw new Error(result.error);
|
throw new Error(result.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
return createContentResponse(result.stdout);
|
return createContentResponse(result.stdout);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in new feature: ${error.message}`);
|
log.error(`Error in new feature: ${error.message}`);
|
||||||
return createErrorResponse(`Error in new feature: ${error.message}`);
|
return createErrorResponse(`Error in new feature: ${error.message}`);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -240,11 +240,11 @@ export function registerNewFeatureTool(server) {
|
|||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// In mcp-server/src/tools/index.js
|
// In mcp-server/src/tools/index.js
|
||||||
import { registerNewFeatureTool } from "./newFeature.js";
|
import { registerNewFeatureTool } from './newFeature.js';
|
||||||
|
|
||||||
export function registerTaskMasterTools(server) {
|
export function registerTaskMasterTools(server) {
|
||||||
// ... existing registrations
|
// ... existing registrations
|
||||||
registerNewFeatureTool(server);
|
registerNewFeatureTool(server);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
1913
context/mcp-protocol-schema-03262025.json
Normal file
1913
context/mcp-protocol-schema-03262025.json
Normal file
File diff suppressed because it is too large
Load Diff
22
docs/README.md
Normal file
22
docs/README.md
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# Task Master Documentation
|
||||||
|
|
||||||
|
Welcome to the Task Master documentation. Use the links below to navigate to the information you need:
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
- [Configuration Guide](configuration.md) - Set up environment variables and customize Task Master
|
||||||
|
- [Tutorial](tutorial.md) - Step-by-step guide to getting started with Task Master
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
- [Command Reference](command-reference.md) - Complete list of all available commands
|
||||||
|
- [Task Structure](task-structure.md) - Understanding the task format and features
|
||||||
|
|
||||||
|
## Examples & Licensing
|
||||||
|
|
||||||
|
- [Example Interactions](examples.md) - Common Cursor AI interaction examples
|
||||||
|
- [Licensing Information](licensing.md) - Detailed information about the license
|
||||||
|
|
||||||
|
## Need More Help?
|
||||||
|
|
||||||
|
If you can't find what you're looking for in these docs, please check the [main README](../README.md) or visit our [GitHub repository](https://github.com/eyaltoledano/claude-task-master).
|
||||||
@@ -7,56 +7,54 @@ This document provides examples of how to use the new AI client utilities with A
|
|||||||
```javascript
|
```javascript
|
||||||
// In your direct function implementation:
|
// In your direct function implementation:
|
||||||
import {
|
import {
|
||||||
getAnthropicClientForMCP,
|
getAnthropicClientForMCP,
|
||||||
getModelConfig,
|
getModelConfig,
|
||||||
handleClaudeError
|
handleClaudeError
|
||||||
} from '../utils/ai-client-utils.js';
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
export async function someAiOperationDirect(args, log, context) {
|
export async function someAiOperationDirect(args, log, context) {
|
||||||
try {
|
try {
|
||||||
// Initialize Anthropic client with session from context
|
// Initialize Anthropic client with session from context
|
||||||
const client = getAnthropicClientForMCP(context.session, log);
|
const client = getAnthropicClientForMCP(context.session, log);
|
||||||
|
|
||||||
// Get model configuration with defaults or session overrides
|
// Get model configuration with defaults or session overrides
|
||||||
const modelConfig = getModelConfig(context.session);
|
const modelConfig = getModelConfig(context.session);
|
||||||
|
|
||||||
// Make API call with proper error handling
|
// Make API call with proper error handling
|
||||||
try {
|
try {
|
||||||
const response = await client.messages.create({
|
const response = await client.messages.create({
|
||||||
model: modelConfig.model,
|
model: modelConfig.model,
|
||||||
max_tokens: modelConfig.maxTokens,
|
max_tokens: modelConfig.maxTokens,
|
||||||
temperature: modelConfig.temperature,
|
temperature: modelConfig.temperature,
|
||||||
messages: [
|
messages: [{ role: 'user', content: 'Your prompt here' }]
|
||||||
{ role: 'user', content: 'Your prompt here' }
|
});
|
||||||
]
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: response
|
data: response
|
||||||
};
|
};
|
||||||
} catch (apiError) {
|
} catch (apiError) {
|
||||||
// Use helper to get user-friendly error message
|
// Use helper to get user-friendly error message
|
||||||
const friendlyMessage = handleClaudeError(apiError);
|
const friendlyMessage = handleClaudeError(apiError);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_API_ERROR',
|
code: 'AI_API_ERROR',
|
||||||
message: friendlyMessage
|
message: friendlyMessage
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Handle client initialization errors
|
// Handle client initialization errors
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_CLIENT_ERROR',
|
code: 'AI_CLIENT_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -64,86 +62,85 @@ export async function someAiOperationDirect(args, log, context) {
|
|||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// In your MCP tool implementation:
|
// In your MCP tool implementation:
|
||||||
import { AsyncOperationManager, StatusCodes } from '../../utils/async-operation-manager.js';
|
import {
|
||||||
|
AsyncOperationManager,
|
||||||
|
StatusCodes
|
||||||
|
} from '../../utils/async-operation-manager.js';
|
||||||
import { someAiOperationDirect } from '../../core/direct-functions/some-ai-operation.js';
|
import { someAiOperationDirect } from '../../core/direct-functions/some-ai-operation.js';
|
||||||
|
|
||||||
export async function someAiOperation(args, context) {
|
export async function someAiOperation(args, context) {
|
||||||
const { session, mcpLog } = context;
|
const { session, mcpLog } = context;
|
||||||
const log = mcpLog || console;
|
const log = mcpLog || console;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Create operation description
|
// Create operation description
|
||||||
const operationDescription = `AI operation: ${args.someParam}`;
|
const operationDescription = `AI operation: ${args.someParam}`;
|
||||||
|
|
||||||
// Start async operation
|
// Start async operation
|
||||||
const operation = AsyncOperationManager.createOperation(
|
const operation = AsyncOperationManager.createOperation(
|
||||||
operationDescription,
|
operationDescription,
|
||||||
async (reportProgress) => {
|
async (reportProgress) => {
|
||||||
try {
|
try {
|
||||||
// Initial progress report
|
// Initial progress report
|
||||||
reportProgress({
|
reportProgress({
|
||||||
progress: 0,
|
progress: 0,
|
||||||
status: 'Starting AI operation...'
|
status: 'Starting AI operation...'
|
||||||
});
|
});
|
||||||
|
|
||||||
// Call direct function with session and progress reporting
|
// Call direct function with session and progress reporting
|
||||||
const result = await someAiOperationDirect(
|
const result = await someAiOperationDirect(args, log, {
|
||||||
args,
|
reportProgress,
|
||||||
log,
|
mcpLog: log,
|
||||||
{
|
session
|
||||||
reportProgress,
|
});
|
||||||
mcpLog: log,
|
|
||||||
session
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// Final progress update
|
// Final progress update
|
||||||
reportProgress({
|
reportProgress({
|
||||||
progress: 100,
|
progress: 100,
|
||||||
status: result.success ? 'Operation completed' : 'Operation failed',
|
status: result.success ? 'Operation completed' : 'Operation failed',
|
||||||
result: result.data,
|
result: result.data,
|
||||||
error: result.error
|
error: result.error
|
||||||
});
|
});
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Handle errors in the operation
|
// Handle errors in the operation
|
||||||
reportProgress({
|
reportProgress({
|
||||||
progress: 100,
|
progress: 100,
|
||||||
status: 'Operation failed',
|
status: 'Operation failed',
|
||||||
error: {
|
error: {
|
||||||
message: error.message,
|
message: error.message,
|
||||||
code: error.code || 'OPERATION_FAILED'
|
code: error.code || 'OPERATION_FAILED'
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// Return immediate response with operation ID
|
// Return immediate response with operation ID
|
||||||
return {
|
return {
|
||||||
status: StatusCodes.ACCEPTED,
|
status: StatusCodes.ACCEPTED,
|
||||||
body: {
|
body: {
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Operation started',
|
message: 'Operation started',
|
||||||
operationId: operation.id
|
operationId: operation.id
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Handle errors in the MCP tool
|
// Handle errors in the MCP tool
|
||||||
log.error(`Error in someAiOperation: ${error.message}`);
|
log.error(`Error in someAiOperation: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
status: StatusCodes.INTERNAL_SERVER_ERROR,
|
status: StatusCodes.INTERNAL_SERVER_ERROR,
|
||||||
body: {
|
body: {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'OPERATION_FAILED',
|
code: 'OPERATION_FAILED',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -152,57 +149,55 @@ export async function someAiOperation(args, context) {
|
|||||||
```javascript
|
```javascript
|
||||||
// In your direct function:
|
// In your direct function:
|
||||||
import {
|
import {
|
||||||
getPerplexityClientForMCP,
|
getPerplexityClientForMCP,
|
||||||
getBestAvailableAIModel
|
getBestAvailableAIModel
|
||||||
} from '../utils/ai-client-utils.js';
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
export async function researchOperationDirect(args, log, context) {
|
export async function researchOperationDirect(args, log, context) {
|
||||||
try {
|
try {
|
||||||
// Get the best AI model for this operation based on needs
|
// Get the best AI model for this operation based on needs
|
||||||
const { type, client } = await getBestAvailableAIModel(
|
const { type, client } = await getBestAvailableAIModel(
|
||||||
context.session,
|
context.session,
|
||||||
{ requiresResearch: true },
|
{ requiresResearch: true },
|
||||||
log
|
log
|
||||||
);
|
);
|
||||||
|
|
||||||
// Report which model we're using
|
// Report which model we're using
|
||||||
if (context.reportProgress) {
|
if (context.reportProgress) {
|
||||||
await context.reportProgress({
|
await context.reportProgress({
|
||||||
progress: 10,
|
progress: 10,
|
||||||
status: `Using ${type} model for research...`
|
status: `Using ${type} model for research...`
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make API call based on the model type
|
// Make API call based on the model type
|
||||||
if (type === 'perplexity') {
|
if (type === 'perplexity') {
|
||||||
// Call Perplexity
|
// Call Perplexity
|
||||||
const response = await client.chat.completions.create({
|
const response = await client.chat.completions.create({
|
||||||
model: context.session?.env?.PERPLEXITY_MODEL || 'sonar-medium-online',
|
model: context.session?.env?.PERPLEXITY_MODEL || 'sonar-medium-online',
|
||||||
messages: [
|
messages: [{ role: 'user', content: args.researchQuery }],
|
||||||
{ role: 'user', content: args.researchQuery }
|
temperature: 0.1
|
||||||
],
|
});
|
||||||
temperature: 0.1
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: response.choices[0].message.content
|
data: response.choices[0].message.content
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
// Call Claude as fallback
|
// Call Claude as fallback
|
||||||
// (Implementation depends on specific needs)
|
// (Implementation depends on specific needs)
|
||||||
// ...
|
// ...
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Handle errors
|
// Handle errors
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'RESEARCH_ERROR',
|
code: 'RESEARCH_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -214,9 +209,9 @@ import { getModelConfig } from '../utils/ai-client-utils.js';
|
|||||||
|
|
||||||
// Using custom defaults for a specific operation
|
// Using custom defaults for a specific operation
|
||||||
const operationDefaults = {
|
const operationDefaults = {
|
||||||
model: 'claude-3-haiku-20240307', // Faster, smaller model
|
model: 'claude-3-haiku-20240307', // Faster, smaller model
|
||||||
maxTokens: 1000, // Lower token limit
|
maxTokens: 1000, // Lower token limit
|
||||||
temperature: 0.2 // Lower temperature for more deterministic output
|
temperature: 0.2 // Lower temperature for more deterministic output
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get model config with operation-specific defaults
|
// Get model config with operation-specific defaults
|
||||||
@@ -224,30 +219,34 @@ const modelConfig = getModelConfig(context.session, operationDefaults);
|
|||||||
|
|
||||||
// Now use modelConfig in your API calls
|
// Now use modelConfig in your API calls
|
||||||
const response = await client.messages.create({
|
const response = await client.messages.create({
|
||||||
model: modelConfig.model,
|
model: modelConfig.model,
|
||||||
max_tokens: modelConfig.maxTokens,
|
max_tokens: modelConfig.maxTokens,
|
||||||
temperature: modelConfig.temperature,
|
temperature: modelConfig.temperature
|
||||||
// Other parameters...
|
// Other parameters...
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Best Practices
|
## Best Practices
|
||||||
|
|
||||||
1. **Error Handling**:
|
1. **Error Handling**:
|
||||||
|
|
||||||
- Always use try/catch blocks around both client initialization and API calls
|
- Always use try/catch blocks around both client initialization and API calls
|
||||||
- Use `handleClaudeError` to provide user-friendly error messages
|
- Use `handleClaudeError` to provide user-friendly error messages
|
||||||
- Return standardized error objects with code and message
|
- Return standardized error objects with code and message
|
||||||
|
|
||||||
2. **Progress Reporting**:
|
2. **Progress Reporting**:
|
||||||
|
|
||||||
- Report progress at key points (starting, processing, completing)
|
- Report progress at key points (starting, processing, completing)
|
||||||
- Include meaningful status messages
|
- Include meaningful status messages
|
||||||
- Include error details in progress reports when failures occur
|
- Include error details in progress reports when failures occur
|
||||||
|
|
||||||
3. **Session Handling**:
|
3. **Session Handling**:
|
||||||
|
|
||||||
- Always pass the session from the context to the AI client getters
|
- Always pass the session from the context to the AI client getters
|
||||||
- Use `getModelConfig` to respect user settings from session
|
- Use `getModelConfig` to respect user settings from session
|
||||||
|
|
||||||
4. **Model Selection**:
|
4. **Model Selection**:
|
||||||
|
|
||||||
- Use `getBestAvailableAIModel` when you need to select between different models
|
- Use `getBestAvailableAIModel` when you need to select between different models
|
||||||
- Set `requiresResearch: true` when you need Perplexity capabilities
|
- Set `requiresResearch: true` when you need Perplexity capabilities
|
||||||
|
|
||||||
|
|||||||
205
docs/command-reference.md
Normal file
205
docs/command-reference.md
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
# Task Master Command Reference
|
||||||
|
|
||||||
|
Here's a comprehensive reference of all available commands:
|
||||||
|
|
||||||
|
## Parse PRD
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Parse a PRD file and generate tasks
|
||||||
|
task-master parse-prd <prd-file.txt>
|
||||||
|
|
||||||
|
# Limit the number of tasks generated
|
||||||
|
task-master parse-prd <prd-file.txt> --num-tasks=10
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Tasks
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# List all tasks
|
||||||
|
task-master list
|
||||||
|
|
||||||
|
# List tasks with a specific status
|
||||||
|
task-master list --status=<status>
|
||||||
|
|
||||||
|
# List tasks with subtasks
|
||||||
|
task-master list --with-subtasks
|
||||||
|
|
||||||
|
# List tasks with a specific status and include subtasks
|
||||||
|
task-master list --status=<status> --with-subtasks
|
||||||
|
```
|
||||||
|
|
||||||
|
## Show Next Task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Show the next task to work on based on dependencies and status
|
||||||
|
task-master next
|
||||||
|
```
|
||||||
|
|
||||||
|
## Show Specific Task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Show details of a specific task
|
||||||
|
task-master show <id>
|
||||||
|
# or
|
||||||
|
task-master show --id=<id>
|
||||||
|
|
||||||
|
# View a specific subtask (e.g., subtask 2 of task 1)
|
||||||
|
task-master show 1.2
|
||||||
|
```
|
||||||
|
|
||||||
|
## Update Tasks
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Update tasks from a specific ID and provide context
|
||||||
|
task-master update --from=<id> --prompt="<prompt>"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Update a Specific Task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Update a single task by ID with new information
|
||||||
|
task-master update-task --id=<id> --prompt="<prompt>"
|
||||||
|
|
||||||
|
# Use research-backed updates with Perplexity AI
|
||||||
|
task-master update-task --id=<id> --prompt="<prompt>" --research
|
||||||
|
```
|
||||||
|
|
||||||
|
## Update a Subtask
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Append additional information to a specific subtask
|
||||||
|
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>"
|
||||||
|
|
||||||
|
# Example: Add details about API rate limiting to subtask 2 of task 5
|
||||||
|
task-master update-subtask --id=5.2 --prompt="Add rate limiting of 100 requests per minute"
|
||||||
|
|
||||||
|
# Use research-backed updates with Perplexity AI
|
||||||
|
task-master update-subtask --id=<parentId.subtaskId> --prompt="<prompt>" --research
|
||||||
|
```
|
||||||
|
|
||||||
|
Unlike the `update-task` command which replaces task information, the `update-subtask` command _appends_ new information to the existing subtask details, marking it with a timestamp. This is useful for iteratively enhancing subtasks while preserving the original content.
|
||||||
|
|
||||||
|
## Generate Task Files
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Generate individual task files from tasks.json
|
||||||
|
task-master generate
|
||||||
|
```
|
||||||
|
|
||||||
|
## Set Task Status
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Set status of a single task
|
||||||
|
task-master set-status --id=<id> --status=<status>
|
||||||
|
|
||||||
|
# Set status for multiple tasks
|
||||||
|
task-master set-status --id=1,2,3 --status=<status>
|
||||||
|
|
||||||
|
# Set status for subtasks
|
||||||
|
task-master set-status --id=1.1,1.2 --status=<status>
|
||||||
|
```
|
||||||
|
|
||||||
|
When marking a task as "done", all of its subtasks will automatically be marked as "done" as well.
|
||||||
|
|
||||||
|
## Expand Tasks
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Expand a specific task with subtasks
|
||||||
|
task-master expand --id=<id> --num=<number>
|
||||||
|
|
||||||
|
# Expand with additional context
|
||||||
|
task-master expand --id=<id> --prompt="<context>"
|
||||||
|
|
||||||
|
# Expand all pending tasks
|
||||||
|
task-master expand --all
|
||||||
|
|
||||||
|
# Force regeneration of subtasks for tasks that already have them
|
||||||
|
task-master expand --all --force
|
||||||
|
|
||||||
|
# Research-backed subtask generation for a specific task
|
||||||
|
task-master expand --id=<id> --research
|
||||||
|
|
||||||
|
# Research-backed generation for all tasks
|
||||||
|
task-master expand --all --research
|
||||||
|
```
|
||||||
|
|
||||||
|
## Clear Subtasks
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Clear subtasks from a specific task
|
||||||
|
task-master clear-subtasks --id=<id>
|
||||||
|
|
||||||
|
# Clear subtasks from multiple tasks
|
||||||
|
task-master clear-subtasks --id=1,2,3
|
||||||
|
|
||||||
|
# Clear subtasks from all tasks
|
||||||
|
task-master clear-subtasks --all
|
||||||
|
```
|
||||||
|
|
||||||
|
## Analyze Task Complexity
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Analyze complexity of all tasks
|
||||||
|
task-master analyze-complexity
|
||||||
|
|
||||||
|
# Save report to a custom location
|
||||||
|
task-master analyze-complexity --output=my-report.json
|
||||||
|
|
||||||
|
# Use a specific LLM model
|
||||||
|
task-master analyze-complexity --model=claude-3-opus-20240229
|
||||||
|
|
||||||
|
# Set a custom complexity threshold (1-10)
|
||||||
|
task-master analyze-complexity --threshold=6
|
||||||
|
|
||||||
|
# Use an alternative tasks file
|
||||||
|
task-master analyze-complexity --file=custom-tasks.json
|
||||||
|
|
||||||
|
# Use Perplexity AI for research-backed complexity analysis
|
||||||
|
task-master analyze-complexity --research
|
||||||
|
```
|
||||||
|
|
||||||
|
## View Complexity Report
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Display the task complexity analysis report
|
||||||
|
task-master complexity-report
|
||||||
|
|
||||||
|
# View a report at a custom location
|
||||||
|
task-master complexity-report --file=my-report.json
|
||||||
|
```
|
||||||
|
|
||||||
|
## Managing Task Dependencies
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Add a dependency to a task
|
||||||
|
task-master add-dependency --id=<id> --depends-on=<id>
|
||||||
|
|
||||||
|
# Remove a dependency from a task
|
||||||
|
task-master remove-dependency --id=<id> --depends-on=<id>
|
||||||
|
|
||||||
|
# Validate dependencies without fixing them
|
||||||
|
task-master validate-dependencies
|
||||||
|
|
||||||
|
# Find and fix invalid dependencies automatically
|
||||||
|
task-master fix-dependencies
|
||||||
|
```
|
||||||
|
|
||||||
|
## Add a New Task
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Add a new task using AI
|
||||||
|
task-master add-task --prompt="Description of the new task"
|
||||||
|
|
||||||
|
# Add a task with dependencies
|
||||||
|
task-master add-task --prompt="Description" --dependencies=1,2,3
|
||||||
|
|
||||||
|
# Add a task with priority
|
||||||
|
task-master add-task --prompt="Description" --priority=high
|
||||||
|
```
|
||||||
|
|
||||||
|
## Initialize a Project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Initialize a new project with Task Master structure
|
||||||
|
task-master init
|
||||||
|
```
|
||||||
65
docs/configuration.md
Normal file
65
docs/configuration.md
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# Configuration
|
||||||
|
|
||||||
|
Task Master can be configured through environment variables in a `.env` file at the root of your project.
|
||||||
|
|
||||||
|
## Required Configuration
|
||||||
|
|
||||||
|
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude (Example: `ANTHROPIC_API_KEY=sk-ant-api03-...`)
|
||||||
|
|
||||||
|
## Optional Configuration
|
||||||
|
|
||||||
|
- `MODEL` (Default: `"claude-3-7-sonnet-20250219"`): Claude model to use (Example: `MODEL=claude-3-opus-20240229`)
|
||||||
|
- `MAX_TOKENS` (Default: `"4000"`): Maximum tokens for responses (Example: `MAX_TOKENS=8000`)
|
||||||
|
- `TEMPERATURE` (Default: `"0.7"`): Temperature for model responses (Example: `TEMPERATURE=0.5`)
|
||||||
|
- `DEBUG` (Default: `"false"`): Enable debug logging (Example: `DEBUG=true`)
|
||||||
|
- `LOG_LEVEL` (Default: `"info"`): Console output level (Example: `LOG_LEVEL=debug`)
|
||||||
|
- `DEFAULT_SUBTASKS` (Default: `"3"`): Default subtask count (Example: `DEFAULT_SUBTASKS=5`)
|
||||||
|
- `DEFAULT_PRIORITY` (Default: `"medium"`): Default priority (Example: `DEFAULT_PRIORITY=high`)
|
||||||
|
- `PROJECT_NAME` (Default: `"MCP SaaS MVP"`): Project name in metadata (Example: `PROJECT_NAME=My Awesome Project`)
|
||||||
|
- `PROJECT_VERSION` (Default: `"1.0.0"`): Version in metadata (Example: `PROJECT_VERSION=2.1.0`)
|
||||||
|
- `PERPLEXITY_API_KEY`: For research-backed features (Example: `PERPLEXITY_API_KEY=pplx-...`)
|
||||||
|
- `PERPLEXITY_MODEL` (Default: `"sonar-medium-online"`): Perplexity model (Example: `PERPLEXITY_MODEL=sonar-large-online`)
|
||||||
|
|
||||||
|
## Example .env File
|
||||||
|
|
||||||
|
```
|
||||||
|
# Required
|
||||||
|
ANTHROPIC_API_KEY=sk-ant-api03-your-api-key
|
||||||
|
|
||||||
|
# Optional - Claude Configuration
|
||||||
|
MODEL=claude-3-7-sonnet-20250219
|
||||||
|
MAX_TOKENS=4000
|
||||||
|
TEMPERATURE=0.7
|
||||||
|
|
||||||
|
# Optional - Perplexity API for Research
|
||||||
|
PERPLEXITY_API_KEY=pplx-your-api-key
|
||||||
|
PERPLEXITY_MODEL=sonar-medium-online
|
||||||
|
|
||||||
|
# Optional - Project Info
|
||||||
|
PROJECT_NAME=My Project
|
||||||
|
PROJECT_VERSION=1.0.0
|
||||||
|
|
||||||
|
# Optional - Application Configuration
|
||||||
|
DEFAULT_SUBTASKS=3
|
||||||
|
DEFAULT_PRIORITY=medium
|
||||||
|
DEBUG=false
|
||||||
|
LOG_LEVEL=info
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### If `task-master init` doesn't respond:
|
||||||
|
|
||||||
|
Try running it with Node directly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node node_modules/claude-task-master/scripts/init.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Or clone the repository and run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/eyaltoledano/claude-task-master.git
|
||||||
|
cd claude-task-master
|
||||||
|
node scripts/init.js
|
||||||
|
```
|
||||||
53
docs/examples.md
Normal file
53
docs/examples.md
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
# Example Cursor AI Interactions
|
||||||
|
|
||||||
|
Here are some common interactions with Cursor AI when using Task Master:
|
||||||
|
|
||||||
|
## Starting a new project
|
||||||
|
|
||||||
|
```
|
||||||
|
I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
|
||||||
|
Can you help me parse it and set up the initial tasks?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Working on tasks
|
||||||
|
|
||||||
|
```
|
||||||
|
What's the next task I should work on? Please consider dependencies and priorities.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implementing a specific task
|
||||||
|
|
||||||
|
```
|
||||||
|
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Managing subtasks
|
||||||
|
|
||||||
|
```
|
||||||
|
I need to regenerate the subtasks for task 3 with a different approach. Can you help me clear and regenerate them?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Handling changes
|
||||||
|
|
||||||
|
```
|
||||||
|
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Completing work
|
||||||
|
|
||||||
|
```
|
||||||
|
I've finished implementing the authentication system described in task 2. All tests are passing.
|
||||||
|
Please mark it as complete and tell me what I should work on next.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Analyzing complexity
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you analyze the complexity of our tasks to help me understand which ones need to be broken down further?
|
||||||
|
```
|
||||||
|
|
||||||
|
## Viewing complexity report
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you show me the complexity report in a more readable format?
|
||||||
|
```
|
||||||
18
docs/licensing.md
Normal file
18
docs/licensing.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Licensing
|
||||||
|
|
||||||
|
Task Master is licensed under the MIT License with Commons Clause. This means you can:
|
||||||
|
|
||||||
|
## ✅ Allowed:
|
||||||
|
|
||||||
|
- Use Task Master for any purpose (personal, commercial, academic)
|
||||||
|
- Modify the code
|
||||||
|
- Distribute copies
|
||||||
|
- Create and sell products built using Task Master
|
||||||
|
|
||||||
|
## ❌ Not Allowed:
|
||||||
|
|
||||||
|
- Sell Task Master itself
|
||||||
|
- Offer Task Master as a hosted service
|
||||||
|
- Create competing products based on Task Master
|
||||||
|
|
||||||
|
See the [LICENSE](../LICENSE) file for the complete license text.
|
||||||
File diff suppressed because it is too large
Load Diff
139
docs/task-structure.md
Normal file
139
docs/task-structure.md
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
# Task Structure
|
||||||
|
|
||||||
|
Tasks in Task Master follow a specific format designed to provide comprehensive information for both humans and AI assistants.
|
||||||
|
|
||||||
|
## Task Fields in tasks.json
|
||||||
|
|
||||||
|
Tasks in tasks.json have the following structure:
|
||||||
|
|
||||||
|
- `id`: Unique identifier for the task (Example: `1`)
|
||||||
|
- `title`: Brief, descriptive title of the task (Example: `"Initialize Repo"`)
|
||||||
|
- `description`: Concise description of what the task involves (Example: `"Create a new repository, set up initial structure."`)
|
||||||
|
- `status`: Current state of the task (Example: `"pending"`, `"done"`, `"deferred"`)
|
||||||
|
- `dependencies`: IDs of tasks that must be completed before this task (Example: `[1, 2]`)
|
||||||
|
- Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending)
|
||||||
|
- This helps quickly identify which prerequisite tasks are blocking work
|
||||||
|
- `priority`: Importance level of the task (Example: `"high"`, `"medium"`, `"low"`)
|
||||||
|
- `details`: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
|
||||||
|
- `testStrategy`: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
|
||||||
|
- `subtasks`: List of smaller, more specific tasks that make up the main task (Example: `[{"id": 1, "title": "Configure OAuth", ...}]`)
|
||||||
|
|
||||||
|
## Task File Format
|
||||||
|
|
||||||
|
Individual task files follow this format:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Task ID: <id>
|
||||||
|
# Title: <title>
|
||||||
|
# Status: <status>
|
||||||
|
# Dependencies: <comma-separated list of dependency IDs>
|
||||||
|
# Priority: <priority>
|
||||||
|
# Description: <brief description>
|
||||||
|
# Details:
|
||||||
|
<detailed implementation notes>
|
||||||
|
|
||||||
|
# Test Strategy:
|
||||||
|
<verification approach>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features in Detail
|
||||||
|
|
||||||
|
### Analyzing Task Complexity
|
||||||
|
|
||||||
|
The `analyze-complexity` command:
|
||||||
|
|
||||||
|
- Analyzes each task using AI to assess its complexity on a scale of 1-10
|
||||||
|
- Recommends optimal number of subtasks based on configured DEFAULT_SUBTASKS
|
||||||
|
- Generates tailored prompts for expanding each task
|
||||||
|
- Creates a comprehensive JSON report with ready-to-use commands
|
||||||
|
- Saves the report to scripts/task-complexity-report.json by default
|
||||||
|
|
||||||
|
The generated report contains:
|
||||||
|
|
||||||
|
- Complexity analysis for each task (scored 1-10)
|
||||||
|
- Recommended number of subtasks based on complexity
|
||||||
|
- AI-generated expansion prompts customized for each task
|
||||||
|
- Ready-to-run expansion commands directly within each task analysis
|
||||||
|
|
||||||
|
### Viewing Complexity Report
|
||||||
|
|
||||||
|
The `complexity-report` command:
|
||||||
|
|
||||||
|
- Displays a formatted, easy-to-read version of the complexity analysis report
|
||||||
|
- Shows tasks organized by complexity score (highest to lowest)
|
||||||
|
- Provides complexity distribution statistics (low, medium, high)
|
||||||
|
- Highlights tasks recommended for expansion based on threshold score
|
||||||
|
- Includes ready-to-use expansion commands for each complex task
|
||||||
|
- If no report exists, offers to generate one on the spot
|
||||||
|
|
||||||
|
### Smart Task Expansion
|
||||||
|
|
||||||
|
The `expand` command automatically checks for and uses the complexity report:
|
||||||
|
|
||||||
|
When a complexity report exists:
|
||||||
|
|
||||||
|
- Tasks are automatically expanded using the recommended subtask count and prompts
|
||||||
|
- When expanding all tasks, they're processed in order of complexity (highest first)
|
||||||
|
- Research-backed generation is preserved from the complexity analysis
|
||||||
|
- You can still override recommendations with explicit command-line options
|
||||||
|
|
||||||
|
Example workflow:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Generate the complexity analysis report with research capabilities
|
||||||
|
task-master analyze-complexity --research
|
||||||
|
|
||||||
|
# Review the report in a readable format
|
||||||
|
task-master complexity-report
|
||||||
|
|
||||||
|
# Expand tasks using the optimized recommendations
|
||||||
|
task-master expand --id=8
|
||||||
|
# or expand all tasks
|
||||||
|
task-master expand --all
|
||||||
|
```
|
||||||
|
|
||||||
|
### Finding the Next Task
|
||||||
|
|
||||||
|
The `next` command:
|
||||||
|
|
||||||
|
- Identifies tasks that are pending/in-progress and have all dependencies satisfied
|
||||||
|
- Prioritizes tasks by priority level, dependency count, and task ID
|
||||||
|
- Displays comprehensive information about the selected task:
|
||||||
|
- Basic task details (ID, title, priority, dependencies)
|
||||||
|
- Implementation details
|
||||||
|
- Subtasks (if they exist)
|
||||||
|
- Provides contextual suggested actions:
|
||||||
|
- Command to mark the task as in-progress
|
||||||
|
- Command to mark the task as done
|
||||||
|
- Commands for working with subtasks
|
||||||
|
|
||||||
|
### Viewing Specific Task Details
|
||||||
|
|
||||||
|
The `show` command:
|
||||||
|
|
||||||
|
- Displays comprehensive details about a specific task or subtask
|
||||||
|
- Shows task status, priority, dependencies, and detailed implementation notes
|
||||||
|
- For parent tasks, displays all subtasks and their status
|
||||||
|
- For subtasks, shows parent task relationship
|
||||||
|
- Provides contextual action suggestions based on the task's state
|
||||||
|
- Works with both regular tasks and subtasks (using the format taskId.subtaskId)
|
||||||
|
|
||||||
|
## Best Practices for AI-Driven Development
|
||||||
|
|
||||||
|
1. **Start with a detailed PRD**: The more detailed your PRD, the better the generated tasks will be.
|
||||||
|
|
||||||
|
2. **Review generated tasks**: After parsing the PRD, review the tasks to ensure they make sense and have appropriate dependencies.
|
||||||
|
|
||||||
|
3. **Analyze task complexity**: Use the complexity analysis feature to identify which tasks should be broken down further.
|
||||||
|
|
||||||
|
4. **Follow the dependency chain**: Always respect task dependencies - the Cursor agent will help with this.
|
||||||
|
|
||||||
|
5. **Update as you go**: If your implementation diverges from the plan, use the update command to keep future tasks aligned with your current approach.
|
||||||
|
|
||||||
|
6. **Break down complex tasks**: Use the expand command to break down complex tasks into manageable subtasks.
|
||||||
|
|
||||||
|
7. **Regenerate task files**: After any updates to tasks.json, regenerate the task files to keep them in sync.
|
||||||
|
|
||||||
|
8. **Communicate context to the agent**: When asking the Cursor agent to help with a task, provide context about what you're trying to achieve.
|
||||||
|
|
||||||
|
9. **Validate dependencies**: Periodically run the validate-dependencies command to check for invalid or circular dependencies.
|
||||||
355
docs/tutorial.md
Normal file
355
docs/tutorial.md
Normal file
@@ -0,0 +1,355 @@
|
|||||||
|
# Task Master Tutorial
|
||||||
|
|
||||||
|
This tutorial will guide you through setting up and using Task Master for AI-driven development.
|
||||||
|
|
||||||
|
## Initial Setup
|
||||||
|
|
||||||
|
There are two ways to set up Task Master: using MCP (recommended) or via npm installation.
|
||||||
|
|
||||||
|
### Option 1: Using MCP (Recommended)
|
||||||
|
|
||||||
|
MCP (Model Control Protocol) provides the easiest way to get started with Task Master directly in your editor.
|
||||||
|
|
||||||
|
1. **Add the MCP config to your editor** (Cursor recommended, but it works with other text editors):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"taskmaster-ai": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "task-master-ai", "mcp-server"],
|
||||||
|
"env": {
|
||||||
|
"ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE",
|
||||||
|
"PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE",
|
||||||
|
"MODEL": "claude-3-7-sonnet-20250219",
|
||||||
|
"PERPLEXITY_MODEL": "sonar-pro",
|
||||||
|
"MAX_TOKENS": 128000,
|
||||||
|
"TEMPERATURE": 0.2,
|
||||||
|
"DEFAULT_SUBTASKS": 5,
|
||||||
|
"DEFAULT_PRIORITY": "medium"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Enable the MCP** in your editor settings
|
||||||
|
|
||||||
|
3. **Prompt the AI** to initialize Task Master:
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you please initialize taskmaster-ai into my project?
|
||||||
|
```
|
||||||
|
|
||||||
|
The AI will:
|
||||||
|
|
||||||
|
- Create necessary project structure
|
||||||
|
- Set up initial configuration files
|
||||||
|
- Guide you through the rest of the process
|
||||||
|
|
||||||
|
4. Place your PRD document in the `scripts/` directory (e.g., `scripts/prd.txt`)
|
||||||
|
|
||||||
|
5. **Use natural language commands** to interact with Task Master:
|
||||||
|
|
||||||
|
```
|
||||||
|
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?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Option 2: Manual Installation
|
||||||
|
|
||||||
|
If you prefer to use the command line interface directly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install globally
|
||||||
|
npm install -g task-master-ai
|
||||||
|
|
||||||
|
# OR install locally within your project
|
||||||
|
npm install task-master-ai
|
||||||
|
```
|
||||||
|
|
||||||
|
Initialize a new project:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# If installed globally
|
||||||
|
task-master init
|
||||||
|
|
||||||
|
# If installed locally
|
||||||
|
npx task-master-init
|
||||||
|
```
|
||||||
|
|
||||||
|
This will prompt you for project details and set up a new project with the necessary files and structure.
|
||||||
|
|
||||||
|
## Common Commands
|
||||||
|
|
||||||
|
After setting up Task Master, you can use these commands (either via AI prompts or CLI):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Parse a PRD and generate tasks
|
||||||
|
task-master parse-prd your-prd.txt
|
||||||
|
|
||||||
|
# List all tasks
|
||||||
|
task-master list
|
||||||
|
|
||||||
|
# Show the next task to work on
|
||||||
|
task-master next
|
||||||
|
|
||||||
|
# Generate task files
|
||||||
|
task-master generate
|
||||||
|
```
|
||||||
|
|
||||||
|
## Setting up Cursor AI Integration
|
||||||
|
|
||||||
|
Task Master is designed to work seamlessly with [Cursor AI](https://www.cursor.so/), providing a structured workflow for AI-driven development.
|
||||||
|
|
||||||
|
### Using Cursor with MCP (Recommended)
|
||||||
|
|
||||||
|
If you've already set up Task Master with MCP in Cursor, the integration is automatic. You can simply use natural language to interact with Task Master:
|
||||||
|
|
||||||
|
```
|
||||||
|
What tasks are available to work on next?
|
||||||
|
Can you analyze the complexity of our tasks?
|
||||||
|
I'd like to implement task 4. What does it involve?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Manual Cursor Setup
|
||||||
|
|
||||||
|
If you're not using MCP, you can still set up Cursor integration:
|
||||||
|
|
||||||
|
1. After initializing your project, open it in Cursor
|
||||||
|
2. The `.cursor/rules/dev_workflow.mdc` file is automatically loaded by Cursor, providing the AI with knowledge about the task management system
|
||||||
|
3. Place your PRD document in the `scripts/` directory (e.g., `scripts/prd.txt`)
|
||||||
|
4. Open Cursor's AI chat and switch to Agent mode
|
||||||
|
|
||||||
|
### Alternative MCP Setup in Cursor
|
||||||
|
|
||||||
|
You can also set up the MCP server in Cursor settings:
|
||||||
|
|
||||||
|
1. Go to Cursor settings
|
||||||
|
2. Navigate to the MCP section
|
||||||
|
3. Click on "Add New MCP Server"
|
||||||
|
4. Configure with the following details:
|
||||||
|
- Name: "Task Master"
|
||||||
|
- Type: "Command"
|
||||||
|
- Command: "npx -y --package task-master-ai task-master-mcp"
|
||||||
|
5. Save the settings
|
||||||
|
|
||||||
|
Once configured, you can interact with Task Master's task management commands directly through Cursor's interface, providing a more integrated experience.
|
||||||
|
|
||||||
|
## Initial Task Generation
|
||||||
|
|
||||||
|
In Cursor's AI chat, instruct the agent to generate tasks from your PRD:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please use the task-master parse-prd command to generate tasks from my PRD. The PRD is located at scripts/prd.txt.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master parse-prd scripts/prd.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
This will:
|
||||||
|
|
||||||
|
- Parse your PRD document
|
||||||
|
- Generate a structured `tasks.json` file with tasks, dependencies, priorities, and test strategies
|
||||||
|
- The agent will understand this process due to the Cursor rules
|
||||||
|
|
||||||
|
### Generate Individual Task Files
|
||||||
|
|
||||||
|
Next, ask the agent to generate individual task files:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please generate individual task files from tasks.json
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master generate
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates individual task files in the `tasks/` directory (e.g., `task_001.txt`, `task_002.txt`), making it easier to reference specific tasks.
|
||||||
|
|
||||||
|
## AI-Driven Development Workflow
|
||||||
|
|
||||||
|
The Cursor agent is pre-configured (via the rules file) to follow this workflow:
|
||||||
|
|
||||||
|
### 1. Task Discovery and Selection
|
||||||
|
|
||||||
|
Ask the agent to list available tasks:
|
||||||
|
|
||||||
|
```
|
||||||
|
What tasks are available to work on next?
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will:
|
||||||
|
|
||||||
|
- Run `task-master list` to see all tasks
|
||||||
|
- Run `task-master next` to determine the next task to work on
|
||||||
|
- 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
|
||||||
|
|
||||||
|
### 2. Task Implementation
|
||||||
|
|
||||||
|
When implementing a task, the agent will:
|
||||||
|
|
||||||
|
- Reference the task's details section for implementation specifics
|
||||||
|
- Consider dependencies on previous tasks
|
||||||
|
- Follow the project's coding standards
|
||||||
|
- Create appropriate tests based on the task's testStrategy
|
||||||
|
|
||||||
|
You can ask:
|
||||||
|
|
||||||
|
```
|
||||||
|
Let's implement task 3. What does it involve?
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Task Verification
|
||||||
|
|
||||||
|
Before marking a task as complete, verify it according to:
|
||||||
|
|
||||||
|
- The task's specified testStrategy
|
||||||
|
- Any automated tests in the codebase
|
||||||
|
- Manual verification if required
|
||||||
|
|
||||||
|
### 4. Task Completion
|
||||||
|
|
||||||
|
When a task is completed, tell the agent:
|
||||||
|
|
||||||
|
```
|
||||||
|
Task 3 is now complete. Please update its status.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master set-status --id=3 --status=done
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Handling Implementation Drift
|
||||||
|
|
||||||
|
If during implementation, you discover that:
|
||||||
|
|
||||||
|
- The current approach differs significantly from what was planned
|
||||||
|
- Future tasks need to be modified due to current implementation choices
|
||||||
|
- New dependencies or requirements have emerged
|
||||||
|
|
||||||
|
Tell the agent:
|
||||||
|
|
||||||
|
```
|
||||||
|
We've changed our approach. We're now using Express instead of Fastify. Please update all future tasks to reflect this change.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master update --from=4 --prompt="Now we are using Express instead of Fastify."
|
||||||
|
```
|
||||||
|
|
||||||
|
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
|
||||||
|
|
||||||
|
### 6. Breaking Down Complex Tasks
|
||||||
|
|
||||||
|
For complex tasks that need more granularity:
|
||||||
|
|
||||||
|
```
|
||||||
|
Task 5 seems complex. Can you break it down into subtasks?
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master expand --id=5 --num=3
|
||||||
|
```
|
||||||
|
|
||||||
|
You can provide additional context:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please break down task 5 with a focus on security considerations.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master expand --id=5 --prompt="Focus on security aspects"
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also expand all pending tasks:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please break down all pending tasks into subtasks.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master expand --all
|
||||||
|
```
|
||||||
|
|
||||||
|
For research-backed subtask generation using Perplexity AI:
|
||||||
|
|
||||||
|
```
|
||||||
|
Please break down task 5 using research-backed generation.
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master expand --id=5 --research
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Cursor AI Interactions
|
||||||
|
|
||||||
|
### Starting a new project
|
||||||
|
|
||||||
|
```
|
||||||
|
I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
|
||||||
|
Can you help me parse it and set up the initial tasks?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Working on tasks
|
||||||
|
|
||||||
|
```
|
||||||
|
What's the next task I should work on? Please consider dependencies and priorities.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Implementing a specific task
|
||||||
|
|
||||||
|
```
|
||||||
|
I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Managing subtasks
|
||||||
|
|
||||||
|
```
|
||||||
|
I need to regenerate the subtasks for task 3 with a different approach. Can you help me clear and regenerate them?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Handling changes
|
||||||
|
|
||||||
|
```
|
||||||
|
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Completing work
|
||||||
|
|
||||||
|
```
|
||||||
|
I've finished implementing the authentication system described in task 2. All tests are passing.
|
||||||
|
Please mark it as complete and tell me what I should work on next.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Analyzing complexity
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you analyze the complexity of our tasks to help me understand which ones need to be broken down further?
|
||||||
|
```
|
||||||
|
|
||||||
|
### Viewing complexity report
|
||||||
|
|
||||||
|
```
|
||||||
|
Can you show me the complexity report in a more readable format?
|
||||||
|
```
|
||||||
41
entries.json
41
entries.json
@@ -1,41 +0,0 @@
|
|||||||
import os
|
|
||||||
import json
|
|
||||||
|
|
||||||
# Path to Cursor's history folder
|
|
||||||
history_path = os.path.expanduser('~/Library/Application Support/Cursor/User/History')
|
|
||||||
|
|
||||||
# File to search for
|
|
||||||
target_file = 'tasks/tasks.json'
|
|
||||||
|
|
||||||
# Function to search through all entries.json files
|
|
||||||
def search_entries_for_file(history_path, target_file):
|
|
||||||
matching_folders = []
|
|
||||||
for folder in os.listdir(history_path):
|
|
||||||
folder_path = os.path.join(history_path, folder)
|
|
||||||
if not os.path.isdir(folder_path):
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Look for entries.json
|
|
||||||
entries_file = os.path.join(folder_path, 'entries.json')
|
|
||||||
if not os.path.exists(entries_file):
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Parse entries.json to find the resource key
|
|
||||||
with open(entries_file, 'r') as f:
|
|
||||||
data = json.load(f)
|
|
||||||
resource = data.get('resource', None)
|
|
||||||
if resource and target_file in resource:
|
|
||||||
matching_folders.append(folder_path)
|
|
||||||
|
|
||||||
return matching_folders
|
|
||||||
|
|
||||||
# Search for the target file
|
|
||||||
matching_folders = search_entries_for_file(history_path, target_file)
|
|
||||||
|
|
||||||
# Output the matching folders
|
|
||||||
if matching_folders:
|
|
||||||
print(f"Found {target_file} in the following folders:")
|
|
||||||
for folder in matching_folders:
|
|
||||||
print(folder)
|
|
||||||
else:
|
|
||||||
print(f"No matches found for {target_file}.")
|
|
||||||
164
index.js
164
index.js
@@ -41,27 +41,27 @@ export const devScriptPath = resolve(__dirname, './scripts/dev.js');
|
|||||||
|
|
||||||
// Export a function to initialize a new project programmatically
|
// Export a function to initialize a new project programmatically
|
||||||
export const initProject = async (options = {}) => {
|
export const initProject = async (options = {}) => {
|
||||||
const init = await import('./scripts/init.js');
|
const init = await import('./scripts/init.js');
|
||||||
return init.initializeProject(options);
|
return init.initializeProject(options);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Export a function to run init as a CLI command
|
// Export a function to run init as a CLI command
|
||||||
export const runInitCLI = async () => {
|
export const runInitCLI = async () => {
|
||||||
// Using spawn to ensure proper handling of stdio and process exit
|
// Using spawn to ensure proper handling of stdio and process exit
|
||||||
const child = spawn('node', [resolve(__dirname, './scripts/init.js')], {
|
const child = spawn('node', [resolve(__dirname, './scripts/init.js')], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: process.cwd()
|
cwd: process.cwd()
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
if (code === 0) {
|
if (code === 0) {
|
||||||
resolve();
|
resolve();
|
||||||
} else {
|
} else {
|
||||||
reject(new Error(`Init script exited with code ${code}`));
|
reject(new Error(`Init script exited with code ${code}`));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Export version information
|
// Export version information
|
||||||
@@ -69,81 +69,81 @@ export const version = packageJson.version;
|
|||||||
|
|
||||||
// CLI implementation
|
// CLI implementation
|
||||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||||
const program = new Command();
|
const program = new Command();
|
||||||
|
|
||||||
program
|
program
|
||||||
.name('task-master')
|
.name('task-master')
|
||||||
.description('Claude Task Master CLI')
|
.description('Claude Task Master CLI')
|
||||||
.version(version);
|
.version(version);
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('init')
|
.command('init')
|
||||||
.description('Initialize a new project')
|
.description('Initialize a new project')
|
||||||
.action(() => {
|
.action(() => {
|
||||||
runInitCLI().catch(err => {
|
runInitCLI().catch((err) => {
|
||||||
console.error('Init failed:', err.message);
|
console.error('Init failed:', err.message);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('dev')
|
.command('dev')
|
||||||
.description('Run the dev.js script')
|
.description('Run the dev.js script')
|
||||||
.allowUnknownOption(true)
|
.allowUnknownOption(true)
|
||||||
.action(() => {
|
.action(() => {
|
||||||
const args = process.argv.slice(process.argv.indexOf('dev') + 1);
|
const args = process.argv.slice(process.argv.indexOf('dev') + 1);
|
||||||
const child = spawn('node', [devScriptPath, ...args], {
|
const child = spawn('node', [devScriptPath, ...args], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: process.cwd()
|
cwd: process.cwd()
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
process.exit(code);
|
process.exit(code);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add shortcuts for common dev.js commands
|
// Add shortcuts for common dev.js commands
|
||||||
program
|
program
|
||||||
.command('list')
|
.command('list')
|
||||||
.description('List all tasks')
|
.description('List all tasks')
|
||||||
.action(() => {
|
.action(() => {
|
||||||
const child = spawn('node', [devScriptPath, 'list'], {
|
const child = spawn('node', [devScriptPath, 'list'], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: process.cwd()
|
cwd: process.cwd()
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
process.exit(code);
|
process.exit(code);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('next')
|
.command('next')
|
||||||
.description('Show the next task to work on')
|
.description('Show the next task to work on')
|
||||||
.action(() => {
|
.action(() => {
|
||||||
const child = spawn('node', [devScriptPath, 'next'], {
|
const child = spawn('node', [devScriptPath, 'next'], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: process.cwd()
|
cwd: process.cwd()
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
process.exit(code);
|
process.exit(code);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('generate')
|
.command('generate')
|
||||||
.description('Generate task files')
|
.description('Generate task files')
|
||||||
.action(() => {
|
.action(() => {
|
||||||
const child = spawn('node', [devScriptPath, 'generate'], {
|
const child = spawn('node', [devScriptPath, 'generate'], {
|
||||||
stdio: 'inherit',
|
stdio: 'inherit',
|
||||||
cwd: process.cwd()
|
cwd: process.cwd()
|
||||||
});
|
});
|
||||||
|
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
process.exit(code);
|
process.exit(code);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
program.parse(process.argv);
|
program.parse(process.argv);
|
||||||
}
|
}
|
||||||
@@ -1,56 +1,56 @@
|
|||||||
export default {
|
export default {
|
||||||
// Use Node.js environment for testing
|
// Use Node.js environment for testing
|
||||||
testEnvironment: 'node',
|
testEnvironment: 'node',
|
||||||
|
|
||||||
// Automatically clear mock calls between every test
|
// Automatically clear mock calls between every test
|
||||||
clearMocks: true,
|
clearMocks: true,
|
||||||
|
|
||||||
// Indicates whether the coverage information should be collected while executing the test
|
// Indicates whether the coverage information should be collected while executing the test
|
||||||
collectCoverage: false,
|
collectCoverage: false,
|
||||||
|
|
||||||
// The directory where Jest should output its coverage files
|
// The directory where Jest should output its coverage files
|
||||||
coverageDirectory: 'coverage',
|
coverageDirectory: 'coverage',
|
||||||
|
|
||||||
// A list of paths to directories that Jest should use to search for files in
|
// A list of paths to directories that Jest should use to search for files in
|
||||||
roots: ['<rootDir>/tests'],
|
roots: ['<rootDir>/tests'],
|
||||||
|
|
||||||
// The glob patterns Jest uses to detect test files
|
// The glob patterns Jest uses to detect test files
|
||||||
testMatch: [
|
testMatch: [
|
||||||
'**/__tests__/**/*.js',
|
'**/__tests__/**/*.js',
|
||||||
'**/?(*.)+(spec|test).js',
|
'**/?(*.)+(spec|test).js',
|
||||||
'**/tests/*.test.js'
|
'**/tests/*.test.js'
|
||||||
],
|
],
|
||||||
|
|
||||||
// Transform files
|
// Transform files
|
||||||
transform: {},
|
transform: {},
|
||||||
|
|
||||||
// Disable transformations for node_modules
|
// Disable transformations for node_modules
|
||||||
transformIgnorePatterns: ['/node_modules/'],
|
transformIgnorePatterns: ['/node_modules/'],
|
||||||
|
|
||||||
// Set moduleNameMapper for absolute paths
|
// Set moduleNameMapper for absolute paths
|
||||||
moduleNameMapper: {
|
moduleNameMapper: {
|
||||||
'^@/(.*)$': '<rootDir>/$1'
|
'^@/(.*)$': '<rootDir>/$1'
|
||||||
},
|
},
|
||||||
|
|
||||||
// Setup module aliases
|
// Setup module aliases
|
||||||
moduleDirectories: ['node_modules', '<rootDir>'],
|
moduleDirectories: ['node_modules', '<rootDir>'],
|
||||||
|
|
||||||
// Configure test coverage thresholds
|
// Configure test coverage thresholds
|
||||||
coverageThreshold: {
|
coverageThreshold: {
|
||||||
global: {
|
global: {
|
||||||
branches: 80,
|
branches: 80,
|
||||||
functions: 80,
|
functions: 80,
|
||||||
lines: 80,
|
lines: 80,
|
||||||
statements: 80
|
statements: 80
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Generate coverage report in these formats
|
// Generate coverage report in these formats
|
||||||
coverageReporters: ['text', 'lcov'],
|
coverageReporters: ['text', 'lcov'],
|
||||||
|
|
||||||
// Verbose output
|
// Verbose output
|
||||||
verbose: true,
|
verbose: true,
|
||||||
|
|
||||||
// Setup file
|
// Setup file
|
||||||
setupFilesAfterEnv: ['<rootDir>/tests/setup.js']
|
setupFilesAfterEnv: ['<rootDir>/tests/setup.js']
|
||||||
};
|
};
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
import TaskMasterMCPServer from "./src/index.js";
|
import TaskMasterMCPServer from './src/index.js';
|
||||||
import dotenv from "dotenv";
|
import dotenv from 'dotenv';
|
||||||
import logger from "./src/logger.js";
|
import logger from './src/logger.js';
|
||||||
|
|
||||||
// Load environment variables
|
// Load environment variables
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
@@ -11,25 +11,25 @@ dotenv.config();
|
|||||||
* Start the MCP server
|
* Start the MCP server
|
||||||
*/
|
*/
|
||||||
async function startServer() {
|
async function startServer() {
|
||||||
const server = new TaskMasterMCPServer();
|
const server = new TaskMasterMCPServer();
|
||||||
|
|
||||||
// Handle graceful shutdown
|
// Handle graceful shutdown
|
||||||
process.on("SIGINT", async () => {
|
process.on('SIGINT', async () => {
|
||||||
await server.stop();
|
await server.stop();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on("SIGTERM", async () => {
|
process.on('SIGTERM', async () => {
|
||||||
await server.stop();
|
await server.stop();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await server.start();
|
await server.start();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`Failed to start MCP server: ${error.message}`);
|
logger.error(`Failed to start MCP server: ${error.message}`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start the server
|
// Start the server
|
||||||
|
|||||||
@@ -2,84 +2,90 @@ import { jest } from '@jest/globals';
|
|||||||
import { ContextManager } from '../context-manager.js';
|
import { ContextManager } from '../context-manager.js';
|
||||||
|
|
||||||
describe('ContextManager', () => {
|
describe('ContextManager', () => {
|
||||||
let contextManager;
|
let contextManager;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
contextManager = new ContextManager({
|
contextManager = new ContextManager({
|
||||||
maxCacheSize: 10,
|
maxCacheSize: 10,
|
||||||
ttl: 1000, // 1 second for testing
|
ttl: 1000, // 1 second for testing
|
||||||
maxContextSize: 1000
|
maxContextSize: 1000
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('getContext', () => {
|
describe('getContext', () => {
|
||||||
it('should create a new context when not in cache', async () => {
|
it('should create a new context when not in cache', async () => {
|
||||||
const context = await contextManager.getContext('test-id', { test: true });
|
const context = await contextManager.getContext('test-id', {
|
||||||
expect(context.id).toBe('test-id');
|
test: true
|
||||||
expect(context.metadata.test).toBe(true);
|
});
|
||||||
expect(contextManager.stats.misses).toBe(1);
|
expect(context.id).toBe('test-id');
|
||||||
expect(contextManager.stats.hits).toBe(0);
|
expect(context.metadata.test).toBe(true);
|
||||||
});
|
expect(contextManager.stats.misses).toBe(1);
|
||||||
|
expect(contextManager.stats.hits).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
it('should return cached context when available', async () => {
|
it('should return cached context when available', async () => {
|
||||||
// First call creates the context
|
// First call creates the context
|
||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
|
|
||||||
// Second call should hit cache
|
// Second call should hit cache
|
||||||
const context = await contextManager.getContext('test-id', { test: true });
|
const context = await contextManager.getContext('test-id', {
|
||||||
expect(context.id).toBe('test-id');
|
test: true
|
||||||
expect(context.metadata.test).toBe(true);
|
});
|
||||||
expect(contextManager.stats.hits).toBe(1);
|
expect(context.id).toBe('test-id');
|
||||||
expect(contextManager.stats.misses).toBe(1);
|
expect(context.metadata.test).toBe(true);
|
||||||
});
|
expect(contextManager.stats.hits).toBe(1);
|
||||||
|
expect(contextManager.stats.misses).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('should respect TTL settings', async () => {
|
it('should respect TTL settings', async () => {
|
||||||
// Create context
|
// Create context
|
||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
|
|
||||||
// Wait for TTL to expire
|
// Wait for TTL to expire
|
||||||
await new Promise(resolve => setTimeout(resolve, 1100));
|
await new Promise((resolve) => setTimeout(resolve, 1100));
|
||||||
|
|
||||||
// Should create new context
|
// Should create new context
|
||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
expect(contextManager.stats.misses).toBe(2);
|
expect(contextManager.stats.misses).toBe(2);
|
||||||
expect(contextManager.stats.hits).toBe(0);
|
expect(contextManager.stats.hits).toBe(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('updateContext', () => {
|
describe('updateContext', () => {
|
||||||
it('should update existing context metadata', async () => {
|
it('should update existing context metadata', async () => {
|
||||||
await contextManager.getContext('test-id', { initial: true });
|
await contextManager.getContext('test-id', { initial: true });
|
||||||
const updated = await contextManager.updateContext('test-id', { updated: true });
|
const updated = await contextManager.updateContext('test-id', {
|
||||||
|
updated: true
|
||||||
|
});
|
||||||
|
|
||||||
expect(updated.metadata.initial).toBe(true);
|
expect(updated.metadata.initial).toBe(true);
|
||||||
expect(updated.metadata.updated).toBe(true);
|
expect(updated.metadata.updated).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('invalidateContext', () => {
|
describe('invalidateContext', () => {
|
||||||
it('should remove context from cache', async () => {
|
it('should remove context from cache', async () => {
|
||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
contextManager.invalidateContext('test-id', { test: true });
|
contextManager.invalidateContext('test-id', { test: true });
|
||||||
|
|
||||||
// Should be a cache miss
|
// Should be a cache miss
|
||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
expect(contextManager.stats.invalidations).toBe(1);
|
expect(contextManager.stats.invalidations).toBe(1);
|
||||||
expect(contextManager.stats.misses).toBe(2);
|
expect(contextManager.stats.misses).toBe(2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('getStats', () => {
|
describe('getStats', () => {
|
||||||
it('should return current cache statistics', async () => {
|
it('should return current cache statistics', async () => {
|
||||||
await contextManager.getContext('test-id', { test: true });
|
await contextManager.getContext('test-id', { test: true });
|
||||||
const stats = contextManager.getStats();
|
const stats = contextManager.getStats();
|
||||||
|
|
||||||
expect(stats.hits).toBe(0);
|
expect(stats.hits).toBe(0);
|
||||||
expect(stats.misses).toBe(1);
|
expect(stats.misses).toBe(1);
|
||||||
expect(stats.invalidations).toBe(0);
|
expect(stats.invalidations).toBe(0);
|
||||||
expect(stats.size).toBe(1);
|
expect(stats.size).toBe(1);
|
||||||
expect(stats.maxSize).toBe(10);
|
expect(stats.maxSize).toBe(10);
|
||||||
expect(stats.ttl).toBe(1000);
|
expect(stats.ttl).toBe(1000);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -15,155 +15,156 @@ import { LRUCache } from 'lru-cache';
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export class ContextManager {
|
export class ContextManager {
|
||||||
/**
|
/**
|
||||||
* Create a new ContextManager instance
|
* Create a new ContextManager instance
|
||||||
* @param {ContextManagerConfig} config - Configuration options
|
* @param {ContextManagerConfig} config - Configuration options
|
||||||
*/
|
*/
|
||||||
constructor(config = {}) {
|
constructor(config = {}) {
|
||||||
this.config = {
|
this.config = {
|
||||||
maxCacheSize: config.maxCacheSize || 1000,
|
maxCacheSize: config.maxCacheSize || 1000,
|
||||||
ttl: config.ttl || 1000 * 60 * 5, // 5 minutes default
|
ttl: config.ttl || 1000 * 60 * 5, // 5 minutes default
|
||||||
maxContextSize: config.maxContextSize || 4000
|
maxContextSize: config.maxContextSize || 4000
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initialize LRU cache for context data
|
// Initialize LRU cache for context data
|
||||||
this.cache = new LRUCache({
|
this.cache = new LRUCache({
|
||||||
max: this.config.maxCacheSize,
|
max: this.config.maxCacheSize,
|
||||||
ttl: this.config.ttl,
|
ttl: this.config.ttl,
|
||||||
updateAgeOnGet: true
|
updateAgeOnGet: true
|
||||||
});
|
});
|
||||||
|
|
||||||
// Cache statistics
|
// Cache statistics
|
||||||
this.stats = {
|
this.stats = {
|
||||||
hits: 0,
|
hits: 0,
|
||||||
misses: 0,
|
misses: 0,
|
||||||
invalidations: 0
|
invalidations: 0
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new context or retrieve from cache
|
* Create a new context or retrieve from cache
|
||||||
* @param {string} contextId - Unique identifier for the context
|
* @param {string} contextId - Unique identifier for the context
|
||||||
* @param {Object} metadata - Additional metadata for the context
|
* @param {Object} metadata - Additional metadata for the context
|
||||||
* @returns {Object} Context object with metadata
|
* @returns {Object} Context object with metadata
|
||||||
*/
|
*/
|
||||||
async getContext(contextId, metadata = {}) {
|
async getContext(contextId, metadata = {}) {
|
||||||
const cacheKey = this._getCacheKey(contextId, metadata);
|
const cacheKey = this._getCacheKey(contextId, metadata);
|
||||||
|
|
||||||
// Try to get from cache first
|
// Try to get from cache first
|
||||||
const cached = this.cache.get(cacheKey);
|
const cached = this.cache.get(cacheKey);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
this.stats.hits++;
|
this.stats.hits++;
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.stats.misses++;
|
this.stats.misses++;
|
||||||
|
|
||||||
// Create new context if not in cache
|
// Create new context if not in cache
|
||||||
const context = {
|
const context = {
|
||||||
id: contextId,
|
id: contextId,
|
||||||
metadata: {
|
metadata: {
|
||||||
...metadata,
|
...metadata,
|
||||||
created: new Date().toISOString()
|
created: new Date().toISOString()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Cache the new context
|
// Cache the new context
|
||||||
this.cache.set(cacheKey, context);
|
this.cache.set(cacheKey, context);
|
||||||
|
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update an existing context
|
* Update an existing context
|
||||||
* @param {string} contextId - Context identifier
|
* @param {string} contextId - Context identifier
|
||||||
* @param {Object} updates - Updates to apply to the context
|
* @param {Object} updates - Updates to apply to the context
|
||||||
* @returns {Object} Updated context
|
* @returns {Object} Updated context
|
||||||
*/
|
*/
|
||||||
async updateContext(contextId, updates) {
|
async updateContext(contextId, updates) {
|
||||||
const context = await this.getContext(contextId);
|
const context = await this.getContext(contextId);
|
||||||
|
|
||||||
// Apply updates to context
|
// Apply updates to context
|
||||||
Object.assign(context.metadata, updates);
|
Object.assign(context.metadata, updates);
|
||||||
|
|
||||||
// Update cache
|
// Update cache
|
||||||
const cacheKey = this._getCacheKey(contextId, context.metadata);
|
const cacheKey = this._getCacheKey(contextId, context.metadata);
|
||||||
this.cache.set(cacheKey, context);
|
this.cache.set(cacheKey, context);
|
||||||
|
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Invalidate a context in the cache
|
* Invalidate a context in the cache
|
||||||
* @param {string} contextId - Context identifier
|
* @param {string} contextId - Context identifier
|
||||||
* @param {Object} metadata - Metadata used in the cache key
|
* @param {Object} metadata - Metadata used in the cache key
|
||||||
*/
|
*/
|
||||||
invalidateContext(contextId, metadata = {}) {
|
invalidateContext(contextId, metadata = {}) {
|
||||||
const cacheKey = this._getCacheKey(contextId, metadata);
|
const cacheKey = this._getCacheKey(contextId, metadata);
|
||||||
this.cache.delete(cacheKey);
|
this.cache.delete(cacheKey);
|
||||||
this.stats.invalidations++;
|
this.stats.invalidations++;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get cached data associated with a specific key.
|
* Get cached data associated with a specific key.
|
||||||
* Increments cache hit stats if found.
|
* Increments cache hit stats if found.
|
||||||
* @param {string} key - The cache key.
|
* @param {string} key - The cache key.
|
||||||
* @returns {any | undefined} The cached data or undefined if not found/expired.
|
* @returns {any | undefined} The cached data or undefined if not found/expired.
|
||||||
*/
|
*/
|
||||||
getCachedData(key) {
|
getCachedData(key) {
|
||||||
const cached = this.cache.get(key);
|
const cached = this.cache.get(key);
|
||||||
if (cached !== undefined) { // Check for undefined specifically, as null/false might be valid cached values
|
if (cached !== undefined) {
|
||||||
this.stats.hits++;
|
// Check for undefined specifically, as null/false might be valid cached values
|
||||||
return cached;
|
this.stats.hits++;
|
||||||
}
|
return cached;
|
||||||
this.stats.misses++;
|
}
|
||||||
return undefined;
|
this.stats.misses++;
|
||||||
}
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set data in the cache with a specific key.
|
* Set data in the cache with a specific key.
|
||||||
* @param {string} key - The cache key.
|
* @param {string} key - The cache key.
|
||||||
* @param {any} data - The data to cache.
|
* @param {any} data - The data to cache.
|
||||||
*/
|
*/
|
||||||
setCachedData(key, data) {
|
setCachedData(key, data) {
|
||||||
this.cache.set(key, data);
|
this.cache.set(key, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Invalidate a specific cache key.
|
* Invalidate a specific cache key.
|
||||||
* Increments invalidation stats.
|
* Increments invalidation stats.
|
||||||
* @param {string} key - The cache key to invalidate.
|
* @param {string} key - The cache key to invalidate.
|
||||||
*/
|
*/
|
||||||
invalidateCacheKey(key) {
|
invalidateCacheKey(key) {
|
||||||
this.cache.delete(key);
|
this.cache.delete(key);
|
||||||
this.stats.invalidations++;
|
this.stats.invalidations++;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get cache statistics
|
* Get cache statistics
|
||||||
* @returns {Object} Cache statistics
|
* @returns {Object} Cache statistics
|
||||||
*/
|
*/
|
||||||
getStats() {
|
getStats() {
|
||||||
return {
|
return {
|
||||||
hits: this.stats.hits,
|
hits: this.stats.hits,
|
||||||
misses: this.stats.misses,
|
misses: this.stats.misses,
|
||||||
invalidations: this.stats.invalidations,
|
invalidations: this.stats.invalidations,
|
||||||
size: this.cache.size,
|
size: this.cache.size,
|
||||||
maxSize: this.config.maxCacheSize,
|
maxSize: this.config.maxCacheSize,
|
||||||
ttl: this.config.ttl
|
ttl: this.config.ttl
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate a cache key from context ID and metadata
|
* Generate a cache key from context ID and metadata
|
||||||
* @private
|
* @private
|
||||||
* @deprecated No longer used for direct cache key generation outside the manager.
|
* @deprecated No longer used for direct cache key generation outside the manager.
|
||||||
* Prefer generating specific keys in calling functions.
|
* Prefer generating specific keys in calling functions.
|
||||||
*/
|
*/
|
||||||
_getCacheKey(contextId, metadata) {
|
_getCacheKey(contextId, metadata) {
|
||||||
// Kept for potential backward compatibility or internal use if needed later.
|
// Kept for potential backward compatibility or internal use if needed later.
|
||||||
return `${contextId}:${JSON.stringify(metadata)}`;
|
return `${contextId}:${JSON.stringify(metadata)}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export a singleton instance with default config
|
// Export a singleton instance with default config
|
||||||
|
|||||||
@@ -5,7 +5,10 @@
|
|||||||
|
|
||||||
import { addDependency } from '../../../../scripts/modules/dependency-manager.js';
|
import { addDependency } from '../../../../scripts/modules/dependency-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for addDependency with error handling.
|
* Direct function wrapper for addDependency with error handling.
|
||||||
@@ -19,67 +22,75 @@ import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules
|
|||||||
* @returns {Promise<Object>} - Result object with success status and data/error information
|
* @returns {Promise<Object>} - Result object with success status and data/error information
|
||||||
*/
|
*/
|
||||||
export async function addDependencyDirect(args, log) {
|
export async function addDependencyDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Adding dependency with args: ${JSON.stringify(args)}`);
|
log.info(`Adding dependency with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Validate required parameters
|
// Validate required parameters
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Task ID (id) is required'
|
message: 'Task ID (id) is required'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!args.dependsOn) {
|
if (!args.dependsOn) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Dependency ID (dependsOn) is required'
|
message: 'Dependency ID (dependsOn) is required'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Format IDs for the core function
|
// Format IDs for the core function
|
||||||
const taskId = args.id.includes && args.id.includes('.') ? args.id : parseInt(args.id, 10);
|
const taskId =
|
||||||
const dependencyId = args.dependsOn.includes && args.dependsOn.includes('.') ? args.dependsOn : parseInt(args.dependsOn, 10);
|
args.id.includes && args.id.includes('.')
|
||||||
|
? args.id
|
||||||
|
: parseInt(args.id, 10);
|
||||||
|
const dependencyId =
|
||||||
|
args.dependsOn.includes && args.dependsOn.includes('.')
|
||||||
|
? args.dependsOn
|
||||||
|
: parseInt(args.dependsOn, 10);
|
||||||
|
|
||||||
log.info(`Adding dependency: task ${taskId} will depend on ${dependencyId}`);
|
log.info(
|
||||||
|
`Adding dependency: task ${taskId} will depend on ${dependencyId}`
|
||||||
|
);
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Call the core function
|
// Call the core function
|
||||||
await addDependency(tasksPath, taskId, dependencyId);
|
await addDependency(tasksPath, taskId, dependencyId);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully added dependency: Task ${taskId} now depends on ${dependencyId}`,
|
message: `Successfully added dependency: Task ${taskId} now depends on ${dependencyId}`,
|
||||||
taskId: taskId,
|
taskId: taskId,
|
||||||
dependencyId: dependencyId
|
dependencyId: dependencyId
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error in addDependencyDirect: ${error.message}`);
|
log.error(`Error in addDependencyDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { addSubtask } from '../../../../scripts/modules/task-manager.js';
|
import { addSubtask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add a subtask to an existing task
|
* Add a subtask to an existing task
|
||||||
@@ -23,106 +26,118 @@ import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules
|
|||||||
* @returns {Promise<{success: boolean, data?: Object, error?: string}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: string}>}
|
||||||
*/
|
*/
|
||||||
export async function addSubtaskDirect(args, log) {
|
export async function addSubtaskDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Adding subtask with args: ${JSON.stringify(args)}`);
|
log.info(`Adding subtask with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Parent task ID is required'
|
message: 'Parent task ID is required'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Either taskId or title must be provided
|
// Either taskId or title must be provided
|
||||||
if (!args.taskId && !args.title) {
|
if (!args.taskId && !args.title) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Either taskId or title must be provided'
|
message: 'Either taskId or title must be provided'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Parse dependencies if provided
|
// Parse dependencies if provided
|
||||||
let dependencies = [];
|
let dependencies = [];
|
||||||
if (args.dependencies) {
|
if (args.dependencies) {
|
||||||
dependencies = args.dependencies.split(',').map(id => {
|
dependencies = args.dependencies.split(',').map((id) => {
|
||||||
// Handle both regular IDs and dot notation
|
// Handle both regular IDs and dot notation
|
||||||
return id.includes('.') ? id.trim() : parseInt(id.trim(), 10);
|
return id.includes('.') ? id.trim() : parseInt(id.trim(), 10);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert existingTaskId to a number if provided
|
// Convert existingTaskId to a number if provided
|
||||||
const existingTaskId = args.taskId ? parseInt(args.taskId, 10) : null;
|
const existingTaskId = args.taskId ? parseInt(args.taskId, 10) : null;
|
||||||
|
|
||||||
// Convert parent ID to a number
|
// Convert parent ID to a number
|
||||||
const parentId = parseInt(args.id, 10);
|
const parentId = parseInt(args.id, 10);
|
||||||
|
|
||||||
// Determine if we should generate files
|
// Determine if we should generate files
|
||||||
const generateFiles = !args.skipGenerate;
|
const generateFiles = !args.skipGenerate;
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Case 1: Convert existing task to subtask
|
// Case 1: Convert existing task to subtask
|
||||||
if (existingTaskId) {
|
if (existingTaskId) {
|
||||||
log.info(`Converting task ${existingTaskId} to a subtask of ${parentId}`);
|
log.info(`Converting task ${existingTaskId} to a subtask of ${parentId}`);
|
||||||
const result = await addSubtask(tasksPath, parentId, existingTaskId, null, generateFiles);
|
const result = await addSubtask(
|
||||||
|
tasksPath,
|
||||||
|
parentId,
|
||||||
|
existingTaskId,
|
||||||
|
null,
|
||||||
|
generateFiles
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Task ${existingTaskId} successfully converted to a subtask of task ${parentId}`,
|
message: `Task ${existingTaskId} successfully converted to a subtask of task ${parentId}`,
|
||||||
subtask: result
|
subtask: result
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// Case 2: Create new subtask
|
// Case 2: Create new subtask
|
||||||
else {
|
else {
|
||||||
log.info(`Creating new subtask for parent task ${parentId}`);
|
log.info(`Creating new subtask for parent task ${parentId}`);
|
||||||
|
|
||||||
const newSubtaskData = {
|
const newSubtaskData = {
|
||||||
title: args.title,
|
title: args.title,
|
||||||
description: args.description || '',
|
description: args.description || '',
|
||||||
details: args.details || '',
|
details: args.details || '',
|
||||||
status: args.status || 'pending',
|
status: args.status || 'pending',
|
||||||
dependencies: dependencies
|
dependencies: dependencies
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = await addSubtask(tasksPath, parentId, null, newSubtaskData, generateFiles);
|
const result = await addSubtask(
|
||||||
|
tasksPath,
|
||||||
|
parentId,
|
||||||
|
null,
|
||||||
|
newSubtaskData,
|
||||||
|
generateFiles
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `New subtask ${parentId}.${result.id} successfully created`,
|
message: `New subtask ${parentId}.${result.id} successfully created`,
|
||||||
subtask: result
|
subtask: result
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error in addSubtaskDirect: ${error.message}`);
|
log.error(`Error in addSubtaskDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,9 +5,19 @@
|
|||||||
|
|
||||||
import { addTask } from '../../../../scripts/modules/task-manager.js';
|
import { addTask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
import { getAnthropicClientForMCP, getModelConfig } from '../utils/ai-client-utils.js';
|
enableSilentMode,
|
||||||
import { _buildAddTaskPrompt, parseTaskJsonResponse, _handleAnthropicStream } from '../../../../scripts/modules/ai-services.js';
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getModelConfig
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
|
import {
|
||||||
|
_buildAddTaskPrompt,
|
||||||
|
parseTaskJsonResponse,
|
||||||
|
_handleAnthropicStream
|
||||||
|
} from '../../../../scripts/modules/ai-services.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for adding a new task with error handling.
|
* Direct function wrapper for adding a new task with error handling.
|
||||||
@@ -24,153 +34,162 @@ import { _buildAddTaskPrompt, parseTaskJsonResponse, _handleAnthropicStream } fr
|
|||||||
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
|
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
|
||||||
*/
|
*/
|
||||||
export async function addTaskDirect(args, log, context = {}) {
|
export async function addTaskDirect(args, log, context = {}) {
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.prompt) {
|
if (!args.prompt) {
|
||||||
log.error('Missing required parameter: prompt');
|
log.error('Missing required parameter: prompt');
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'MISSING_PARAMETER',
|
code: 'MISSING_PARAMETER',
|
||||||
message: 'The prompt parameter is required for adding a task'
|
message: 'The prompt parameter is required for adding a task'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract and prepare parameters
|
// Extract and prepare parameters
|
||||||
const prompt = args.prompt;
|
const prompt = args.prompt;
|
||||||
const dependencies = Array.isArray(args.dependencies)
|
const dependencies = Array.isArray(args.dependencies)
|
||||||
? args.dependencies
|
? args.dependencies
|
||||||
: (args.dependencies ? String(args.dependencies).split(',').map(id => parseInt(id.trim(), 10)) : []);
|
: args.dependencies
|
||||||
const priority = args.priority || 'medium';
|
? String(args.dependencies)
|
||||||
|
.split(',')
|
||||||
|
.map((id) => parseInt(id.trim(), 10))
|
||||||
|
: [];
|
||||||
|
const priority = args.priority || 'medium';
|
||||||
|
|
||||||
log.info(`Adding new task with prompt: "${prompt}", dependencies: [${dependencies.join(', ')}], priority: ${priority}`);
|
log.info(
|
||||||
|
`Adding new task with prompt: "${prompt}", dependencies: [${dependencies.join(', ')}], priority: ${priority}`
|
||||||
|
);
|
||||||
|
|
||||||
// Extract context parameters for advanced functionality
|
// Extract context parameters for advanced functionality
|
||||||
// Commenting out reportProgress extraction
|
// Commenting out reportProgress extraction
|
||||||
// const { reportProgress, session } = context;
|
// const { reportProgress, session } = context;
|
||||||
const { session } = context; // Keep session
|
const { session } = context; // Keep session
|
||||||
|
|
||||||
// Initialize AI client with session environment
|
// Initialize AI client with session environment
|
||||||
let localAnthropic;
|
let localAnthropic;
|
||||||
try {
|
try {
|
||||||
localAnthropic = getAnthropicClientForMCP(session, log);
|
localAnthropic = getAnthropicClientForMCP(session, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to initialize Anthropic client: ${error.message}`);
|
log.error(`Failed to initialize Anthropic client: ${error.message}`);
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_CLIENT_ERROR',
|
code: 'AI_CLIENT_ERROR',
|
||||||
message: `Cannot initialize AI client: ${error.message}`
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get model configuration from session
|
// Get model configuration from session
|
||||||
const modelConfig = getModelConfig(session);
|
const modelConfig = getModelConfig(session);
|
||||||
|
|
||||||
// Read existing tasks to provide context
|
// Read existing tasks to provide context
|
||||||
let tasksData;
|
let tasksData;
|
||||||
try {
|
try {
|
||||||
const fs = await import('fs');
|
const fs = await import('fs');
|
||||||
tasksData = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
tasksData = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.warn(`Could not read existing tasks for context: ${error.message}`);
|
log.warn(`Could not read existing tasks for context: ${error.message}`);
|
||||||
tasksData = { tasks: [] };
|
tasksData = { tasks: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build prompts for AI
|
// Build prompts for AI
|
||||||
const { systemPrompt, userPrompt } = _buildAddTaskPrompt(prompt, tasksData.tasks);
|
const { systemPrompt, userPrompt } = _buildAddTaskPrompt(
|
||||||
|
prompt,
|
||||||
|
tasksData.tasks
|
||||||
|
);
|
||||||
|
|
||||||
// Make the AI call using the streaming helper
|
// Make the AI call using the streaming helper
|
||||||
let responseText;
|
let responseText;
|
||||||
try {
|
try {
|
||||||
responseText = await _handleAnthropicStream(
|
responseText = await _handleAnthropicStream(
|
||||||
localAnthropic,
|
localAnthropic,
|
||||||
{
|
{
|
||||||
model: modelConfig.model,
|
model: modelConfig.model,
|
||||||
max_tokens: modelConfig.maxTokens,
|
max_tokens: modelConfig.maxTokens,
|
||||||
temperature: modelConfig.temperature,
|
temperature: modelConfig.temperature,
|
||||||
messages: [{ role: "user", content: userPrompt }],
|
messages: [{ role: 'user', content: userPrompt }],
|
||||||
system: systemPrompt
|
system: systemPrompt
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
// reportProgress: context.reportProgress, // Commented out to prevent Cursor stroking out
|
// reportProgress: context.reportProgress, // Commented out to prevent Cursor stroking out
|
||||||
mcpLog: log
|
mcpLog: log
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`AI processing failed: ${error.message}`);
|
log.error(`AI processing failed: ${error.message}`);
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_PROCESSING_ERROR',
|
code: 'AI_PROCESSING_ERROR',
|
||||||
message: `Failed to generate task with AI: ${error.message}`
|
message: `Failed to generate task with AI: ${error.message}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the AI response
|
// Parse the AI response
|
||||||
let taskDataFromAI;
|
let taskDataFromAI;
|
||||||
try {
|
try {
|
||||||
taskDataFromAI = parseTaskJsonResponse(responseText);
|
taskDataFromAI = parseTaskJsonResponse(responseText);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to parse AI response: ${error.message}`);
|
log.error(`Failed to parse AI response: ${error.message}`);
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'RESPONSE_PARSING_ERROR',
|
code: 'RESPONSE_PARSING_ERROR',
|
||||||
message: `Failed to parse AI response: ${error.message}`
|
message: `Failed to parse AI response: ${error.message}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call the addTask function with 'json' outputFormat to prevent console output when called via MCP
|
// Call the addTask function with 'json' outputFormat to prevent console output when called via MCP
|
||||||
const newTaskId = await addTask(
|
const newTaskId = await addTask(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
prompt,
|
prompt,
|
||||||
dependencies,
|
dependencies,
|
||||||
priority,
|
priority,
|
||||||
{
|
{
|
||||||
// reportProgress, // Commented out
|
// reportProgress, // Commented out
|
||||||
mcpLog: log,
|
mcpLog: log,
|
||||||
session,
|
session,
|
||||||
taskDataFromAI // Pass the parsed AI result
|
taskDataFromAI // Pass the parsed AI result
|
||||||
},
|
},
|
||||||
'json'
|
'json'
|
||||||
);
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
taskId: newTaskId,
|
taskId: newTaskId,
|
||||||
message: `Successfully added new task #${newTaskId}`
|
message: `Successfully added new task #${newTaskId}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error in addTaskDirect: ${error.message}`);
|
log.error(`Error in addTaskDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'ADD_TASK_ERROR',
|
code: 'ADD_TASK_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,12 @@
|
|||||||
|
|
||||||
import { analyzeTaskComplexity } from '../../../../scripts/modules/task-manager.js';
|
import { analyzeTaskComplexity } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode, isSilentMode, readJSON } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode,
|
||||||
|
isSilentMode,
|
||||||
|
readJSON
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
@@ -22,135 +27,142 @@ import path from 'path';
|
|||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||||
const { session } = context; // Only extract session, not reportProgress
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Analyzing task complexity with args: ${JSON.stringify(args)}`);
|
log.info(`Analyzing task complexity with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Determine output path
|
// Determine output path
|
||||||
let outputPath = args.output || 'scripts/task-complexity-report.json';
|
let outputPath = args.output || 'scripts/task-complexity-report.json';
|
||||||
if (!path.isAbsolute(outputPath) && args.projectRoot) {
|
if (!path.isAbsolute(outputPath) && args.projectRoot) {
|
||||||
outputPath = path.join(args.projectRoot, outputPath);
|
outputPath = path.join(args.projectRoot, outputPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Analyzing task complexity from: ${tasksPath}`);
|
log.info(`Analyzing task complexity from: ${tasksPath}`);
|
||||||
log.info(`Output report will be saved to: ${outputPath}`);
|
log.info(`Output report will be saved to: ${outputPath}`);
|
||||||
|
|
||||||
if (args.research) {
|
if (args.research) {
|
||||||
log.info('Using Perplexity AI for research-backed complexity analysis');
|
log.info('Using Perplexity AI for research-backed complexity analysis');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create options object for analyzeTaskComplexity
|
// Create options object for analyzeTaskComplexity
|
||||||
const options = {
|
const options = {
|
||||||
file: tasksPath,
|
file: tasksPath,
|
||||||
output: outputPath,
|
output: outputPath,
|
||||||
model: args.model,
|
model: args.model,
|
||||||
threshold: args.threshold,
|
threshold: args.threshold,
|
||||||
research: args.research === true
|
research: args.research === true
|
||||||
};
|
};
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
const wasSilent = isSilentMode();
|
const wasSilent = isSilentMode();
|
||||||
if (!wasSilent) {
|
if (!wasSilent) {
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a logWrapper that matches the expected mcpLog interface as specified in utilities.mdc
|
// Create a logWrapper that matches the expected mcpLog interface as specified in utilities.mdc
|
||||||
const logWrapper = {
|
const logWrapper = {
|
||||||
info: (message, ...args) => log.info(message, ...args),
|
info: (message, ...args) => log.info(message, ...args),
|
||||||
warn: (message, ...args) => log.warn(message, ...args),
|
warn: (message, ...args) => log.warn(message, ...args),
|
||||||
error: (message, ...args) => log.error(message, ...args),
|
error: (message, ...args) => log.error(message, ...args),
|
||||||
debug: (message, ...args) => log.debug && log.debug(message, ...args),
|
debug: (message, ...args) => log.debug && log.debug(message, ...args),
|
||||||
success: (message, ...args) => log.info(message, ...args) // Map success to info
|
success: (message, ...args) => log.info(message, ...args) // Map success to info
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Call the core function with session and logWrapper as mcpLog
|
// Call the core function with session and logWrapper as mcpLog
|
||||||
await analyzeTaskComplexity(options, {
|
await analyzeTaskComplexity(options, {
|
||||||
session,
|
session,
|
||||||
mcpLog: logWrapper // Use the wrapper instead of passing log directly
|
mcpLog: logWrapper // Use the wrapper instead of passing log directly
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in analyzeTaskComplexity: ${error.message}`);
|
log.error(`Error in analyzeTaskComplexity: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'ANALYZE_ERROR',
|
code: 'ANALYZE_ERROR',
|
||||||
message: `Error running complexity analysis: ${error.message}`
|
message: `Error running complexity analysis: ${error.message}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} finally {
|
} finally {
|
||||||
// Always restore normal logging in finally block, but only if we enabled it
|
// Always restore normal logging in finally block, but only if we enabled it
|
||||||
if (!wasSilent) {
|
if (!wasSilent) {
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify the report file was created
|
// Verify the report file was created
|
||||||
if (!fs.existsSync(outputPath)) {
|
if (!fs.existsSync(outputPath)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'ANALYZE_ERROR',
|
code: 'ANALYZE_ERROR',
|
||||||
message: 'Analysis completed but no report file was created'
|
message: 'Analysis completed but no report file was created'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the report file
|
// Read the report file
|
||||||
let report;
|
let report;
|
||||||
try {
|
try {
|
||||||
report = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
report = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
||||||
|
|
||||||
// Important: Handle different report formats
|
// Important: Handle different report formats
|
||||||
// The core function might return an array or an object with a complexityAnalysis property
|
// The core function might return an array or an object with a complexityAnalysis property
|
||||||
const analysisArray = Array.isArray(report) ? report :
|
const analysisArray = Array.isArray(report)
|
||||||
(report.complexityAnalysis || []);
|
? report
|
||||||
|
: report.complexityAnalysis || [];
|
||||||
|
|
||||||
// Count tasks by complexity
|
// Count tasks by complexity
|
||||||
const highComplexityTasks = analysisArray.filter(t => t.complexityScore >= 8).length;
|
const highComplexityTasks = analysisArray.filter(
|
||||||
const mediumComplexityTasks = analysisArray.filter(t => t.complexityScore >= 5 && t.complexityScore < 8).length;
|
(t) => t.complexityScore >= 8
|
||||||
const lowComplexityTasks = analysisArray.filter(t => t.complexityScore < 5).length;
|
).length;
|
||||||
|
const mediumComplexityTasks = analysisArray.filter(
|
||||||
|
(t) => t.complexityScore >= 5 && t.complexityScore < 8
|
||||||
|
).length;
|
||||||
|
const lowComplexityTasks = analysisArray.filter(
|
||||||
|
(t) => t.complexityScore < 5
|
||||||
|
).length;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Task complexity analysis complete. Report saved to ${outputPath}`,
|
message: `Task complexity analysis complete. Report saved to ${outputPath}`,
|
||||||
reportPath: outputPath,
|
reportPath: outputPath,
|
||||||
reportSummary: {
|
reportSummary: {
|
||||||
taskCount: analysisArray.length,
|
taskCount: analysisArray.length,
|
||||||
highComplexityTasks,
|
highComplexityTasks,
|
||||||
mediumComplexityTasks,
|
mediumComplexityTasks,
|
||||||
lowComplexityTasks
|
lowComplexityTasks
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (parseError) {
|
} catch (parseError) {
|
||||||
log.error(`Error parsing report file: ${parseError.message}`);
|
log.error(`Error parsing report file: ${parseError.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'REPORT_PARSE_ERROR',
|
code: 'REPORT_PARSE_ERROR',
|
||||||
message: `Error parsing complexity report: ${parseError.message}`
|
message: `Error parsing complexity report: ${parseError.message}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
if (isSilentMode()) {
|
if (isSilentMode()) {
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
}
|
}
|
||||||
|
|
||||||
log.error(`Error in analyzeTaskComplexityDirect: ${error.message}`);
|
log.error(`Error in analyzeTaskComplexityDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,21 +12,21 @@ import { contextManager } from '../context-manager.js';
|
|||||||
* @returns {Object} - Cache statistics
|
* @returns {Object} - Cache statistics
|
||||||
*/
|
*/
|
||||||
export async function getCacheStatsDirect(args, log) {
|
export async function getCacheStatsDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info('Retrieving cache statistics');
|
log.info('Retrieving cache statistics');
|
||||||
const stats = contextManager.getStats();
|
const stats = contextManager.getStats();
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: stats
|
data: stats
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error getting cache stats: ${error.message}`);
|
log.error(`Error getting cache stats: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CACHE_STATS_ERROR',
|
code: 'CACHE_STATS_ERROR',
|
||||||
message: error.message || 'Unknown error occurred'
|
message: error.message || 'Unknown error occurred'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { clearSubtasks } from '../../../../scripts/modules/task-manager.js';
|
import { clearSubtasks } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -18,95 +21,96 @@ import fs from 'fs';
|
|||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function clearSubtasksDirect(args, log) {
|
export async function clearSubtasksDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Clearing subtasks with args: ${JSON.stringify(args)}`);
|
log.info(`Clearing subtasks with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Either id or all must be provided
|
// Either id or all must be provided
|
||||||
if (!args.id && !args.all) {
|
if (!args.id && !args.all) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Either task IDs with id parameter or all parameter must be provided'
|
message:
|
||||||
}
|
'Either task IDs with id parameter or all parameter must be provided'
|
||||||
};
|
}
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Check if tasks.json exists
|
// Check if tasks.json exists
|
||||||
if (!fs.existsSync(tasksPath)) {
|
if (!fs.existsSync(tasksPath)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND_ERROR',
|
code: 'FILE_NOT_FOUND_ERROR',
|
||||||
message: `Tasks file not found at ${tasksPath}`
|
message: `Tasks file not found at ${tasksPath}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let taskIds;
|
let taskIds;
|
||||||
|
|
||||||
// If all is specified, get all task IDs
|
// If all is specified, get all task IDs
|
||||||
if (args.all) {
|
if (args.all) {
|
||||||
log.info('Clearing subtasks from all tasks');
|
log.info('Clearing subtasks from all tasks');
|
||||||
const data = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
const data = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
||||||
if (!data || !data.tasks || data.tasks.length === 0) {
|
if (!data || !data.tasks || data.tasks.length === 0) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'No valid tasks found in the tasks file'
|
message: 'No valid tasks found in the tasks file'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
taskIds = data.tasks.map(t => t.id).join(',');
|
taskIds = data.tasks.map((t) => t.id).join(',');
|
||||||
} else {
|
} else {
|
||||||
// Use the provided task IDs
|
// Use the provided task IDs
|
||||||
taskIds = args.id;
|
taskIds = args.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Clearing subtasks from tasks: ${taskIds}`);
|
log.info(`Clearing subtasks from tasks: ${taskIds}`);
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Call the core function
|
// Call the core function
|
||||||
clearSubtasks(tasksPath, taskIds);
|
clearSubtasks(tasksPath, taskIds);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
// Read the updated data to provide a summary
|
// Read the updated data to provide a summary
|
||||||
const updatedData = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
const updatedData = JSON.parse(fs.readFileSync(tasksPath, 'utf8'));
|
||||||
const taskIdArray = taskIds.split(',').map(id => parseInt(id.trim(), 10));
|
const taskIdArray = taskIds.split(',').map((id) => parseInt(id.trim(), 10));
|
||||||
|
|
||||||
// Build a summary of what was done
|
// Build a summary of what was done
|
||||||
const clearedTasksCount = taskIdArray.length;
|
const clearedTasksCount = taskIdArray.length;
|
||||||
const taskSummary = taskIdArray.map(id => {
|
const taskSummary = taskIdArray.map((id) => {
|
||||||
const task = updatedData.tasks.find(t => t.id === id);
|
const task = updatedData.tasks.find((t) => t.id === id);
|
||||||
return task ? { id, title: task.title } : { id, title: 'Task not found' };
|
return task ? { id, title: task.title } : { id, title: 'Task not found' };
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully cleared subtasks from ${clearedTasksCount} task(s)`,
|
message: `Successfully cleared subtasks from ${clearedTasksCount} task(s)`,
|
||||||
tasksCleared: taskSummary
|
tasksCleared: taskSummary
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error in clearSubtasksDirect: ${error.message}`);
|
log.error(`Error in clearSubtasksDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,11 @@
|
|||||||
* Direct function implementation for displaying complexity analysis report
|
* Direct function implementation for displaying complexity analysis report
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { readComplexityReport, enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
readComplexityReport,
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
@@ -16,106 +20,114 @@ import path from 'path';
|
|||||||
* @returns {Promise<Object>} - Result object with success status and data/error information
|
* @returns {Promise<Object>} - Result object with success status and data/error information
|
||||||
*/
|
*/
|
||||||
export async function complexityReportDirect(args, log) {
|
export async function complexityReportDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Getting complexity report with args: ${JSON.stringify(args)}`);
|
log.info(`Getting complexity report with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Get tasks file path to determine project root for the default report location
|
// Get tasks file path to determine project root for the default report location
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.warn(`Tasks file not found, using current directory: ${error.message}`);
|
log.warn(
|
||||||
// Continue with default or specified report path
|
`Tasks file not found, using current directory: ${error.message}`
|
||||||
}
|
);
|
||||||
|
// Continue with default or specified report path
|
||||||
|
}
|
||||||
|
|
||||||
// Get report file path from args or use default
|
// Get report file path from args or use default
|
||||||
const reportPath = args.file || path.join(process.cwd(), 'scripts', 'task-complexity-report.json');
|
const reportPath =
|
||||||
|
args.file ||
|
||||||
|
path.join(process.cwd(), 'scripts', 'task-complexity-report.json');
|
||||||
|
|
||||||
log.info(`Looking for complexity report at: ${reportPath}`);
|
log.info(`Looking for complexity report at: ${reportPath}`);
|
||||||
|
|
||||||
// Generate cache key based on report path
|
// Generate cache key based on report path
|
||||||
const cacheKey = `complexityReport:${reportPath}`;
|
const cacheKey = `complexityReport:${reportPath}`;
|
||||||
|
|
||||||
// Define the core action function to read the report
|
// Define the core action function to read the report
|
||||||
const coreActionFn = async () => {
|
const coreActionFn = async () => {
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
const report = readComplexityReport(reportPath);
|
const report = readComplexityReport(reportPath);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
if (!report) {
|
if (!report) {
|
||||||
log.warn(`No complexity report found at ${reportPath}`);
|
log.warn(`No complexity report found at ${reportPath}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND_ERROR',
|
code: 'FILE_NOT_FOUND_ERROR',
|
||||||
message: `No complexity report found at ${reportPath}. Run 'analyze-complexity' first.`
|
message: `No complexity report found at ${reportPath}. Run 'analyze-complexity' first.`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
report,
|
report,
|
||||||
reportPath
|
reportPath
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error reading complexity report: ${error.message}`);
|
log.error(`Error reading complexity report: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'READ_ERROR',
|
code: 'READ_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Use the caching utility
|
// Use the caching utility
|
||||||
try {
|
try {
|
||||||
const result = await getCachedOrExecute({
|
const result = await getCachedOrExecute({
|
||||||
cacheKey,
|
cacheKey,
|
||||||
actionFn: coreActionFn,
|
actionFn: coreActionFn,
|
||||||
log
|
log
|
||||||
});
|
});
|
||||||
log.info(`complexityReportDirect completed. From cache: ${result.fromCache}`);
|
log.info(
|
||||||
return result; // Returns { success, data/error, fromCache }
|
`complexityReportDirect completed. From cache: ${result.fromCache}`
|
||||||
} catch (error) {
|
);
|
||||||
// Catch unexpected errors from getCachedOrExecute itself
|
return result; // Returns { success, data/error, fromCache }
|
||||||
// Ensure silent mode is disabled
|
} catch (error) {
|
||||||
disableSilentMode();
|
// Catch unexpected errors from getCachedOrExecute itself
|
||||||
|
// Ensure silent mode is disabled
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Unexpected error during getCachedOrExecute for complexityReport: ${error.message}`);
|
log.error(
|
||||||
return {
|
`Unexpected error during getCachedOrExecute for complexityReport: ${error.message}`
|
||||||
success: false,
|
);
|
||||||
error: {
|
return {
|
||||||
code: 'UNEXPECTED_ERROR',
|
success: false,
|
||||||
message: error.message
|
error: {
|
||||||
},
|
code: 'UNEXPECTED_ERROR',
|
||||||
fromCache: false
|
message: error.message
|
||||||
};
|
},
|
||||||
}
|
fromCache: false
|
||||||
} catch (error) {
|
};
|
||||||
// Ensure silent mode is disabled if an outer error occurs
|
}
|
||||||
disableSilentMode();
|
} catch (error) {
|
||||||
|
// Ensure silent mode is disabled if an outer error occurs
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error in complexityReportDirect: ${error.message}`);
|
log.error(`Error in complexityReportDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'UNEXPECTED_ERROR',
|
code: 'UNEXPECTED_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { expandAllTasks } from '../../../../scripts/modules/task-manager.js';
|
import { expandAllTasks } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode,
|
||||||
|
isSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { getAnthropicClientForMCP } from '../utils/ai-client-utils.js';
|
import { getAnthropicClientForMCP } from '../utils/ai-client-utils.js';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
@@ -23,98 +27,100 @@ import fs from 'fs';
|
|||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function expandAllTasksDirect(args, log, context = {}) {
|
export async function expandAllTasksDirect(args, log, context = {}) {
|
||||||
const { session } = context; // Only extract session, not reportProgress
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Expanding all tasks with args: ${JSON.stringify(args)}`);
|
log.info(`Expanding all tasks with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Enable silent mode early to prevent any console output
|
// Enable silent mode early to prevent any console output
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Parse parameters
|
// Parse parameters
|
||||||
const numSubtasks = args.num ? parseInt(args.num, 10) : undefined;
|
const numSubtasks = args.num ? parseInt(args.num, 10) : undefined;
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
const additionalContext = args.prompt || '';
|
const additionalContext = args.prompt || '';
|
||||||
const forceFlag = args.force === true;
|
const forceFlag = args.force === true;
|
||||||
|
|
||||||
log.info(`Expanding all tasks with ${numSubtasks || 'default'} subtasks each...`);
|
log.info(
|
||||||
|
`Expanding all tasks with ${numSubtasks || 'default'} subtasks each...`
|
||||||
|
);
|
||||||
|
|
||||||
if (useResearch) {
|
if (useResearch) {
|
||||||
log.info('Using Perplexity AI for research-backed subtask generation');
|
log.info('Using Perplexity AI for research-backed subtask generation');
|
||||||
|
|
||||||
// Initialize AI client for research-backed expansion
|
// Initialize AI client for research-backed expansion
|
||||||
try {
|
try {
|
||||||
await getAnthropicClientForMCP(session, log);
|
await getAnthropicClientForMCP(session, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ensure silent mode is disabled before returning error
|
// Ensure silent mode is disabled before returning error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Failed to initialize AI client: ${error.message}`);
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_CLIENT_ERROR',
|
code: 'AI_CLIENT_ERROR',
|
||||||
message: `Cannot initialize AI client: ${error.message}`
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (additionalContext) {
|
if (additionalContext) {
|
||||||
log.info(`Additional context: "${additionalContext}"`);
|
log.info(`Additional context: "${additionalContext}"`);
|
||||||
}
|
}
|
||||||
if (forceFlag) {
|
if (forceFlag) {
|
||||||
log.info('Force regeneration of subtasks is enabled');
|
log.info('Force regeneration of subtasks is enabled');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call the core function with session context for AI operations
|
// Call the core function with session context for AI operations
|
||||||
// and outputFormat as 'json' to prevent UI elements
|
// and outputFormat as 'json' to prevent UI elements
|
||||||
const result = await expandAllTasks(
|
const result = await expandAllTasks(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
numSubtasks,
|
numSubtasks,
|
||||||
useResearch,
|
useResearch,
|
||||||
additionalContext,
|
additionalContext,
|
||||||
forceFlag,
|
forceFlag,
|
||||||
{ mcpLog: log, session },
|
{ mcpLog: log, session },
|
||||||
'json' // Use JSON output format to prevent UI elements
|
'json' // Use JSON output format to prevent UI elements
|
||||||
);
|
);
|
||||||
|
|
||||||
// The expandAllTasks function now returns a result object
|
// The expandAllTasks function now returns a result object
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: "Successfully expanded all pending tasks with subtasks",
|
message: 'Successfully expanded all pending tasks with subtasks',
|
||||||
details: {
|
details: {
|
||||||
numSubtasks: numSubtasks,
|
numSubtasks: numSubtasks,
|
||||||
research: useResearch,
|
research: useResearch,
|
||||||
prompt: additionalContext,
|
prompt: additionalContext,
|
||||||
force: forceFlag,
|
force: forceFlag,
|
||||||
tasksExpanded: result.expandedCount,
|
tasksExpanded: result.expandedCount,
|
||||||
totalEligibleTasks: result.tasksToExpand
|
totalEligibleTasks: result.tasksToExpand
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} finally {
|
} finally {
|
||||||
// Restore normal logging in finally block to ensure it runs even if there's an error
|
// Restore normal logging in finally block to ensure it runs even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ensure silent mode is disabled if an error occurs
|
// Ensure silent mode is disabled if an error occurs
|
||||||
if (isSilentMode()) {
|
if (isSilentMode()) {
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
}
|
}
|
||||||
|
|
||||||
log.error(`Error in expandAllTasksDirect: ${error.message}`);
|
log.error(`Error in expandAllTasksDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,9 +4,18 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { expandTask } from '../../../../scripts/modules/task-manager.js';
|
import { expandTask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { readJSON, writeJSON, enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
readJSON,
|
||||||
|
writeJSON,
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode,
|
||||||
|
isSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { getAnthropicClientForMCP, getModelConfig } from '../utils/ai-client-utils.js';
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getModelConfig
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
@@ -19,231 +28,248 @@ import fs from 'fs';
|
|||||||
* @returns {Promise<Object>} - Task expansion result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
* @returns {Promise<Object>} - Task expansion result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
||||||
*/
|
*/
|
||||||
export async function expandTaskDirect(args, log, context = {}) {
|
export async function expandTaskDirect(args, log, context = {}) {
|
||||||
const { session } = context;
|
const { session } = context;
|
||||||
|
|
||||||
// Log session root data for debugging
|
// Log session root data for debugging
|
||||||
log.info(`Session data in expandTaskDirect: ${JSON.stringify({
|
log.info(
|
||||||
hasSession: !!session,
|
`Session data in expandTaskDirect: ${JSON.stringify({
|
||||||
sessionKeys: session ? Object.keys(session) : [],
|
hasSession: !!session,
|
||||||
roots: session?.roots,
|
sessionKeys: session ? Object.keys(session) : [],
|
||||||
rootsStr: JSON.stringify(session?.roots)
|
roots: session?.roots,
|
||||||
})}`);
|
rootsStr: JSON.stringify(session?.roots)
|
||||||
|
})}`
|
||||||
|
);
|
||||||
|
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
// If a direct file path is provided, use it directly
|
// If a direct file path is provided, use it directly
|
||||||
if (args.file && fs.existsSync(args.file)) {
|
if (args.file && fs.existsSync(args.file)) {
|
||||||
log.info(`[expandTaskDirect] Using explicitly provided tasks file: ${args.file}`);
|
log.info(
|
||||||
tasksPath = args.file;
|
`[expandTaskDirect] Using explicitly provided tasks file: ${args.file}`
|
||||||
} else {
|
);
|
||||||
// Find the tasks path through standard logic
|
tasksPath = args.file;
|
||||||
log.info(`[expandTaskDirect] No direct file path provided or file not found at ${args.file}, searching using findTasksJsonPath`);
|
} else {
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
// Find the tasks path through standard logic
|
||||||
}
|
log.info(
|
||||||
} catch (error) {
|
`[expandTaskDirect] No direct file path provided or file not found at ${args.file}, searching using findTasksJsonPath`
|
||||||
log.error(`[expandTaskDirect] Error during tasksPath determination: ${error.message}`);
|
);
|
||||||
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
log.error(
|
||||||
|
`[expandTaskDirect] Error during tasksPath determination: ${error.message}`
|
||||||
|
);
|
||||||
|
|
||||||
// Include session roots information in error
|
// Include session roots information in error
|
||||||
const sessionRootsInfo = session ?
|
const sessionRootsInfo = session
|
||||||
`\nSession.roots: ${JSON.stringify(session.roots)}\n` +
|
? `\nSession.roots: ${JSON.stringify(session.roots)}\n` +
|
||||||
`Current Working Directory: ${process.cwd()}\n` +
|
`Current Working Directory: ${process.cwd()}\n` +
|
||||||
`Args.projectRoot: ${args.projectRoot}\n` +
|
`Args.projectRoot: ${args.projectRoot}\n` +
|
||||||
`Args.file: ${args.file}\n` :
|
`Args.file: ${args.file}\n`
|
||||||
'\nSession object not available';
|
: '\nSession object not available';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND_ERROR',
|
code: 'FILE_NOT_FOUND_ERROR',
|
||||||
message: `Error determining tasksPath: ${error.message}${sessionRootsInfo}`
|
message: `Error determining tasksPath: ${error.message}${sessionRootsInfo}`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`[expandTaskDirect] Determined tasksPath: ${tasksPath}`);
|
log.info(`[expandTaskDirect] Determined tasksPath: ${tasksPath}`);
|
||||||
|
|
||||||
// Validate task ID
|
// Validate task ID
|
||||||
const taskId = args.id ? parseInt(args.id, 10) : null;
|
const taskId = args.id ? parseInt(args.id, 10) : null;
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
log.error('Task ID is required');
|
log.error('Task ID is required');
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Task ID is required'
|
message: 'Task ID is required'
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process other parameters
|
// Process other parameters
|
||||||
const numSubtasks = args.num ? parseInt(args.num, 10) : undefined;
|
const numSubtasks = args.num ? parseInt(args.num, 10) : undefined;
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
const additionalContext = args.prompt || '';
|
const additionalContext = args.prompt || '';
|
||||||
|
|
||||||
// Initialize AI client if needed (for expandTask function)
|
// Initialize AI client if needed (for expandTask function)
|
||||||
try {
|
try {
|
||||||
// This ensures the AI client is available by checking it
|
// This ensures the AI client is available by checking it
|
||||||
if (useResearch) {
|
if (useResearch) {
|
||||||
log.info('Verifying AI client for research-backed expansion');
|
log.info('Verifying AI client for research-backed expansion');
|
||||||
await getAnthropicClientForMCP(session, log);
|
await getAnthropicClientForMCP(session, log);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to initialize AI client: ${error.message}`);
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_CLIENT_ERROR',
|
code: 'AI_CLIENT_ERROR',
|
||||||
message: `Cannot initialize AI client: ${error.message}`
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`[expandTaskDirect] Expanding task ${taskId} into ${numSubtasks || 'default'} subtasks. Research: ${useResearch}`);
|
log.info(
|
||||||
|
`[expandTaskDirect] Expanding task ${taskId} into ${numSubtasks || 'default'} subtasks. Research: ${useResearch}`
|
||||||
|
);
|
||||||
|
|
||||||
// Read tasks data
|
// Read tasks data
|
||||||
log.info(`[expandTaskDirect] Attempting to read JSON from: ${tasksPath}`);
|
log.info(`[expandTaskDirect] Attempting to read JSON from: ${tasksPath}`);
|
||||||
const data = readJSON(tasksPath);
|
const data = readJSON(tasksPath);
|
||||||
log.info(`[expandTaskDirect] Result of readJSON: ${data ? 'Data read successfully' : 'readJSON returned null or undefined'}`);
|
log.info(
|
||||||
|
`[expandTaskDirect] Result of readJSON: ${data ? 'Data read successfully' : 'readJSON returned null or undefined'}`
|
||||||
|
);
|
||||||
|
|
||||||
if (!data || !data.tasks) {
|
if (!data || !data.tasks) {
|
||||||
log.error(`[expandTaskDirect] readJSON failed or returned invalid data for path: ${tasksPath}`);
|
log.error(
|
||||||
return {
|
`[expandTaskDirect] readJSON failed or returned invalid data for path: ${tasksPath}`
|
||||||
success: false,
|
);
|
||||||
error: {
|
return {
|
||||||
code: 'INVALID_TASKS_FILE',
|
success: false,
|
||||||
message: `No valid tasks found in ${tasksPath}. readJSON returned: ${JSON.stringify(data)}`
|
error: {
|
||||||
},
|
code: 'INVALID_TASKS_FILE',
|
||||||
fromCache: false
|
message: `No valid tasks found in ${tasksPath}. readJSON returned: ${JSON.stringify(data)}`
|
||||||
};
|
},
|
||||||
}
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Find the specific task
|
// Find the specific task
|
||||||
log.info(`[expandTaskDirect] Searching for task ID ${taskId} in data`);
|
log.info(`[expandTaskDirect] Searching for task ID ${taskId} in data`);
|
||||||
const task = data.tasks.find(t => t.id === taskId);
|
const task = data.tasks.find((t) => t.id === taskId);
|
||||||
log.info(`[expandTaskDirect] Task found: ${task ? 'Yes' : 'No'}`);
|
log.info(`[expandTaskDirect] Task found: ${task ? 'Yes' : 'No'}`);
|
||||||
|
|
||||||
if (!task) {
|
if (!task) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'TASK_NOT_FOUND',
|
code: 'TASK_NOT_FOUND',
|
||||||
message: `Task with ID ${taskId} not found`
|
message: `Task with ID ${taskId} not found`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if task is completed
|
// Check if task is completed
|
||||||
if (task.status === 'done' || task.status === 'completed') {
|
if (task.status === 'done' || task.status === 'completed') {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'TASK_COMPLETED',
|
code: 'TASK_COMPLETED',
|
||||||
message: `Task ${taskId} is already marked as ${task.status} and cannot be expanded`
|
message: `Task ${taskId} is already marked as ${task.status} and cannot be expanded`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for existing subtasks
|
// Check for existing subtasks
|
||||||
const hasExistingSubtasks = task.subtasks && task.subtasks.length > 0;
|
const hasExistingSubtasks = task.subtasks && task.subtasks.length > 0;
|
||||||
|
|
||||||
// If the task already has subtasks, just return it (matching core behavior)
|
// If the task already has subtasks, just return it (matching core behavior)
|
||||||
if (hasExistingSubtasks) {
|
if (hasExistingSubtasks) {
|
||||||
log.info(`Task ${taskId} already has ${task.subtasks.length} subtasks`);
|
log.info(`Task ${taskId} already has ${task.subtasks.length} subtasks`);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
task,
|
task,
|
||||||
subtasksAdded: 0,
|
subtasksAdded: 0,
|
||||||
hasExistingSubtasks
|
hasExistingSubtasks
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keep a copy of the task before modification
|
// Keep a copy of the task before modification
|
||||||
const originalTask = JSON.parse(JSON.stringify(task));
|
const originalTask = JSON.parse(JSON.stringify(task));
|
||||||
|
|
||||||
// Tracking subtasks count before expansion
|
// Tracking subtasks count before expansion
|
||||||
const subtasksCountBefore = task.subtasks ? task.subtasks.length : 0;
|
const subtasksCountBefore = task.subtasks ? task.subtasks.length : 0;
|
||||||
|
|
||||||
// Create a backup of the tasks.json file
|
// Create a backup of the tasks.json file
|
||||||
const backupPath = path.join(path.dirname(tasksPath), 'tasks.json.bak');
|
const backupPath = path.join(path.dirname(tasksPath), 'tasks.json.bak');
|
||||||
fs.copyFileSync(tasksPath, backupPath);
|
fs.copyFileSync(tasksPath, backupPath);
|
||||||
|
|
||||||
// Directly modify the data instead of calling the CLI function
|
// Directly modify the data instead of calling the CLI function
|
||||||
if (!task.subtasks) {
|
if (!task.subtasks) {
|
||||||
task.subtasks = [];
|
task.subtasks = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save tasks.json with potentially empty subtasks array
|
// Save tasks.json with potentially empty subtasks array
|
||||||
writeJSON(tasksPath, data);
|
writeJSON(tasksPath, data);
|
||||||
|
|
||||||
// Process the request
|
// Process the request
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Call expandTask with session context to ensure AI client is properly initialized
|
// Call expandTask with session context to ensure AI client is properly initialized
|
||||||
const result = await expandTask(
|
const result = await expandTask(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
taskId,
|
taskId,
|
||||||
numSubtasks,
|
numSubtasks,
|
||||||
useResearch,
|
useResearch,
|
||||||
additionalContext,
|
additionalContext,
|
||||||
{ mcpLog: log, session } // Only pass mcpLog and session, NOT reportProgress
|
{ mcpLog: log, session } // Only pass mcpLog and session, NOT reportProgress
|
||||||
);
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
// Read the updated data
|
// Read the updated data
|
||||||
const updatedData = readJSON(tasksPath);
|
const updatedData = readJSON(tasksPath);
|
||||||
const updatedTask = updatedData.tasks.find(t => t.id === taskId);
|
const updatedTask = updatedData.tasks.find((t) => t.id === taskId);
|
||||||
|
|
||||||
// Calculate how many subtasks were added
|
// Calculate how many subtasks were added
|
||||||
const subtasksAdded = updatedTask.subtasks ?
|
const subtasksAdded = updatedTask.subtasks
|
||||||
updatedTask.subtasks.length - subtasksCountBefore : 0;
|
? updatedTask.subtasks.length - subtasksCountBefore
|
||||||
|
: 0;
|
||||||
|
|
||||||
// Return the result
|
// Return the result
|
||||||
log.info(`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`);
|
log.info(
|
||||||
return {
|
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
|
||||||
success: true,
|
);
|
||||||
data: {
|
return {
|
||||||
task: updatedTask,
|
success: true,
|
||||||
subtasksAdded,
|
data: {
|
||||||
hasExistingSubtasks
|
task: updatedTask,
|
||||||
},
|
subtasksAdded,
|
||||||
fromCache: false
|
hasExistingSubtasks
|
||||||
};
|
},
|
||||||
} catch (error) {
|
fromCache: false
|
||||||
// Make sure to restore normal logging even if there's an error
|
};
|
||||||
disableSilentMode();
|
} catch (error) {
|
||||||
|
// Make sure to restore normal logging even if there's an error
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error expanding task: ${error.message}`);
|
log.error(`Error expanding task: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message || 'Failed to expand task'
|
message: error.message || 'Failed to expand task'
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error expanding task: ${error.message}`);
|
log.error(`Error expanding task: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message || 'Failed to expand task'
|
message: error.message || 'Failed to expand task'
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { fixDependenciesCommand } from '../../../../scripts/modules/dependency-manager.js';
|
import { fixDependenciesCommand } from '../../../../scripts/modules/dependency-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,50 +19,50 @@ import fs from 'fs';
|
|||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function fixDependenciesDirect(args, log) {
|
export async function fixDependenciesDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Fixing invalid dependencies in tasks...`);
|
log.info(`Fixing invalid dependencies in tasks...`);
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Verify the file exists
|
// Verify the file exists
|
||||||
if (!fs.existsSync(tasksPath)) {
|
if (!fs.existsSync(tasksPath)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND',
|
code: 'FILE_NOT_FOUND',
|
||||||
message: `Tasks file not found at ${tasksPath}`
|
message: `Tasks file not found at ${tasksPath}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Call the original command function
|
// Call the original command function
|
||||||
await fixDependenciesCommand(tasksPath);
|
await fixDependenciesCommand(tasksPath);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: 'Dependencies fixed successfully',
|
message: 'Dependencies fixed successfully',
|
||||||
tasksPath
|
tasksPath
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error fixing dependencies: ${error.message}`);
|
log.error(`Error fixing dependencies: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FIX_DEPENDENCIES_ERROR',
|
code: 'FIX_DEPENDENCIES_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { generateTaskFiles } from '../../../../scripts/modules/task-manager.js';
|
import { generateTaskFiles } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
@@ -16,72 +19,76 @@ import path from 'path';
|
|||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function generateTaskFilesDirect(args, log) {
|
export async function generateTaskFilesDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Generating task files with args: ${JSON.stringify(args)}`);
|
log.info(`Generating task files with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Get tasks file path
|
// Get tasks file path
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error finding tasks file: ${error.message}`);
|
log.error(`Error finding tasks file: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'TASKS_FILE_ERROR', message: error.message },
|
error: { code: 'TASKS_FILE_ERROR', message: error.message },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get output directory (defaults to the same directory as the tasks file)
|
// Get output directory (defaults to the same directory as the tasks file)
|
||||||
let outputDir = args.output;
|
let outputDir = args.output;
|
||||||
if (!outputDir) {
|
if (!outputDir) {
|
||||||
outputDir = path.dirname(tasksPath);
|
outputDir = path.dirname(tasksPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Generating task files from ${tasksPath} to ${outputDir}`);
|
log.info(`Generating task files from ${tasksPath} to ${outputDir}`);
|
||||||
|
|
||||||
// Execute core generateTaskFiles function in a separate try/catch
|
// Execute core generateTaskFiles function in a separate try/catch
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent logs from being written to stdout
|
// Enable silent mode to prevent logs from being written to stdout
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// The function is synchronous despite being awaited elsewhere
|
// The function is synchronous despite being awaited elsewhere
|
||||||
generateTaskFiles(tasksPath, outputDir);
|
generateTaskFiles(tasksPath, outputDir);
|
||||||
|
|
||||||
// Restore normal logging after task generation
|
// Restore normal logging after task generation
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
} catch (genError) {
|
} catch (genError) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error in generateTaskFiles: ${genError.message}`);
|
log.error(`Error in generateTaskFiles: ${genError.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'GENERATE_FILES_ERROR', message: genError.message },
|
error: { code: 'GENERATE_FILES_ERROR', message: genError.message },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return success with file paths
|
// Return success with file paths
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully generated task files`,
|
message: `Successfully generated task files`,
|
||||||
tasksPath,
|
tasksPath,
|
||||||
outputDir,
|
outputDir,
|
||||||
taskFiles: 'Individual task files have been generated in the output directory'
|
taskFiles:
|
||||||
},
|
'Individual task files have been generated in the output directory'
|
||||||
fromCache: false // This operation always modifies state and should never be cached
|
},
|
||||||
};
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
} catch (error) {
|
};
|
||||||
// Make sure to restore normal logging if an outer error occurs
|
} catch (error) {
|
||||||
disableSilentMode();
|
// Make sure to restore normal logging if an outer error occurs
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error generating task files: ${error.message}`);
|
log.error(`Error generating task files: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'GENERATE_TASKS_ERROR', message: error.message || 'Unknown error generating task files' },
|
error: {
|
||||||
fromCache: false
|
code: 'GENERATE_TASKS_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error generating task files'
|
||||||
}
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,10 @@
|
|||||||
import { listTasks } from '../../../../scripts/modules/task-manager.js';
|
import { listTasks } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for listTasks with error handling and caching.
|
* Direct function wrapper for listTasks with error handling and caching.
|
||||||
@@ -16,68 +19,102 @@ import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules
|
|||||||
* @returns {Promise<Object>} - Task list result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }.
|
* @returns {Promise<Object>} - Task list result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }.
|
||||||
*/
|
*/
|
||||||
export async function listTasksDirect(args, log) {
|
export async function listTasksDirect(args, log) {
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
// Find the tasks path first - needed for cache key and execution
|
// Find the tasks path first - needed for cache key and execution
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.code === 'TASKS_FILE_NOT_FOUND') {
|
if (error.code === 'TASKS_FILE_NOT_FOUND') {
|
||||||
log.error(`Tasks file not found: ${error.message}`);
|
log.error(`Tasks file not found: ${error.message}`);
|
||||||
// Return the error structure expected by the calling tool/handler
|
// Return the error structure expected by the calling tool/handler
|
||||||
return { success: false, error: { code: error.code, message: error.message }, fromCache: false };
|
return {
|
||||||
}
|
success: false,
|
||||||
log.error(`Unexpected error finding tasks file: ${error.message}`);
|
error: { code: error.code, message: error.message },
|
||||||
// Re-throw for outer catch or return structured error
|
fromCache: false
|
||||||
return { success: false, error: { code: 'FIND_TASKS_PATH_ERROR', message: error.message }, fromCache: false };
|
};
|
||||||
}
|
}
|
||||||
|
log.error(`Unexpected error finding tasks file: ${error.message}`);
|
||||||
|
// Re-throw for outer catch or return structured error
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: { code: 'FIND_TASKS_PATH_ERROR', message: error.message },
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Generate cache key *after* finding tasksPath
|
// Generate cache key *after* finding tasksPath
|
||||||
const statusFilter = args.status || 'all';
|
const statusFilter = args.status || 'all';
|
||||||
const withSubtasks = args.withSubtasks || false;
|
const withSubtasks = args.withSubtasks || false;
|
||||||
const cacheKey = `listTasks:${tasksPath}:${statusFilter}:${withSubtasks}`;
|
const cacheKey = `listTasks:${tasksPath}:${statusFilter}:${withSubtasks}`;
|
||||||
|
|
||||||
// Define the action function to be executed on cache miss
|
// Define the action function to be executed on cache miss
|
||||||
const coreListTasksAction = async () => {
|
const coreListTasksAction = async () => {
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
log.info(`Executing core listTasks function for path: ${tasksPath}, filter: ${statusFilter}, subtasks: ${withSubtasks}`);
|
log.info(
|
||||||
const resultData = listTasks(tasksPath, statusFilter, withSubtasks, 'json');
|
`Executing core listTasks function for path: ${tasksPath}, filter: ${statusFilter}, subtasks: ${withSubtasks}`
|
||||||
|
);
|
||||||
|
const resultData = listTasks(
|
||||||
|
tasksPath,
|
||||||
|
statusFilter,
|
||||||
|
withSubtasks,
|
||||||
|
'json'
|
||||||
|
);
|
||||||
|
|
||||||
if (!resultData || !resultData.tasks) {
|
if (!resultData || !resultData.tasks) {
|
||||||
log.error('Invalid or empty response from listTasks core function');
|
log.error('Invalid or empty response from listTasks core function');
|
||||||
return { success: false, error: { code: 'INVALID_CORE_RESPONSE', message: 'Invalid or empty response from listTasks core function' } };
|
return {
|
||||||
}
|
success: false,
|
||||||
log.info(`Core listTasks function retrieved ${resultData.tasks.length} tasks`);
|
error: {
|
||||||
|
code: 'INVALID_CORE_RESPONSE',
|
||||||
|
message: 'Invalid or empty response from listTasks core function'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
log.info(
|
||||||
|
`Core listTasks function retrieved ${resultData.tasks.length} tasks`
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return { success: true, data: resultData };
|
return { success: true, data: resultData };
|
||||||
|
} catch (error) {
|
||||||
|
// Make sure to restore normal logging even if there's an error
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
} catch (error) {
|
log.error(`Core listTasks function failed: ${error.message}`);
|
||||||
// Make sure to restore normal logging even if there's an error
|
return {
|
||||||
disableSilentMode();
|
success: false,
|
||||||
|
error: {
|
||||||
|
code: 'LIST_TASKS_CORE_ERROR',
|
||||||
|
message: error.message || 'Failed to list tasks'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
log.error(`Core listTasks function failed: ${error.message}`);
|
// Use the caching utility
|
||||||
return { success: false, error: { code: 'LIST_TASKS_CORE_ERROR', message: error.message || 'Failed to list tasks' } };
|
try {
|
||||||
}
|
const result = await getCachedOrExecute({
|
||||||
};
|
cacheKey,
|
||||||
|
actionFn: coreListTasksAction,
|
||||||
// Use the caching utility
|
log
|
||||||
try {
|
});
|
||||||
const result = await getCachedOrExecute({
|
log.info(`listTasksDirect completed. From cache: ${result.fromCache}`);
|
||||||
cacheKey,
|
return result; // Returns { success, data/error, fromCache }
|
||||||
actionFn: coreListTasksAction,
|
} catch (error) {
|
||||||
log
|
// Catch unexpected errors from getCachedOrExecute itself (though unlikely)
|
||||||
});
|
log.error(
|
||||||
log.info(`listTasksDirect completed. From cache: ${result.fromCache}`);
|
`Unexpected error during getCachedOrExecute for listTasks: ${error.message}`
|
||||||
return result; // Returns { success, data/error, fromCache }
|
);
|
||||||
} catch(error) {
|
console.error(error.stack);
|
||||||
// Catch unexpected errors from getCachedOrExecute itself (though unlikely)
|
return {
|
||||||
log.error(`Unexpected error during getCachedOrExecute for listTasks: ${error.message}`);
|
success: false,
|
||||||
console.error(error.stack);
|
error: { code: 'CACHE_UTIL_ERROR', message: error.message },
|
||||||
return { success: false, error: { code: 'CACHE_UTIL_ERROR', message: error.message }, fromCache: false };
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,10 @@ import { findNextTask } from '../../../../scripts/modules/task-manager.js';
|
|||||||
import { readJSON } from '../../../../scripts/modules/utils.js';
|
import { readJSON } from '../../../../scripts/modules/utils.js';
|
||||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for finding the next task to work on with error handling and caching.
|
* Direct function wrapper for finding the next task to work on with error handling and caching.
|
||||||
@@ -17,106 +20,113 @@ import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules
|
|||||||
* @returns {Promise<Object>} - Next task result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
* @returns {Promise<Object>} - Next task result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
||||||
*/
|
*/
|
||||||
export async function nextTaskDirect(args, log) {
|
export async function nextTaskDirect(args, log) {
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
// Find the tasks path first - needed for cache key and execution
|
// Find the tasks path first - needed for cache key and execution
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Tasks file not found: ${error.message}`);
|
log.error(`Tasks file not found: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND_ERROR',
|
code: 'FILE_NOT_FOUND_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate cache key using task path
|
// Generate cache key using task path
|
||||||
const cacheKey = `nextTask:${tasksPath}`;
|
const cacheKey = `nextTask:${tasksPath}`;
|
||||||
|
|
||||||
// Define the action function to be executed on cache miss
|
// Define the action function to be executed on cache miss
|
||||||
const coreNextTaskAction = async () => {
|
const coreNextTaskAction = async () => {
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
log.info(`Finding next task from ${tasksPath}`);
|
log.info(`Finding next task from ${tasksPath}`);
|
||||||
|
|
||||||
// Read tasks data
|
// Read tasks data
|
||||||
const data = readJSON(tasksPath);
|
const data = readJSON(tasksPath);
|
||||||
if (!data || !data.tasks) {
|
if (!data || !data.tasks) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INVALID_TASKS_FILE',
|
code: 'INVALID_TASKS_FILE',
|
||||||
message: `No valid tasks found in ${tasksPath}`
|
message: `No valid tasks found in ${tasksPath}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the next task
|
// Find the next task
|
||||||
const nextTask = findNextTask(data.tasks);
|
const nextTask = findNextTask(data.tasks);
|
||||||
|
|
||||||
if (!nextTask) {
|
if (!nextTask) {
|
||||||
log.info('No eligible next task found. All tasks are either completed or have unsatisfied dependencies');
|
log.info(
|
||||||
return {
|
'No eligible next task found. All tasks are either completed or have unsatisfied dependencies'
|
||||||
success: true,
|
);
|
||||||
data: {
|
return {
|
||||||
message: 'No eligible next task found. All tasks are either completed or have unsatisfied dependencies',
|
success: true,
|
||||||
nextTask: null,
|
data: {
|
||||||
allTasks: data.tasks
|
message:
|
||||||
}
|
'No eligible next task found. All tasks are either completed or have unsatisfied dependencies',
|
||||||
};
|
nextTask: null,
|
||||||
}
|
allTasks: data.tasks
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
// Return the next task data with the full tasks array for reference
|
// Return the next task data with the full tasks array for reference
|
||||||
log.info(`Successfully found next task ${nextTask.id}: ${nextTask.title}`);
|
log.info(
|
||||||
return {
|
`Successfully found next task ${nextTask.id}: ${nextTask.title}`
|
||||||
success: true,
|
);
|
||||||
data: {
|
return {
|
||||||
nextTask,
|
success: true,
|
||||||
allTasks: data.tasks
|
data: {
|
||||||
}
|
nextTask,
|
||||||
};
|
allTasks: data.tasks
|
||||||
} catch (error) {
|
}
|
||||||
// Make sure to restore normal logging even if there's an error
|
};
|
||||||
disableSilentMode();
|
} catch (error) {
|
||||||
|
// Make sure to restore normal logging even if there's an error
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error finding next task: ${error.message}`);
|
log.error(`Error finding next task: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message || 'Failed to find next task'
|
message: error.message || 'Failed to find next task'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Use the caching utility
|
// Use the caching utility
|
||||||
try {
|
try {
|
||||||
const result = await getCachedOrExecute({
|
const result = await getCachedOrExecute({
|
||||||
cacheKey,
|
cacheKey,
|
||||||
actionFn: coreNextTaskAction,
|
actionFn: coreNextTaskAction,
|
||||||
log
|
log
|
||||||
});
|
});
|
||||||
log.info(`nextTaskDirect completed. From cache: ${result.fromCache}`);
|
log.info(`nextTaskDirect completed. From cache: ${result.fromCache}`);
|
||||||
return result; // Returns { success, data/error, fromCache }
|
return result; // Returns { success, data/error, fromCache }
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catch unexpected errors from getCachedOrExecute itself
|
// Catch unexpected errors from getCachedOrExecute itself
|
||||||
log.error(`Unexpected error during getCachedOrExecute for nextTask: ${error.message}`);
|
log.error(
|
||||||
return {
|
`Unexpected error during getCachedOrExecute for nextTask: ${error.message}`
|
||||||
success: false,
|
);
|
||||||
error: {
|
return {
|
||||||
code: 'UNEXPECTED_ERROR',
|
success: false,
|
||||||
message: error.message
|
error: {
|
||||||
},
|
code: 'UNEXPECTED_ERROR',
|
||||||
fromCache: false
|
message: error.message
|
||||||
};
|
},
|
||||||
}
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,8 +7,14 @@ import path from 'path';
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { parsePRD } from '../../../../scripts/modules/task-manager.js';
|
import { parsePRD } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
import { getAnthropicClientForMCP, getModelConfig } from '../utils/ai-client-utils.js';
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getModelConfig
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for parsing PRD documents and generating tasks.
|
* Direct function wrapper for parsing PRD documents and generating tasks.
|
||||||
@@ -19,132 +25,154 @@ import { getAnthropicClientForMCP, getModelConfig } from '../utils/ai-client-uti
|
|||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function parsePRDDirect(args, log, context = {}) {
|
export async function parsePRDDirect(args, log, context = {}) {
|
||||||
const { session } = context; // Only extract session, not reportProgress
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Parsing PRD document with args: ${JSON.stringify(args)}`);
|
log.info(`Parsing PRD document with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Initialize AI client for PRD parsing
|
// Initialize AI client for PRD parsing
|
||||||
let aiClient;
|
let aiClient;
|
||||||
try {
|
try {
|
||||||
aiClient = getAnthropicClientForMCP(session, log);
|
aiClient = getAnthropicClientForMCP(session, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to initialize AI client: ${error.message}`);
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_CLIENT_ERROR',
|
code: 'AI_CLIENT_ERROR',
|
||||||
message: `Cannot initialize AI client: ${error.message}`
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parameter validation and path resolution
|
// Parameter validation and path resolution
|
||||||
if (!args.input) {
|
if (!args.input) {
|
||||||
const errorMessage = 'No input file specified. Please provide an input PRD document path.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No input file specified. Please provide an input PRD document path.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_INPUT_FILE', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_INPUT_FILE', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Resolve input path (relative to project root if provided)
|
// Resolve input path (relative to project root if provided)
|
||||||
const projectRoot = args.projectRoot || process.cwd();
|
const projectRoot = args.projectRoot || process.cwd();
|
||||||
const inputPath = path.isAbsolute(args.input) ? args.input : path.resolve(projectRoot, args.input);
|
const inputPath = path.isAbsolute(args.input)
|
||||||
|
? args.input
|
||||||
|
: path.resolve(projectRoot, args.input);
|
||||||
|
|
||||||
// Determine output path
|
// Determine output path
|
||||||
let outputPath;
|
let outputPath;
|
||||||
if (args.output) {
|
if (args.output) {
|
||||||
outputPath = path.isAbsolute(args.output) ? args.output : path.resolve(projectRoot, args.output);
|
outputPath = path.isAbsolute(args.output)
|
||||||
} else {
|
? args.output
|
||||||
// Default to tasks/tasks.json in the project root
|
: path.resolve(projectRoot, args.output);
|
||||||
outputPath = path.resolve(projectRoot, 'tasks', 'tasks.json');
|
} else {
|
||||||
}
|
// Default to tasks/tasks.json in the project root
|
||||||
|
outputPath = path.resolve(projectRoot, 'tasks', 'tasks.json');
|
||||||
|
}
|
||||||
|
|
||||||
// Verify input file exists
|
// Verify input file exists
|
||||||
if (!fs.existsSync(inputPath)) {
|
if (!fs.existsSync(inputPath)) {
|
||||||
const errorMessage = `Input file not found: ${inputPath}`;
|
const errorMessage = `Input file not found: ${inputPath}`;
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'INPUT_FILE_NOT_FOUND', message: errorMessage },
|
error: { code: 'INPUT_FILE_NOT_FOUND', message: errorMessage },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse number of tasks - handle both string and number values
|
// Parse number of tasks - handle both string and number values
|
||||||
let numTasks = 10; // Default
|
let numTasks = 10; // Default
|
||||||
if (args.numTasks) {
|
if (args.numTasks) {
|
||||||
numTasks = typeof args.numTasks === 'string' ? parseInt(args.numTasks, 10) : args.numTasks;
|
numTasks =
|
||||||
if (isNaN(numTasks)) {
|
typeof args.numTasks === 'string'
|
||||||
numTasks = 10; // Fallback to default if parsing fails
|
? parseInt(args.numTasks, 10)
|
||||||
log.warn(`Invalid numTasks value: ${args.numTasks}. Using default: 10`);
|
: args.numTasks;
|
||||||
}
|
if (isNaN(numTasks)) {
|
||||||
}
|
numTasks = 10; // Fallback to default if parsing fails
|
||||||
|
log.warn(`Invalid numTasks value: ${args.numTasks}. Using default: 10`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
log.info(`Preparing to parse PRD from ${inputPath} and output to ${outputPath} with ${numTasks} tasks`);
|
log.info(
|
||||||
|
`Preparing to parse PRD from ${inputPath} and output to ${outputPath} with ${numTasks} tasks`
|
||||||
|
);
|
||||||
|
|
||||||
// Create the logger wrapper for proper logging in the core function
|
// Create the logger wrapper for proper logging in the core function
|
||||||
const logWrapper = {
|
const logWrapper = {
|
||||||
info: (message, ...args) => log.info(message, ...args),
|
info: (message, ...args) => log.info(message, ...args),
|
||||||
warn: (message, ...args) => log.warn(message, ...args),
|
warn: (message, ...args) => log.warn(message, ...args),
|
||||||
error: (message, ...args) => log.error(message, ...args),
|
error: (message, ...args) => log.error(message, ...args),
|
||||||
debug: (message, ...args) => log.debug && log.debug(message, ...args),
|
debug: (message, ...args) => log.debug && log.debug(message, ...args),
|
||||||
success: (message, ...args) => log.info(message, ...args) // Map success to info
|
success: (message, ...args) => log.info(message, ...args) // Map success to info
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get model config from session
|
// Get model config from session
|
||||||
const modelConfig = getModelConfig(session);
|
const modelConfig = getModelConfig(session);
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
try {
|
try {
|
||||||
// Execute core parsePRD function with AI client
|
// Execute core parsePRD function with AI client
|
||||||
await parsePRD(inputPath, outputPath, numTasks, {
|
await parsePRD(
|
||||||
mcpLog: logWrapper,
|
inputPath,
|
||||||
session
|
outputPath,
|
||||||
}, aiClient, modelConfig);
|
numTasks,
|
||||||
|
{
|
||||||
|
mcpLog: logWrapper,
|
||||||
|
session
|
||||||
|
},
|
||||||
|
aiClient,
|
||||||
|
modelConfig
|
||||||
|
);
|
||||||
|
|
||||||
// Since parsePRD doesn't return a value but writes to a file, we'll read the result
|
// Since parsePRD doesn't return a value but writes to a file, we'll read the result
|
||||||
// to return it to the caller
|
// to return it to the caller
|
||||||
if (fs.existsSync(outputPath)) {
|
if (fs.existsSync(outputPath)) {
|
||||||
const tasksData = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
const tasksData = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
||||||
log.info(`Successfully parsed PRD and generated ${tasksData.tasks?.length || 0} tasks`);
|
log.info(
|
||||||
|
`Successfully parsed PRD and generated ${tasksData.tasks?.length || 0} tasks`
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully generated ${tasksData.tasks?.length || 0} tasks from PRD`,
|
message: `Successfully generated ${tasksData.tasks?.length || 0} tasks from PRD`,
|
||||||
taskCount: tasksData.tasks?.length || 0,
|
taskCount: tasksData.tasks?.length || 0,
|
||||||
outputPath
|
outputPath
|
||||||
},
|
},
|
||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
const errorMessage = `Tasks file was not created at ${outputPath}`;
|
const errorMessage = `Tasks file was not created at ${outputPath}`;
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'OUTPUT_FILE_NOT_CREATED', message: errorMessage },
|
error: { code: 'OUTPUT_FILE_NOT_CREATED', message: errorMessage },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
// Always restore normal logging
|
// Always restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error parsing PRD: ${error.message}`);
|
log.error(`Error parsing PRD: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'PARSE_PRD_ERROR', message: error.message || 'Unknown error parsing PRD' },
|
error: {
|
||||||
fromCache: false
|
code: 'PARSE_PRD_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error parsing PRD'
|
||||||
}
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { removeDependency } from '../../../../scripts/modules/dependency-manager.js';
|
import { removeDependency } from '../../../../scripts/modules/dependency-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove a dependency from a task
|
* Remove a dependency from a task
|
||||||
@@ -17,67 +20,75 @@ import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules
|
|||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function removeDependencyDirect(args, log) {
|
export async function removeDependencyDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Removing dependency with args: ${JSON.stringify(args)}`);
|
log.info(`Removing dependency with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Validate required parameters
|
// Validate required parameters
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Task ID (id) is required'
|
message: 'Task ID (id) is required'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!args.dependsOn) {
|
if (!args.dependsOn) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Dependency ID (dependsOn) is required'
|
message: 'Dependency ID (dependsOn) is required'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Format IDs for the core function
|
// Format IDs for the core function
|
||||||
const taskId = args.id.includes && args.id.includes('.') ? args.id : parseInt(args.id, 10);
|
const taskId =
|
||||||
const dependencyId = args.dependsOn.includes && args.dependsOn.includes('.') ? args.dependsOn : parseInt(args.dependsOn, 10);
|
args.id.includes && args.id.includes('.')
|
||||||
|
? args.id
|
||||||
|
: parseInt(args.id, 10);
|
||||||
|
const dependencyId =
|
||||||
|
args.dependsOn.includes && args.dependsOn.includes('.')
|
||||||
|
? args.dependsOn
|
||||||
|
: parseInt(args.dependsOn, 10);
|
||||||
|
|
||||||
log.info(`Removing dependency: task ${taskId} no longer depends on ${dependencyId}`);
|
log.info(
|
||||||
|
`Removing dependency: task ${taskId} no longer depends on ${dependencyId}`
|
||||||
|
);
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Call the core function
|
// Call the core function
|
||||||
await removeDependency(tasksPath, taskId, dependencyId);
|
await removeDependency(tasksPath, taskId, dependencyId);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully removed dependency: Task ${taskId} no longer depends on ${dependencyId}`,
|
message: `Successfully removed dependency: Task ${taskId} no longer depends on ${dependencyId}`,
|
||||||
taskId: taskId,
|
taskId: taskId,
|
||||||
dependencyId: dependencyId
|
dependencyId: dependencyId
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error in removeDependencyDirect: ${error.message}`);
|
log.error(`Error in removeDependencyDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { removeSubtask } from '../../../../scripts/modules/task-manager.js';
|
import { removeSubtask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove a subtask from its parent task
|
* Remove a subtask from its parent task
|
||||||
@@ -18,78 +21,86 @@ import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules
|
|||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function removeSubtaskDirect(args, log) {
|
export async function removeSubtaskDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
log.info(`Removing subtask with args: ${JSON.stringify(args)}`);
|
log.info(`Removing subtask with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Subtask ID is required and must be in format "parentId.subtaskId"'
|
message:
|
||||||
}
|
'Subtask ID is required and must be in format "parentId.subtaskId"'
|
||||||
};
|
}
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Validate subtask ID format
|
// Validate subtask ID format
|
||||||
if (!args.id.includes('.')) {
|
if (!args.id.includes('.')) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: `Invalid subtask ID format: ${args.id}. Expected format: "parentId.subtaskId"`
|
message: `Invalid subtask ID format: ${args.id}. Expected format: "parentId.subtaskId"`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Convert convertToTask to a boolean
|
// Convert convertToTask to a boolean
|
||||||
const convertToTask = args.convert === true;
|
const convertToTask = args.convert === true;
|
||||||
|
|
||||||
// Determine if we should generate files
|
// Determine if we should generate files
|
||||||
const generateFiles = !args.skipGenerate;
|
const generateFiles = !args.skipGenerate;
|
||||||
|
|
||||||
log.info(`Removing subtask ${args.id} (convertToTask: ${convertToTask}, generateFiles: ${generateFiles})`);
|
log.info(
|
||||||
|
`Removing subtask ${args.id} (convertToTask: ${convertToTask}, generateFiles: ${generateFiles})`
|
||||||
|
);
|
||||||
|
|
||||||
const result = await removeSubtask(tasksPath, args.id, convertToTask, generateFiles);
|
const result = await removeSubtask(
|
||||||
|
tasksPath,
|
||||||
|
args.id,
|
||||||
|
convertToTask,
|
||||||
|
generateFiles
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
if (convertToTask && result) {
|
if (convertToTask && result) {
|
||||||
// Return info about the converted task
|
// Return info about the converted task
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Subtask ${args.id} successfully converted to task #${result.id}`,
|
message: `Subtask ${args.id} successfully converted to task #${result.id}`,
|
||||||
task: result
|
task: result
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
// Return simple success message for deletion
|
// Return simple success message for deletion
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Subtask ${args.id} successfully removed`
|
message: `Subtask ${args.id} successfully removed`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ensure silent mode is disabled even if an outer error occurs
|
// Ensure silent mode is disabled even if an outer error occurs
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error in removeSubtaskDirect: ${error.message}`);
|
log.error(`Error in removeSubtaskDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { removeTask } from '../../../../scripts/modules/task-manager.js';
|
import { removeTask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -15,90 +18,90 @@ import { findTasksJsonPath } from '../utils/path-utils.js';
|
|||||||
* @returns {Promise<Object>} - Remove task result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: false }
|
* @returns {Promise<Object>} - Remove task result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: false }
|
||||||
*/
|
*/
|
||||||
export async function removeTaskDirect(args, log) {
|
export async function removeTaskDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
// Find the tasks path first
|
// Find the tasks path first
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Tasks file not found: ${error.message}`);
|
log.error(`Tasks file not found: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND_ERROR',
|
code: 'FILE_NOT_FOUND_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate task ID parameter
|
// Validate task ID parameter
|
||||||
const taskId = args.id;
|
const taskId = args.id;
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
log.error('Task ID is required');
|
log.error('Task ID is required');
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Task ID is required'
|
message: 'Task ID is required'
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip confirmation in the direct function since it's handled by the client
|
// Skip confirmation in the direct function since it's handled by the client
|
||||||
log.info(`Removing task with ID: ${taskId} from ${tasksPath}`);
|
log.info(`Removing task with ID: ${taskId} from ${tasksPath}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Call the core removeTask function
|
// Call the core removeTask function
|
||||||
const result = await removeTask(tasksPath, taskId);
|
const result = await removeTask(tasksPath, taskId);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.info(`Successfully removed task: ${taskId}`);
|
log.info(`Successfully removed task: ${taskId}`);
|
||||||
|
|
||||||
// Return the result
|
// Return the result
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: result.message,
|
message: result.message,
|
||||||
taskId: taskId,
|
taskId: taskId,
|
||||||
tasksPath: tasksPath,
|
tasksPath: tasksPath,
|
||||||
removedTask: result.removedTask
|
removedTask: result.removedTask
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error removing task: ${error.message}`);
|
log.error(`Error removing task: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: error.code || 'REMOVE_TASK_ERROR',
|
code: error.code || 'REMOVE_TASK_ERROR',
|
||||||
message: error.message || 'Failed to remove task'
|
message: error.message || 'Failed to remove task'
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ensure silent mode is disabled even if an outer error occurs
|
// Ensure silent mode is disabled even if an outer error occurs
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
// Catch any unexpected errors
|
// Catch any unexpected errors
|
||||||
log.error(`Unexpected error in removeTaskDirect: ${error.message}`);
|
log.error(`Unexpected error in removeTaskDirect: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'UNEXPECTED_ERROR',
|
code: 'UNEXPECTED_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,11 @@
|
|||||||
|
|
||||||
import { setTaskStatus } from '../../../../scripts/modules/task-manager.js';
|
import { setTaskStatus } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode,
|
||||||
|
isSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for setTaskStatus with error handling.
|
* Direct function wrapper for setTaskStatus with error handling.
|
||||||
@@ -15,98 +19,106 @@ import { enableSilentMode, disableSilentMode, isSilentMode } from '../../../../s
|
|||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function setTaskStatusDirect(args, log) {
|
export async function setTaskStatusDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Setting task status with args: ${JSON.stringify(args)}`);
|
log.info(`Setting task status with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
const errorMessage = 'No task ID specified. Please provide a task ID to update.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No task ID specified. Please provide a task ID to update.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_TASK_ID', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_TASK_ID', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (!args.status) {
|
if (!args.status) {
|
||||||
const errorMessage = 'No status specified. Please provide a new status value.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No status specified. Please provide a new status value.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_STATUS', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_STATUS', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Get tasks file path
|
// Get tasks file path
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
// The enhanced findTasksJsonPath will now search in parent directories if needed
|
// The enhanced findTasksJsonPath will now search in parent directories if needed
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
log.info(`Found tasks file at: ${tasksPath}`);
|
log.info(`Found tasks file at: ${tasksPath}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error finding tasks file: ${error.message}`);
|
log.error(`Error finding tasks file: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'TASKS_FILE_ERROR',
|
code: 'TASKS_FILE_ERROR',
|
||||||
message: `${error.message}\n\nPlease ensure you are in a Task Master project directory or use the --project-root parameter to specify the path to your project.`
|
message: `${error.message}\n\nPlease ensure you are in a Task Master project directory or use the --project-root parameter to specify the path to your project.`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute core setTaskStatus function
|
// Execute core setTaskStatus function
|
||||||
const taskId = args.id;
|
const taskId = args.id;
|
||||||
const newStatus = args.status;
|
const newStatus = args.status;
|
||||||
|
|
||||||
log.info(`Setting task ${taskId} status to "${newStatus}"`);
|
log.info(`Setting task ${taskId} status to "${newStatus}"`);
|
||||||
|
|
||||||
// Call the core function with proper silent mode handling
|
// Call the core function with proper silent mode handling
|
||||||
let result;
|
let result;
|
||||||
enableSilentMode(); // Enable silent mode before calling core function
|
enableSilentMode(); // Enable silent mode before calling core function
|
||||||
try {
|
try {
|
||||||
// Call the core function
|
// Call the core function
|
||||||
await setTaskStatus(tasksPath, taskId, newStatus, { mcpLog: log });
|
await setTaskStatus(tasksPath, taskId, newStatus, { mcpLog: log });
|
||||||
|
|
||||||
log.info(`Successfully set task ${taskId} status to ${newStatus}`);
|
log.info(`Successfully set task ${taskId} status to ${newStatus}`);
|
||||||
|
|
||||||
// Return success data
|
// Return success data
|
||||||
result = {
|
result = {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully updated task ${taskId} status to "${newStatus}"`,
|
message: `Successfully updated task ${taskId} status to "${newStatus}"`,
|
||||||
taskId,
|
taskId,
|
||||||
status: newStatus,
|
status: newStatus,
|
||||||
tasksPath
|
tasksPath
|
||||||
},
|
},
|
||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error setting task status: ${error.message}`);
|
log.error(`Error setting task status: ${error.message}`);
|
||||||
result = {
|
result = {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'SET_STATUS_ERROR', message: error.message || 'Unknown error setting task status' },
|
error: {
|
||||||
fromCache: false
|
code: 'SET_STATUS_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error setting task status'
|
||||||
} finally {
|
},
|
||||||
// ALWAYS restore normal logging in finally block
|
fromCache: false
|
||||||
disableSilentMode();
|
};
|
||||||
}
|
} finally {
|
||||||
|
// ALWAYS restore normal logging in finally block
|
||||||
|
disableSilentMode();
|
||||||
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ensure silent mode is disabled if there was an uncaught error in the outer try block
|
// Ensure silent mode is disabled if there was an uncaught error in the outer try block
|
||||||
if (isSilentMode()) {
|
if (isSilentMode()) {
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
}
|
}
|
||||||
|
|
||||||
log.error(`Error setting task status: ${error.message}`);
|
log.error(`Error setting task status: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'SET_STATUS_ERROR', message: error.message || 'Unknown error setting task status' },
|
error: {
|
||||||
fromCache: false
|
code: 'SET_STATUS_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error setting task status'
|
||||||
}
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,10 @@ import { findTaskById } from '../../../../scripts/modules/utils.js';
|
|||||||
import { readJSON } from '../../../../scripts/modules/utils.js';
|
import { readJSON } from '../../../../scripts/modules/utils.js';
|
||||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for showing task details with error handling and caching.
|
* Direct function wrapper for showing task details with error handling and caching.
|
||||||
@@ -17,120 +20,122 @@ import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules
|
|||||||
* @returns {Promise<Object>} - Task details result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
* @returns {Promise<Object>} - Task details result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
||||||
*/
|
*/
|
||||||
export async function showTaskDirect(args, log) {
|
export async function showTaskDirect(args, log) {
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
// Find the tasks path first - needed for cache key and execution
|
// Find the tasks path first - needed for cache key and execution
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Tasks file not found: ${error.message}`);
|
log.error(`Tasks file not found: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND_ERROR',
|
code: 'FILE_NOT_FOUND_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate task ID
|
// Validate task ID
|
||||||
const taskId = args.id;
|
const taskId = args.id;
|
||||||
if (!taskId) {
|
if (!taskId) {
|
||||||
log.error('Task ID is required');
|
log.error('Task ID is required');
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INPUT_VALIDATION_ERROR',
|
code: 'INPUT_VALIDATION_ERROR',
|
||||||
message: 'Task ID is required'
|
message: 'Task ID is required'
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate cache key using task path and ID
|
// Generate cache key using task path and ID
|
||||||
const cacheKey = `showTask:${tasksPath}:${taskId}`;
|
const cacheKey = `showTask:${tasksPath}:${taskId}`;
|
||||||
|
|
||||||
// Define the action function to be executed on cache miss
|
// Define the action function to be executed on cache miss
|
||||||
const coreShowTaskAction = async () => {
|
const coreShowTaskAction = async () => {
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
log.info(`Retrieving task details for ID: ${taskId} from ${tasksPath}`);
|
log.info(`Retrieving task details for ID: ${taskId} from ${tasksPath}`);
|
||||||
|
|
||||||
// Read tasks data
|
// Read tasks data
|
||||||
const data = readJSON(tasksPath);
|
const data = readJSON(tasksPath);
|
||||||
if (!data || !data.tasks) {
|
if (!data || !data.tasks) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'INVALID_TASKS_FILE',
|
code: 'INVALID_TASKS_FILE',
|
||||||
message: `No valid tasks found in ${tasksPath}`
|
message: `No valid tasks found in ${tasksPath}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the specific task
|
// Find the specific task
|
||||||
const task = findTaskById(data.tasks, taskId);
|
const task = findTaskById(data.tasks, taskId);
|
||||||
|
|
||||||
if (!task) {
|
if (!task) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'TASK_NOT_FOUND',
|
code: 'TASK_NOT_FOUND',
|
||||||
message: `Task with ID ${taskId} not found`
|
message: `Task with ID ${taskId} not found`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
// Return the task data with the full tasks array for reference
|
// Return the task data with the full tasks array for reference
|
||||||
// (needed for formatDependenciesWithStatus function in UI)
|
// (needed for formatDependenciesWithStatus function in UI)
|
||||||
log.info(`Successfully found task ${taskId}`);
|
log.info(`Successfully found task ${taskId}`);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
task,
|
task,
|
||||||
allTasks: data.tasks
|
allTasks: data.tasks
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error showing task: ${error.message}`);
|
log.error(`Error showing task: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'CORE_FUNCTION_ERROR',
|
code: 'CORE_FUNCTION_ERROR',
|
||||||
message: error.message || 'Failed to show task details'
|
message: error.message || 'Failed to show task details'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Use the caching utility
|
// Use the caching utility
|
||||||
try {
|
try {
|
||||||
const result = await getCachedOrExecute({
|
const result = await getCachedOrExecute({
|
||||||
cacheKey,
|
cacheKey,
|
||||||
actionFn: coreShowTaskAction,
|
actionFn: coreShowTaskAction,
|
||||||
log
|
log
|
||||||
});
|
});
|
||||||
log.info(`showTaskDirect completed. From cache: ${result.fromCache}`);
|
log.info(`showTaskDirect completed. From cache: ${result.fromCache}`);
|
||||||
return result; // Returns { success, data/error, fromCache }
|
return result; // Returns { success, data/error, fromCache }
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catch unexpected errors from getCachedOrExecute itself
|
// Catch unexpected errors from getCachedOrExecute itself
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
log.error(`Unexpected error during getCachedOrExecute for showTask: ${error.message}`);
|
log.error(
|
||||||
return {
|
`Unexpected error during getCachedOrExecute for showTask: ${error.message}`
|
||||||
success: false,
|
);
|
||||||
error: {
|
return {
|
||||||
code: 'UNEXPECTED_ERROR',
|
success: false,
|
||||||
message: error.message
|
error: {
|
||||||
},
|
code: 'UNEXPECTED_ERROR',
|
||||||
fromCache: false
|
message: error.message
|
||||||
};
|
},
|
||||||
}
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,9 +4,15 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { updateSubtaskById } from '../../../../scripts/modules/task-manager.js';
|
import { updateSubtaskById } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { getAnthropicClientForMCP, getPerplexityClientForMCP } from '../utils/ai-client-utils.js';
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getPerplexityClientForMCP
|
||||||
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for updateSubtaskById with error handling.
|
* Direct function wrapper for updateSubtaskById with error handling.
|
||||||
@@ -17,154 +23,171 @@ import { getAnthropicClientForMCP, getPerplexityClientForMCP } from '../utils/ai
|
|||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||||
const { session } = context; // Only extract session, not reportProgress
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
const errorMessage = 'No subtask ID specified. Please provide a subtask ID to update.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No subtask ID specified. Please provide a subtask ID to update.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_SUBTASK_ID', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_SUBTASK_ID', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (!args.prompt) {
|
if (!args.prompt) {
|
||||||
const errorMessage = 'No prompt specified. Please provide a prompt with information to add to the subtask.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No prompt specified. Please provide a prompt with information to add to the subtask.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Validate subtask ID format
|
// Validate subtask ID format
|
||||||
const subtaskId = args.id;
|
const subtaskId = args.id;
|
||||||
if (typeof subtaskId !== 'string' && typeof subtaskId !== 'number') {
|
if (typeof subtaskId !== 'string' && typeof subtaskId !== 'number') {
|
||||||
const errorMessage = `Invalid subtask ID type: ${typeof subtaskId}. Subtask ID must be a string or number.`;
|
const errorMessage = `Invalid subtask ID type: ${typeof subtaskId}. Subtask ID must be a string or number.`;
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'INVALID_SUBTASK_ID_TYPE', message: errorMessage },
|
error: { code: 'INVALID_SUBTASK_ID_TYPE', message: errorMessage },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const subtaskIdStr = String(subtaskId);
|
const subtaskIdStr = String(subtaskId);
|
||||||
if (!subtaskIdStr.includes('.')) {
|
if (!subtaskIdStr.includes('.')) {
|
||||||
const errorMessage = `Invalid subtask ID format: ${subtaskIdStr}. Subtask ID must be in format "parentId.subtaskId" (e.g., "5.2").`;
|
const errorMessage = `Invalid subtask ID format: ${subtaskIdStr}. Subtask ID must be in format "parentId.subtaskId" (e.g., "5.2").`;
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'INVALID_SUBTASK_ID_FORMAT', message: errorMessage },
|
error: { code: 'INVALID_SUBTASK_ID_FORMAT', message: errorMessage },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get tasks file path
|
// Get tasks file path
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error finding tasks file: ${error.message}`);
|
log.error(`Error finding tasks file: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'TASKS_FILE_ERROR', message: error.message },
|
error: { code: 'TASKS_FILE_ERROR', message: error.message },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get research flag
|
// Get research flag
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
|
|
||||||
log.info(`Updating subtask with ID ${subtaskIdStr} with prompt "${args.prompt}" and research: ${useResearch}`);
|
log.info(
|
||||||
|
`Updating subtask with ID ${subtaskIdStr} with prompt "${args.prompt}" and research: ${useResearch}`
|
||||||
|
);
|
||||||
|
|
||||||
// Initialize the appropriate AI client based on research flag
|
// Initialize the appropriate AI client based on research flag
|
||||||
try {
|
try {
|
||||||
if (useResearch) {
|
if (useResearch) {
|
||||||
// Initialize Perplexity client
|
// Initialize Perplexity client
|
||||||
await getPerplexityClientForMCP(session);
|
await getPerplexityClientForMCP(session);
|
||||||
} else {
|
} else {
|
||||||
// Initialize Anthropic client
|
// Initialize Anthropic client
|
||||||
await getAnthropicClientForMCP(session);
|
await getAnthropicClientForMCP(session);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`AI client initialization error: ${error.message}`);
|
log.error(`AI client initialization error: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'AI_CLIENT_ERROR', message: error.message || 'Failed to initialize AI client' },
|
error: {
|
||||||
fromCache: false
|
code: 'AI_CLIENT_ERROR',
|
||||||
};
|
message: error.message || 'Failed to initialize AI client'
|
||||||
}
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Create a logger wrapper object to handle logging without breaking the mcpLog[level] calls
|
// Create a logger wrapper object to handle logging without breaking the mcpLog[level] calls
|
||||||
// This ensures outputFormat is set to 'json' while still supporting proper logging
|
// This ensures outputFormat is set to 'json' while still supporting proper logging
|
||||||
const logWrapper = {
|
const logWrapper = {
|
||||||
info: (message) => log.info(message),
|
info: (message) => log.info(message),
|
||||||
warn: (message) => log.warn(message),
|
warn: (message) => log.warn(message),
|
||||||
error: (message) => log.error(message),
|
error: (message) => log.error(message),
|
||||||
debug: (message) => log.debug && log.debug(message),
|
debug: (message) => log.debug && log.debug(message),
|
||||||
success: (message) => log.info(message) // Map success to info if needed
|
success: (message) => log.info(message) // Map success to info if needed
|
||||||
};
|
};
|
||||||
|
|
||||||
// Execute core updateSubtaskById function
|
// Execute core updateSubtaskById function
|
||||||
// Pass both session and logWrapper as mcpLog to ensure outputFormat is 'json'
|
// Pass both session and logWrapper as mcpLog to ensure outputFormat is 'json'
|
||||||
const updatedSubtask = await updateSubtaskById(tasksPath, subtaskIdStr, args.prompt, useResearch, {
|
const updatedSubtask = await updateSubtaskById(
|
||||||
session,
|
tasksPath,
|
||||||
mcpLog: logWrapper
|
subtaskIdStr,
|
||||||
});
|
args.prompt,
|
||||||
|
useResearch,
|
||||||
|
{
|
||||||
|
session,
|
||||||
|
mcpLog: logWrapper
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
// Handle the case where the subtask couldn't be updated (e.g., already marked as done)
|
// Handle the case where the subtask couldn't be updated (e.g., already marked as done)
|
||||||
if (!updatedSubtask) {
|
if (!updatedSubtask) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'SUBTASK_UPDATE_FAILED',
|
code: 'SUBTASK_UPDATE_FAILED',
|
||||||
message: 'Failed to update subtask. It may be marked as completed, or another error occurred.'
|
message:
|
||||||
},
|
'Failed to update subtask. It may be marked as completed, or another error occurred.'
|
||||||
fromCache: false
|
},
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Return the updated subtask information
|
// Return the updated subtask information
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully updated subtask with ID ${subtaskIdStr}`,
|
message: `Successfully updated subtask with ID ${subtaskIdStr}`,
|
||||||
subtaskId: subtaskIdStr,
|
subtaskId: subtaskIdStr,
|
||||||
parentId: subtaskIdStr.split('.')[0],
|
parentId: subtaskIdStr.split('.')[0],
|
||||||
subtask: updatedSubtask,
|
subtask: updatedSubtask,
|
||||||
tasksPath,
|
tasksPath,
|
||||||
useResearch
|
useResearch
|
||||||
},
|
},
|
||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
throw error; // Rethrow to be caught by outer catch block
|
throw error; // Rethrow to be caught by outer catch block
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ensure silent mode is disabled
|
// Ensure silent mode is disabled
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error updating subtask by ID: ${error.message}`);
|
log.error(`Error updating subtask by ID: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'UPDATE_SUBTASK_ERROR', message: error.message || 'Unknown error updating subtask' },
|
error: {
|
||||||
fromCache: false
|
code: 'UPDATE_SUBTASK_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error updating subtask'
|
||||||
}
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -5,10 +5,13 @@
|
|||||||
|
|
||||||
import { updateTaskById } from '../../../../scripts/modules/task-manager.js';
|
import { updateTaskById } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
|
||||||
import {
|
import {
|
||||||
getAnthropicClientForMCP,
|
enableSilentMode,
|
||||||
getPerplexityClientForMCP
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
import {
|
||||||
|
getAnthropicClientForMCP,
|
||||||
|
getPerplexityClientForMCP
|
||||||
} from '../utils/ai-client-utils.js';
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,153 +23,163 @@ import {
|
|||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function updateTaskByIdDirect(args, log, context = {}) {
|
export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||||
const { session } = context; // Only extract session, not reportProgress
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.id) {
|
if (!args.id) {
|
||||||
const errorMessage = 'No task ID specified. Please provide a task ID to update.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No task ID specified. Please provide a task ID to update.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_TASK_ID', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_TASK_ID', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (!args.prompt) {
|
if (!args.prompt) {
|
||||||
const errorMessage = 'No prompt specified. Please provide a prompt with new information for the task update.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No prompt specified. Please provide a prompt with new information for the task update.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Parse taskId - handle both string and number values
|
// Parse taskId - handle both string and number values
|
||||||
let taskId;
|
let taskId;
|
||||||
if (typeof args.id === 'string') {
|
if (typeof args.id === 'string') {
|
||||||
// Handle subtask IDs (e.g., "5.2")
|
// Handle subtask IDs (e.g., "5.2")
|
||||||
if (args.id.includes('.')) {
|
if (args.id.includes('.')) {
|
||||||
taskId = args.id; // Keep as string for subtask IDs
|
taskId = args.id; // Keep as string for subtask IDs
|
||||||
} else {
|
} else {
|
||||||
// Parse as integer for main task IDs
|
// Parse as integer for main task IDs
|
||||||
taskId = parseInt(args.id, 10);
|
taskId = parseInt(args.id, 10);
|
||||||
if (isNaN(taskId)) {
|
if (isNaN(taskId)) {
|
||||||
const errorMessage = `Invalid task ID: ${args.id}. Task ID must be a positive integer or subtask ID (e.g., "5.2").`;
|
const errorMessage = `Invalid task ID: ${args.id}. Task ID must be a positive integer or subtask ID (e.g., "5.2").`;
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'INVALID_TASK_ID', message: errorMessage },
|
error: { code: 'INVALID_TASK_ID', message: errorMessage },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
taskId = args.id;
|
taskId = args.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get tasks file path
|
// Get tasks file path
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error finding tasks file: ${error.message}`);
|
log.error(`Error finding tasks file: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'TASKS_FILE_ERROR', message: error.message },
|
error: { code: 'TASKS_FILE_ERROR', message: error.message },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get research flag
|
// Get research flag
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
|
|
||||||
// Initialize appropriate AI client based on research flag
|
// Initialize appropriate AI client based on research flag
|
||||||
let aiClient;
|
let aiClient;
|
||||||
try {
|
try {
|
||||||
if (useResearch) {
|
if (useResearch) {
|
||||||
log.info('Using Perplexity AI for research-backed task update');
|
log.info('Using Perplexity AI for research-backed task update');
|
||||||
aiClient = await getPerplexityClientForMCP(session, log);
|
aiClient = await getPerplexityClientForMCP(session, log);
|
||||||
} else {
|
} else {
|
||||||
log.info('Using Claude AI for task update');
|
log.info('Using Claude AI for task update');
|
||||||
aiClient = getAnthropicClientForMCP(session, log);
|
aiClient = getAnthropicClientForMCP(session, log);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to initialize AI client: ${error.message}`);
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_CLIENT_ERROR',
|
code: 'AI_CLIENT_ERROR',
|
||||||
message: `Cannot initialize AI client: ${error.message}`
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Updating task with ID ${taskId} with prompt "${args.prompt}" and research: ${useResearch}`);
|
log.info(
|
||||||
|
`Updating task with ID ${taskId} with prompt "${args.prompt}" and research: ${useResearch}`
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Create a logger wrapper that matches what updateTaskById expects
|
// Create a logger wrapper that matches what updateTaskById expects
|
||||||
const logWrapper = {
|
const logWrapper = {
|
||||||
info: (message) => log.info(message),
|
info: (message) => log.info(message),
|
||||||
warn: (message) => log.warn(message),
|
warn: (message) => log.warn(message),
|
||||||
error: (message) => log.error(message),
|
error: (message) => log.error(message),
|
||||||
debug: (message) => log.debug && log.debug(message),
|
debug: (message) => log.debug && log.debug(message),
|
||||||
success: (message) => log.info(message) // Map success to info since many loggers don't have success
|
success: (message) => log.info(message) // Map success to info since many loggers don't have success
|
||||||
};
|
};
|
||||||
|
|
||||||
// Execute core updateTaskById function with proper parameters
|
// Execute core updateTaskById function with proper parameters
|
||||||
await updateTaskById(
|
await updateTaskById(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
taskId,
|
taskId,
|
||||||
args.prompt,
|
args.prompt,
|
||||||
useResearch,
|
useResearch,
|
||||||
{
|
{
|
||||||
mcpLog: logWrapper, // Use our wrapper object that has the expected method structure
|
mcpLog: logWrapper, // Use our wrapper object that has the expected method structure
|
||||||
session
|
session
|
||||||
},
|
},
|
||||||
'json'
|
'json'
|
||||||
);
|
);
|
||||||
|
|
||||||
// Since updateTaskById doesn't return a value but modifies the tasks file,
|
// Since updateTaskById doesn't return a value but modifies the tasks file,
|
||||||
// we'll return a success message
|
// we'll return a success message
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully updated task with ID ${taskId} based on the prompt`,
|
message: `Successfully updated task with ID ${taskId} based on the prompt`,
|
||||||
taskId,
|
taskId,
|
||||||
tasksPath,
|
tasksPath,
|
||||||
useResearch
|
useResearch
|
||||||
},
|
},
|
||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error updating task by ID: ${error.message}`);
|
log.error(`Error updating task by ID: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'UPDATE_TASK_ERROR', message: error.message || 'Unknown error updating task' },
|
error: {
|
||||||
fromCache: false
|
code: 'UPDATE_TASK_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error updating task'
|
||||||
} finally {
|
},
|
||||||
// Make sure to restore normal logging even if there's an error
|
fromCache: false
|
||||||
disableSilentMode();
|
};
|
||||||
}
|
} finally {
|
||||||
} catch (error) {
|
// Make sure to restore normal logging even if there's an error
|
||||||
// Ensure silent mode is disabled
|
disableSilentMode();
|
||||||
disableSilentMode();
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Ensure silent mode is disabled
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error updating task by ID: ${error.message}`);
|
log.error(`Error updating task by ID: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'UPDATE_TASK_ERROR', message: error.message || 'Unknown error updating task' },
|
error: {
|
||||||
fromCache: false
|
code: 'UPDATE_TASK_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error updating task'
|
||||||
}
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,11 +4,14 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { updateTasks } from '../../../../scripts/modules/task-manager.js';
|
import { updateTasks } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import {
|
import {
|
||||||
getAnthropicClientForMCP,
|
getAnthropicClientForMCP,
|
||||||
getPerplexityClientForMCP
|
getPerplexityClientForMCP
|
||||||
} from '../utils/ai-client-utils.js';
|
} from '../utils/ai-client-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -20,152 +23,158 @@ import {
|
|||||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||||
*/
|
*/
|
||||||
export async function updateTasksDirect(args, log, context = {}) {
|
export async function updateTasksDirect(args, log, context = {}) {
|
||||||
const { session } = context; // Only extract session, not reportProgress
|
const { session } = context; // Only extract session, not reportProgress
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Updating tasks with args: ${JSON.stringify(args)}`);
|
log.info(`Updating tasks with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Check for the common mistake of using 'id' instead of 'from'
|
// Check for the common mistake of using 'id' instead of 'from'
|
||||||
if (args.id !== undefined && args.from === undefined) {
|
if (args.id !== undefined && args.from === undefined) {
|
||||||
const errorMessage = "You specified 'id' parameter but 'update' requires 'from' parameter. Use 'from' for this tool or use 'update_task' tool if you want to update a single task.";
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
"You specified 'id' parameter but 'update' requires 'from' parameter. Use 'from' for this tool or use 'update_task' tool if you want to update a single task.";
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: {
|
success: false,
|
||||||
code: 'PARAMETER_MISMATCH',
|
error: {
|
||||||
message: errorMessage,
|
code: 'PARAMETER_MISMATCH',
|
||||||
suggestion: "Use 'from' parameter instead of 'id', or use the 'update_task' tool for single task updates"
|
message: errorMessage,
|
||||||
},
|
suggestion:
|
||||||
fromCache: false
|
"Use 'from' parameter instead of 'id', or use the 'update_task' tool for single task updates"
|
||||||
};
|
},
|
||||||
}
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Check required parameters
|
// Check required parameters
|
||||||
if (!args.from) {
|
if (!args.from) {
|
||||||
const errorMessage = 'No from ID specified. Please provide a task ID to start updating from.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No from ID specified. Please provide a task ID to start updating from.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_FROM_ID', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_FROM_ID', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (!args.prompt) {
|
if (!args.prompt) {
|
||||||
const errorMessage = 'No prompt specified. Please provide a prompt with new context for task updates.';
|
const errorMessage =
|
||||||
log.error(errorMessage);
|
'No prompt specified. Please provide a prompt with new context for task updates.';
|
||||||
return {
|
log.error(errorMessage);
|
||||||
success: false,
|
return {
|
||||||
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
success: false,
|
||||||
fromCache: false
|
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
||||||
};
|
fromCache: false
|
||||||
}
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Parse fromId - handle both string and number values
|
// Parse fromId - handle both string and number values
|
||||||
let fromId;
|
let fromId;
|
||||||
if (typeof args.from === 'string') {
|
if (typeof args.from === 'string') {
|
||||||
fromId = parseInt(args.from, 10);
|
fromId = parseInt(args.from, 10);
|
||||||
if (isNaN(fromId)) {
|
if (isNaN(fromId)) {
|
||||||
const errorMessage = `Invalid from ID: ${args.from}. Task ID must be a positive integer.`;
|
const errorMessage = `Invalid from ID: ${args.from}. Task ID must be a positive integer.`;
|
||||||
log.error(errorMessage);
|
log.error(errorMessage);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'INVALID_FROM_ID', message: errorMessage },
|
error: { code: 'INVALID_FROM_ID', message: errorMessage },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
fromId = args.from;
|
fromId = args.from;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get tasks file path
|
// Get tasks file path
|
||||||
let tasksPath;
|
let tasksPath;
|
||||||
try {
|
try {
|
||||||
tasksPath = findTasksJsonPath(args, log);
|
tasksPath = findTasksJsonPath(args, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error finding tasks file: ${error.message}`);
|
log.error(`Error finding tasks file: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'TASKS_FILE_ERROR', message: error.message },
|
error: { code: 'TASKS_FILE_ERROR', message: error.message },
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get research flag
|
// Get research flag
|
||||||
const useResearch = args.research === true;
|
const useResearch = args.research === true;
|
||||||
|
|
||||||
// Initialize appropriate AI client based on research flag
|
// Initialize appropriate AI client based on research flag
|
||||||
let aiClient;
|
let aiClient;
|
||||||
try {
|
try {
|
||||||
if (useResearch) {
|
if (useResearch) {
|
||||||
log.info('Using Perplexity AI for research-backed task updates');
|
log.info('Using Perplexity AI for research-backed task updates');
|
||||||
aiClient = await getPerplexityClientForMCP(session, log);
|
aiClient = await getPerplexityClientForMCP(session, log);
|
||||||
} else {
|
} else {
|
||||||
log.info('Using Claude AI for task updates');
|
log.info('Using Claude AI for task updates');
|
||||||
aiClient = getAnthropicClientForMCP(session, log);
|
aiClient = getAnthropicClientForMCP(session, log);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to initialize AI client: ${error.message}`);
|
log.error(`Failed to initialize AI client: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'AI_CLIENT_ERROR',
|
code: 'AI_CLIENT_ERROR',
|
||||||
message: `Cannot initialize AI client: ${error.message}`
|
message: `Cannot initialize AI client: ${error.message}`
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Updating tasks from ID ${fromId} with prompt "${args.prompt}" and research: ${useResearch}`);
|
log.info(
|
||||||
|
`Updating tasks from ID ${fromId} with prompt "${args.prompt}" and research: ${useResearch}`
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Execute core updateTasks function, passing the AI client and session
|
// Execute core updateTasks function, passing the AI client and session
|
||||||
await updateTasks(
|
await updateTasks(tasksPath, fromId, args.prompt, useResearch, {
|
||||||
tasksPath,
|
mcpLog: log,
|
||||||
fromId,
|
session
|
||||||
args.prompt,
|
});
|
||||||
useResearch,
|
|
||||||
{
|
|
||||||
mcpLog: log,
|
|
||||||
session
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// Since updateTasks doesn't return a value but modifies the tasks file,
|
// Since updateTasks doesn't return a value but modifies the tasks file,
|
||||||
// we'll return a success message
|
// we'll return a success message
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully updated tasks from ID ${fromId} based on the prompt`,
|
message: `Successfully updated tasks from ID ${fromId} based on the prompt`,
|
||||||
fromId,
|
fromId,
|
||||||
tasksPath,
|
tasksPath,
|
||||||
useResearch
|
useResearch
|
||||||
},
|
},
|
||||||
fromCache: false // This operation always modifies state and should never be cached
|
fromCache: false // This operation always modifies state and should never be cached
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error updating tasks: ${error.message}`);
|
log.error(`Error updating tasks: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'UPDATE_TASKS_ERROR', message: error.message || 'Unknown error updating tasks' },
|
error: {
|
||||||
fromCache: false
|
code: 'UPDATE_TASKS_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error updating tasks'
|
||||||
} finally {
|
},
|
||||||
// Make sure to restore normal logging even if there's an error
|
fromCache: false
|
||||||
disableSilentMode();
|
};
|
||||||
}
|
} finally {
|
||||||
} catch (error) {
|
// Make sure to restore normal logging even if there's an error
|
||||||
// Ensure silent mode is disabled
|
disableSilentMode();
|
||||||
disableSilentMode();
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Ensure silent mode is disabled
|
||||||
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error updating tasks: ${error.message}`);
|
log.error(`Error updating tasks: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'UPDATE_TASKS_ERROR', message: error.message || 'Unknown error updating tasks' },
|
error: {
|
||||||
fromCache: false
|
code: 'UPDATE_TASKS_ERROR',
|
||||||
};
|
message: error.message || 'Unknown error updating tasks'
|
||||||
}
|
},
|
||||||
|
fromCache: false
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
import { validateDependenciesCommand } from '../../../../scripts/modules/dependency-manager.js';
|
import { validateDependenciesCommand } from '../../../../scripts/modules/dependency-manager.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
import { enableSilentMode, disableSilentMode } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
enableSilentMode,
|
||||||
|
disableSilentMode
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,50 +19,50 @@ import fs from 'fs';
|
|||||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||||
*/
|
*/
|
||||||
export async function validateDependenciesDirect(args, log) {
|
export async function validateDependenciesDirect(args, log) {
|
||||||
try {
|
try {
|
||||||
log.info(`Validating dependencies in tasks...`);
|
log.info(`Validating dependencies in tasks...`);
|
||||||
|
|
||||||
// Find the tasks.json path
|
// Find the tasks.json path
|
||||||
const tasksPath = findTasksJsonPath(args, log);
|
const tasksPath = findTasksJsonPath(args, log);
|
||||||
|
|
||||||
// Verify the file exists
|
// Verify the file exists
|
||||||
if (!fs.existsSync(tasksPath)) {
|
if (!fs.existsSync(tasksPath)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'FILE_NOT_FOUND',
|
code: 'FILE_NOT_FOUND',
|
||||||
message: `Tasks file not found at ${tasksPath}`
|
message: `Tasks file not found at ${tasksPath}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||||
enableSilentMode();
|
enableSilentMode();
|
||||||
|
|
||||||
// Call the original command function
|
// Call the original command function
|
||||||
await validateDependenciesCommand(tasksPath);
|
await validateDependenciesCommand(tasksPath);
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: 'Dependencies validated successfully',
|
message: 'Dependencies validated successfully',
|
||||||
tasksPath
|
tasksPath
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Make sure to restore normal logging even if there's an error
|
// Make sure to restore normal logging even if there's an error
|
||||||
disableSilentMode();
|
disableSilentMode();
|
||||||
|
|
||||||
log.error(`Error validating dependencies: ${error.message}`);
|
log.error(`Error validating dependencies: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: {
|
error: {
|
||||||
code: 'VALIDATION_ERROR',
|
code: 'VALIDATION_ERROR',
|
||||||
message: error.message
|
message: error.message
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -34,63 +34,63 @@ export { findTasksJsonPath } from './utils/path-utils.js';
|
|||||||
|
|
||||||
// Re-export AI client utilities
|
// Re-export AI client utilities
|
||||||
export {
|
export {
|
||||||
getAnthropicClientForMCP,
|
getAnthropicClientForMCP,
|
||||||
getPerplexityClientForMCP,
|
getPerplexityClientForMCP,
|
||||||
getModelConfig,
|
getModelConfig,
|
||||||
getBestAvailableAIModel,
|
getBestAvailableAIModel,
|
||||||
handleClaudeError
|
handleClaudeError
|
||||||
} from './utils/ai-client-utils.js';
|
} from './utils/ai-client-utils.js';
|
||||||
|
|
||||||
// Use Map for potential future enhancements like introspection or dynamic dispatch
|
// Use Map for potential future enhancements like introspection or dynamic dispatch
|
||||||
export const directFunctions = new Map([
|
export const directFunctions = new Map([
|
||||||
['listTasksDirect', listTasksDirect],
|
['listTasksDirect', listTasksDirect],
|
||||||
['getCacheStatsDirect', getCacheStatsDirect],
|
['getCacheStatsDirect', getCacheStatsDirect],
|
||||||
['parsePRDDirect', parsePRDDirect],
|
['parsePRDDirect', parsePRDDirect],
|
||||||
['updateTasksDirect', updateTasksDirect],
|
['updateTasksDirect', updateTasksDirect],
|
||||||
['updateTaskByIdDirect', updateTaskByIdDirect],
|
['updateTaskByIdDirect', updateTaskByIdDirect],
|
||||||
['updateSubtaskByIdDirect', updateSubtaskByIdDirect],
|
['updateSubtaskByIdDirect', updateSubtaskByIdDirect],
|
||||||
['generateTaskFilesDirect', generateTaskFilesDirect],
|
['generateTaskFilesDirect', generateTaskFilesDirect],
|
||||||
['setTaskStatusDirect', setTaskStatusDirect],
|
['setTaskStatusDirect', setTaskStatusDirect],
|
||||||
['showTaskDirect', showTaskDirect],
|
['showTaskDirect', showTaskDirect],
|
||||||
['nextTaskDirect', nextTaskDirect],
|
['nextTaskDirect', nextTaskDirect],
|
||||||
['expandTaskDirect', expandTaskDirect],
|
['expandTaskDirect', expandTaskDirect],
|
||||||
['addTaskDirect', addTaskDirect],
|
['addTaskDirect', addTaskDirect],
|
||||||
['addSubtaskDirect', addSubtaskDirect],
|
['addSubtaskDirect', addSubtaskDirect],
|
||||||
['removeSubtaskDirect', removeSubtaskDirect],
|
['removeSubtaskDirect', removeSubtaskDirect],
|
||||||
['analyzeTaskComplexityDirect', analyzeTaskComplexityDirect],
|
['analyzeTaskComplexityDirect', analyzeTaskComplexityDirect],
|
||||||
['clearSubtasksDirect', clearSubtasksDirect],
|
['clearSubtasksDirect', clearSubtasksDirect],
|
||||||
['expandAllTasksDirect', expandAllTasksDirect],
|
['expandAllTasksDirect', expandAllTasksDirect],
|
||||||
['removeDependencyDirect', removeDependencyDirect],
|
['removeDependencyDirect', removeDependencyDirect],
|
||||||
['validateDependenciesDirect', validateDependenciesDirect],
|
['validateDependenciesDirect', validateDependenciesDirect],
|
||||||
['fixDependenciesDirect', fixDependenciesDirect],
|
['fixDependenciesDirect', fixDependenciesDirect],
|
||||||
['complexityReportDirect', complexityReportDirect],
|
['complexityReportDirect', complexityReportDirect],
|
||||||
['addDependencyDirect', addDependencyDirect],
|
['addDependencyDirect', addDependencyDirect],
|
||||||
['removeTaskDirect', removeTaskDirect]
|
['removeTaskDirect', removeTaskDirect]
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Re-export all direct function implementations
|
// Re-export all direct function implementations
|
||||||
export {
|
export {
|
||||||
listTasksDirect,
|
listTasksDirect,
|
||||||
getCacheStatsDirect,
|
getCacheStatsDirect,
|
||||||
parsePRDDirect,
|
parsePRDDirect,
|
||||||
updateTasksDirect,
|
updateTasksDirect,
|
||||||
updateTaskByIdDirect,
|
updateTaskByIdDirect,
|
||||||
updateSubtaskByIdDirect,
|
updateSubtaskByIdDirect,
|
||||||
generateTaskFilesDirect,
|
generateTaskFilesDirect,
|
||||||
setTaskStatusDirect,
|
setTaskStatusDirect,
|
||||||
showTaskDirect,
|
showTaskDirect,
|
||||||
nextTaskDirect,
|
nextTaskDirect,
|
||||||
expandTaskDirect,
|
expandTaskDirect,
|
||||||
addTaskDirect,
|
addTaskDirect,
|
||||||
addSubtaskDirect,
|
addSubtaskDirect,
|
||||||
removeSubtaskDirect,
|
removeSubtaskDirect,
|
||||||
analyzeTaskComplexityDirect,
|
analyzeTaskComplexityDirect,
|
||||||
clearSubtasksDirect,
|
clearSubtasksDirect,
|
||||||
expandAllTasksDirect,
|
expandAllTasksDirect,
|
||||||
removeDependencyDirect,
|
removeDependencyDirect,
|
||||||
validateDependenciesDirect,
|
validateDependenciesDirect,
|
||||||
fixDependenciesDirect,
|
fixDependenciesDirect,
|
||||||
complexityReportDirect,
|
complexityReportDirect,
|
||||||
addDependencyDirect,
|
addDependencyDirect,
|
||||||
removeTaskDirect
|
removeTaskDirect
|
||||||
};
|
};
|
||||||
@@ -11,9 +11,9 @@ dotenv.config();
|
|||||||
|
|
||||||
// Default model configuration from CLI environment
|
// Default model configuration from CLI environment
|
||||||
const DEFAULT_MODEL_CONFIG = {
|
const DEFAULT_MODEL_CONFIG = {
|
||||||
model: 'claude-3-7-sonnet-20250219',
|
model: 'claude-3-7-sonnet-20250219',
|
||||||
maxTokens: 64000,
|
maxTokens: 64000,
|
||||||
temperature: 0.2
|
temperature: 0.2
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,25 +24,28 @@ const DEFAULT_MODEL_CONFIG = {
|
|||||||
* @throws {Error} If API key is missing
|
* @throws {Error} If API key is missing
|
||||||
*/
|
*/
|
||||||
export function getAnthropicClientForMCP(session, log = console) {
|
export function getAnthropicClientForMCP(session, log = console) {
|
||||||
try {
|
try {
|
||||||
// Extract API key from session.env or fall back to environment variables
|
// Extract API key from session.env or fall back to environment variables
|
||||||
const apiKey = session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY;
|
const apiKey =
|
||||||
|
session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY;
|
||||||
|
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
throw new Error('ANTHROPIC_API_KEY not found in session environment or process.env');
|
throw new Error(
|
||||||
}
|
'ANTHROPIC_API_KEY not found in session environment or process.env'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Initialize and return a new Anthropic client
|
// Initialize and return a new Anthropic client
|
||||||
return new Anthropic({
|
return new Anthropic({
|
||||||
apiKey,
|
apiKey,
|
||||||
defaultHeaders: {
|
defaultHeaders: {
|
||||||
'anthropic-beta': 'output-128k-2025-02-19' // Include header for increased token limit
|
'anthropic-beta': 'output-128k-2025-02-19' // Include header for increased token limit
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to initialize Anthropic client: ${error.message}`);
|
log.error(`Failed to initialize Anthropic client: ${error.message}`);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -53,26 +56,29 @@ export function getAnthropicClientForMCP(session, log = console) {
|
|||||||
* @throws {Error} If API key is missing or OpenAI package can't be imported
|
* @throws {Error} If API key is missing or OpenAI package can't be imported
|
||||||
*/
|
*/
|
||||||
export async function getPerplexityClientForMCP(session, log = console) {
|
export async function getPerplexityClientForMCP(session, log = console) {
|
||||||
try {
|
try {
|
||||||
// Extract API key from session.env or fall back to environment variables
|
// Extract API key from session.env or fall back to environment variables
|
||||||
const apiKey = session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY;
|
const apiKey =
|
||||||
|
session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY;
|
||||||
|
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
throw new Error('PERPLEXITY_API_KEY not found in session environment or process.env');
|
throw new Error(
|
||||||
}
|
'PERPLEXITY_API_KEY not found in session environment or process.env'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Dynamically import OpenAI (it may not be used in all contexts)
|
// Dynamically import OpenAI (it may not be used in all contexts)
|
||||||
const { default: OpenAI } = await import('openai');
|
const { default: OpenAI } = await import('openai');
|
||||||
|
|
||||||
// Initialize and return a new OpenAI client configured for Perplexity
|
// Initialize and return a new OpenAI client configured for Perplexity
|
||||||
return new OpenAI({
|
return new OpenAI({
|
||||||
apiKey,
|
apiKey,
|
||||||
baseURL: 'https://api.perplexity.ai'
|
baseURL: 'https://api.perplexity.ai'
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Failed to initialize Perplexity client: ${error.message}`);
|
log.error(`Failed to initialize Perplexity client: ${error.message}`);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,12 +88,12 @@ export async function getPerplexityClientForMCP(session, log = console) {
|
|||||||
* @returns {Object} Model configuration with model, maxTokens, and temperature
|
* @returns {Object} Model configuration with model, maxTokens, and temperature
|
||||||
*/
|
*/
|
||||||
export function getModelConfig(session, defaults = DEFAULT_MODEL_CONFIG) {
|
export function getModelConfig(session, defaults = DEFAULT_MODEL_CONFIG) {
|
||||||
// Get values from session or fall back to defaults
|
// Get values from session or fall back to defaults
|
||||||
return {
|
return {
|
||||||
model: session?.env?.MODEL || defaults.model,
|
model: session?.env?.MODEL || defaults.model,
|
||||||
maxTokens: parseInt(session?.env?.MAX_TOKENS || defaults.maxTokens),
|
maxTokens: parseInt(session?.env?.MAX_TOKENS || defaults.maxTokens),
|
||||||
temperature: parseFloat(session?.env?.TEMPERATURE || defaults.temperature)
|
temperature: parseFloat(session?.env?.TEMPERATURE || defaults.temperature)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -100,59 +106,78 @@ export function getModelConfig(session, defaults = DEFAULT_MODEL_CONFIG) {
|
|||||||
* @returns {Promise<Object>} Selected model info with type and client
|
* @returns {Promise<Object>} Selected model info with type and client
|
||||||
* @throws {Error} If no AI models are available
|
* @throws {Error} If no AI models are available
|
||||||
*/
|
*/
|
||||||
export async function getBestAvailableAIModel(session, options = {}, log = console) {
|
export async function getBestAvailableAIModel(
|
||||||
const { requiresResearch = false, claudeOverloaded = false } = options;
|
session,
|
||||||
|
options = {},
|
||||||
|
log = console
|
||||||
|
) {
|
||||||
|
const { requiresResearch = false, claudeOverloaded = false } = options;
|
||||||
|
|
||||||
// Test case: When research is needed but no Perplexity, use Claude
|
// Test case: When research is needed but no Perplexity, use Claude
|
||||||
if (requiresResearch &&
|
if (
|
||||||
!(session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY) &&
|
requiresResearch &&
|
||||||
(session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)) {
|
!(session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY) &&
|
||||||
try {
|
(session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)
|
||||||
log.warn('Perplexity not available for research, using Claude');
|
) {
|
||||||
const client = getAnthropicClientForMCP(session, log);
|
try {
|
||||||
return { type: 'claude', client };
|
log.warn('Perplexity not available for research, using Claude');
|
||||||
} catch (error) {
|
const client = getAnthropicClientForMCP(session, log);
|
||||||
log.error(`Claude not available: ${error.message}`);
|
return { type: 'claude', client };
|
||||||
throw new Error('No AI models available for research');
|
} catch (error) {
|
||||||
}
|
log.error(`Claude not available: ${error.message}`);
|
||||||
}
|
throw new Error('No AI models available for research');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Regular path: Perplexity for research when available
|
// Regular path: Perplexity for research when available
|
||||||
if (requiresResearch && (session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY)) {
|
if (
|
||||||
try {
|
requiresResearch &&
|
||||||
const client = await getPerplexityClientForMCP(session, log);
|
(session?.env?.PERPLEXITY_API_KEY || process.env.PERPLEXITY_API_KEY)
|
||||||
return { type: 'perplexity', client };
|
) {
|
||||||
} catch (error) {
|
try {
|
||||||
log.warn(`Perplexity not available: ${error.message}`);
|
const client = await getPerplexityClientForMCP(session, log);
|
||||||
// Fall through to Claude as backup
|
return { type: 'perplexity', client };
|
||||||
}
|
} catch (error) {
|
||||||
}
|
log.warn(`Perplexity not available: ${error.message}`);
|
||||||
|
// Fall through to Claude as backup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Test case: Claude for overloaded scenario
|
// Test case: Claude for overloaded scenario
|
||||||
if (claudeOverloaded && (session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)) {
|
if (
|
||||||
try {
|
claudeOverloaded &&
|
||||||
log.warn('Claude is overloaded but no alternatives are available. Proceeding with Claude anyway.');
|
(session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)
|
||||||
const client = getAnthropicClientForMCP(session, log);
|
) {
|
||||||
return { type: 'claude', client };
|
try {
|
||||||
} catch (error) {
|
log.warn(
|
||||||
log.error(`Claude not available despite being overloaded: ${error.message}`);
|
'Claude is overloaded but no alternatives are available. Proceeding with Claude anyway.'
|
||||||
throw new Error('No AI models available');
|
);
|
||||||
}
|
const client = getAnthropicClientForMCP(session, log);
|
||||||
}
|
return { type: 'claude', client };
|
||||||
|
} catch (error) {
|
||||||
|
log.error(
|
||||||
|
`Claude not available despite being overloaded: ${error.message}`
|
||||||
|
);
|
||||||
|
throw new Error('No AI models available');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Default case: Use Claude when available and not overloaded
|
// Default case: Use Claude when available and not overloaded
|
||||||
if (!claudeOverloaded && (session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)) {
|
if (
|
||||||
try {
|
!claudeOverloaded &&
|
||||||
const client = getAnthropicClientForMCP(session, log);
|
(session?.env?.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY)
|
||||||
return { type: 'claude', client };
|
) {
|
||||||
} catch (error) {
|
try {
|
||||||
log.warn(`Claude not available: ${error.message}`);
|
const client = getAnthropicClientForMCP(session, log);
|
||||||
// Fall through to error if no other options
|
return { type: 'claude', client };
|
||||||
}
|
} catch (error) {
|
||||||
}
|
log.warn(`Claude not available: ${error.message}`);
|
||||||
|
// Fall through to error if no other options
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// If we got here, no models were successfully initialized
|
// If we got here, no models were successfully initialized
|
||||||
throw new Error('No AI models available. Please check your API keys.');
|
throw new Error('No AI models available. Please check your API keys.');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -161,28 +186,28 @@ export async function getBestAvailableAIModel(session, options = {}, log = conso
|
|||||||
* @returns {string} User-friendly error message
|
* @returns {string} User-friendly error message
|
||||||
*/
|
*/
|
||||||
export function handleClaudeError(error) {
|
export function handleClaudeError(error) {
|
||||||
// Check if it's a structured error response
|
// Check if it's a structured error response
|
||||||
if (error.type === 'error' && error.error) {
|
if (error.type === 'error' && error.error) {
|
||||||
switch (error.error.type) {
|
switch (error.error.type) {
|
||||||
case 'overloaded_error':
|
case 'overloaded_error':
|
||||||
return 'Claude is currently experiencing high demand and is overloaded. Please wait a few minutes and try again.';
|
return 'Claude is currently experiencing high demand and is overloaded. Please wait a few minutes and try again.';
|
||||||
case 'rate_limit_error':
|
case 'rate_limit_error':
|
||||||
return 'You have exceeded the rate limit. Please wait a few minutes before making more requests.';
|
return 'You have exceeded the rate limit. Please wait a few minutes before making more requests.';
|
||||||
case 'invalid_request_error':
|
case 'invalid_request_error':
|
||||||
return 'There was an issue with the request format. If this persists, please report it as a bug.';
|
return 'There was an issue with the request format. If this persists, please report it as a bug.';
|
||||||
default:
|
default:
|
||||||
return `Claude API error: ${error.error.message}`;
|
return `Claude API error: ${error.error.message}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for network/timeout errors
|
// Check for network/timeout errors
|
||||||
if (error.message?.toLowerCase().includes('timeout')) {
|
if (error.message?.toLowerCase().includes('timeout')) {
|
||||||
return 'The request to Claude timed out. Please try again.';
|
return 'The request to Claude timed out. Please try again.';
|
||||||
}
|
}
|
||||||
if (error.message?.toLowerCase().includes('network')) {
|
if (error.message?.toLowerCase().includes('network')) {
|
||||||
return 'There was a network error connecting to Claude. Please check your internet connection and try again.';
|
return 'There was a network error connecting to Claude. Please check your internet connection and try again.';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default error message
|
// Default error message
|
||||||
return `Error communicating with Claude: ${error.message}`;
|
return `Error communicating with Claude: ${error.message}`;
|
||||||
}
|
}
|
||||||
@@ -1,213 +1,247 @@
|
|||||||
import { v4 as uuidv4 } from 'uuid';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
|
||||||
class AsyncOperationManager {
|
class AsyncOperationManager {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.operations = new Map(); // Stores active operation state
|
this.operations = new Map(); // Stores active operation state
|
||||||
this.completedOperations = new Map(); // Stores completed operations
|
this.completedOperations = new Map(); // Stores completed operations
|
||||||
this.maxCompletedOperations = 100; // Maximum number of completed operations to store
|
this.maxCompletedOperations = 100; // Maximum number of completed operations to store
|
||||||
this.listeners = new Map(); // For potential future notifications
|
this.listeners = new Map(); // For potential future notifications
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds an operation to be executed asynchronously.
|
* Adds an operation to be executed asynchronously.
|
||||||
* @param {Function} operationFn - The async function to execute (e.g., a Direct function).
|
* @param {Function} operationFn - The async function to execute (e.g., a Direct function).
|
||||||
* @param {Object} args - Arguments to pass to the operationFn.
|
* @param {Object} args - Arguments to pass to the operationFn.
|
||||||
* @param {Object} context - The MCP tool context { log, reportProgress, session }.
|
* @param {Object} context - The MCP tool context { log, reportProgress, session }.
|
||||||
* @returns {string} The unique ID assigned to this operation.
|
* @returns {string} The unique ID assigned to this operation.
|
||||||
*/
|
*/
|
||||||
addOperation(operationFn, args, context) {
|
addOperation(operationFn, args, context) {
|
||||||
const operationId = `op-${uuidv4()}`;
|
const operationId = `op-${uuidv4()}`;
|
||||||
const operation = {
|
const operation = {
|
||||||
id: operationId,
|
id: operationId,
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
startTime: Date.now(),
|
startTime: Date.now(),
|
||||||
endTime: null,
|
endTime: null,
|
||||||
result: null,
|
result: null,
|
||||||
error: null,
|
error: null,
|
||||||
// Store necessary parts of context, especially log for background execution
|
// Store necessary parts of context, especially log for background execution
|
||||||
log: context.log,
|
log: context.log,
|
||||||
reportProgress: context.reportProgress, // Pass reportProgress through
|
reportProgress: context.reportProgress, // Pass reportProgress through
|
||||||
session: context.session // Pass session through if needed by the operationFn
|
session: context.session // Pass session through if needed by the operationFn
|
||||||
};
|
};
|
||||||
this.operations.set(operationId, operation);
|
this.operations.set(operationId, operation);
|
||||||
this.log(operationId, 'info', `Operation added.`);
|
this.log(operationId, 'info', `Operation added.`);
|
||||||
|
|
||||||
// Start execution in the background (don't await here)
|
// Start execution in the background (don't await here)
|
||||||
this._runOperation(operationId, operationFn, args, context).catch(err => {
|
this._runOperation(operationId, operationFn, args, context).catch((err) => {
|
||||||
// Catch unexpected errors during the async execution setup itself
|
// Catch unexpected errors during the async execution setup itself
|
||||||
this.log(operationId, 'error', `Critical error starting operation: ${err.message}`, { stack: err.stack });
|
this.log(
|
||||||
operation.status = 'failed';
|
operationId,
|
||||||
operation.error = { code: 'MANAGER_EXECUTION_ERROR', message: err.message };
|
'error',
|
||||||
operation.endTime = Date.now();
|
`Critical error starting operation: ${err.message}`,
|
||||||
|
{ stack: err.stack }
|
||||||
|
);
|
||||||
|
operation.status = 'failed';
|
||||||
|
operation.error = {
|
||||||
|
code: 'MANAGER_EXECUTION_ERROR',
|
||||||
|
message: err.message
|
||||||
|
};
|
||||||
|
operation.endTime = Date.now();
|
||||||
|
|
||||||
// Move to completed operations
|
// Move to completed operations
|
||||||
this._moveToCompleted(operationId);
|
this._moveToCompleted(operationId);
|
||||||
});
|
});
|
||||||
|
|
||||||
return operationId;
|
return operationId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Internal function to execute the operation.
|
* Internal function to execute the operation.
|
||||||
* @param {string} operationId - The ID of the operation.
|
* @param {string} operationId - The ID of the operation.
|
||||||
* @param {Function} operationFn - The async function to execute.
|
* @param {Function} operationFn - The async function to execute.
|
||||||
* @param {Object} args - Arguments for the function.
|
* @param {Object} args - Arguments for the function.
|
||||||
* @param {Object} context - The original MCP tool context.
|
* @param {Object} context - The original MCP tool context.
|
||||||
*/
|
*/
|
||||||
async _runOperation(operationId, operationFn, args, context) {
|
async _runOperation(operationId, operationFn, args, context) {
|
||||||
const operation = this.operations.get(operationId);
|
const operation = this.operations.get(operationId);
|
||||||
if (!operation) return; // Should not happen
|
if (!operation) return; // Should not happen
|
||||||
|
|
||||||
operation.status = 'running';
|
operation.status = 'running';
|
||||||
this.log(operationId, 'info', `Operation running.`);
|
this.log(operationId, 'info', `Operation running.`);
|
||||||
this.emit('statusChanged', { operationId, status: 'running' });
|
this.emit('statusChanged', { operationId, status: 'running' });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Pass the necessary context parts to the direct function
|
// Pass the necessary context parts to the direct function
|
||||||
// The direct function needs to be adapted if it needs reportProgress
|
// The direct function needs to be adapted if it needs reportProgress
|
||||||
// We pass the original context's log, plus our wrapped reportProgress
|
// We pass the original context's log, plus our wrapped reportProgress
|
||||||
const result = await operationFn(args, operation.log, {
|
const result = await operationFn(args, operation.log, {
|
||||||
reportProgress: (progress) => this._handleProgress(operationId, progress),
|
reportProgress: (progress) =>
|
||||||
mcpLog: operation.log, // Pass log as mcpLog if direct fn expects it
|
this._handleProgress(operationId, progress),
|
||||||
session: operation.session
|
mcpLog: operation.log, // Pass log as mcpLog if direct fn expects it
|
||||||
});
|
session: operation.session
|
||||||
|
});
|
||||||
|
|
||||||
operation.status = result.success ? 'completed' : 'failed';
|
operation.status = result.success ? 'completed' : 'failed';
|
||||||
operation.result = result.success ? result.data : null;
|
operation.result = result.success ? result.data : null;
|
||||||
operation.error = result.success ? null : result.error;
|
operation.error = result.success ? null : result.error;
|
||||||
this.log(operationId, 'info', `Operation finished with status: ${operation.status}`);
|
this.log(
|
||||||
|
operationId,
|
||||||
|
'info',
|
||||||
|
`Operation finished with status: ${operation.status}`
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
this.log(
|
||||||
|
operationId,
|
||||||
|
'error',
|
||||||
|
`Operation failed with error: ${error.message}`,
|
||||||
|
{ stack: error.stack }
|
||||||
|
);
|
||||||
|
operation.status = 'failed';
|
||||||
|
operation.error = {
|
||||||
|
code: 'OPERATION_EXECUTION_ERROR',
|
||||||
|
message: error.message
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
operation.endTime = Date.now();
|
||||||
|
this.emit('statusChanged', {
|
||||||
|
operationId,
|
||||||
|
status: operation.status,
|
||||||
|
result: operation.result,
|
||||||
|
error: operation.error
|
||||||
|
});
|
||||||
|
|
||||||
} catch (error) {
|
// Move to completed operations if done or failed
|
||||||
this.log(operationId, 'error', `Operation failed with error: ${error.message}`, { stack: error.stack });
|
if (operation.status === 'completed' || operation.status === 'failed') {
|
||||||
operation.status = 'failed';
|
this._moveToCompleted(operationId);
|
||||||
operation.error = { code: 'OPERATION_EXECUTION_ERROR', message: error.message };
|
}
|
||||||
} finally {
|
}
|
||||||
operation.endTime = Date.now();
|
}
|
||||||
this.emit('statusChanged', { operationId, status: operation.status, result: operation.result, error: operation.error });
|
|
||||||
|
|
||||||
// Move to completed operations if done or failed
|
/**
|
||||||
if (operation.status === 'completed' || operation.status === 'failed') {
|
* Move an operation from active operations to completed operations history.
|
||||||
this._moveToCompleted(operationId);
|
* @param {string} operationId - The ID of the operation to move.
|
||||||
}
|
* @private
|
||||||
}
|
*/
|
||||||
}
|
_moveToCompleted(operationId) {
|
||||||
|
const operation = this.operations.get(operationId);
|
||||||
|
if (!operation) return;
|
||||||
|
|
||||||
/**
|
// Store only the necessary data in completed operations
|
||||||
* Move an operation from active operations to completed operations history.
|
const completedData = {
|
||||||
* @param {string} operationId - The ID of the operation to move.
|
id: operation.id,
|
||||||
* @private
|
status: operation.status,
|
||||||
*/
|
startTime: operation.startTime,
|
||||||
_moveToCompleted(operationId) {
|
endTime: operation.endTime,
|
||||||
const operation = this.operations.get(operationId);
|
result: operation.result,
|
||||||
if (!operation) return;
|
error: operation.error
|
||||||
|
};
|
||||||
|
|
||||||
// Store only the necessary data in completed operations
|
this.completedOperations.set(operationId, completedData);
|
||||||
const completedData = {
|
this.operations.delete(operationId);
|
||||||
id: operation.id,
|
|
||||||
status: operation.status,
|
|
||||||
startTime: operation.startTime,
|
|
||||||
endTime: operation.endTime,
|
|
||||||
result: operation.result,
|
|
||||||
error: operation.error,
|
|
||||||
};
|
|
||||||
|
|
||||||
this.completedOperations.set(operationId, completedData);
|
// Trim completed operations if exceeding maximum
|
||||||
this.operations.delete(operationId);
|
if (this.completedOperations.size > this.maxCompletedOperations) {
|
||||||
|
// Get the oldest operation (sorted by endTime)
|
||||||
|
const oldest = [...this.completedOperations.entries()].sort(
|
||||||
|
(a, b) => a[1].endTime - b[1].endTime
|
||||||
|
)[0];
|
||||||
|
|
||||||
// Trim completed operations if exceeding maximum
|
if (oldest) {
|
||||||
if (this.completedOperations.size > this.maxCompletedOperations) {
|
this.completedOperations.delete(oldest[0]);
|
||||||
// Get the oldest operation (sorted by endTime)
|
}
|
||||||
const oldest = [...this.completedOperations.entries()]
|
}
|
||||||
.sort((a, b) => a[1].endTime - b[1].endTime)[0];
|
}
|
||||||
|
|
||||||
if (oldest) {
|
/**
|
||||||
this.completedOperations.delete(oldest[0]);
|
* Handles progress updates from the running operation and forwards them.
|
||||||
}
|
* @param {string} operationId - The ID of the operation reporting progress.
|
||||||
}
|
* @param {Object} progress - The progress object { progress, total? }.
|
||||||
}
|
*/
|
||||||
|
_handleProgress(operationId, progress) {
|
||||||
|
const operation = this.operations.get(operationId);
|
||||||
|
if (operation && operation.reportProgress) {
|
||||||
|
try {
|
||||||
|
// Use the reportProgress function captured from the original context
|
||||||
|
operation.reportProgress(progress);
|
||||||
|
this.log(
|
||||||
|
operationId,
|
||||||
|
'debug',
|
||||||
|
`Reported progress: ${JSON.stringify(progress)}`
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
this.log(
|
||||||
|
operationId,
|
||||||
|
'warn',
|
||||||
|
`Failed to report progress: ${err.message}`
|
||||||
|
);
|
||||||
|
// Don't stop the operation, just log the reporting failure
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles progress updates from the running operation and forwards them.
|
* Retrieves the status and result/error of an operation.
|
||||||
* @param {string} operationId - The ID of the operation reporting progress.
|
* @param {string} operationId - The ID of the operation.
|
||||||
* @param {Object} progress - The progress object { progress, total? }.
|
* @returns {Object | null} The operation details or null if not found.
|
||||||
*/
|
*/
|
||||||
_handleProgress(operationId, progress) {
|
getStatus(operationId) {
|
||||||
const operation = this.operations.get(operationId);
|
// First check active operations
|
||||||
if (operation && operation.reportProgress) {
|
const operation = this.operations.get(operationId);
|
||||||
try {
|
if (operation) {
|
||||||
// Use the reportProgress function captured from the original context
|
return {
|
||||||
operation.reportProgress(progress);
|
id: operation.id,
|
||||||
this.log(operationId, 'debug', `Reported progress: ${JSON.stringify(progress)}`);
|
status: operation.status,
|
||||||
} catch(err) {
|
startTime: operation.startTime,
|
||||||
this.log(operationId, 'warn', `Failed to report progress: ${err.message}`);
|
endTime: operation.endTime,
|
||||||
// Don't stop the operation, just log the reporting failure
|
result: operation.result,
|
||||||
}
|
error: operation.error
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Then check completed operations
|
||||||
* Retrieves the status and result/error of an operation.
|
const completedOperation = this.completedOperations.get(operationId);
|
||||||
* @param {string} operationId - The ID of the operation.
|
if (completedOperation) {
|
||||||
* @returns {Object | null} The operation details or null if not found.
|
return completedOperation;
|
||||||
*/
|
}
|
||||||
getStatus(operationId) {
|
|
||||||
// First check active operations
|
|
||||||
const operation = this.operations.get(operationId);
|
|
||||||
if (operation) {
|
|
||||||
return {
|
|
||||||
id: operation.id,
|
|
||||||
status: operation.status,
|
|
||||||
startTime: operation.startTime,
|
|
||||||
endTime: operation.endTime,
|
|
||||||
result: operation.result,
|
|
||||||
error: operation.error,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Then check completed operations
|
// Operation not found in either active or completed
|
||||||
const completedOperation = this.completedOperations.get(operationId);
|
return {
|
||||||
if (completedOperation) {
|
error: {
|
||||||
return completedOperation;
|
code: 'OPERATION_NOT_FOUND',
|
||||||
}
|
message: `Operation ID ${operationId} not found. It may have been completed and removed from history, or the ID may be invalid.`
|
||||||
|
},
|
||||||
|
status: 'not_found'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Operation not found in either active or completed
|
/**
|
||||||
return {
|
* Internal logging helper to prefix logs with the operation ID.
|
||||||
error: {
|
* @param {string} operationId - The ID of the operation.
|
||||||
code: 'OPERATION_NOT_FOUND',
|
* @param {'info'|'warn'|'error'|'debug'} level - Log level.
|
||||||
message: `Operation ID ${operationId} not found. It may have been completed and removed from history, or the ID may be invalid.`
|
* @param {string} message - Log message.
|
||||||
},
|
* @param {Object} [meta] - Additional metadata.
|
||||||
status: 'not_found'
|
*/
|
||||||
};
|
log(operationId, level, message, meta = {}) {
|
||||||
}
|
const operation = this.operations.get(operationId);
|
||||||
|
// Use the logger instance associated with the operation if available, otherwise console
|
||||||
|
const logger = operation?.log || console;
|
||||||
|
const logFn = logger[level] || logger.log || console.log; // Fallback
|
||||||
|
logFn(`[AsyncOp ${operationId}] ${message}`, meta);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
// --- Basic Event Emitter ---
|
||||||
* Internal logging helper to prefix logs with the operation ID.
|
on(eventName, listener) {
|
||||||
* @param {string} operationId - The ID of the operation.
|
if (!this.listeners.has(eventName)) {
|
||||||
* @param {'info'|'warn'|'error'|'debug'} level - Log level.
|
this.listeners.set(eventName, []);
|
||||||
* @param {string} message - Log message.
|
}
|
||||||
* @param {Object} [meta] - Additional metadata.
|
this.listeners.get(eventName).push(listener);
|
||||||
*/
|
}
|
||||||
log(operationId, level, message, meta = {}) {
|
|
||||||
const operation = this.operations.get(operationId);
|
|
||||||
// Use the logger instance associated with the operation if available, otherwise console
|
|
||||||
const logger = operation?.log || console;
|
|
||||||
const logFn = logger[level] || logger.log || console.log; // Fallback
|
|
||||||
logFn(`[AsyncOp ${operationId}] ${message}`, meta);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Basic Event Emitter ---
|
emit(eventName, data) {
|
||||||
on(eventName, listener) {
|
if (this.listeners.has(eventName)) {
|
||||||
if (!this.listeners.has(eventName)) {
|
this.listeners.get(eventName).forEach((listener) => listener(data));
|
||||||
this.listeners.set(eventName, []);
|
}
|
||||||
}
|
}
|
||||||
this.listeners.get(eventName).push(listener);
|
|
||||||
}
|
|
||||||
|
|
||||||
emit(eventName, data) {
|
|
||||||
if (this.listeners.has(eventName)) {
|
|
||||||
this.listeners.get(eventName).forEach(listener => listener(data));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export a singleton instance
|
// Export a singleton instance
|
||||||
|
|||||||
@@ -6,38 +6,42 @@
|
|||||||
* @returns {Promise<any>} The result of the actionFn.
|
* @returns {Promise<any>} The result of the actionFn.
|
||||||
*/
|
*/
|
||||||
export async function withSessionEnv(sessionEnv, actionFn) {
|
export async function withSessionEnv(sessionEnv, actionFn) {
|
||||||
if (!sessionEnv || typeof sessionEnv !== 'object' || Object.keys(sessionEnv).length === 0) {
|
if (
|
||||||
// If no sessionEnv is provided, just run the action directly
|
!sessionEnv ||
|
||||||
return await actionFn();
|
typeof sessionEnv !== 'object' ||
|
||||||
}
|
Object.keys(sessionEnv).length === 0
|
||||||
|
) {
|
||||||
|
// If no sessionEnv is provided, just run the action directly
|
||||||
|
return await actionFn();
|
||||||
|
}
|
||||||
|
|
||||||
const originalEnv = {};
|
const originalEnv = {};
|
||||||
const keysToRestore = [];
|
const keysToRestore = [];
|
||||||
|
|
||||||
// Set environment variables from sessionEnv
|
// Set environment variables from sessionEnv
|
||||||
for (const key in sessionEnv) {
|
for (const key in sessionEnv) {
|
||||||
if (Object.prototype.hasOwnProperty.call(sessionEnv, key)) {
|
if (Object.prototype.hasOwnProperty.call(sessionEnv, key)) {
|
||||||
// Store original value if it exists, otherwise mark for deletion
|
// Store original value if it exists, otherwise mark for deletion
|
||||||
if (process.env[key] !== undefined) {
|
if (process.env[key] !== undefined) {
|
||||||
originalEnv[key] = process.env[key];
|
originalEnv[key] = process.env[key];
|
||||||
}
|
}
|
||||||
keysToRestore.push(key);
|
keysToRestore.push(key);
|
||||||
process.env[key] = sessionEnv[key];
|
process.env[key] = sessionEnv[key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Execute the provided action function
|
// Execute the provided action function
|
||||||
return await actionFn();
|
return await actionFn();
|
||||||
} finally {
|
} finally {
|
||||||
// Restore original environment variables
|
// Restore original environment variables
|
||||||
for (const key of keysToRestore) {
|
for (const key of keysToRestore) {
|
||||||
if (Object.prototype.hasOwnProperty.call(originalEnv, key)) {
|
if (Object.prototype.hasOwnProperty.call(originalEnv, key)) {
|
||||||
process.env[key] = originalEnv[key];
|
process.env[key] = originalEnv[key];
|
||||||
} else {
|
} else {
|
||||||
// If the key didn't exist originally, delete it
|
// If the key didn't exist originally, delete it
|
||||||
delete process.env[key];
|
delete process.env[key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,43 +18,43 @@ export let lastFoundProjectRoot = null;
|
|||||||
|
|
||||||
// Project marker files that indicate a potential project root
|
// Project marker files that indicate a potential project root
|
||||||
export const PROJECT_MARKERS = [
|
export const PROJECT_MARKERS = [
|
||||||
// Task Master specific
|
// Task Master specific
|
||||||
'tasks.json',
|
'tasks.json',
|
||||||
'tasks/tasks.json',
|
'tasks/tasks.json',
|
||||||
|
|
||||||
// Common version control
|
// Common version control
|
||||||
'.git',
|
'.git',
|
||||||
'.svn',
|
'.svn',
|
||||||
|
|
||||||
// Common package files
|
// Common package files
|
||||||
'package.json',
|
'package.json',
|
||||||
'pyproject.toml',
|
'pyproject.toml',
|
||||||
'Gemfile',
|
'Gemfile',
|
||||||
'go.mod',
|
'go.mod',
|
||||||
'Cargo.toml',
|
'Cargo.toml',
|
||||||
|
|
||||||
// Common IDE/editor folders
|
// Common IDE/editor folders
|
||||||
'.cursor',
|
'.cursor',
|
||||||
'.vscode',
|
'.vscode',
|
||||||
'.idea',
|
'.idea',
|
||||||
|
|
||||||
// Common dependency directories (check if directory)
|
// Common dependency directories (check if directory)
|
||||||
'node_modules',
|
'node_modules',
|
||||||
'venv',
|
'venv',
|
||||||
'.venv',
|
'.venv',
|
||||||
|
|
||||||
// Common config files
|
// Common config files
|
||||||
'.env',
|
'.env',
|
||||||
'.eslintrc',
|
'.eslintrc',
|
||||||
'tsconfig.json',
|
'tsconfig.json',
|
||||||
'babel.config.js',
|
'babel.config.js',
|
||||||
'jest.config.js',
|
'jest.config.js',
|
||||||
'webpack.config.js',
|
'webpack.config.js',
|
||||||
|
|
||||||
// Common CI/CD files
|
// Common CI/CD files
|
||||||
'.github/workflows',
|
'.github/workflows',
|
||||||
'.gitlab-ci.yml',
|
'.gitlab-ci.yml',
|
||||||
'.circleci/config.yml'
|
'.circleci/config.yml'
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -63,15 +63,15 @@ export const PROJECT_MARKERS = [
|
|||||||
* @returns {string} - Absolute path to the package installation directory
|
* @returns {string} - Absolute path to the package installation directory
|
||||||
*/
|
*/
|
||||||
export function getPackagePath() {
|
export function getPackagePath() {
|
||||||
// When running from source, __dirname is the directory containing this file
|
// When running from source, __dirname is the directory containing this file
|
||||||
// When running from npm, we need to find the package root
|
// When running from npm, we need to find the package root
|
||||||
const thisFilePath = fileURLToPath(import.meta.url);
|
const thisFilePath = fileURLToPath(import.meta.url);
|
||||||
const thisFileDir = path.dirname(thisFilePath);
|
const thisFileDir = path.dirname(thisFilePath);
|
||||||
|
|
||||||
// Navigate from core/utils up to the package root
|
// Navigate from core/utils up to the package root
|
||||||
// In dev: /path/to/task-master/mcp-server/src/core/utils -> /path/to/task-master
|
// In dev: /path/to/task-master/mcp-server/src/core/utils -> /path/to/task-master
|
||||||
// In npm: /path/to/node_modules/task-master/mcp-server/src/core/utils -> /path/to/node_modules/task-master
|
// In npm: /path/to/node_modules/task-master/mcp-server/src/core/utils -> /path/to/node_modules/task-master
|
||||||
return path.resolve(thisFileDir, '../../../../');
|
return path.resolve(thisFileDir, '../../../../');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,62 +82,73 @@ export function getPackagePath() {
|
|||||||
* @throws {Error} - If tasks.json cannot be found.
|
* @throws {Error} - If tasks.json cannot be found.
|
||||||
*/
|
*/
|
||||||
export function findTasksJsonPath(args, log) {
|
export function findTasksJsonPath(args, log) {
|
||||||
// PRECEDENCE ORDER for finding tasks.json:
|
// PRECEDENCE ORDER for finding tasks.json:
|
||||||
// 1. Explicitly provided `projectRoot` in args (Highest priority, expected in MCP context)
|
// 1. Explicitly provided `projectRoot` in args (Highest priority, expected in MCP context)
|
||||||
// 2. Previously found/cached `lastFoundProjectRoot` (primarily for CLI performance)
|
// 2. Previously found/cached `lastFoundProjectRoot` (primarily for CLI performance)
|
||||||
// 3. Search upwards from current working directory (`process.cwd()`) - CLI usage
|
// 3. Search upwards from current working directory (`process.cwd()`) - CLI usage
|
||||||
|
|
||||||
// 1. If project root is explicitly provided (e.g., from MCP session), use it directly
|
// 1. If project root is explicitly provided (e.g., from MCP session), use it directly
|
||||||
if (args.projectRoot) {
|
if (args.projectRoot) {
|
||||||
const projectRoot = args.projectRoot;
|
const projectRoot = args.projectRoot;
|
||||||
log.info(`Using explicitly provided project root: ${projectRoot}`);
|
log.info(`Using explicitly provided project root: ${projectRoot}`);
|
||||||
try {
|
try {
|
||||||
// This will throw if tasks.json isn't found within this root
|
// This will throw if tasks.json isn't found within this root
|
||||||
return findTasksJsonInDirectory(projectRoot, args.file, log);
|
return findTasksJsonInDirectory(projectRoot, args.file, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Include debug info in error
|
// Include debug info in error
|
||||||
const debugInfo = {
|
const debugInfo = {
|
||||||
projectRoot,
|
projectRoot,
|
||||||
currentDir: process.cwd(),
|
currentDir: process.cwd(),
|
||||||
serverDir: path.dirname(process.argv[1]),
|
serverDir: path.dirname(process.argv[1]),
|
||||||
possibleProjectRoot: path.resolve(path.dirname(process.argv[1]), '../..'),
|
possibleProjectRoot: path.resolve(
|
||||||
lastFoundProjectRoot,
|
path.dirname(process.argv[1]),
|
||||||
searchedPaths: error.message
|
'../..'
|
||||||
};
|
),
|
||||||
|
lastFoundProjectRoot,
|
||||||
|
searchedPaths: error.message
|
||||||
|
};
|
||||||
|
|
||||||
error.message = `Tasks file not found in any of the expected locations relative to project root "${projectRoot}" (from session).\nDebug Info: ${JSON.stringify(debugInfo, null, 2)}`;
|
error.message = `Tasks file not found in any of the expected locations relative to project root "${projectRoot}" (from session).\nDebug Info: ${JSON.stringify(debugInfo, null, 2)}`;
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Fallback logic primarily for CLI or when projectRoot isn't passed ---
|
// --- Fallback logic primarily for CLI or when projectRoot isn't passed ---
|
||||||
|
|
||||||
// 2. If we have a last known project root that worked, try it first
|
// 2. If we have a last known project root that worked, try it first
|
||||||
if (lastFoundProjectRoot) {
|
if (lastFoundProjectRoot) {
|
||||||
log.info(`Trying last known project root: ${lastFoundProjectRoot}`);
|
log.info(`Trying last known project root: ${lastFoundProjectRoot}`);
|
||||||
try {
|
try {
|
||||||
// Use the cached root
|
// Use the cached root
|
||||||
const tasksPath = findTasksJsonInDirectory(lastFoundProjectRoot, args.file, log);
|
const tasksPath = findTasksJsonInDirectory(
|
||||||
return tasksPath; // Return if found in cached root
|
lastFoundProjectRoot,
|
||||||
} catch (error) {
|
args.file,
|
||||||
log.info(`Task file not found in last known project root, continuing search.`);
|
log
|
||||||
// Continue with search if not found in cache
|
);
|
||||||
}
|
return tasksPath; // Return if found in cached root
|
||||||
}
|
} catch (error) {
|
||||||
|
log.info(
|
||||||
|
`Task file not found in last known project root, continuing search.`
|
||||||
|
);
|
||||||
|
// Continue with search if not found in cache
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 3. Start search from current directory (most common CLI scenario)
|
// 3. Start search from current directory (most common CLI scenario)
|
||||||
const startDir = process.cwd();
|
const startDir = process.cwd();
|
||||||
log.info(`Searching for tasks.json starting from current directory: ${startDir}`);
|
log.info(
|
||||||
|
`Searching for tasks.json starting from current directory: ${startDir}`
|
||||||
|
);
|
||||||
|
|
||||||
// Try to find tasks.json by walking up the directory tree from cwd
|
// Try to find tasks.json by walking up the directory tree from cwd
|
||||||
try {
|
try {
|
||||||
// This will throw if not found in the CWD tree
|
// This will throw if not found in the CWD tree
|
||||||
return findTasksJsonWithParentSearch(startDir, args.file, log);
|
return findTasksJsonWithParentSearch(startDir, args.file, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// If all attempts fail, augment and throw the original error from CWD search
|
// If all attempts fail, augment and throw the original error from CWD search
|
||||||
error.message = `${error.message}\n\nPossible solutions:\n1. Run the command from your project directory containing tasks.json\n2. Use --project-root=/path/to/project to specify the project location (if using CLI)\n3. Ensure the project root is correctly passed from the client (if using MCP)\n\nCurrent working directory: ${startDir}\nLast known project root: ${lastFoundProjectRoot}\nProject root from args: ${args.projectRoot}`;
|
error.message = `${error.message}\n\nPossible solutions:\n1. Run the command from your project directory containing tasks.json\n2. Use --project-root=/path/to/project to specify the project location (if using CLI)\n3. Ensure the project root is correctly passed from the client (if using MCP)\n\nCurrent working directory: ${startDir}\nLast known project root: ${lastFoundProjectRoot}\nProject root from args: ${args.projectRoot}`;
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -146,11 +157,11 @@ export function findTasksJsonPath(args, log) {
|
|||||||
* @returns {boolean} - True if the directory contains any project markers
|
* @returns {boolean} - True if the directory contains any project markers
|
||||||
*/
|
*/
|
||||||
function hasProjectMarkers(dirPath) {
|
function hasProjectMarkers(dirPath) {
|
||||||
return PROJECT_MARKERS.some(marker => {
|
return PROJECT_MARKERS.some((marker) => {
|
||||||
const markerPath = path.join(dirPath, marker);
|
const markerPath = path.join(dirPath, marker);
|
||||||
// Check if the marker exists as either a file or directory
|
// Check if the marker exists as either a file or directory
|
||||||
return fs.existsSync(markerPath);
|
return fs.existsSync(markerPath);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -162,39 +173,41 @@ function hasProjectMarkers(dirPath) {
|
|||||||
* @throws {Error} - If tasks.json cannot be found
|
* @throws {Error} - If tasks.json cannot be found
|
||||||
*/
|
*/
|
||||||
function findTasksJsonInDirectory(dirPath, explicitFilePath, log) {
|
function findTasksJsonInDirectory(dirPath, explicitFilePath, log) {
|
||||||
const possiblePaths = [];
|
const possiblePaths = [];
|
||||||
|
|
||||||
// 1. If a file is explicitly provided relative to dirPath
|
// 1. If a file is explicitly provided relative to dirPath
|
||||||
if (explicitFilePath) {
|
if (explicitFilePath) {
|
||||||
possiblePaths.push(path.resolve(dirPath, explicitFilePath));
|
possiblePaths.push(path.resolve(dirPath, explicitFilePath));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Check the standard locations relative to dirPath
|
// 2. Check the standard locations relative to dirPath
|
||||||
possiblePaths.push(
|
possiblePaths.push(
|
||||||
path.join(dirPath, 'tasks.json'),
|
path.join(dirPath, 'tasks.json'),
|
||||||
path.join(dirPath, 'tasks', 'tasks.json')
|
path.join(dirPath, 'tasks', 'tasks.json')
|
||||||
);
|
);
|
||||||
|
|
||||||
log.info(`Checking potential task file paths: ${possiblePaths.join(', ')}`);
|
log.info(`Checking potential task file paths: ${possiblePaths.join(', ')}`);
|
||||||
|
|
||||||
// Find the first existing path
|
// Find the first existing path
|
||||||
for (const p of possiblePaths) {
|
for (const p of possiblePaths) {
|
||||||
log.info(`Checking if exists: ${p}`);
|
log.info(`Checking if exists: ${p}`);
|
||||||
const exists = fs.existsSync(p);
|
const exists = fs.existsSync(p);
|
||||||
log.info(`Path ${p} exists: ${exists}`);
|
log.info(`Path ${p} exists: ${exists}`);
|
||||||
|
|
||||||
if (exists) {
|
if (exists) {
|
||||||
log.info(`Found tasks file at: ${p}`);
|
log.info(`Found tasks file at: ${p}`);
|
||||||
// Store the project root for future use
|
// Store the project root for future use
|
||||||
lastFoundProjectRoot = dirPath;
|
lastFoundProjectRoot = dirPath;
|
||||||
return p;
|
return p;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If no file was found, throw an error
|
// If no file was found, throw an error
|
||||||
const error = new Error(`Tasks file not found in any of the expected locations relative to ${dirPath}: ${possiblePaths.join(', ')}`);
|
const error = new Error(
|
||||||
error.code = 'TASKS_FILE_NOT_FOUND';
|
`Tasks file not found in any of the expected locations relative to ${dirPath}: ${possiblePaths.join(', ')}`
|
||||||
throw error;
|
);
|
||||||
|
error.code = 'TASKS_FILE_NOT_FOUND';
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -207,66 +220,74 @@ function findTasksJsonInDirectory(dirPath, explicitFilePath, log) {
|
|||||||
* @throws {Error} - If tasks.json cannot be found in any parent directory
|
* @throws {Error} - If tasks.json cannot be found in any parent directory
|
||||||
*/
|
*/
|
||||||
function findTasksJsonWithParentSearch(startDir, explicitFilePath, log) {
|
function findTasksJsonWithParentSearch(startDir, explicitFilePath, log) {
|
||||||
let currentDir = startDir;
|
let currentDir = startDir;
|
||||||
const rootDir = path.parse(currentDir).root;
|
const rootDir = path.parse(currentDir).root;
|
||||||
|
|
||||||
// Keep traversing up until we hit the root directory
|
// Keep traversing up until we hit the root directory
|
||||||
while (currentDir !== rootDir) {
|
while (currentDir !== rootDir) {
|
||||||
// First check for tasks.json directly
|
// First check for tasks.json directly
|
||||||
try {
|
try {
|
||||||
return findTasksJsonInDirectory(currentDir, explicitFilePath, log);
|
return findTasksJsonInDirectory(currentDir, explicitFilePath, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// If tasks.json not found but the directory has project markers,
|
// If tasks.json not found but the directory has project markers,
|
||||||
// log it as a potential project root (helpful for debugging)
|
// log it as a potential project root (helpful for debugging)
|
||||||
if (hasProjectMarkers(currentDir)) {
|
if (hasProjectMarkers(currentDir)) {
|
||||||
log.info(`Found project markers in ${currentDir}, but no tasks.json`);
|
log.info(`Found project markers in ${currentDir}, but no tasks.json`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move up to parent directory
|
// Move up to parent directory
|
||||||
const parentDir = path.dirname(currentDir);
|
const parentDir = path.dirname(currentDir);
|
||||||
|
|
||||||
// Check if we've reached the root
|
// Check if we've reached the root
|
||||||
if (parentDir === currentDir) {
|
if (parentDir === currentDir) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Tasks file not found in ${currentDir}, searching in parent directory: ${parentDir}`);
|
log.info(
|
||||||
currentDir = parentDir;
|
`Tasks file not found in ${currentDir}, searching in parent directory: ${parentDir}`
|
||||||
}
|
);
|
||||||
}
|
currentDir = parentDir;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// If we've searched all the way to the root and found nothing
|
// If we've searched all the way to the root and found nothing
|
||||||
const error = new Error(`Tasks file not found in ${startDir} or any parent directory.`);
|
const error = new Error(
|
||||||
error.code = 'TASKS_FILE_NOT_FOUND';
|
`Tasks file not found in ${startDir} or any parent directory.`
|
||||||
throw error;
|
);
|
||||||
|
error.code = 'TASKS_FILE_NOT_FOUND';
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Note: findTasksWithNpmConsideration is not used by findTasksJsonPath and might be legacy or used elsewhere.
|
// Note: findTasksWithNpmConsideration is not used by findTasksJsonPath and might be legacy or used elsewhere.
|
||||||
// If confirmed unused, it could potentially be removed in a separate cleanup.
|
// If confirmed unused, it could potentially be removed in a separate cleanup.
|
||||||
function findTasksWithNpmConsideration(startDir, log) {
|
function findTasksWithNpmConsideration(startDir, log) {
|
||||||
// First try our recursive parent search from cwd
|
// First try our recursive parent search from cwd
|
||||||
try {
|
try {
|
||||||
return findTasksJsonWithParentSearch(startDir, null, log);
|
return findTasksJsonWithParentSearch(startDir, null, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// If that fails, try looking relative to the executable location
|
// If that fails, try looking relative to the executable location
|
||||||
const execPath = process.argv[1];
|
const execPath = process.argv[1];
|
||||||
const execDir = path.dirname(execPath);
|
const execDir = path.dirname(execPath);
|
||||||
log.info(`Looking for tasks file relative to executable at: ${execDir}`);
|
log.info(`Looking for tasks file relative to executable at: ${execDir}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return findTasksJsonWithParentSearch(execDir, null, log);
|
return findTasksJsonWithParentSearch(execDir, null, log);
|
||||||
} catch (secondError) {
|
} catch (secondError) {
|
||||||
// If that also fails, check standard locations in user's home directory
|
// If that also fails, check standard locations in user's home directory
|
||||||
const homeDir = os.homedir();
|
const homeDir = os.homedir();
|
||||||
log.info(`Looking for tasks file in home directory: ${homeDir}`);
|
log.info(`Looking for tasks file in home directory: ${homeDir}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Check standard locations in home dir
|
// Check standard locations in home dir
|
||||||
return findTasksJsonInDirectory(path.join(homeDir, '.task-master'), null, log);
|
return findTasksJsonInDirectory(
|
||||||
} catch (thirdError) {
|
path.join(homeDir, '.task-master'),
|
||||||
// If all approaches fail, throw the original error
|
null,
|
||||||
throw error;
|
log
|
||||||
}
|
);
|
||||||
}
|
} catch (thirdError) {
|
||||||
}
|
// If all approaches fail, throw the original error
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { FastMCP } from "fastmcp";
|
import { FastMCP } from 'fastmcp';
|
||||||
import path from "path";
|
import path from 'path';
|
||||||
import dotenv from "dotenv";
|
import dotenv from 'dotenv';
|
||||||
import { fileURLToPath } from "url";
|
import { fileURLToPath } from 'url';
|
||||||
import fs from "fs";
|
import fs from 'fs';
|
||||||
import logger from "./logger.js";
|
import logger from './logger.js';
|
||||||
import { registerTaskMasterTools } from "./tools/index.js";
|
import { registerTaskMasterTools } from './tools/index.js';
|
||||||
import { asyncOperationManager } from './core/utils/async-manager.js';
|
import { asyncOperationManager } from './core/utils/async-manager.js';
|
||||||
|
|
||||||
// Load environment variables
|
// Load environment variables
|
||||||
@@ -18,74 +18,74 @@ const __dirname = path.dirname(__filename);
|
|||||||
* Main MCP server class that integrates with Task Master
|
* Main MCP server class that integrates with Task Master
|
||||||
*/
|
*/
|
||||||
class TaskMasterMCPServer {
|
class TaskMasterMCPServer {
|
||||||
constructor() {
|
constructor() {
|
||||||
// Get version from package.json using synchronous fs
|
// Get version from package.json using synchronous fs
|
||||||
const packagePath = path.join(__dirname, "../../package.json");
|
const packagePath = path.join(__dirname, '../../package.json');
|
||||||
const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf8"));
|
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
|
||||||
|
|
||||||
this.options = {
|
this.options = {
|
||||||
name: "Task Master MCP Server",
|
name: 'Task Master MCP Server',
|
||||||
version: packageJson.version,
|
version: packageJson.version
|
||||||
};
|
};
|
||||||
|
|
||||||
this.server = new FastMCP(this.options);
|
this.server = new FastMCP(this.options);
|
||||||
this.initialized = false;
|
this.initialized = false;
|
||||||
|
|
||||||
this.server.addResource({});
|
this.server.addResource({});
|
||||||
|
|
||||||
this.server.addResourceTemplate({});
|
this.server.addResourceTemplate({});
|
||||||
|
|
||||||
// Make the manager accessible (e.g., pass it to tool registration)
|
// Make the manager accessible (e.g., pass it to tool registration)
|
||||||
this.asyncManager = asyncOperationManager;
|
this.asyncManager = asyncOperationManager;
|
||||||
|
|
||||||
// Bind methods
|
// Bind methods
|
||||||
this.init = this.init.bind(this);
|
this.init = this.init.bind(this);
|
||||||
this.start = this.start.bind(this);
|
this.start = this.start.bind(this);
|
||||||
this.stop = this.stop.bind(this);
|
this.stop = this.stop.bind(this);
|
||||||
|
|
||||||
// Setup logging
|
// Setup logging
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize the MCP server with necessary tools and routes
|
* Initialize the MCP server with necessary tools and routes
|
||||||
*/
|
*/
|
||||||
async init() {
|
async init() {
|
||||||
if (this.initialized) return;
|
if (this.initialized) return;
|
||||||
|
|
||||||
// Pass the manager instance to the tool registration function
|
// Pass the manager instance to the tool registration function
|
||||||
registerTaskMasterTools(this.server, this.asyncManager);
|
registerTaskMasterTools(this.server, this.asyncManager);
|
||||||
|
|
||||||
this.initialized = true;
|
this.initialized = true;
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start the MCP server
|
* Start the MCP server
|
||||||
*/
|
*/
|
||||||
async start() {
|
async start() {
|
||||||
if (!this.initialized) {
|
if (!this.initialized) {
|
||||||
await this.init();
|
await this.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start the FastMCP server with increased timeout
|
// Start the FastMCP server with increased timeout
|
||||||
await this.server.start({
|
await this.server.start({
|
||||||
transportType: "stdio",
|
transportType: 'stdio',
|
||||||
timeout: 120000 // 2 minutes timeout (in milliseconds)
|
timeout: 120000 // 2 minutes timeout (in milliseconds)
|
||||||
});
|
});
|
||||||
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stop the MCP server
|
* Stop the MCP server
|
||||||
*/
|
*/
|
||||||
async stop() {
|
async stop() {
|
||||||
if (this.server) {
|
if (this.server) {
|
||||||
await this.server.stop();
|
await this.server.stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export the manager from here as well, if needed elsewhere
|
// Export the manager from here as well, if needed elsewhere
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
import chalk from "chalk";
|
import chalk from 'chalk';
|
||||||
import { isSilentMode } from "../../scripts/modules/utils.js";
|
import { isSilentMode } from '../../scripts/modules/utils.js';
|
||||||
|
|
||||||
// Define log levels
|
// Define log levels
|
||||||
const LOG_LEVELS = {
|
const LOG_LEVELS = {
|
||||||
debug: 0,
|
debug: 0,
|
||||||
info: 1,
|
info: 1,
|
||||||
warn: 2,
|
warn: 2,
|
||||||
error: 3,
|
error: 3,
|
||||||
success: 4,
|
success: 4
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get log level from environment or default to info
|
// Get log level from environment or default to info
|
||||||
const LOG_LEVEL = process.env.LOG_LEVEL
|
const LOG_LEVEL = process.env.LOG_LEVEL
|
||||||
? LOG_LEVELS[process.env.LOG_LEVEL.toLowerCase()] ?? LOG_LEVELS.info
|
? (LOG_LEVELS[process.env.LOG_LEVEL.toLowerCase()] ?? LOG_LEVELS.info)
|
||||||
: LOG_LEVELS.info;
|
: LOG_LEVELS.info;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logs a message with the specified level
|
* Logs a message with the specified level
|
||||||
@@ -21,56 +21,66 @@ const LOG_LEVEL = process.env.LOG_LEVEL
|
|||||||
* @param {...any} args - Arguments to log
|
* @param {...any} args - Arguments to log
|
||||||
*/
|
*/
|
||||||
function log(level, ...args) {
|
function log(level, ...args) {
|
||||||
// Skip logging if silent mode is enabled
|
// Skip logging if silent mode is enabled
|
||||||
if (isSilentMode()) {
|
if (isSilentMode()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use text prefixes instead of emojis
|
// Use text prefixes instead of emojis
|
||||||
const prefixes = {
|
const prefixes = {
|
||||||
debug: chalk.gray("[DEBUG]"),
|
debug: chalk.gray('[DEBUG]'),
|
||||||
info: chalk.blue("[INFO]"),
|
info: chalk.blue('[INFO]'),
|
||||||
warn: chalk.yellow("[WARN]"),
|
warn: chalk.yellow('[WARN]'),
|
||||||
error: chalk.red("[ERROR]"),
|
error: chalk.red('[ERROR]'),
|
||||||
success: chalk.green("[SUCCESS]"),
|
success: chalk.green('[SUCCESS]')
|
||||||
};
|
};
|
||||||
|
|
||||||
if (LOG_LEVELS[level] !== undefined && LOG_LEVELS[level] >= LOG_LEVEL) {
|
if (LOG_LEVELS[level] !== undefined && LOG_LEVELS[level] >= LOG_LEVEL) {
|
||||||
const prefix = prefixes[level] || "";
|
const prefix = prefixes[level] || '';
|
||||||
let coloredArgs = args;
|
let coloredArgs = args;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
switch(level) {
|
switch (level) {
|
||||||
case "error":
|
case 'error':
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.red(arg) : arg);
|
coloredArgs = args.map((arg) =>
|
||||||
break;
|
typeof arg === 'string' ? chalk.red(arg) : arg
|
||||||
case "warn":
|
);
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.yellow(arg) : arg);
|
break;
|
||||||
break;
|
case 'warn':
|
||||||
case "success":
|
coloredArgs = args.map((arg) =>
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.green(arg) : arg);
|
typeof arg === 'string' ? chalk.yellow(arg) : arg
|
||||||
break;
|
);
|
||||||
case "info":
|
break;
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.blue(arg) : arg);
|
case 'success':
|
||||||
break;
|
coloredArgs = args.map((arg) =>
|
||||||
case "debug":
|
typeof arg === 'string' ? chalk.green(arg) : arg
|
||||||
coloredArgs = args.map(arg => typeof arg === 'string' ? chalk.gray(arg) : arg);
|
);
|
||||||
break;
|
break;
|
||||||
// default: use original args (no color)
|
case 'info':
|
||||||
}
|
coloredArgs = args.map((arg) =>
|
||||||
} catch (colorError) {
|
typeof arg === 'string' ? chalk.blue(arg) : arg
|
||||||
// Fallback if chalk fails on an argument
|
);
|
||||||
// Use console.error here for internal logger errors, separate from normal logging
|
break;
|
||||||
console.error("Internal Logger Error applying chalk color:", colorError);
|
case 'debug':
|
||||||
coloredArgs = args;
|
coloredArgs = args.map((arg) =>
|
||||||
}
|
typeof arg === 'string' ? chalk.gray(arg) : arg
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
// default: use original args (no color)
|
||||||
|
}
|
||||||
|
} catch (colorError) {
|
||||||
|
// Fallback if chalk fails on an argument
|
||||||
|
// Use console.error here for internal logger errors, separate from normal logging
|
||||||
|
console.error('Internal Logger Error applying chalk color:', colorError);
|
||||||
|
coloredArgs = args;
|
||||||
|
}
|
||||||
|
|
||||||
// Revert to console.log - FastMCP's context logger (context.log)
|
// Revert to console.log - FastMCP's context logger (context.log)
|
||||||
// is responsible for directing logs correctly (e.g., to stderr)
|
// is responsible for directing logs correctly (e.g., to stderr)
|
||||||
// during tool execution without upsetting the client connection.
|
// during tool execution without upsetting the client connection.
|
||||||
// Logs outside of tool execution (like startup) will go to stdout.
|
// Logs outside of tool execution (like startup) will go to stdout.
|
||||||
console.log(prefix, ...coloredArgs);
|
console.log(prefix, ...coloredArgs);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -78,16 +88,19 @@ function log(level, ...args) {
|
|||||||
* @returns {Object} Logger object with info, error, debug, warn, and success methods
|
* @returns {Object} Logger object with info, error, debug, warn, and success methods
|
||||||
*/
|
*/
|
||||||
export function createLogger() {
|
export function createLogger() {
|
||||||
const createLogMethod = (level) => (...args) => log(level, ...args);
|
const createLogMethod =
|
||||||
|
(level) =>
|
||||||
|
(...args) =>
|
||||||
|
log(level, ...args);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
debug: createLogMethod("debug"),
|
debug: createLogMethod('debug'),
|
||||||
info: createLogMethod("info"),
|
info: createLogMethod('info'),
|
||||||
warn: createLogMethod("warn"),
|
warn: createLogMethod('warn'),
|
||||||
error: createLogMethod("error"),
|
error: createLogMethod('error'),
|
||||||
success: createLogMethod("success"),
|
success: createLogMethod('success'),
|
||||||
log: log, // Also expose the raw log function
|
log: log // Also expose the raw log function
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export a default logger instance
|
// Export a default logger instance
|
||||||
|
|||||||
@@ -3,63 +3,79 @@
|
|||||||
* Tool for adding a dependency to a task
|
* Tool for adding a dependency to a task
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { addDependencyDirect } from "../core/task-master-core.js";
|
import { addDependencyDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the addDependency tool with the MCP server
|
* Register the addDependency tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerAddDependencyTool(server) {
|
export function registerAddDependencyTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "add_dependency",
|
name: 'add_dependency',
|
||||||
description: "Add a dependency relationship between two tasks",
|
description: 'Add a dependency relationship between two tasks',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("ID of task that will depend on another task"),
|
id: z.string().describe('ID of task that will depend on another task'),
|
||||||
dependsOn: z.string().describe("ID of task that will become a dependency"),
|
dependsOn: z
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.string()
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.describe('ID of task that will become a dependency'),
|
||||||
}),
|
file: z
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.string()
|
||||||
try {
|
.optional()
|
||||||
log.info(`Adding dependency for task ${args.id} to depend on ${args.dependsOn}`);
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
reportProgress({ progress: 0 });
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(
|
||||||
|
`Adding dependency for task ${args.id} to depend on ${args.dependsOn}`
|
||||||
|
);
|
||||||
|
reportProgress({ progress: 0 });
|
||||||
|
|
||||||
// Get project root using the utility function
|
// Get project root using the utility function
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
// Fallback to args.projectRoot if session didn't provide one
|
// Fallback to args.projectRoot if session didn't provide one
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call the direct function with the resolved rootFolder
|
// Call the direct function with the resolved rootFolder
|
||||||
const result = await addDependencyDirect({
|
const result = await addDependencyDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
reportProgress({ progress: 100 });
|
reportProgress({ progress: 100 });
|
||||||
|
|
||||||
// Log result
|
// Log result
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully added dependency: ${result.data.message}`);
|
log.info(`Successfully added dependency: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to add dependency: ${result.error.message}`);
|
log.error(`Failed to add dependency: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use handleApiResult to format the response
|
// Use handleApiResult to format the response
|
||||||
return handleApiResult(result, log, 'Error adding dependency');
|
return handleApiResult(result, log, 'Error adding dependency');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in addDependency tool: ${error.message}`);
|
log.error(`Error in addDependency tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,61 +3,94 @@
|
|||||||
* Tool for adding subtasks to existing tasks
|
* Tool for adding subtasks to existing tasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { addSubtaskDirect } from "../core/task-master-core.js";
|
import { addSubtaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the addSubtask tool with the MCP server
|
* Register the addSubtask tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerAddSubtaskTool(server) {
|
export function registerAddSubtaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "add_subtask",
|
name: 'add_subtask',
|
||||||
description: "Add a subtask to an existing task",
|
description: 'Add a subtask to an existing task',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("Parent task ID (required)"),
|
id: z.string().describe('Parent task ID (required)'),
|
||||||
taskId: z.string().optional().describe("Existing task ID to convert to subtask"),
|
taskId: z
|
||||||
title: z.string().optional().describe("Title for the new subtask (when creating a new subtask)"),
|
.string()
|
||||||
description: z.string().optional().describe("Description for the new subtask"),
|
.optional()
|
||||||
details: z.string().optional().describe("Implementation details for the new subtask"),
|
.describe('Existing task ID to convert to subtask'),
|
||||||
status: z.string().optional().describe("Status for the new subtask (default: 'pending')"),
|
title: z
|
||||||
dependencies: z.string().optional().describe("Comma-separated list of dependency IDs for the new subtask"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.optional()
|
||||||
skipGenerate: z.boolean().optional().describe("Skip regenerating task files"),
|
.describe('Title for the new subtask (when creating a new subtask)'),
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
description: z
|
||||||
}),
|
.string()
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.optional()
|
||||||
try {
|
.describe('Description for the new subtask'),
|
||||||
log.info(`Adding subtask with args: ${JSON.stringify(args)}`);
|
details: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Implementation details for the new subtask'),
|
||||||
|
status: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe("Status for the new subtask (default: 'pending')"),
|
||||||
|
dependencies: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Comma-separated list of dependency IDs for the new subtask'),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
skipGenerate: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Skip regenerating task files'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Adding subtask with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await addSubtaskDirect({
|
const result = await addSubtaskDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Subtask added successfully: ${result.data.message}`);
|
log.info(`Subtask added successfully: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to add subtask: ${result.error.message}`);
|
log.error(`Failed to add subtask: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error adding subtask');
|
return handleApiResult(result, log, 'Error adding subtask');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in addSubtask tool: ${error.message}`);
|
log.error(`Error in addSubtask tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,56 +3,72 @@
|
|||||||
* Tool to add a new task using AI
|
* Tool to add a new task using AI
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
createContentResponse,
|
createContentResponse,
|
||||||
getProjectRootFromSession,
|
getProjectRootFromSession,
|
||||||
executeTaskMasterCommand,
|
executeTaskMasterCommand,
|
||||||
handleApiResult
|
handleApiResult
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { addTaskDirect } from "../core/task-master-core.js";
|
import { addTaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the addTask tool with the MCP server
|
* Register the addTask tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerAddTaskTool(server) {
|
export function registerAddTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "add_task",
|
name: 'add_task',
|
||||||
description: "Add a new task using AI",
|
description: 'Add a new task using AI',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
prompt: z.string().describe("Description of the task to add"),
|
prompt: z.string().describe('Description of the task to add'),
|
||||||
dependencies: z.string().optional().describe("Comma-separated list of task IDs this task depends on"),
|
dependencies: z
|
||||||
priority: z.string().optional().describe("Task priority (high, medium, low)"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.optional()
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project"),
|
.describe('Comma-separated list of task IDs this task depends on'),
|
||||||
research: z.boolean().optional().describe("Whether to use research capabilities for task creation")
|
priority: z
|
||||||
}),
|
.string()
|
||||||
execute: async (args, { log, reportProgress, session }) => {
|
.optional()
|
||||||
try {
|
.describe('Task priority (high, medium, low)'),
|
||||||
log.info(`Starting add-task with args: ${JSON.stringify(args)}`);
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Root directory of the project'),
|
||||||
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Whether to use research capabilities for task creation')
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, reportProgress, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Starting add-task with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Get project root from session
|
// Get project root from session
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call the direct function
|
// Call the direct function
|
||||||
const result = await addTaskDirect({
|
const result = await addTaskDirect(
|
||||||
...args,
|
{
|
||||||
projectRoot: rootFolder
|
...args,
|
||||||
}, log, { reportProgress, session });
|
projectRoot: rootFolder
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, session }
|
||||||
|
);
|
||||||
|
|
||||||
// Return the result
|
// Return the result
|
||||||
return handleApiResult(result, log);
|
return handleApiResult(result, log);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in add-task tool: ${error.message}`);
|
log.error(`Error in add-task tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,58 +3,95 @@
|
|||||||
* Tool for analyzing task complexity and generating recommendations
|
* Tool for analyzing task complexity and generating recommendations
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { analyzeTaskComplexityDirect } from "../core/task-master-core.js";
|
import { analyzeTaskComplexityDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the analyze tool with the MCP server
|
* Register the analyze tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerAnalyzeTool(server) {
|
export function registerAnalyzeTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "analyze_project_complexity",
|
name: 'analyze_project_complexity',
|
||||||
description: "Analyze task complexity and generate expansion recommendations",
|
description:
|
||||||
parameters: z.object({
|
'Analyze task complexity and generate expansion recommendations',
|
||||||
output: z.string().optional().describe("Output file path for the report (default: scripts/task-complexity-report.json)"),
|
parameters: z.object({
|
||||||
model: z.string().optional().describe("LLM model to use for analysis (defaults to configured model)"),
|
output: z
|
||||||
threshold: z.union([z.number(), z.string()]).optional().describe("Minimum complexity score to recommend expansion (1-10) (default: 5)"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.optional()
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed complexity analysis"),
|
.describe(
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
'Output file path for the report (default: scripts/task-complexity-report.json)'
|
||||||
}),
|
),
|
||||||
execute: async (args, { log, session }) => {
|
model: z
|
||||||
try {
|
.string()
|
||||||
log.info(`Analyzing task complexity with args: ${JSON.stringify(args)}`);
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'LLM model to use for analysis (defaults to configured model)'
|
||||||
|
),
|
||||||
|
threshold: z
|
||||||
|
.union([z.number(), z.string()])
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Minimum complexity score to recommend expansion (1-10) (default: 5)'
|
||||||
|
),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Use Perplexity AI for research-backed complexity analysis'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(
|
||||||
|
`Analyzing task complexity with args: ${JSON.stringify(args)}`
|
||||||
|
);
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await analyzeTaskComplexityDirect({
|
const result = await analyzeTaskComplexityDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { session });
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Task complexity analysis complete: ${result.data.message}`);
|
log.info(`Task complexity analysis complete: ${result.data.message}`);
|
||||||
log.info(`Report summary: ${JSON.stringify(result.data.reportSummary)}`);
|
log.info(
|
||||||
} else {
|
`Report summary: ${JSON.stringify(result.data.reportSummary)}`
|
||||||
log.error(`Failed to analyze task complexity: ${result.error.message}`);
|
);
|
||||||
}
|
} else {
|
||||||
|
log.error(
|
||||||
|
`Failed to analyze task complexity: ${result.error.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error analyzing task complexity');
|
return handleApiResult(result, log, 'Error analyzing task complexity');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in analyze tool: ${error.message}`);
|
log.error(`Error in analyze tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,61 +3,78 @@
|
|||||||
* Tool for clearing subtasks from parent tasks
|
* Tool for clearing subtasks from parent tasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { clearSubtasksDirect } from "../core/task-master-core.js";
|
import { clearSubtasksDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the clearSubtasks tool with the MCP server
|
* Register the clearSubtasks tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerClearSubtasksTool(server) {
|
export function registerClearSubtasksTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "clear_subtasks",
|
name: 'clear_subtasks',
|
||||||
description: "Clear subtasks from specified tasks",
|
description: 'Clear subtasks from specified tasks',
|
||||||
parameters: z.object({
|
parameters: z
|
||||||
id: z.string().optional().describe("Task IDs (comma-separated) to clear subtasks from"),
|
.object({
|
||||||
all: z.boolean().optional().describe("Clear subtasks from all tasks"),
|
id: z
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.string()
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.optional()
|
||||||
}).refine(data => data.id || data.all, {
|
.describe('Task IDs (comma-separated) to clear subtasks from'),
|
||||||
message: "Either 'id' or 'all' parameter must be provided",
|
all: z.boolean().optional().describe('Clear subtasks from all tasks'),
|
||||||
path: ["id", "all"]
|
file: z
|
||||||
}),
|
.string()
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.optional()
|
||||||
try {
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
log.info(`Clearing subtasks with args: ${JSON.stringify(args)}`);
|
projectRoot: z
|
||||||
await reportProgress({ progress: 0 });
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.refine((data) => data.id || data.all, {
|
||||||
|
message: "Either 'id' or 'all' parameter must be provided",
|
||||||
|
path: ['id', 'all']
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Clearing subtasks with args: ${JSON.stringify(args)}`);
|
||||||
|
await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await clearSubtasksDirect({
|
const result = await clearSubtasksDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
reportProgress({ progress: 100 });
|
reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Subtasks cleared successfully: ${result.data.message}`);
|
log.info(`Subtasks cleared successfully: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to clear subtasks: ${result.error.message}`);
|
log.error(`Failed to clear subtasks: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error clearing subtasks');
|
return handleApiResult(result, log, 'Error clearing subtasks');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in clearSubtasks tool: ${error.message}`);
|
log.error(`Error in clearSubtasks tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,56 +3,81 @@
|
|||||||
* Tool for displaying the complexity analysis report
|
* Tool for displaying the complexity analysis report
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { complexityReportDirect } from "../core/task-master-core.js";
|
import { complexityReportDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the complexityReport tool with the MCP server
|
* Register the complexityReport tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerComplexityReportTool(server) {
|
export function registerComplexityReportTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "complexity_report",
|
name: 'complexity_report',
|
||||||
description: "Display the complexity analysis report in a readable format",
|
description: 'Display the complexity analysis report in a readable format',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe("Path to the report file (default: scripts/task-complexity-report.json)"),
|
file: z
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.string()
|
||||||
}),
|
.optional()
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.describe(
|
||||||
try {
|
'Path to the report file (default: scripts/task-complexity-report.json)'
|
||||||
log.info(`Getting complexity report with args: ${JSON.stringify(args)}`);
|
),
|
||||||
// await reportProgress({ progress: 0 });
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(
|
||||||
|
`Getting complexity report with args: ${JSON.stringify(args)}`
|
||||||
|
);
|
||||||
|
// await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await complexityReportDirect({
|
const result = await complexityReportDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
...args
|
||||||
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully retrieved complexity report${result.fromCache ? ' (from cache)' : ''}`);
|
log.info(
|
||||||
} else {
|
`Successfully retrieved complexity report${result.fromCache ? ' (from cache)' : ''}`
|
||||||
log.error(`Failed to retrieve complexity report: ${result.error.message}`);
|
);
|
||||||
}
|
} else {
|
||||||
|
log.error(
|
||||||
|
`Failed to retrieve complexity report: ${result.error.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error retrieving complexity report');
|
return handleApiResult(
|
||||||
} catch (error) {
|
result,
|
||||||
log.error(`Error in complexity-report tool: ${error.message}`);
|
log,
|
||||||
return createErrorResponse(`Failed to retrieve complexity report: ${error.message}`);
|
'Error retrieving complexity report'
|
||||||
}
|
);
|
||||||
},
|
} catch (error) {
|
||||||
});
|
log.error(`Error in complexity-report tool: ${error.message}`);
|
||||||
|
return createErrorResponse(
|
||||||
|
`Failed to retrieve complexity report: ${error.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -3,57 +3,87 @@
|
|||||||
* Tool for expanding all pending tasks with subtasks
|
* Tool for expanding all pending tasks with subtasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { expandAllTasksDirect } from "../core/task-master-core.js";
|
import { expandAllTasksDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the expandAll tool with the MCP server
|
* Register the expandAll tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerExpandAllTool(server) {
|
export function registerExpandAllTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "expand_all",
|
name: 'expand_all',
|
||||||
description: "Expand all pending tasks into subtasks",
|
description: 'Expand all pending tasks into subtasks',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
num: z.string().optional().describe("Number of subtasks to generate for each task"),
|
num: z
|
||||||
research: z.boolean().optional().describe("Enable Perplexity AI for research-backed subtask generation"),
|
.string()
|
||||||
prompt: z.string().optional().describe("Additional context to guide subtask generation"),
|
.optional()
|
||||||
force: z.boolean().optional().describe("Force regeneration of subtasks for tasks that already have them"),
|
.describe('Number of subtasks to generate for each task'),
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
research: z
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.boolean()
|
||||||
}),
|
.optional()
|
||||||
execute: async (args, { log, session }) => {
|
.describe(
|
||||||
try {
|
'Enable Perplexity AI for research-backed subtask generation'
|
||||||
log.info(`Expanding all tasks with args: ${JSON.stringify(args)}`);
|
),
|
||||||
|
prompt: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Additional context to guide subtask generation'),
|
||||||
|
force: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Force regeneration of subtasks for tasks that already have them'
|
||||||
|
),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Expanding all tasks with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await expandAllTasksDirect({
|
const result = await expandAllTasksDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { session });
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully expanded all tasks: ${result.data.message}`);
|
log.info(`Successfully expanded all tasks: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to expand all tasks: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
}
|
`Failed to expand all tasks: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error expanding all tasks');
|
return handleApiResult(result, log, 'Error expanding all tasks');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in expand-all tool: ${error.message}`);
|
log.error(`Error in expand-all tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,75 +3,88 @@
|
|||||||
* Tool to expand a task into subtasks
|
* Tool to expand a task into subtasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { expandTaskDirect } from "../core/task-master-core.js";
|
import { expandTaskDirect } from '../core/task-master-core.js';
|
||||||
import fs from "fs";
|
import fs from 'fs';
|
||||||
import path from "path";
|
import path from 'path';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the expand-task tool with the MCP server
|
* Register the expand-task tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerExpandTaskTool(server) {
|
export function registerExpandTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "expand_task",
|
name: 'expand_task',
|
||||||
description: "Expand a task into subtasks for detailed implementation",
|
description: 'Expand a task into subtasks for detailed implementation',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("ID of task to expand"),
|
id: z.string().describe('ID of task to expand'),
|
||||||
num: z.union([z.string(), z.number()]).optional().describe("Number of subtasks to generate"),
|
num: z
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed generation"),
|
.union([z.string(), z.number()])
|
||||||
prompt: z.string().optional().describe("Additional context for subtask generation"),
|
.optional()
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.describe('Number of subtasks to generate'),
|
||||||
projectRoot: z
|
research: z
|
||||||
.string()
|
.boolean()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe('Use Perplexity AI for research-backed generation'),
|
||||||
"Root directory of the project (default: current working directory)"
|
prompt: z
|
||||||
),
|
.string()
|
||||||
}),
|
.optional()
|
||||||
execute: async (args, { log, reportProgress, session }) => {
|
.describe('Additional context for subtask generation'),
|
||||||
try {
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
log.info(`Starting expand-task with args: ${JSON.stringify(args)}`);
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, reportProgress, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Starting expand-task with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
// Get project root from session
|
// Get project root from session
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Project root resolved to: ${rootFolder}`);
|
log.info(`Project root resolved to: ${rootFolder}`);
|
||||||
|
|
||||||
// Check for tasks.json in the standard locations
|
// Check for tasks.json in the standard locations
|
||||||
const tasksJsonPath = path.join(rootFolder, 'tasks', 'tasks.json');
|
const tasksJsonPath = path.join(rootFolder, 'tasks', 'tasks.json');
|
||||||
|
|
||||||
if (fs.existsSync(tasksJsonPath)) {
|
if (fs.existsSync(tasksJsonPath)) {
|
||||||
log.info(`Found tasks.json at ${tasksJsonPath}`);
|
log.info(`Found tasks.json at ${tasksJsonPath}`);
|
||||||
// Add the file parameter directly to args
|
// Add the file parameter directly to args
|
||||||
args.file = tasksJsonPath;
|
args.file = tasksJsonPath;
|
||||||
} else {
|
} else {
|
||||||
log.warn(`Could not find tasks.json at ${tasksJsonPath}`);
|
log.warn(`Could not find tasks.json at ${tasksJsonPath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call direct function with only session in the context, not reportProgress
|
// Call direct function with only session in the context, not reportProgress
|
||||||
// Use the pattern recommended in the MCP guidelines
|
// Use the pattern recommended in the MCP guidelines
|
||||||
const result = await expandTaskDirect({
|
const result = await expandTaskDirect(
|
||||||
...args,
|
{
|
||||||
projectRoot: rootFolder
|
...args,
|
||||||
}, log, { session }); // Only pass session, NOT reportProgress
|
projectRoot: rootFolder
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
); // Only pass session, NOT reportProgress
|
||||||
|
|
||||||
// Return the result
|
// Return the result
|
||||||
return handleApiResult(result, log, 'Error expanding task');
|
return handleApiResult(result, log, 'Error expanding task');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in expand task tool: ${error.message}`);
|
log.error(`Error in expand task tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,56 +3,65 @@
|
|||||||
* Tool for automatically fixing invalid task dependencies
|
* Tool for automatically fixing invalid task dependencies
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { fixDependenciesDirect } from "../core/task-master-core.js";
|
import { fixDependenciesDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the fixDependencies tool with the MCP server
|
* Register the fixDependencies tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerFixDependenciesTool(server) {
|
export function registerFixDependenciesTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "fix_dependencies",
|
name: 'fix_dependencies',
|
||||||
description: "Fix invalid dependencies in tasks automatically",
|
description: 'Fix invalid dependencies in tasks automatically',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
projectRoot: z
|
||||||
}),
|
.string()
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.optional()
|
||||||
try {
|
.describe(
|
||||||
log.info(`Fixing dependencies with args: ${JSON.stringify(args)}`);
|
'Root directory of the project (default: current working directory)'
|
||||||
await reportProgress({ progress: 0 });
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Fixing dependencies with args: ${JSON.stringify(args)}`);
|
||||||
|
await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await fixDependenciesDirect({
|
const result = await fixDependenciesDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
await reportProgress({ progress: 100 });
|
await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully fixed dependencies: ${result.data.message}`);
|
log.info(`Successfully fixed dependencies: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to fix dependencies: ${result.error.message}`);
|
log.error(`Failed to fix dependencies: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error fixing dependencies');
|
return handleApiResult(result, log, 'Error fixing dependencies');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in fixDependencies tool: ${error.message}`);
|
log.error(`Error in fixDependencies tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,62 +3,71 @@
|
|||||||
* Tool to generate individual task files from tasks.json
|
* Tool to generate individual task files from tasks.json
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { generateTaskFilesDirect } from "../core/task-master-core.js";
|
import { generateTaskFilesDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the generate tool with the MCP server
|
* Register the generate tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerGenerateTool(server) {
|
export function registerGenerateTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "generate",
|
name: 'generate',
|
||||||
description: "Generates individual task files in tasks/ directory based on tasks.json",
|
description:
|
||||||
parameters: z.object({
|
'Generates individual task files in tasks/ directory based on tasks.json',
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
parameters: z.object({
|
||||||
output: z.string().optional().describe("Output directory (default: same directory as tasks file)"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
output: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe('Output directory (default: same directory as tasks file)'),
|
||||||
"Root directory of the project (default: current working directory)"
|
projectRoot: z
|
||||||
),
|
.string()
|
||||||
}),
|
.optional()
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.describe(
|
||||||
try {
|
'Root directory of the project (default: current working directory)'
|
||||||
log.info(`Generating task files with args: ${JSON.stringify(args)}`);
|
)
|
||||||
// await reportProgress({ progress: 0 });
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Generating task files with args: ${JSON.stringify(args)}`);
|
||||||
|
// await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await generateTaskFilesDirect({
|
const result = await generateTaskFilesDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
...args
|
||||||
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully generated task files: ${result.data.message}`);
|
log.info(`Successfully generated task files: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to generate task files: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
}
|
`Failed to generate task files: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error generating task files');
|
return handleApiResult(result, log, 'Error generating task files');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in generate tool: ${error.message}`);
|
log.error(`Error in generate tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -8,35 +8,40 @@ import { createErrorResponse, createContentResponse } from './utils.js'; // Assu
|
|||||||
* @param {AsyncOperationManager} asyncManager - The async operation manager.
|
* @param {AsyncOperationManager} asyncManager - The async operation manager.
|
||||||
*/
|
*/
|
||||||
export function registerGetOperationStatusTool(server, asyncManager) {
|
export function registerGetOperationStatusTool(server, asyncManager) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: 'get_operation_status',
|
name: 'get_operation_status',
|
||||||
description: 'Retrieves the status and result/error of a background operation.',
|
description:
|
||||||
parameters: z.object({
|
'Retrieves the status and result/error of a background operation.',
|
||||||
operationId: z.string().describe('The ID of the operation to check.'),
|
parameters: z.object({
|
||||||
}),
|
operationId: z.string().describe('The ID of the operation to check.')
|
||||||
execute: async (args, { log }) => {
|
}),
|
||||||
try {
|
execute: async (args, { log }) => {
|
||||||
const { operationId } = args;
|
try {
|
||||||
log.info(`Checking status for operation ID: ${operationId}`);
|
const { operationId } = args;
|
||||||
|
log.info(`Checking status for operation ID: ${operationId}`);
|
||||||
|
|
||||||
const status = asyncManager.getStatus(operationId);
|
const status = asyncManager.getStatus(operationId);
|
||||||
|
|
||||||
// Status will now always return an object, but it might have status='not_found'
|
// Status will now always return an object, but it might have status='not_found'
|
||||||
if (status.status === 'not_found') {
|
if (status.status === 'not_found') {
|
||||||
log.warn(`Operation ID not found: ${operationId}`);
|
log.warn(`Operation ID not found: ${operationId}`);
|
||||||
return createErrorResponse(
|
return createErrorResponse(
|
||||||
status.error?.message || `Operation ID not found: ${operationId}`,
|
status.error?.message || `Operation ID not found: ${operationId}`,
|
||||||
status.error?.code || 'OPERATION_NOT_FOUND'
|
status.error?.code || 'OPERATION_NOT_FOUND'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Status for ${operationId}: ${status.status}`);
|
log.info(`Status for ${operationId}: ${status.status}`);
|
||||||
return createContentResponse(status);
|
return createContentResponse(status);
|
||||||
|
} catch (error) {
|
||||||
} catch (error) {
|
log.error(`Error in get_operation_status tool: ${error.message}`, {
|
||||||
log.error(`Error in get_operation_status tool: ${error.message}`, { stack: error.stack });
|
stack: error.stack
|
||||||
return createErrorResponse(`Failed to get operation status: ${error.message}`, 'GET_STATUS_ERROR');
|
});
|
||||||
}
|
return createErrorResponse(
|
||||||
},
|
`Failed to get operation status: ${error.message}`,
|
||||||
});
|
'GET_STATUS_ERROR'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,13 @@
|
|||||||
* Tool to get task details by ID
|
* Tool to get task details by ID
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { showTaskDirect } from "../core/task-master-core.js";
|
import { showTaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Custom processor function that removes allTasks from the response
|
* Custom processor function that removes allTasks from the response
|
||||||
@@ -17,16 +17,16 @@ import { showTaskDirect } from "../core/task-master-core.js";
|
|||||||
* @returns {Object} - The processed data with allTasks removed
|
* @returns {Object} - The processed data with allTasks removed
|
||||||
*/
|
*/
|
||||||
function processTaskResponse(data) {
|
function processTaskResponse(data) {
|
||||||
if (!data) return data;
|
if (!data) return data;
|
||||||
|
|
||||||
// If we have the expected structure with task and allTasks
|
// If we have the expected structure with task and allTasks
|
||||||
if (data.task) {
|
if (data.task) {
|
||||||
// Return only the task object, removing the allTasks array
|
// Return only the task object, removing the allTasks array
|
||||||
return data.task;
|
return data.task;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If structure is unexpected, return as is
|
// If structure is unexpected, return as is
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -34,59 +34,75 @@ function processTaskResponse(data) {
|
|||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerShowTaskTool(server) {
|
export function registerShowTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "get_task",
|
name: 'get_task',
|
||||||
description: "Get detailed information about a specific task",
|
description: 'Get detailed information about a specific task',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("Task ID to get"),
|
id: z.string().describe('Task ID to get'),
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
"Root directory of the project (default: current working directory)"
|
'Root directory of the project (default: current working directory)'
|
||||||
),
|
)
|
||||||
}),
|
}),
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
// Log the session right at the start of execute
|
// Log the session right at the start of execute
|
||||||
log.info(`Session object received in execute: ${JSON.stringify(session)}`); // Use JSON.stringify for better visibility
|
log.info(
|
||||||
|
`Session object received in execute: ${JSON.stringify(session)}`
|
||||||
|
); // Use JSON.stringify for better visibility
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.info(`Getting task details for ID: ${args.id}`);
|
log.info(`Getting task details for ID: ${args.id}`);
|
||||||
|
|
||||||
log.info(`Session object received in execute: ${JSON.stringify(session)}`); // Use JSON.stringify for better visibility
|
log.info(
|
||||||
|
`Session object received in execute: ${JSON.stringify(session)}`
|
||||||
|
); // Use JSON.stringify for better visibility
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
} else if (!rootFolder) {
|
} else if (!rootFolder) {
|
||||||
// Ensure we always have *some* root, even if session failed and args didn't provide one
|
// Ensure we always have *some* root, even if session failed and args didn't provide one
|
||||||
rootFolder = process.cwd();
|
rootFolder = process.cwd();
|
||||||
log.warn(`Session and args failed to provide root, using CWD: ${rootFolder}`);
|
log.warn(
|
||||||
}
|
`Session and args failed to provide root, using CWD: ${rootFolder}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
log.info(`Attempting to use project root: ${rootFolder}`); // Log the final resolved root
|
log.info(`Attempting to use project root: ${rootFolder}`); // Log the final resolved root
|
||||||
|
|
||||||
log.info(`Root folder: ${rootFolder}`); // Log the final resolved root
|
log.info(`Root folder: ${rootFolder}`); // Log the final resolved root
|
||||||
const result = await showTaskDirect({
|
const result = await showTaskDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log);
|
...args
|
||||||
|
},
|
||||||
|
log
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully retrieved task details for ID: ${args.id}${result.fromCache ? ' (from cache)' : ''}`);
|
log.info(
|
||||||
} else {
|
`Successfully retrieved task details for ID: ${args.id}${result.fromCache ? ' (from cache)' : ''}`
|
||||||
log.error(`Failed to get task: ${result.error.message}`);
|
);
|
||||||
}
|
} else {
|
||||||
|
log.error(`Failed to get task: ${result.error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
// Use our custom processor function to remove allTasks from the response
|
// Use our custom processor function to remove allTasks from the response
|
||||||
return handleApiResult(result, log, 'Error retrieving task details', processTaskResponse);
|
return handleApiResult(
|
||||||
} catch (error) {
|
result,
|
||||||
log.error(`Error in get-task tool: ${error.message}\n${error.stack}`); // Add stack trace
|
log,
|
||||||
return createErrorResponse(`Failed to get task: ${error.message}`);
|
'Error retrieving task details',
|
||||||
}
|
processTaskResponse
|
||||||
},
|
);
|
||||||
});
|
} catch (error) {
|
||||||
|
log.error(`Error in get-task tool: ${error.message}\n${error.stack}`); // Add stack trace
|
||||||
|
return createErrorResponse(`Failed to get task: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -3,63 +3,79 @@
|
|||||||
* Tool to get all tasks from Task Master
|
* Tool to get all tasks from Task Master
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { listTasksDirect } from "../core/task-master-core.js";
|
import { listTasksDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the getTasks tool with the MCP server
|
* Register the getTasks tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerListTasksTool(server) {
|
export function registerListTasksTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "get_tasks",
|
name: 'get_tasks',
|
||||||
description: "Get all tasks from Task Master, optionally filtering by status and including subtasks.",
|
description:
|
||||||
parameters: z.object({
|
'Get all tasks from Task Master, optionally filtering by status and including subtasks.',
|
||||||
status: z.string().optional().describe("Filter tasks by status (e.g., 'pending', 'done')"),
|
parameters: z.object({
|
||||||
withSubtasks: z
|
status: z
|
||||||
.boolean()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe("Include subtasks nested within their parent tasks in the response"),
|
.describe("Filter tasks by status (e.g., 'pending', 'done')"),
|
||||||
file: z.string().optional().describe("Path to the tasks file (relative to project root or absolute)"),
|
withSubtasks: z
|
||||||
projectRoot: z
|
.boolean()
|
||||||
.string()
|
.optional()
|
||||||
.optional()
|
.describe(
|
||||||
.describe(
|
'Include subtasks nested within their parent tasks in the response'
|
||||||
"Root directory of the project (default: automatically detected from session or CWD)"
|
),
|
||||||
),
|
file: z
|
||||||
}),
|
.string()
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.optional()
|
||||||
try {
|
.describe(
|
||||||
log.info(`Getting tasks with filters: ${JSON.stringify(args)}`);
|
'Path to the tasks file (relative to project root or absolute)'
|
||||||
// await reportProgress({ progress: 0 });
|
),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: automatically detected from session or CWD)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Getting tasks with filters: ${JSON.stringify(args)}`);
|
||||||
|
// await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await listTasksDirect({
|
const result = await listTasksDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
...args
|
||||||
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
log.info(`Retrieved ${result.success ? (result.data?.tasks?.length || 0) : 0} tasks${result.fromCache ? ' (from cache)' : ''}`);
|
log.info(
|
||||||
return handleApiResult(result, log, 'Error getting tasks');
|
`Retrieved ${result.success ? result.data?.tasks?.length || 0 : 0} tasks${result.fromCache ? ' (from cache)' : ''}`
|
||||||
} catch (error) {
|
);
|
||||||
log.error(`Error getting tasks: ${error.message}`);
|
return handleApiResult(result, log, 'Error getting tasks');
|
||||||
return createErrorResponse(error.message);
|
} catch (error) {
|
||||||
}
|
log.error(`Error getting tasks: ${error.message}`);
|
||||||
},
|
return createErrorResponse(error.message);
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// We no longer need the formatTasksResponse function as we're returning raw JSON data
|
// We no longer need the formatTasksResponse function as we're returning raw JSON data
|
||||||
|
|||||||
@@ -3,28 +3,28 @@
|
|||||||
* Export all Task Master CLI tools for MCP server
|
* Export all Task Master CLI tools for MCP server
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { registerListTasksTool } from "./get-tasks.js";
|
import { registerListTasksTool } from './get-tasks.js';
|
||||||
import logger from "../logger.js";
|
import logger from '../logger.js';
|
||||||
import { registerSetTaskStatusTool } from "./set-task-status.js";
|
import { registerSetTaskStatusTool } from './set-task-status.js';
|
||||||
import { registerParsePRDTool } from "./parse-prd.js";
|
import { registerParsePRDTool } from './parse-prd.js';
|
||||||
import { registerUpdateTool } from "./update.js";
|
import { registerUpdateTool } from './update.js';
|
||||||
import { registerUpdateTaskTool } from "./update-task.js";
|
import { registerUpdateTaskTool } from './update-task.js';
|
||||||
import { registerUpdateSubtaskTool } from "./update-subtask.js";
|
import { registerUpdateSubtaskTool } from './update-subtask.js';
|
||||||
import { registerGenerateTool } from "./generate.js";
|
import { registerGenerateTool } from './generate.js';
|
||||||
import { registerShowTaskTool } from "./get-task.js";
|
import { registerShowTaskTool } from './get-task.js';
|
||||||
import { registerNextTaskTool } from "./next-task.js";
|
import { registerNextTaskTool } from './next-task.js';
|
||||||
import { registerExpandTaskTool } from "./expand-task.js";
|
import { registerExpandTaskTool } from './expand-task.js';
|
||||||
import { registerAddTaskTool } from "./add-task.js";
|
import { registerAddTaskTool } from './add-task.js';
|
||||||
import { registerAddSubtaskTool } from "./add-subtask.js";
|
import { registerAddSubtaskTool } from './add-subtask.js';
|
||||||
import { registerRemoveSubtaskTool } from "./remove-subtask.js";
|
import { registerRemoveSubtaskTool } from './remove-subtask.js';
|
||||||
import { registerAnalyzeTool } from "./analyze.js";
|
import { registerAnalyzeTool } from './analyze.js';
|
||||||
import { registerClearSubtasksTool } from "./clear-subtasks.js";
|
import { registerClearSubtasksTool } from './clear-subtasks.js';
|
||||||
import { registerExpandAllTool } from "./expand-all.js";
|
import { registerExpandAllTool } from './expand-all.js';
|
||||||
import { registerRemoveDependencyTool } from "./remove-dependency.js";
|
import { registerRemoveDependencyTool } from './remove-dependency.js';
|
||||||
import { registerValidateDependenciesTool } from "./validate-dependencies.js";
|
import { registerValidateDependenciesTool } from './validate-dependencies.js';
|
||||||
import { registerFixDependenciesTool } from "./fix-dependencies.js";
|
import { registerFixDependenciesTool } from './fix-dependencies.js';
|
||||||
import { registerComplexityReportTool } from "./complexity-report.js";
|
import { registerComplexityReportTool } from './complexity-report.js';
|
||||||
import { registerAddDependencyTool } from "./add-dependency.js";
|
import { registerAddDependencyTool } from './add-dependency.js';
|
||||||
import { registerRemoveTaskTool } from './remove-task.js';
|
import { registerRemoveTaskTool } from './remove-task.js';
|
||||||
import { registerInitializeProjectTool } from './initialize-project.js';
|
import { registerInitializeProjectTool } from './initialize-project.js';
|
||||||
import { asyncOperationManager } from '../core/utils/async-manager.js';
|
import { asyncOperationManager } from '../core/utils/async-manager.js';
|
||||||
@@ -35,39 +35,39 @@ import { asyncOperationManager } from '../core/utils/async-manager.js';
|
|||||||
* @param {asyncOperationManager} asyncManager - The async operation manager instance
|
* @param {asyncOperationManager} asyncManager - The async operation manager instance
|
||||||
*/
|
*/
|
||||||
export function registerTaskMasterTools(server, asyncManager) {
|
export function registerTaskMasterTools(server, asyncManager) {
|
||||||
try {
|
try {
|
||||||
// Register each tool
|
// Register each tool
|
||||||
registerListTasksTool(server);
|
registerListTasksTool(server);
|
||||||
registerSetTaskStatusTool(server);
|
registerSetTaskStatusTool(server);
|
||||||
registerParsePRDTool(server);
|
registerParsePRDTool(server);
|
||||||
registerUpdateTool(server);
|
registerUpdateTool(server);
|
||||||
registerUpdateTaskTool(server);
|
registerUpdateTaskTool(server);
|
||||||
registerUpdateSubtaskTool(server);
|
registerUpdateSubtaskTool(server);
|
||||||
registerGenerateTool(server);
|
registerGenerateTool(server);
|
||||||
registerShowTaskTool(server);
|
registerShowTaskTool(server);
|
||||||
registerNextTaskTool(server);
|
registerNextTaskTool(server);
|
||||||
registerExpandTaskTool(server);
|
registerExpandTaskTool(server);
|
||||||
registerAddTaskTool(server, asyncManager);
|
registerAddTaskTool(server, asyncManager);
|
||||||
registerAddSubtaskTool(server);
|
registerAddSubtaskTool(server);
|
||||||
registerRemoveSubtaskTool(server);
|
registerRemoveSubtaskTool(server);
|
||||||
registerAnalyzeTool(server);
|
registerAnalyzeTool(server);
|
||||||
registerClearSubtasksTool(server);
|
registerClearSubtasksTool(server);
|
||||||
registerExpandAllTool(server);
|
registerExpandAllTool(server);
|
||||||
registerRemoveDependencyTool(server);
|
registerRemoveDependencyTool(server);
|
||||||
registerValidateDependenciesTool(server);
|
registerValidateDependenciesTool(server);
|
||||||
registerFixDependenciesTool(server);
|
registerFixDependenciesTool(server);
|
||||||
registerComplexityReportTool(server);
|
registerComplexityReportTool(server);
|
||||||
registerAddDependencyTool(server);
|
registerAddDependencyTool(server);
|
||||||
registerRemoveTaskTool(server);
|
registerRemoveTaskTool(server);
|
||||||
registerInitializeProjectTool(server);
|
registerInitializeProjectTool(server);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`Error registering Task Master tools: ${error.message}`);
|
logger.error(`Error registering Task Master tools: ${error.message}`);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info('Registered Task Master MCP tools');
|
logger.info('Registered Task Master MCP tools');
|
||||||
}
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
registerTaskMasterTools,
|
registerTaskMasterTools
|
||||||
};
|
};
|
||||||
@@ -1,62 +1,99 @@
|
|||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
import { createContentResponse, createErrorResponse } from "./utils.js"; // Only need response creators
|
import { createContentResponse, createErrorResponse } from './utils.js'; // Only need response creators
|
||||||
|
|
||||||
export function registerInitializeProjectTool(server) {
|
export function registerInitializeProjectTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "initialize_project", // snake_case for tool name
|
name: 'initialize_project', // snake_case for tool name
|
||||||
description: "Initializes a new Task Master project structure in the current working directory by running 'task-master init'.",
|
description:
|
||||||
parameters: z.object({
|
"Initializes a new Task Master project structure in the current working directory by running 'task-master init'.",
|
||||||
projectName: z.string().optional().describe("The name for the new project."),
|
parameters: z.object({
|
||||||
projectDescription: z.string().optional().describe("A brief description for the project."),
|
projectName: z
|
||||||
projectVersion: z.string().optional().describe("The initial version for the project (e.g., '0.1.0')."),
|
.string()
|
||||||
authorName: z.string().optional().describe("The author's name."),
|
.optional()
|
||||||
skipInstall: z.boolean().optional().default(false).describe("Skip installing dependencies automatically."),
|
.describe('The name for the new project.'),
|
||||||
addAliases: z.boolean().optional().default(false).describe("Add shell aliases (tm, taskmaster) to shell config file."),
|
projectDescription: z
|
||||||
yes: z.boolean().optional().default(false).describe("Skip prompts and use default values or provided arguments."),
|
.string()
|
||||||
// projectRoot is not needed here as 'init' works on the current directory
|
.optional()
|
||||||
}),
|
.describe('A brief description for the project.'),
|
||||||
execute: async (args, { log }) => { // Destructure context to get log
|
projectVersion: z
|
||||||
try {
|
.string()
|
||||||
log.info(`Executing initialize_project with args: ${JSON.stringify(args)}`);
|
.optional()
|
||||||
|
.describe("The initial version for the project (e.g., '0.1.0')."),
|
||||||
|
authorName: z.string().optional().describe("The author's name."),
|
||||||
|
skipInstall: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe('Skip installing dependencies automatically.'),
|
||||||
|
addAliases: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe('Add shell aliases (tm, taskmaster) to shell config file.'),
|
||||||
|
yes: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe('Skip prompts and use default values or provided arguments.')
|
||||||
|
// projectRoot is not needed here as 'init' works on the current directory
|
||||||
|
}),
|
||||||
|
execute: async (args, { log }) => {
|
||||||
|
// Destructure context to get log
|
||||||
|
try {
|
||||||
|
log.info(
|
||||||
|
`Executing initialize_project with args: ${JSON.stringify(args)}`
|
||||||
|
);
|
||||||
|
|
||||||
// Construct the command arguments carefully
|
// Construct the command arguments carefully
|
||||||
// Using npx ensures it uses the locally installed version if available, or fetches it
|
// Using npx ensures it uses the locally installed version if available, or fetches it
|
||||||
let command = 'npx task-master init';
|
let command = 'npx task-master init';
|
||||||
const cliArgs = [];
|
const cliArgs = [];
|
||||||
if (args.projectName) cliArgs.push(`--name "${args.projectName.replace(/"/g, '\\"')}"`); // Escape quotes
|
if (args.projectName)
|
||||||
if (args.projectDescription) cliArgs.push(`--description "${args.projectDescription.replace(/"/g, '\\"')}"`);
|
cliArgs.push(`--name "${args.projectName.replace(/"/g, '\\"')}"`); // Escape quotes
|
||||||
if (args.projectVersion) cliArgs.push(`--version "${args.projectVersion.replace(/"/g, '\\"')}"`);
|
if (args.projectDescription)
|
||||||
if (args.authorName) cliArgs.push(`--author "${args.authorName.replace(/"/g, '\\"')}"`);
|
cliArgs.push(
|
||||||
if (args.skipInstall) cliArgs.push('--skip-install');
|
`--description "${args.projectDescription.replace(/"/g, '\\"')}"`
|
||||||
if (args.addAliases) cliArgs.push('--aliases');
|
);
|
||||||
if (args.yes) cliArgs.push('--yes');
|
if (args.projectVersion)
|
||||||
|
cliArgs.push(
|
||||||
|
`--version "${args.projectVersion.replace(/"/g, '\\"')}"`
|
||||||
|
);
|
||||||
|
if (args.authorName)
|
||||||
|
cliArgs.push(`--author "${args.authorName.replace(/"/g, '\\"')}"`);
|
||||||
|
if (args.skipInstall) cliArgs.push('--skip-install');
|
||||||
|
if (args.addAliases) cliArgs.push('--aliases');
|
||||||
|
if (args.yes) cliArgs.push('--yes');
|
||||||
|
|
||||||
command += ' ' + cliArgs.join(' ');
|
command += ' ' + cliArgs.join(' ');
|
||||||
|
|
||||||
log.info(`Constructed command: ${command}`);
|
log.info(`Constructed command: ${command}`);
|
||||||
|
|
||||||
// Execute the command in the current working directory of the server process
|
// Execute the command in the current working directory of the server process
|
||||||
// Capture stdout/stderr. Use a reasonable timeout (e.g., 5 minutes)
|
// Capture stdout/stderr. Use a reasonable timeout (e.g., 5 minutes)
|
||||||
const output = execSync(command, { encoding: 'utf8', stdio: 'pipe', timeout: 300000 });
|
const output = execSync(command, {
|
||||||
|
encoding: 'utf8',
|
||||||
|
stdio: 'pipe',
|
||||||
|
timeout: 300000
|
||||||
|
});
|
||||||
|
|
||||||
log.info(`Initialization output:\n${output}`);
|
log.info(`Initialization output:\n${output}`);
|
||||||
|
|
||||||
// Return a standard success response manually
|
// Return a standard success response manually
|
||||||
return createContentResponse(
|
return createContentResponse(
|
||||||
"Project initialized successfully.",
|
'Project initialized successfully.',
|
||||||
{ output: output } // Include output in the data payload
|
{ output: output } // Include output in the data payload
|
||||||
);
|
);
|
||||||
|
} catch (error) {
|
||||||
|
// Catch errors from execSync or timeouts
|
||||||
|
const errorMessage = `Project initialization failed: ${error.message}`;
|
||||||
|
const errorDetails =
|
||||||
|
error.stderr?.toString() || error.stdout?.toString() || error.message; // Provide stderr/stdout if available
|
||||||
|
log.error(`${errorMessage}\nDetails: ${errorDetails}`);
|
||||||
|
|
||||||
} catch (error) {
|
// Return a standard error response manually
|
||||||
// Catch errors from execSync or timeouts
|
return createErrorResponse(errorMessage, { details: errorDetails });
|
||||||
const errorMessage = `Project initialization failed: ${error.message}`;
|
}
|
||||||
const errorDetails = error.stderr?.toString() || error.stdout?.toString() || error.message; // Provide stderr/stdout if available
|
}
|
||||||
log.error(`${errorMessage}\nDetails: ${errorDetails}`);
|
});
|
||||||
|
|
||||||
// Return a standard error response manually
|
|
||||||
return createErrorResponse(errorMessage, { details: errorDetails });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
@@ -3,61 +3,69 @@
|
|||||||
* Tool to find the next task to work on
|
* Tool to find the next task to work on
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { nextTaskDirect } from "../core/task-master-core.js";
|
import { nextTaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the next-task tool with the MCP server
|
* Register the next-task tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerNextTaskTool(server) {
|
export function registerNextTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "next_task",
|
name: 'next_task',
|
||||||
description: "Find the next task to work on based on dependencies and status",
|
description:
|
||||||
parameters: z.object({
|
'Find the next task to work on based on dependencies and status',
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
parameters: z.object({
|
||||||
projectRoot: z
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
.string()
|
projectRoot: z
|
||||||
.optional()
|
.string()
|
||||||
.describe(
|
.optional()
|
||||||
"Root directory of the project (default: current working directory)"
|
.describe(
|
||||||
),
|
'Root directory of the project (default: current working directory)'
|
||||||
}),
|
)
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
}),
|
||||||
try {
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
log.info(`Finding next task with args: ${JSON.stringify(args)}`);
|
try {
|
||||||
// await reportProgress({ progress: 0 });
|
log.info(`Finding next task with args: ${JSON.stringify(args)}`);
|
||||||
|
// await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await nextTaskDirect({
|
const result = await nextTaskDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
...args
|
||||||
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully found next task: ${result.data?.task?.id || 'No available tasks'}`);
|
log.info(
|
||||||
} else {
|
`Successfully found next task: ${result.data?.task?.id || 'No available tasks'}`
|
||||||
log.error(`Failed to find next task: ${result.error?.message || 'Unknown error'}`);
|
);
|
||||||
}
|
} else {
|
||||||
|
log.error(
|
||||||
|
`Failed to find next task: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error finding next task');
|
return handleApiResult(result, log, 'Error finding next task');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in nextTask tool: ${error.message}`);
|
log.error(`Error in nextTask tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,61 +3,86 @@
|
|||||||
* Tool to parse PRD document and generate tasks
|
* Tool to parse PRD document and generate tasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { parsePRDDirect } from "../core/task-master-core.js";
|
import { parsePRDDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the parsePRD tool with the MCP server
|
* Register the parsePRD tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerParsePRDTool(server) {
|
export function registerParsePRDTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "parse_prd",
|
name: 'parse_prd',
|
||||||
description: "Parse a Product Requirements Document (PRD) or text file to automatically generate initial tasks.",
|
description:
|
||||||
parameters: z.object({
|
'Parse a Product Requirements Document (PRD) or text file to automatically generate initial tasks.',
|
||||||
input: z.string().default("tasks/tasks.json").describe("Path to the PRD document file (relative to project root or absolute)"),
|
parameters: z.object({
|
||||||
numTasks: z.string().optional().describe("Approximate number of top-level tasks to generate (default: 10)"),
|
input: z
|
||||||
output: z.string().optional().describe("Output path for tasks.json file (relative to project root or absolute, default: tasks/tasks.json)"),
|
.string()
|
||||||
force: z.boolean().optional().describe("Allow overwriting an existing tasks.json file."),
|
.default('tasks/tasks.json')
|
||||||
projectRoot: z
|
.describe(
|
||||||
.string()
|
'Path to the PRD document file (relative to project root or absolute)'
|
||||||
.optional()
|
),
|
||||||
.describe(
|
numTasks: z
|
||||||
"Root directory of the project (default: automatically detected from session or CWD)"
|
.string()
|
||||||
),
|
.optional()
|
||||||
}),
|
.describe(
|
||||||
execute: async (args, { log, session }) => {
|
'Approximate number of top-level tasks to generate (default: 10)'
|
||||||
try {
|
),
|
||||||
log.info(`Parsing PRD with args: ${JSON.stringify(args)}`);
|
output: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Output path for tasks.json file (relative to project root or absolute, default: tasks/tasks.json)'
|
||||||
|
),
|
||||||
|
force: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Allow overwriting an existing tasks.json file.'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: automatically detected from session or CWD)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Parsing PRD with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await parsePRDDirect({
|
const result = await parsePRDDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { session });
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully parsed PRD: ${result.data.message}`);
|
log.info(`Successfully parsed PRD: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to parse PRD: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
}
|
`Failed to parse PRD: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error parsing PRD');
|
return handleApiResult(result, log, 'Error parsing PRD');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in parse-prd tool: ${error.message}`);
|
log.error(`Error in parse-prd tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,58 +3,71 @@
|
|||||||
* Tool for removing a dependency from a task
|
* Tool for removing a dependency from a task
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { removeDependencyDirect } from "../core/task-master-core.js";
|
import { removeDependencyDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the removeDependency tool with the MCP server
|
* Register the removeDependency tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerRemoveDependencyTool(server) {
|
export function registerRemoveDependencyTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "remove_dependency",
|
name: 'remove_dependency',
|
||||||
description: "Remove a dependency from a task",
|
description: 'Remove a dependency from a task',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("Task ID to remove dependency from"),
|
id: z.string().describe('Task ID to remove dependency from'),
|
||||||
dependsOn: z.string().describe("Task ID to remove as a dependency"),
|
dependsOn: z.string().describe('Task ID to remove as a dependency'),
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
file: z
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
.string()
|
||||||
}),
|
.optional()
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
try {
|
projectRoot: z
|
||||||
log.info(`Removing dependency for task ${args.id} from ${args.dependsOn} with args: ${JSON.stringify(args)}`);
|
.string()
|
||||||
// await reportProgress({ progress: 0 });
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(
|
||||||
|
`Removing dependency for task ${args.id} from ${args.dependsOn} with args: ${JSON.stringify(args)}`
|
||||||
|
);
|
||||||
|
// await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await removeDependencyDirect({
|
const result = await removeDependencyDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
...args
|
||||||
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully removed dependency: ${result.data.message}`);
|
log.info(`Successfully removed dependency: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to remove dependency: ${result.error.message}`);
|
log.error(`Failed to remove dependency: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error removing dependency');
|
return handleApiResult(result, log, 'Error removing dependency');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in removeDependency tool: ${error.message}`);
|
log.error(`Error in removeDependency tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,59 +3,82 @@
|
|||||||
* Tool for removing subtasks from parent tasks
|
* Tool for removing subtasks from parent tasks
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { removeSubtaskDirect } from "../core/task-master-core.js";
|
import { removeSubtaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the removeSubtask tool with the MCP server
|
* Register the removeSubtask tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerRemoveSubtaskTool(server) {
|
export function registerRemoveSubtaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "remove_subtask",
|
name: 'remove_subtask',
|
||||||
description: "Remove a subtask from its parent task",
|
description: 'Remove a subtask from its parent task',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("Subtask ID to remove in format 'parentId.subtaskId' (required)"),
|
id: z
|
||||||
convert: z.boolean().optional().describe("Convert the subtask to a standalone task instead of deleting it"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file (default: tasks/tasks.json)"),
|
.describe(
|
||||||
skipGenerate: z.boolean().optional().describe("Skip regenerating task files"),
|
"Subtask ID to remove in format 'parentId.subtaskId' (required)"
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
),
|
||||||
}),
|
convert: z
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.boolean()
|
||||||
try {
|
.optional()
|
||||||
log.info(`Removing subtask with args: ${JSON.stringify(args)}`);
|
.describe(
|
||||||
// await reportProgress({ progress: 0 });
|
'Convert the subtask to a standalone task instead of deleting it'
|
||||||
|
),
|
||||||
|
file: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe('Path to the tasks file (default: tasks/tasks.json)'),
|
||||||
|
skipGenerate: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.describe('Skip regenerating task files'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Removing subtask with args: ${JSON.stringify(args)}`);
|
||||||
|
// await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await removeSubtaskDirect({
|
const result = await removeSubtaskDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log/*, { reportProgress, mcpLog: log, session}*/);
|
...args
|
||||||
|
},
|
||||||
|
log /*, { reportProgress, mcpLog: log, session}*/
|
||||||
|
);
|
||||||
|
|
||||||
// await reportProgress({ progress: 100 });
|
// await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Subtask removed successfully: ${result.data.message}`);
|
log.info(`Subtask removed successfully: ${result.data.message}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to remove subtask: ${result.error.message}`);
|
log.error(`Failed to remove subtask: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error removing subtask');
|
return handleApiResult(result, log, 'Error removing subtask');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in removeSubtask tool: ${error.message}`);
|
log.error(`Error in removeSubtask tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,69 +3,79 @@
|
|||||||
* Tool to remove a task by ID
|
* Tool to remove a task by ID
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { removeTaskDirect } from "../core/task-master-core.js";
|
import { removeTaskDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the remove-task tool with the MCP server
|
* Register the remove-task tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerRemoveTaskTool(server) {
|
export function registerRemoveTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "remove_task",
|
name: 'remove_task',
|
||||||
description: "Remove a task or subtask permanently from the tasks list",
|
description: 'Remove a task or subtask permanently from the tasks list',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z.string().describe("ID of the task or subtask to remove (e.g., '5' or '5.2')"),
|
id: z
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.string()
|
||||||
projectRoot: z
|
.describe("ID of the task or subtask to remove (e.g., '5' or '5.2')"),
|
||||||
.string()
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
.optional()
|
projectRoot: z
|
||||||
.describe(
|
.string()
|
||||||
"Root directory of the project (default: current working directory)"
|
.optional()
|
||||||
),
|
.describe(
|
||||||
confirm: z.boolean().optional().describe("Whether to skip confirmation prompt (default: false)")
|
'Root directory of the project (default: current working directory)'
|
||||||
}),
|
),
|
||||||
execute: async (args, { log, session }) => {
|
confirm: z
|
||||||
try {
|
.boolean()
|
||||||
log.info(`Removing task with ID: ${args.id}`);
|
.optional()
|
||||||
|
.describe('Whether to skip confirmation prompt (default: false)')
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Removing task with ID: ${args.id}`);
|
||||||
|
|
||||||
// Get project root from session
|
// Get project root from session
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
} else if (!rootFolder) {
|
} else if (!rootFolder) {
|
||||||
// Ensure we have a default if nothing else works
|
// Ensure we have a default if nothing else works
|
||||||
rootFolder = process.cwd();
|
rootFolder = process.cwd();
|
||||||
log.warn(`Session and args failed to provide root, using CWD: ${rootFolder}`);
|
log.warn(
|
||||||
}
|
`Session and args failed to provide root, using CWD: ${rootFolder}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
log.info(`Using project root: ${rootFolder}`);
|
log.info(`Using project root: ${rootFolder}`);
|
||||||
|
|
||||||
// Assume client has already handled confirmation if needed
|
// Assume client has already handled confirmation if needed
|
||||||
const result = await removeTaskDirect({
|
const result = await removeTaskDirect(
|
||||||
id: args.id,
|
{
|
||||||
file: args.file,
|
id: args.id,
|
||||||
projectRoot: rootFolder
|
file: args.file,
|
||||||
}, log);
|
projectRoot: rootFolder
|
||||||
|
},
|
||||||
|
log
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully removed task: ${args.id}`);
|
log.info(`Successfully removed task: ${args.id}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to remove task: ${result.error.message}`);
|
log.error(`Failed to remove task: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error removing task');
|
return handleApiResult(result, log, 'Error removing task');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in remove-task tool: ${error.message}`);
|
log.error(`Error in remove-task tool: ${error.message}`);
|
||||||
return createErrorResponse(`Failed to remove task: ${error.message}`);
|
return createErrorResponse(`Failed to remove task: ${error.message}`);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,68 +3,81 @@
|
|||||||
* Tool to set the status of a task
|
* Tool to set the status of a task
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { setTaskStatusDirect } from "../core/task-master-core.js";
|
import { setTaskStatusDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the setTaskStatus tool with the MCP server
|
* Register the setTaskStatus tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerSetTaskStatusTool(server) {
|
export function registerSetTaskStatusTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "set_task_status",
|
name: 'set_task_status',
|
||||||
description: "Set the status of one or more tasks or subtasks.",
|
description: 'Set the status of one or more tasks or subtasks.',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
id: z
|
id: z
|
||||||
.string()
|
.string()
|
||||||
.describe("Task ID or subtask ID (e.g., '15', '15.2'). Can be comma-separated for multiple updates."),
|
.describe(
|
||||||
status: z
|
"Task ID or subtask ID (e.g., '15', '15.2'). Can be comma-separated for multiple updates."
|
||||||
.string()
|
),
|
||||||
.describe("New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."),
|
status: z
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.string()
|
||||||
projectRoot: z
|
.describe(
|
||||||
.string()
|
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
|
||||||
.optional()
|
),
|
||||||
.describe(
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
"Root directory of the project (default: automatically detected)"
|
projectRoot: z
|
||||||
),
|
.string()
|
||||||
}),
|
.optional()
|
||||||
execute: async (args, { log, session }) => {
|
.describe(
|
||||||
try {
|
'Root directory of the project (default: automatically detected)'
|
||||||
log.info(`Setting status of task(s) ${args.id} to: ${args.status}`);
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Setting status of task(s) ${args.id} to: ${args.status}`);
|
||||||
|
|
||||||
// Get project root from session
|
// Get project root from session
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call the direct function with the project root
|
// Call the direct function with the project root
|
||||||
const result = await setTaskStatusDirect({
|
const result = await setTaskStatusDirect(
|
||||||
...args,
|
{
|
||||||
projectRoot: rootFolder
|
...args,
|
||||||
}, log);
|
projectRoot: rootFolder
|
||||||
|
},
|
||||||
|
log
|
||||||
|
);
|
||||||
|
|
||||||
// Log the result
|
// Log the result
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully updated status for task(s) ${args.id} to "${args.status}": ${result.data.message}`);
|
log.info(
|
||||||
} else {
|
`Successfully updated status for task(s) ${args.id} to "${args.status}": ${result.data.message}`
|
||||||
log.error(`Failed to update task status: ${result.error?.message || 'Unknown error'}`);
|
);
|
||||||
}
|
} else {
|
||||||
|
log.error(
|
||||||
|
`Failed to update task status: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Format and return the result
|
// Format and return the result
|
||||||
return handleApiResult(result, log, 'Error setting task status');
|
return handleApiResult(result, log, 'Error setting task status');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in setTaskStatus tool: ${error.message}`);
|
log.error(`Error in setTaskStatus tool: ${error.message}`);
|
||||||
return createErrorResponse(`Error setting task status: ${error.message}`);
|
return createErrorResponse(
|
||||||
}
|
`Error setting task status: ${error.message}`
|
||||||
},
|
);
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,61 +3,75 @@
|
|||||||
* Tool to append additional information to a specific subtask
|
* Tool to append additional information to a specific subtask
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { updateSubtaskByIdDirect } from "../core/task-master-core.js";
|
import { updateSubtaskByIdDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the update-subtask tool with the MCP server
|
* Register the update-subtask tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerUpdateSubtaskTool(server) {
|
export function registerUpdateSubtaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "update_subtask",
|
name: 'update_subtask',
|
||||||
description: "Appends additional information to a specific subtask without replacing existing content",
|
description:
|
||||||
parameters: z.object({
|
'Appends additional information to a specific subtask without replacing existing content',
|
||||||
id: z.string().describe("ID of the subtask to update in format \"parentId.subtaskId\" (e.g., \"5.2\")"),
|
parameters: z.object({
|
||||||
prompt: z.string().describe("Information to add to the subtask"),
|
id: z
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed updates"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.describe(
|
||||||
projectRoot: z
|
'ID of the subtask to update in format "parentId.subtaskId" (e.g., "5.2")'
|
||||||
.string()
|
),
|
||||||
.optional()
|
prompt: z.string().describe('Information to add to the subtask'),
|
||||||
.describe(
|
research: z
|
||||||
"Root directory of the project (default: current working directory)"
|
.boolean()
|
||||||
),
|
.optional()
|
||||||
}),
|
.describe('Use Perplexity AI for research-backed updates'),
|
||||||
execute: async (args, { log, session }) => {
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
try {
|
projectRoot: z
|
||||||
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await updateSubtaskByIdDirect({
|
const result = await updateSubtaskByIdDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { session });
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully updated subtask with ID ${args.id}`);
|
log.info(`Successfully updated subtask with ID ${args.id}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to update subtask: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
}
|
`Failed to update subtask: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error updating subtask');
|
return handleApiResult(result, log, 'Error updating subtask');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in update_subtask tool: ${error.message}`);
|
log.error(`Error in update_subtask tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,61 +3,75 @@
|
|||||||
* Tool to update a single task by ID with new information
|
* Tool to update a single task by ID with new information
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { updateTaskByIdDirect } from "../core/task-master-core.js";
|
import { updateTaskByIdDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the update-task tool with the MCP server
|
* Register the update-task tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerUpdateTaskTool(server) {
|
export function registerUpdateTaskTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "update_task",
|
name: 'update_task',
|
||||||
description: "Updates a single task by ID with new information or context provided in the prompt.",
|
description:
|
||||||
parameters: z.object({
|
'Updates a single task by ID with new information or context provided in the prompt.',
|
||||||
id: z.string().describe("ID of the task or subtask (e.g., '15', '15.2') to update"),
|
parameters: z.object({
|
||||||
prompt: z.string().describe("New information or context to incorporate into the task"),
|
id: z
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed updates"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.describe("ID of the task or subtask (e.g., '15', '15.2') to update"),
|
||||||
projectRoot: z
|
prompt: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.describe('New information or context to incorporate into the task'),
|
||||||
.describe(
|
research: z
|
||||||
"Root directory of the project (default: current working directory)"
|
.boolean()
|
||||||
),
|
.optional()
|
||||||
}),
|
.describe('Use Perplexity AI for research-backed updates'),
|
||||||
execute: async (args, { log, session }) => {
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
try {
|
projectRoot: z
|
||||||
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await updateTaskByIdDirect({
|
const result = await updateTaskByIdDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { session });
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully updated task with ID ${args.id}`);
|
log.info(`Successfully updated task with ID ${args.id}`);
|
||||||
} else {
|
} else {
|
||||||
log.error(`Failed to update task: ${result.error?.message || 'Unknown error'}`);
|
log.error(
|
||||||
}
|
`Failed to update task: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error updating task');
|
return handleApiResult(result, log, 'Error updating task');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in update_task tool: ${error.message}`);
|
log.error(`Error in update_task tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,61 +3,79 @@
|
|||||||
* Tool to update tasks based on new context/prompt
|
* Tool to update tasks based on new context/prompt
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { updateTasksDirect } from "../core/task-master-core.js";
|
import { updateTasksDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the update tool with the MCP server
|
* Register the update tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerUpdateTool(server) {
|
export function registerUpdateTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "update",
|
name: 'update',
|
||||||
description: "Update multiple upcoming tasks (with ID >= 'from' ID) based on new context or changes provided in the prompt. Use 'update_task' instead for a single specific task.",
|
description:
|
||||||
parameters: z.object({
|
"Update multiple upcoming tasks (with ID >= 'from' ID) based on new context or changes provided in the prompt. Use 'update_task' instead for a single specific task.",
|
||||||
from: z.string().describe("Task ID from which to start updating (inclusive). IMPORTANT: This tool uses 'from', not 'id'"),
|
parameters: z.object({
|
||||||
prompt: z.string().describe("Explanation of changes or new context to apply"),
|
from: z
|
||||||
research: z.boolean().optional().describe("Use Perplexity AI for research-backed updates"),
|
.string()
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
.describe(
|
||||||
projectRoot: z
|
"Task ID from which to start updating (inclusive). IMPORTANT: This tool uses 'from', not 'id'"
|
||||||
.string()
|
),
|
||||||
.optional()
|
prompt: z
|
||||||
.describe(
|
.string()
|
||||||
"Root directory of the project (default: current working directory)"
|
.describe('Explanation of changes or new context to apply'),
|
||||||
),
|
research: z
|
||||||
}),
|
.boolean()
|
||||||
execute: async (args, { log, session }) => {
|
.optional()
|
||||||
try {
|
.describe('Use Perplexity AI for research-backed updates'),
|
||||||
log.info(`Updating tasks with args: ${JSON.stringify(args)}`);
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
|
projectRoot: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Updating tasks with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await updateTasksDirect({
|
const result = await updateTasksDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { session });
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully updated tasks from ID ${args.from}: ${result.data.message}`);
|
log.info(
|
||||||
} else {
|
`Successfully updated tasks from ID ${args.from}: ${result.data.message}`
|
||||||
log.error(`Failed to update tasks: ${result.error?.message || 'Unknown error'}`);
|
);
|
||||||
}
|
} else {
|
||||||
|
log.error(
|
||||||
|
`Failed to update tasks: ${result.error?.message || 'Unknown error'}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error updating tasks');
|
return handleApiResult(result, log, 'Error updating tasks');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in update tool: ${error.message}`);
|
log.error(`Error in update tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,13 +3,16 @@
|
|||||||
* Utility functions for Task Master CLI integration
|
* Utility functions for Task Master CLI integration
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { spawnSync } from "child_process";
|
import { spawnSync } from 'child_process';
|
||||||
import path from "path";
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { contextManager } from '../core/context-manager.js'; // Import the singleton
|
import { contextManager } from '../core/context-manager.js'; // Import the singleton
|
||||||
|
|
||||||
// Import path utilities to ensure consistent path resolution
|
// Import path utilities to ensure consistent path resolution
|
||||||
import { lastFoundProjectRoot, PROJECT_MARKERS } from '../core/utils/path-utils.js';
|
import {
|
||||||
|
lastFoundProjectRoot,
|
||||||
|
PROJECT_MARKERS
|
||||||
|
} from '../core/utils/path-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get normalized project root path
|
* Get normalized project root path
|
||||||
@@ -18,53 +21,65 @@ import { lastFoundProjectRoot, PROJECT_MARKERS } from '../core/utils/path-utils.
|
|||||||
* @returns {string} - Normalized absolute path to project root
|
* @returns {string} - Normalized absolute path to project root
|
||||||
*/
|
*/
|
||||||
function getProjectRoot(projectRootRaw, log) {
|
function getProjectRoot(projectRootRaw, log) {
|
||||||
// PRECEDENCE ORDER:
|
// PRECEDENCE ORDER:
|
||||||
// 1. Environment variable override
|
// 1. Environment variable override
|
||||||
// 2. Explicitly provided projectRoot in args
|
// 2. Explicitly provided projectRoot in args
|
||||||
// 3. Previously found/cached project root
|
// 3. Previously found/cached project root
|
||||||
// 4. Current directory if it has project markers
|
// 4. Current directory if it has project markers
|
||||||
// 5. Current directory with warning
|
// 5. Current directory with warning
|
||||||
|
|
||||||
// 1. Check for environment variable override
|
// 1. Check for environment variable override
|
||||||
if (process.env.TASK_MASTER_PROJECT_ROOT) {
|
if (process.env.TASK_MASTER_PROJECT_ROOT) {
|
||||||
const envRoot = process.env.TASK_MASTER_PROJECT_ROOT;
|
const envRoot = process.env.TASK_MASTER_PROJECT_ROOT;
|
||||||
const absolutePath = path.isAbsolute(envRoot)
|
const absolutePath = path.isAbsolute(envRoot)
|
||||||
? envRoot
|
? envRoot
|
||||||
: path.resolve(process.cwd(), envRoot);
|
: path.resolve(process.cwd(), envRoot);
|
||||||
log.info(`Using project root from TASK_MASTER_PROJECT_ROOT environment variable: ${absolutePath}`);
|
log.info(
|
||||||
return absolutePath;
|
`Using project root from TASK_MASTER_PROJECT_ROOT environment variable: ${absolutePath}`
|
||||||
}
|
);
|
||||||
|
return absolutePath;
|
||||||
|
}
|
||||||
|
|
||||||
// 2. If project root is explicitly provided, use it
|
// 2. If project root is explicitly provided, use it
|
||||||
if (projectRootRaw) {
|
if (projectRootRaw) {
|
||||||
const absolutePath = path.isAbsolute(projectRootRaw)
|
const absolutePath = path.isAbsolute(projectRootRaw)
|
||||||
? projectRootRaw
|
? projectRootRaw
|
||||||
: path.resolve(process.cwd(), projectRootRaw);
|
: path.resolve(process.cwd(), projectRootRaw);
|
||||||
|
|
||||||
log.info(`Using explicitly provided project root: ${absolutePath}`);
|
log.info(`Using explicitly provided project root: ${absolutePath}`);
|
||||||
return absolutePath;
|
return absolutePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. If we have a last found project root from a tasks.json search, use that for consistency
|
// 3. If we have a last found project root from a tasks.json search, use that for consistency
|
||||||
if (lastFoundProjectRoot) {
|
if (lastFoundProjectRoot) {
|
||||||
log.info(`Using last known project root where tasks.json was found: ${lastFoundProjectRoot}`);
|
log.info(
|
||||||
return lastFoundProjectRoot;
|
`Using last known project root where tasks.json was found: ${lastFoundProjectRoot}`
|
||||||
}
|
);
|
||||||
|
return lastFoundProjectRoot;
|
||||||
|
}
|
||||||
|
|
||||||
// 4. Check if the current directory has any indicators of being a task-master project
|
// 4. Check if the current directory has any indicators of being a task-master project
|
||||||
const currentDir = process.cwd();
|
const currentDir = process.cwd();
|
||||||
if (PROJECT_MARKERS.some(marker => {
|
if (
|
||||||
const markerPath = path.join(currentDir, marker);
|
PROJECT_MARKERS.some((marker) => {
|
||||||
return fs.existsSync(markerPath);
|
const markerPath = path.join(currentDir, marker);
|
||||||
})) {
|
return fs.existsSync(markerPath);
|
||||||
log.info(`Using current directory as project root (found project markers): ${currentDir}`);
|
})
|
||||||
return currentDir;
|
) {
|
||||||
}
|
log.info(
|
||||||
|
`Using current directory as project root (found project markers): ${currentDir}`
|
||||||
|
);
|
||||||
|
return currentDir;
|
||||||
|
}
|
||||||
|
|
||||||
// 5. Default to current working directory but warn the user
|
// 5. Default to current working directory but warn the user
|
||||||
log.warn(`No task-master project detected in current directory. Using ${currentDir} as project root.`);
|
log.warn(
|
||||||
log.warn('Consider using --project-root to specify the correct project location or set TASK_MASTER_PROJECT_ROOT environment variable.');
|
`No task-master project detected in current directory. Using ${currentDir} as project root.`
|
||||||
return currentDir;
|
);
|
||||||
|
log.warn(
|
||||||
|
'Consider using --project-root to specify the correct project location or set TASK_MASTER_PROJECT_ROOT environment variable.'
|
||||||
|
);
|
||||||
|
return currentDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -74,81 +89,87 @@ function getProjectRoot(projectRootRaw, log) {
|
|||||||
* @returns {string|null} - The absolute path to the project root, or null if not found.
|
* @returns {string|null} - The absolute path to the project root, or null if not found.
|
||||||
*/
|
*/
|
||||||
function getProjectRootFromSession(session, log) {
|
function getProjectRootFromSession(session, log) {
|
||||||
try {
|
try {
|
||||||
// Add detailed logging of session structure
|
// Add detailed logging of session structure
|
||||||
log.info(`Session object: ${JSON.stringify({
|
log.info(
|
||||||
hasSession: !!session,
|
`Session object: ${JSON.stringify({
|
||||||
hasRoots: !!session?.roots,
|
hasSession: !!session,
|
||||||
rootsType: typeof session?.roots,
|
hasRoots: !!session?.roots,
|
||||||
isRootsArray: Array.isArray(session?.roots),
|
rootsType: typeof session?.roots,
|
||||||
rootsLength: session?.roots?.length,
|
isRootsArray: Array.isArray(session?.roots),
|
||||||
firstRoot: session?.roots?.[0],
|
rootsLength: session?.roots?.length,
|
||||||
hasRootsRoots: !!session?.roots?.roots,
|
firstRoot: session?.roots?.[0],
|
||||||
rootsRootsType: typeof session?.roots?.roots,
|
hasRootsRoots: !!session?.roots?.roots,
|
||||||
isRootsRootsArray: Array.isArray(session?.roots?.roots),
|
rootsRootsType: typeof session?.roots?.roots,
|
||||||
rootsRootsLength: session?.roots?.roots?.length,
|
isRootsRootsArray: Array.isArray(session?.roots?.roots),
|
||||||
firstRootsRoot: session?.roots?.roots?.[0]
|
rootsRootsLength: session?.roots?.roots?.length,
|
||||||
})}`);
|
firstRootsRoot: session?.roots?.roots?.[0]
|
||||||
|
})}`
|
||||||
|
);
|
||||||
|
|
||||||
// ALWAYS ensure we return a valid path for project root
|
// ALWAYS ensure we return a valid path for project root
|
||||||
const cwd = process.cwd();
|
const cwd = process.cwd();
|
||||||
|
|
||||||
// If we have a session with roots array
|
// If we have a session with roots array
|
||||||
if (session?.roots?.[0]?.uri) {
|
if (session?.roots?.[0]?.uri) {
|
||||||
const rootUri = session.roots[0].uri;
|
const rootUri = session.roots[0].uri;
|
||||||
log.info(`Found rootUri in session.roots[0].uri: ${rootUri}`);
|
log.info(`Found rootUri in session.roots[0].uri: ${rootUri}`);
|
||||||
const rootPath = rootUri.startsWith('file://')
|
const rootPath = rootUri.startsWith('file://')
|
||||||
? decodeURIComponent(rootUri.slice(7))
|
? decodeURIComponent(rootUri.slice(7))
|
||||||
: rootUri;
|
: rootUri;
|
||||||
log.info(`Decoded rootPath: ${rootPath}`);
|
log.info(`Decoded rootPath: ${rootPath}`);
|
||||||
return rootPath;
|
return rootPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we have a session with roots.roots array (different structure)
|
// If we have a session with roots.roots array (different structure)
|
||||||
if (session?.roots?.roots?.[0]?.uri) {
|
if (session?.roots?.roots?.[0]?.uri) {
|
||||||
const rootUri = session.roots.roots[0].uri;
|
const rootUri = session.roots.roots[0].uri;
|
||||||
log.info(`Found rootUri in session.roots.roots[0].uri: ${rootUri}`);
|
log.info(`Found rootUri in session.roots.roots[0].uri: ${rootUri}`);
|
||||||
const rootPath = rootUri.startsWith('file://')
|
const rootPath = rootUri.startsWith('file://')
|
||||||
? decodeURIComponent(rootUri.slice(7))
|
? decodeURIComponent(rootUri.slice(7))
|
||||||
: rootUri;
|
: rootUri;
|
||||||
log.info(`Decoded rootPath: ${rootPath}`);
|
log.info(`Decoded rootPath: ${rootPath}`);
|
||||||
return rootPath;
|
return rootPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the server's location and try to find project root -- this is a fallback necessary in Cursor IDE
|
// Get the server's location and try to find project root -- this is a fallback necessary in Cursor IDE
|
||||||
const serverPath = process.argv[1]; // This should be the path to server.js, which is in mcp-server/
|
const serverPath = process.argv[1]; // This should be the path to server.js, which is in mcp-server/
|
||||||
if (serverPath && serverPath.includes('mcp-server')) {
|
if (serverPath && serverPath.includes('mcp-server')) {
|
||||||
// Find the mcp-server directory first
|
// Find the mcp-server directory first
|
||||||
const mcpServerIndex = serverPath.indexOf('mcp-server');
|
const mcpServerIndex = serverPath.indexOf('mcp-server');
|
||||||
if (mcpServerIndex !== -1) {
|
if (mcpServerIndex !== -1) {
|
||||||
// Get the path up to mcp-server, which should be the project root
|
// Get the path up to mcp-server, which should be the project root
|
||||||
const projectRoot = serverPath.substring(0, mcpServerIndex - 1); // -1 to remove trailing slash
|
const projectRoot = serverPath.substring(0, mcpServerIndex - 1); // -1 to remove trailing slash
|
||||||
|
|
||||||
// Verify this looks like our project root by checking for key files/directories
|
// Verify this looks like our project root by checking for key files/directories
|
||||||
if (fs.existsSync(path.join(projectRoot, '.cursor')) ||
|
if (
|
||||||
fs.existsSync(path.join(projectRoot, 'mcp-server')) ||
|
fs.existsSync(path.join(projectRoot, '.cursor')) ||
|
||||||
fs.existsSync(path.join(projectRoot, 'package.json'))) {
|
fs.existsSync(path.join(projectRoot, 'mcp-server')) ||
|
||||||
log.info(`Found project root from server path: ${projectRoot}`);
|
fs.existsSync(path.join(projectRoot, 'package.json'))
|
||||||
return projectRoot;
|
) {
|
||||||
}
|
log.info(`Found project root from server path: ${projectRoot}`);
|
||||||
}
|
return projectRoot;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ALWAYS ensure we return a valid path as a last resort
|
// ALWAYS ensure we return a valid path as a last resort
|
||||||
log.info(`Using current working directory as ultimate fallback: ${cwd}`);
|
log.info(`Using current working directory as ultimate fallback: ${cwd}`);
|
||||||
return cwd;
|
return cwd;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// If we have a server path, use it as a basis for project root
|
// If we have a server path, use it as a basis for project root
|
||||||
const serverPath = process.argv[1];
|
const serverPath = process.argv[1];
|
||||||
if (serverPath && serverPath.includes('mcp-server')) {
|
if (serverPath && serverPath.includes('mcp-server')) {
|
||||||
const mcpServerIndex = serverPath.indexOf('mcp-server');
|
const mcpServerIndex = serverPath.indexOf('mcp-server');
|
||||||
return mcpServerIndex !== -1 ? serverPath.substring(0, mcpServerIndex - 1) : process.cwd();
|
return mcpServerIndex !== -1
|
||||||
}
|
? serverPath.substring(0, mcpServerIndex - 1)
|
||||||
|
: process.cwd();
|
||||||
|
}
|
||||||
|
|
||||||
// Only use cwd if it's not "/"
|
// Only use cwd if it's not "/"
|
||||||
const cwd = process.cwd();
|
const cwd = process.cwd();
|
||||||
return cwd !== '/' ? cwd : '/';
|
return cwd !== '/' ? cwd : '/';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -159,28 +180,35 @@ function getProjectRootFromSession(session, log) {
|
|||||||
* @param {Function} processFunction - Optional function to process successful result data
|
* @param {Function} processFunction - Optional function to process successful result data
|
||||||
* @returns {Object} - Standardized MCP response object
|
* @returns {Object} - Standardized MCP response object
|
||||||
*/
|
*/
|
||||||
function handleApiResult(result, log, errorPrefix = 'API error', processFunction = processMCPResponseData) {
|
function handleApiResult(
|
||||||
if (!result.success) {
|
result,
|
||||||
const errorMsg = result.error?.message || `Unknown ${errorPrefix}`;
|
log,
|
||||||
// Include cache status in error logs
|
errorPrefix = 'API error',
|
||||||
log.error(`${errorPrefix}: ${errorMsg}. From cache: ${result.fromCache}`); // Keep logging cache status on error
|
processFunction = processMCPResponseData
|
||||||
return createErrorResponse(errorMsg);
|
) {
|
||||||
}
|
if (!result.success) {
|
||||||
|
const errorMsg = result.error?.message || `Unknown ${errorPrefix}`;
|
||||||
|
// Include cache status in error logs
|
||||||
|
log.error(`${errorPrefix}: ${errorMsg}. From cache: ${result.fromCache}`); // Keep logging cache status on error
|
||||||
|
return createErrorResponse(errorMsg);
|
||||||
|
}
|
||||||
|
|
||||||
// Process the result data if needed
|
// Process the result data if needed
|
||||||
const processedData = processFunction ? processFunction(result.data) : result.data;
|
const processedData = processFunction
|
||||||
|
? processFunction(result.data)
|
||||||
|
: result.data;
|
||||||
|
|
||||||
// Log success including cache status
|
// Log success including cache status
|
||||||
log.info(`Successfully completed operation. From cache: ${result.fromCache}`); // Add success log with cache status
|
log.info(`Successfully completed operation. From cache: ${result.fromCache}`); // Add success log with cache status
|
||||||
|
|
||||||
// Create the response payload including the fromCache flag
|
// Create the response payload including the fromCache flag
|
||||||
const responsePayload = {
|
const responsePayload = {
|
||||||
fromCache: result.fromCache, // Get the flag from the original 'result'
|
fromCache: result.fromCache, // Get the flag from the original 'result'
|
||||||
data: processedData // Nest the processed data under a 'data' key
|
data: processedData // Nest the processed data under a 'data' key
|
||||||
};
|
};
|
||||||
|
|
||||||
// Pass this combined payload to createContentResponse
|
// Pass this combined payload to createContentResponse
|
||||||
return createContentResponse(responsePayload);
|
return createContentResponse(responsePayload);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -193,75 +221,75 @@ function handleApiResult(result, log, errorPrefix = 'API error', processFunction
|
|||||||
* @returns {Object} - The result of the command execution
|
* @returns {Object} - The result of the command execution
|
||||||
*/
|
*/
|
||||||
function executeTaskMasterCommand(
|
function executeTaskMasterCommand(
|
||||||
command,
|
command,
|
||||||
log,
|
log,
|
||||||
args = [],
|
args = [],
|
||||||
projectRootRaw = null,
|
projectRootRaw = null,
|
||||||
customEnv = null // Changed from session to customEnv
|
customEnv = null // Changed from session to customEnv
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
// Normalize project root internally using the getProjectRoot utility
|
// Normalize project root internally using the getProjectRoot utility
|
||||||
const cwd = getProjectRoot(projectRootRaw, log);
|
const cwd = getProjectRoot(projectRootRaw, log);
|
||||||
|
|
||||||
log.info(
|
log.info(
|
||||||
`Executing task-master ${command} with args: ${JSON.stringify(
|
`Executing task-master ${command} with args: ${JSON.stringify(
|
||||||
args
|
args
|
||||||
)} in directory: ${cwd}`
|
)} in directory: ${cwd}`
|
||||||
);
|
);
|
||||||
|
|
||||||
// Prepare full arguments array
|
// Prepare full arguments array
|
||||||
const fullArgs = [command, ...args];
|
const fullArgs = [command, ...args];
|
||||||
|
|
||||||
// Common options for spawn
|
// Common options for spawn
|
||||||
const spawnOptions = {
|
const spawnOptions = {
|
||||||
encoding: "utf8",
|
encoding: 'utf8',
|
||||||
cwd: cwd,
|
cwd: cwd,
|
||||||
// Merge process.env with customEnv, giving precedence to customEnv
|
// Merge process.env with customEnv, giving precedence to customEnv
|
||||||
env: { ...process.env, ...(customEnv || {}) }
|
env: { ...process.env, ...(customEnv || {}) }
|
||||||
};
|
};
|
||||||
|
|
||||||
// Log the environment being passed (optional, for debugging)
|
// Log the environment being passed (optional, for debugging)
|
||||||
// log.info(`Spawn options env: ${JSON.stringify(spawnOptions.env)}`);
|
// log.info(`Spawn options env: ${JSON.stringify(spawnOptions.env)}`);
|
||||||
|
|
||||||
// Execute the command using the global task-master CLI or local script
|
// Execute the command using the global task-master CLI or local script
|
||||||
// Try the global CLI first
|
// Try the global CLI first
|
||||||
let result = spawnSync("task-master", fullArgs, spawnOptions);
|
let result = spawnSync('task-master', fullArgs, spawnOptions);
|
||||||
|
|
||||||
// If global CLI is not available, try fallback to the local script
|
// If global CLI is not available, try fallback to the local script
|
||||||
if (result.error && result.error.code === "ENOENT") {
|
if (result.error && result.error.code === 'ENOENT') {
|
||||||
log.info("Global task-master not found, falling back to local script");
|
log.info('Global task-master not found, falling back to local script');
|
||||||
// Pass the same spawnOptions (including env) to the fallback
|
// Pass the same spawnOptions (including env) to the fallback
|
||||||
result = spawnSync("node", ["scripts/dev.js", ...fullArgs], spawnOptions);
|
result = spawnSync('node', ['scripts/dev.js', ...fullArgs], spawnOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.error) {
|
if (result.error) {
|
||||||
throw new Error(`Command execution error: ${result.error.message}`);
|
throw new Error(`Command execution error: ${result.error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.status !== 0) {
|
if (result.status !== 0) {
|
||||||
// Improve error handling by combining stderr and stdout if stderr is empty
|
// Improve error handling by combining stderr and stdout if stderr is empty
|
||||||
const errorOutput = result.stderr
|
const errorOutput = result.stderr
|
||||||
? result.stderr.trim()
|
? result.stderr.trim()
|
||||||
: result.stdout
|
: result.stdout
|
||||||
? result.stdout.trim()
|
? result.stdout.trim()
|
||||||
: "Unknown error";
|
: 'Unknown error';
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Command failed with exit code ${result.status}: ${errorOutput}`
|
`Command failed with exit code ${result.status}: ${errorOutput}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
stdout: result.stdout,
|
stdout: result.stdout,
|
||||||
stderr: result.stderr,
|
stderr: result.stderr
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error executing task-master command: ${error.message}`);
|
log.error(`Error executing task-master command: ${error.message}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: error.message,
|
error: error.message
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -277,40 +305,44 @@ function executeTaskMasterCommand(
|
|||||||
* Format: { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
* Format: { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
||||||
*/
|
*/
|
||||||
async function getCachedOrExecute({ cacheKey, actionFn, log }) {
|
async function getCachedOrExecute({ cacheKey, actionFn, log }) {
|
||||||
// Check cache first
|
// Check cache first
|
||||||
const cachedResult = contextManager.getCachedData(cacheKey);
|
const cachedResult = contextManager.getCachedData(cacheKey);
|
||||||
|
|
||||||
if (cachedResult !== undefined) {
|
if (cachedResult !== undefined) {
|
||||||
log.info(`Cache hit for key: ${cacheKey}`);
|
log.info(`Cache hit for key: ${cacheKey}`);
|
||||||
// Return the cached data in the same structure as a fresh result
|
// Return the cached data in the same structure as a fresh result
|
||||||
return {
|
return {
|
||||||
...cachedResult, // Spread the cached result to maintain its structure
|
...cachedResult, // Spread the cached result to maintain its structure
|
||||||
fromCache: true // Just add the fromCache flag
|
fromCache: true // Just add the fromCache flag
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(`Cache miss for key: ${cacheKey}. Executing action function.`);
|
log.info(`Cache miss for key: ${cacheKey}. Executing action function.`);
|
||||||
|
|
||||||
// Execute the action function if cache missed
|
// Execute the action function if cache missed
|
||||||
const result = await actionFn();
|
const result = await actionFn();
|
||||||
|
|
||||||
// If the action was successful, cache the result (but without fromCache flag)
|
// If the action was successful, cache the result (but without fromCache flag)
|
||||||
if (result.success && result.data !== undefined) {
|
if (result.success && result.data !== undefined) {
|
||||||
log.info(`Action successful. Caching result for key: ${cacheKey}`);
|
log.info(`Action successful. Caching result for key: ${cacheKey}`);
|
||||||
// Cache the entire result structure (minus the fromCache flag)
|
// Cache the entire result structure (minus the fromCache flag)
|
||||||
const { fromCache, ...resultToCache } = result;
|
const { fromCache, ...resultToCache } = result;
|
||||||
contextManager.setCachedData(cacheKey, resultToCache);
|
contextManager.setCachedData(cacheKey, resultToCache);
|
||||||
} else if (!result.success) {
|
} else if (!result.success) {
|
||||||
log.warn(`Action failed for cache key ${cacheKey}. Result not cached. Error: ${result.error?.message}`);
|
log.warn(
|
||||||
} else {
|
`Action failed for cache key ${cacheKey}. Result not cached. Error: ${result.error?.message}`
|
||||||
log.warn(`Action for cache key ${cacheKey} succeeded but returned no data. Result not cached.`);
|
);
|
||||||
}
|
} else {
|
||||||
|
log.warn(
|
||||||
|
`Action for cache key ${cacheKey} succeeded but returned no data. Result not cached.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Return the fresh result, indicating it wasn't from cache
|
// Return the fresh result, indicating it wasn't from cache
|
||||||
return {
|
return {
|
||||||
...result,
|
...result,
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -320,56 +352,68 @@ async function getCachedOrExecute({ cacheKey, actionFn, log }) {
|
|||||||
* @param {string[]} fieldsToRemove - An array of field names to remove.
|
* @param {string[]} fieldsToRemove - An array of field names to remove.
|
||||||
* @returns {Object|Array} - The processed data with specified fields removed.
|
* @returns {Object|Array} - The processed data with specified fields removed.
|
||||||
*/
|
*/
|
||||||
function processMCPResponseData(taskOrData, fieldsToRemove = ['details', 'testStrategy']) {
|
function processMCPResponseData(
|
||||||
if (!taskOrData) {
|
taskOrData,
|
||||||
return taskOrData;
|
fieldsToRemove = ['details', 'testStrategy']
|
||||||
}
|
) {
|
||||||
|
if (!taskOrData) {
|
||||||
|
return taskOrData;
|
||||||
|
}
|
||||||
|
|
||||||
// Helper function to process a single task object
|
// Helper function to process a single task object
|
||||||
const processSingleTask = (task) => {
|
const processSingleTask = (task) => {
|
||||||
if (typeof task !== 'object' || task === null) {
|
if (typeof task !== 'object' || task === null) {
|
||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
const processedTask = { ...task };
|
const processedTask = { ...task };
|
||||||
|
|
||||||
// Remove specified fields from the task
|
// Remove specified fields from the task
|
||||||
fieldsToRemove.forEach(field => {
|
fieldsToRemove.forEach((field) => {
|
||||||
delete processedTask[field];
|
delete processedTask[field];
|
||||||
});
|
});
|
||||||
|
|
||||||
// Recursively process subtasks if they exist and are an array
|
// Recursively process subtasks if they exist and are an array
|
||||||
if (processedTask.subtasks && Array.isArray(processedTask.subtasks)) {
|
if (processedTask.subtasks && Array.isArray(processedTask.subtasks)) {
|
||||||
// Use processArrayOfTasks to handle the subtasks array
|
// Use processArrayOfTasks to handle the subtasks array
|
||||||
processedTask.subtasks = processArrayOfTasks(processedTask.subtasks);
|
processedTask.subtasks = processArrayOfTasks(processedTask.subtasks);
|
||||||
}
|
}
|
||||||
|
|
||||||
return processedTask;
|
return processedTask;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Helper function to process an array of tasks
|
// Helper function to process an array of tasks
|
||||||
const processArrayOfTasks = (tasks) => {
|
const processArrayOfTasks = (tasks) => {
|
||||||
return tasks.map(processSingleTask);
|
return tasks.map(processSingleTask);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check if the input is a data structure containing a 'tasks' array (like from listTasks)
|
// Check if the input is a data structure containing a 'tasks' array (like from listTasks)
|
||||||
if (typeof taskOrData === 'object' && taskOrData !== null && Array.isArray(taskOrData.tasks)) {
|
if (
|
||||||
return {
|
typeof taskOrData === 'object' &&
|
||||||
...taskOrData, // Keep other potential fields like 'stats', 'filter'
|
taskOrData !== null &&
|
||||||
tasks: processArrayOfTasks(taskOrData.tasks),
|
Array.isArray(taskOrData.tasks)
|
||||||
};
|
) {
|
||||||
}
|
return {
|
||||||
// Check if the input is likely a single task object (add more checks if needed)
|
...taskOrData, // Keep other potential fields like 'stats', 'filter'
|
||||||
else if (typeof taskOrData === 'object' && taskOrData !== null && 'id' in taskOrData && 'title' in taskOrData) {
|
tasks: processArrayOfTasks(taskOrData.tasks)
|
||||||
return processSingleTask(taskOrData);
|
};
|
||||||
}
|
}
|
||||||
// Check if the input is an array of tasks directly (less common but possible)
|
// Check if the input is likely a single task object (add more checks if needed)
|
||||||
else if (Array.isArray(taskOrData)) {
|
else if (
|
||||||
return processArrayOfTasks(taskOrData);
|
typeof taskOrData === 'object' &&
|
||||||
}
|
taskOrData !== null &&
|
||||||
|
'id' in taskOrData &&
|
||||||
|
'title' in taskOrData
|
||||||
|
) {
|
||||||
|
return processSingleTask(taskOrData);
|
||||||
|
}
|
||||||
|
// Check if the input is an array of tasks directly (less common but possible)
|
||||||
|
else if (Array.isArray(taskOrData)) {
|
||||||
|
return processArrayOfTasks(taskOrData);
|
||||||
|
}
|
||||||
|
|
||||||
// If it doesn't match known task structures, return it as is
|
// If it doesn't match known task structures, return it as is
|
||||||
return taskOrData;
|
return taskOrData;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -378,19 +422,20 @@ function processMCPResponseData(taskOrData, fieldsToRemove = ['details', 'testSt
|
|||||||
* @returns {Object} - Content response object in FastMCP format
|
* @returns {Object} - Content response object in FastMCP format
|
||||||
*/
|
*/
|
||||||
function createContentResponse(content) {
|
function createContentResponse(content) {
|
||||||
// FastMCP requires text type, so we format objects as JSON strings
|
// FastMCP requires text type, so we format objects as JSON strings
|
||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: 'text',
|
||||||
text: typeof content === 'object' ?
|
text:
|
||||||
// Format JSON nicely with indentation
|
typeof content === 'object'
|
||||||
JSON.stringify(content, null, 2) :
|
? // Format JSON nicely with indentation
|
||||||
// Keep other content types as-is
|
JSON.stringify(content, null, 2)
|
||||||
String(content)
|
: // Keep other content types as-is
|
||||||
}
|
String(content)
|
||||||
]
|
}
|
||||||
};
|
]
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -399,24 +444,24 @@ function createContentResponse(content) {
|
|||||||
* @returns {Object} - Error content response object in FastMCP format
|
* @returns {Object} - Error content response object in FastMCP format
|
||||||
*/
|
*/
|
||||||
export function createErrorResponse(errorMessage) {
|
export function createErrorResponse(errorMessage) {
|
||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
type: "text",
|
type: 'text',
|
||||||
text: `Error: ${errorMessage}`
|
text: `Error: ${errorMessage}`
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
isError: true
|
isError: true
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure all functions are exported
|
// Ensure all functions are exported
|
||||||
export {
|
export {
|
||||||
getProjectRoot,
|
getProjectRoot,
|
||||||
getProjectRootFromSession,
|
getProjectRootFromSession,
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
executeTaskMasterCommand,
|
executeTaskMasterCommand,
|
||||||
getCachedOrExecute,
|
getCachedOrExecute,
|
||||||
processMCPResponseData,
|
processMCPResponseData,
|
||||||
createContentResponse,
|
createContentResponse
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,56 +3,68 @@
|
|||||||
* Tool for validating task dependencies
|
* Tool for validating task dependencies
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { z } from "zod";
|
import { z } from 'zod';
|
||||||
import {
|
import {
|
||||||
handleApiResult,
|
handleApiResult,
|
||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
getProjectRootFromSession
|
getProjectRootFromSession
|
||||||
} from "./utils.js";
|
} from './utils.js';
|
||||||
import { validateDependenciesDirect } from "../core/task-master-core.js";
|
import { validateDependenciesDirect } from '../core/task-master-core.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the validateDependencies tool with the MCP server
|
* Register the validateDependencies tool with the MCP server
|
||||||
* @param {Object} server - FastMCP server instance
|
* @param {Object} server - FastMCP server instance
|
||||||
*/
|
*/
|
||||||
export function registerValidateDependenciesTool(server) {
|
export function registerValidateDependenciesTool(server) {
|
||||||
server.addTool({
|
server.addTool({
|
||||||
name: "validate_dependencies",
|
name: 'validate_dependencies',
|
||||||
description: "Check tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.",
|
description:
|
||||||
parameters: z.object({
|
'Check tasks for dependency issues (like circular references or links to non-existent tasks) without making changes.',
|
||||||
file: z.string().optional().describe("Path to the tasks file"),
|
parameters: z.object({
|
||||||
projectRoot: z.string().optional().describe("Root directory of the project (default: current working directory)")
|
file: z.string().optional().describe('Path to the tasks file'),
|
||||||
}),
|
projectRoot: z
|
||||||
execute: async (args, { log, session, reportProgress }) => {
|
.string()
|
||||||
try {
|
.optional()
|
||||||
log.info(`Validating dependencies with args: ${JSON.stringify(args)}`);
|
.describe(
|
||||||
await reportProgress({ progress: 0 });
|
'Root directory of the project (default: current working directory)'
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
execute: async (args, { log, session, reportProgress }) => {
|
||||||
|
try {
|
||||||
|
log.info(`Validating dependencies with args: ${JSON.stringify(args)}`);
|
||||||
|
await reportProgress({ progress: 0 });
|
||||||
|
|
||||||
let rootFolder = getProjectRootFromSession(session, log);
|
let rootFolder = getProjectRootFromSession(session, log);
|
||||||
|
|
||||||
if (!rootFolder && args.projectRoot) {
|
if (!rootFolder && args.projectRoot) {
|
||||||
rootFolder = args.projectRoot;
|
rootFolder = args.projectRoot;
|
||||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await validateDependenciesDirect({
|
const result = await validateDependenciesDirect(
|
||||||
projectRoot: rootFolder,
|
{
|
||||||
...args
|
projectRoot: rootFolder,
|
||||||
}, log, { reportProgress, mcpLog: log, session});
|
...args
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
{ reportProgress, mcpLog: log, session }
|
||||||
|
);
|
||||||
|
|
||||||
await reportProgress({ progress: 100 });
|
await reportProgress({ progress: 100 });
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
log.info(`Successfully validated dependencies: ${result.data.message}`);
|
log.info(
|
||||||
} else {
|
`Successfully validated dependencies: ${result.data.message}`
|
||||||
log.error(`Failed to validate dependencies: ${result.error.message}`);
|
);
|
||||||
}
|
} else {
|
||||||
|
log.error(`Failed to validate dependencies: ${result.error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
return handleApiResult(result, log, 'Error validating dependencies');
|
return handleApiResult(result, log, 'Error validating dependencies');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error in validateDependencies tool: ${error.message}`);
|
log.error(`Error in validateDependencies tool: ${error.message}`);
|
||||||
return createErrorResponse(error.message);
|
return createErrorResponse(error.message);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
96
mcp-test.js
96
mcp-test.js
@@ -8,64 +8,68 @@ import fs from 'fs';
|
|||||||
console.error(`Current working directory: ${process.cwd()}`);
|
console.error(`Current working directory: ${process.cwd()}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.error('Attempting to load FastMCP Config...');
|
console.error('Attempting to load FastMCP Config...');
|
||||||
|
|
||||||
// Check if .cursor/mcp.json exists
|
// Check if .cursor/mcp.json exists
|
||||||
const mcpPath = path.join(process.cwd(), '.cursor', 'mcp.json');
|
const mcpPath = path.join(process.cwd(), '.cursor', 'mcp.json');
|
||||||
console.error(`Checking if mcp.json exists at: ${mcpPath}`);
|
console.error(`Checking if mcp.json exists at: ${mcpPath}`);
|
||||||
|
|
||||||
if (fs.existsSync(mcpPath)) {
|
if (fs.existsSync(mcpPath)) {
|
||||||
console.error('mcp.json file found');
|
console.error('mcp.json file found');
|
||||||
console.error(`File content: ${JSON.stringify(JSON.parse(fs.readFileSync(mcpPath, 'utf8')), null, 2)}`);
|
console.error(
|
||||||
} else {
|
`File content: ${JSON.stringify(JSON.parse(fs.readFileSync(mcpPath, 'utf8')), null, 2)}`
|
||||||
console.error('mcp.json file not found');
|
);
|
||||||
}
|
} else {
|
||||||
|
console.error('mcp.json file not found');
|
||||||
|
}
|
||||||
|
|
||||||
// Try to create Config
|
// Try to create Config
|
||||||
const config = new Config();
|
const config = new Config();
|
||||||
console.error('Config created successfully');
|
console.error('Config created successfully');
|
||||||
|
|
||||||
// Check if env property exists
|
// Check if env property exists
|
||||||
if (config.env) {
|
if (config.env) {
|
||||||
console.error(`Config.env exists with keys: ${Object.keys(config.env).join(', ')}`);
|
console.error(
|
||||||
|
`Config.env exists with keys: ${Object.keys(config.env).join(', ')}`
|
||||||
|
);
|
||||||
|
|
||||||
// Print each env var value (careful with sensitive values)
|
// Print each env var value (careful with sensitive values)
|
||||||
for (const [key, value] of Object.entries(config.env)) {
|
for (const [key, value] of Object.entries(config.env)) {
|
||||||
if (key.includes('KEY')) {
|
if (key.includes('KEY')) {
|
||||||
console.error(`${key}: [value hidden]`);
|
console.error(`${key}: [value hidden]`);
|
||||||
} else {
|
} else {
|
||||||
console.error(`${key}: ${value}`);
|
console.error(`${key}: ${value}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.error('Config.env does not exist');
|
console.error('Config.env does not exist');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Error loading Config: ${error.message}`);
|
console.error(`Error loading Config: ${error.message}`);
|
||||||
console.error(`Stack trace: ${error.stack}`);
|
console.error(`Stack trace: ${error.stack}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log process.env to see if values from mcp.json were loaded automatically
|
// Log process.env to see if values from mcp.json were loaded automatically
|
||||||
console.error('\nChecking if process.env already has values from mcp.json:');
|
console.error('\nChecking if process.env already has values from mcp.json:');
|
||||||
const envVars = [
|
const envVars = [
|
||||||
'ANTHROPIC_API_KEY',
|
'ANTHROPIC_API_KEY',
|
||||||
'PERPLEXITY_API_KEY',
|
'PERPLEXITY_API_KEY',
|
||||||
'MODEL',
|
'MODEL',
|
||||||
'PERPLEXITY_MODEL',
|
'PERPLEXITY_MODEL',
|
||||||
'MAX_TOKENS',
|
'MAX_TOKENS',
|
||||||
'TEMPERATURE',
|
'TEMPERATURE',
|
||||||
'DEFAULT_SUBTASKS',
|
'DEFAULT_SUBTASKS',
|
||||||
'DEFAULT_PRIORITY'
|
'DEFAULT_PRIORITY'
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const varName of envVars) {
|
for (const varName of envVars) {
|
||||||
if (process.env[varName]) {
|
if (process.env[varName]) {
|
||||||
if (varName.includes('KEY')) {
|
if (varName.includes('KEY')) {
|
||||||
console.error(`${varName}: [value hidden]`);
|
console.error(`${varName}: [value hidden]`);
|
||||||
} else {
|
} else {
|
||||||
console.error(`${varName}: ${process.env[varName]}`);
|
console.error(`${varName}: ${process.env[varName]}`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.error(`${varName}: not set`);
|
console.error(`${varName}: not set`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"key": "value",
|
"key": "value",
|
||||||
"nested": {
|
"nested": {
|
||||||
"prop": true
|
"prop": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
16083
package-lock.json
generated
16083
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
191
package.json
191
package.json
@@ -1,96 +1,99 @@
|
|||||||
{
|
{
|
||||||
"name": "task-master-ai",
|
"name": "task-master-ai",
|
||||||
"version": "0.10.1",
|
"version": "0.10.1",
|
||||||
"description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
|
"description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
"task-master": "bin/task-master.js",
|
"task-master": "bin/task-master.js",
|
||||||
"task-master-init": "bin/task-master-init.js",
|
"task-master-init": "bin/task-master-init.js",
|
||||||
"task-master-mcp": "mcp-server/server.js",
|
"task-master-mcp": "mcp-server/server.js",
|
||||||
"task-master-mcp-server": "mcp-server/server.js"
|
"task-master-mcp-server": "mcp-server/server.js"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node --experimental-vm-modules node_modules/.bin/jest",
|
"test": "node --experimental-vm-modules node_modules/.bin/jest",
|
||||||
"test:fails": "node --experimental-vm-modules node_modules/.bin/jest --onlyFailures",
|
"test:fails": "node --experimental-vm-modules node_modules/.bin/jest --onlyFailures",
|
||||||
"test:watch": "node --experimental-vm-modules node_modules/.bin/jest --watch",
|
"test:watch": "node --experimental-vm-modules node_modules/.bin/jest --watch",
|
||||||
"test:coverage": "node --experimental-vm-modules node_modules/.bin/jest --coverage",
|
"test:coverage": "node --experimental-vm-modules node_modules/.bin/jest --coverage",
|
||||||
"prepare-package": "node scripts/prepare-package.js",
|
"prepare-package": "node scripts/prepare-package.js",
|
||||||
"prepublishOnly": "npm run prepare-package",
|
"prepublishOnly": "npm run prepare-package",
|
||||||
"prepare": "chmod +x bin/task-master.js bin/task-master-init.js mcp-server/server.js",
|
"prepare": "chmod +x bin/task-master.js bin/task-master-init.js mcp-server/server.js",
|
||||||
"changeset": "changeset",
|
"changeset": "changeset",
|
||||||
"release": "changeset publish",
|
"release": "changeset publish",
|
||||||
"inspector": "CLIENT_PORT=8888 SERVER_PORT=9000 npx @modelcontextprotocol/inspector node mcp-server/server.js",
|
"inspector": "CLIENT_PORT=8888 SERVER_PORT=9000 npx @modelcontextprotocol/inspector node mcp-server/server.js",
|
||||||
"mcp-server": "node mcp-server/server.js"
|
"mcp-server": "node mcp-server/server.js",
|
||||||
},
|
"format-check": "prettier --check .",
|
||||||
"keywords": [
|
"format": "prettier --write ."
|
||||||
"claude",
|
},
|
||||||
"task",
|
"keywords": [
|
||||||
"management",
|
"claude",
|
||||||
"ai",
|
"task",
|
||||||
"development",
|
"management",
|
||||||
"cursor",
|
"ai",
|
||||||
"anthropic",
|
"development",
|
||||||
"llm",
|
"cursor",
|
||||||
"mcp",
|
"anthropic",
|
||||||
"context"
|
"llm",
|
||||||
],
|
"mcp",
|
||||||
"author": "Eyal Toledano",
|
"context"
|
||||||
"license": "MIT WITH Commons-Clause",
|
],
|
||||||
"dependencies": {
|
"author": "Eyal Toledano",
|
||||||
"@anthropic-ai/sdk": "^0.39.0",
|
"license": "MIT WITH Commons-Clause",
|
||||||
"boxen": "^8.0.1",
|
"dependencies": {
|
||||||
"chalk": "^4.1.2",
|
"@anthropic-ai/sdk": "^0.39.0",
|
||||||
"cli-table3": "^0.6.5",
|
"boxen": "^8.0.1",
|
||||||
"commander": "^11.1.0",
|
"chalk": "^4.1.2",
|
||||||
"cors": "^2.8.5",
|
"cli-table3": "^0.6.5",
|
||||||
"dotenv": "^16.3.1",
|
"commander": "^11.1.0",
|
||||||
"express": "^4.21.2",
|
"cors": "^2.8.5",
|
||||||
"fastmcp": "^1.20.5",
|
"dotenv": "^16.3.1",
|
||||||
"figlet": "^1.8.0",
|
"express": "^4.21.2",
|
||||||
"fuse.js": "^7.0.0",
|
"fastmcp": "^1.20.5",
|
||||||
"gradient-string": "^3.0.0",
|
"figlet": "^1.8.0",
|
||||||
"helmet": "^8.1.0",
|
"fuse.js": "^7.0.0",
|
||||||
"inquirer": "^12.5.0",
|
"gradient-string": "^3.0.0",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"helmet": "^8.1.0",
|
||||||
"lru-cache": "^10.2.0",
|
"inquirer": "^12.5.0",
|
||||||
"openai": "^4.89.0",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"ora": "^8.2.0",
|
"lru-cache": "^10.2.0",
|
||||||
"uuid": "^11.1.0"
|
"openai": "^4.89.0",
|
||||||
},
|
"ora": "^8.2.0",
|
||||||
"engines": {
|
"uuid": "^11.1.0"
|
||||||
"node": ">=14.0.0"
|
},
|
||||||
},
|
"engines": {
|
||||||
"repository": {
|
"node": ">=14.0.0"
|
||||||
"type": "git",
|
},
|
||||||
"url": "git+https://github.com/eyaltoledano/claude-task-master.git"
|
"repository": {
|
||||||
},
|
"type": "git",
|
||||||
"homepage": "https://github.com/eyaltoledano/claude-task-master#readme",
|
"url": "git+https://github.com/eyaltoledano/claude-task-master.git"
|
||||||
"bugs": {
|
},
|
||||||
"url": "https://github.com/eyaltoledano/claude-task-master/issues"
|
"homepage": "https://github.com/eyaltoledano/claude-task-master#readme",
|
||||||
},
|
"bugs": {
|
||||||
"files": [
|
"url": "https://github.com/eyaltoledano/claude-task-master/issues"
|
||||||
"scripts/init.js",
|
},
|
||||||
"scripts/dev.js",
|
"files": [
|
||||||
"scripts/modules/**",
|
"scripts/init.js",
|
||||||
"assets/**",
|
"scripts/dev.js",
|
||||||
".cursor/**",
|
"scripts/modules/**",
|
||||||
"README-task-master.md",
|
"assets/**",
|
||||||
"index.js",
|
".cursor/**",
|
||||||
"bin/**",
|
"README-task-master.md",
|
||||||
"mcp-server/**"
|
"index.js",
|
||||||
],
|
"bin/**",
|
||||||
"overrides": {
|
"mcp-server/**"
|
||||||
"node-fetch": "^3.3.2",
|
],
|
||||||
"whatwg-url": "^11.0.0"
|
"overrides": {
|
||||||
},
|
"node-fetch": "^3.3.2",
|
||||||
"devDependencies": {
|
"whatwg-url": "^11.0.0"
|
||||||
"@changesets/changelog-github": "^0.5.1",
|
},
|
||||||
"@changesets/cli": "^2.28.1",
|
"devDependencies": {
|
||||||
"@types/jest": "^29.5.14",
|
"@changesets/changelog-github": "^0.5.1",
|
||||||
"jest": "^29.7.0",
|
"@changesets/cli": "^2.28.1",
|
||||||
"jest-environment-node": "^29.7.0",
|
"@types/jest": "^29.5.14",
|
||||||
"mock-fs": "^5.5.0",
|
"jest": "^29.7.0",
|
||||||
"supertest": "^7.1.0"
|
"jest-environment-node": "^29.7.0",
|
||||||
}
|
"mock-fs": "^5.5.0",
|
||||||
|
"prettier": "^3.5.3",
|
||||||
|
"supertest": "^7.1.0"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,9 +21,11 @@ In an AI-driven development process—particularly with tools like [Cursor](http
|
|||||||
The script can be configured through environment variables in a `.env` file at the root of the project:
|
The script can be configured through environment variables in a `.env` file at the root of the project:
|
||||||
|
|
||||||
### Required Configuration
|
### Required Configuration
|
||||||
|
|
||||||
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
|
- `ANTHROPIC_API_KEY`: Your Anthropic API key for Claude
|
||||||
|
|
||||||
### Optional Configuration
|
### Optional Configuration
|
||||||
|
|
||||||
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
|
- `MODEL`: Specify which Claude model to use (default: "claude-3-7-sonnet-20250219")
|
||||||
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
|
- `MAX_TOKENS`: Maximum tokens for model responses (default: 4000)
|
||||||
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
|
- `TEMPERATURE`: Temperature for model responses (default: 0.7)
|
||||||
@@ -39,6 +41,7 @@ The script can be configured through environment variables in a `.env` file at t
|
|||||||
## How It Works
|
## How It Works
|
||||||
|
|
||||||
1. **`tasks.json`**:
|
1. **`tasks.json`**:
|
||||||
|
|
||||||
- A JSON file at the project root containing an array of tasks (each with `id`, `title`, `description`, `status`, etc.).
|
- A JSON file at the project root containing an array of tasks (each with `id`, `title`, `description`, `status`, etc.).
|
||||||
- The `meta` field can store additional info like the project's name, version, or reference to the PRD.
|
- The `meta` field can store additional info like the project's name, version, or reference to the PRD.
|
||||||
- Tasks can have `subtasks` for more detailed implementation steps.
|
- Tasks can have `subtasks` for more detailed implementation steps.
|
||||||
@@ -102,6 +105,7 @@ node scripts/dev.js update --file=custom-tasks.json --from=5 --prompt="Change da
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- The `--prompt` parameter is required and should explain the changes or new context
|
- The `--prompt` parameter is required and should explain the changes or new context
|
||||||
- Only tasks that aren't marked as 'done' will be updated
|
- Only tasks that aren't marked as 'done' will be updated
|
||||||
- Tasks with ID >= the specified --from value will be updated
|
- Tasks with ID >= the specified --from value will be updated
|
||||||
@@ -120,6 +124,7 @@ node scripts/dev.js update-task --id=4 --prompt="Use JWT for authentication" --r
|
|||||||
```
|
```
|
||||||
|
|
||||||
This command:
|
This command:
|
||||||
|
|
||||||
- Updates only the specified task rather than a range of tasks
|
- Updates only the specified task rather than a range of tasks
|
||||||
- Provides detailed validation with helpful error messages
|
- Provides detailed validation with helpful error messages
|
||||||
- Checks for required API keys when using research mode
|
- Checks for required API keys when using research mode
|
||||||
@@ -146,6 +151,7 @@ node scripts/dev.js set-status --id=1,2,3 --status=done
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- When marking a parent task as "done", all of its subtasks will automatically be marked as "done" as well
|
- When marking a parent task as "done", all of its subtasks will automatically be marked as "done" as well
|
||||||
- Common status values are 'done', 'pending', and 'deferred', but any string is accepted
|
- Common status values are 'done', 'pending', and 'deferred', but any string is accepted
|
||||||
- You can specify multiple task IDs by separating them with commas
|
- You can specify multiple task IDs by separating them with commas
|
||||||
@@ -195,6 +201,7 @@ node scripts/dev.js clear-subtasks --all
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- After clearing subtasks, task files are automatically regenerated
|
- After clearing subtasks, task files are automatically regenerated
|
||||||
- This is useful when you want to regenerate subtasks with a different approach
|
- This is useful when you want to regenerate subtasks with a different approach
|
||||||
- Can be combined with the `expand` command to immediately generate new subtasks
|
- Can be combined with the `expand` command to immediately generate new subtasks
|
||||||
@@ -210,6 +217,7 @@ The script integrates with two AI services:
|
|||||||
The Perplexity integration uses the OpenAI client to connect to Perplexity's API, which provides enhanced research capabilities for generating more informed subtasks. If the Perplexity API is unavailable or encounters an error, the script will automatically fall back to using Anthropic's Claude.
|
The Perplexity integration uses the OpenAI client to connect to Perplexity's API, which provides enhanced research capabilities for generating more informed subtasks. If the Perplexity API is unavailable or encounters an error, the script will automatically fall back to using Anthropic's Claude.
|
||||||
|
|
||||||
To use the Perplexity integration:
|
To use the Perplexity integration:
|
||||||
|
|
||||||
1. Obtain a Perplexity API key
|
1. Obtain a Perplexity API key
|
||||||
2. Add `PERPLEXITY_API_KEY` to your `.env` file
|
2. Add `PERPLEXITY_API_KEY` to your `.env` file
|
||||||
3. Optionally specify `PERPLEXITY_MODEL` in your `.env` file (default: "sonar-medium-online")
|
3. Optionally specify `PERPLEXITY_MODEL` in your `.env` file (default: "sonar-medium-online")
|
||||||
@@ -218,6 +226,7 @@ To use the Perplexity integration:
|
|||||||
## Logging
|
## Logging
|
||||||
|
|
||||||
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
|
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
|
||||||
|
|
||||||
- `debug`: Detailed information, typically useful for troubleshooting
|
- `debug`: Detailed information, typically useful for troubleshooting
|
||||||
- `info`: Confirmation that things are working as expected (default)
|
- `info`: Confirmation that things are working as expected (default)
|
||||||
- `warn`: Warning messages that don't prevent execution
|
- `warn`: Warning messages that don't prevent execution
|
||||||
@@ -240,17 +249,20 @@ node scripts/dev.js remove-dependency --id=<id> --depends-on=<id>
|
|||||||
These commands:
|
These commands:
|
||||||
|
|
||||||
1. **Allow precise dependency management**:
|
1. **Allow precise dependency management**:
|
||||||
|
|
||||||
- Add dependencies between tasks with automatic validation
|
- Add dependencies between tasks with automatic validation
|
||||||
- Remove dependencies when they're no longer needed
|
- Remove dependencies when they're no longer needed
|
||||||
- Update task files automatically after changes
|
- Update task files automatically after changes
|
||||||
|
|
||||||
2. **Include validation checks**:
|
2. **Include validation checks**:
|
||||||
|
|
||||||
- Prevent circular dependencies (a task depending on itself)
|
- Prevent circular dependencies (a task depending on itself)
|
||||||
- Prevent duplicate dependencies
|
- Prevent duplicate dependencies
|
||||||
- Verify that both tasks exist before adding/removing dependencies
|
- Verify that both tasks exist before adding/removing dependencies
|
||||||
- Check if dependencies exist before attempting to remove them
|
- Check if dependencies exist before attempting to remove them
|
||||||
|
|
||||||
3. **Provide clear feedback**:
|
3. **Provide clear feedback**:
|
||||||
|
|
||||||
- Success messages confirm when dependencies are added/removed
|
- Success messages confirm when dependencies are added/removed
|
||||||
- Error messages explain why operations failed (if applicable)
|
- Error messages explain why operations failed (if applicable)
|
||||||
|
|
||||||
@@ -275,6 +287,7 @@ node scripts/dev.js validate-dependencies --file=custom-tasks.json
|
|||||||
```
|
```
|
||||||
|
|
||||||
This command:
|
This command:
|
||||||
|
|
||||||
- Scans all tasks and subtasks for non-existent dependencies
|
- Scans all tasks and subtasks for non-existent dependencies
|
||||||
- Identifies potential self-dependencies (tasks referencing themselves)
|
- Identifies potential self-dependencies (tasks referencing themselves)
|
||||||
- Reports all found issues without modifying files
|
- Reports all found issues without modifying files
|
||||||
@@ -296,6 +309,7 @@ node scripts/dev.js fix-dependencies --file=custom-tasks.json
|
|||||||
```
|
```
|
||||||
|
|
||||||
This command:
|
This command:
|
||||||
|
|
||||||
1. **Validates all dependencies** across tasks and subtasks
|
1. **Validates all dependencies** across tasks and subtasks
|
||||||
2. **Automatically removes**:
|
2. **Automatically removes**:
|
||||||
- References to non-existent tasks and subtasks
|
- References to non-existent tasks and subtasks
|
||||||
@@ -333,6 +347,7 @@ node scripts/dev.js analyze-complexity --research
|
|||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- The command uses Claude to analyze each task's complexity (or Perplexity with --research flag)
|
- The command uses Claude to analyze each task's complexity (or Perplexity with --research flag)
|
||||||
- Tasks are scored on a scale of 1-10
|
- Tasks are scored on a scale of 1-10
|
||||||
- Each task receives a recommended number of subtasks based on DEFAULT_SUBTASKS configuration
|
- Each task receives a recommended number of subtasks based on DEFAULT_SUBTASKS configuration
|
||||||
@@ -357,33 +372,35 @@ node scripts/dev.js expand --id=8 --num=5 --prompt="Custom prompt"
|
|||||||
```
|
```
|
||||||
|
|
||||||
When a complexity report exists:
|
When a complexity report exists:
|
||||||
|
|
||||||
- The `expand` command will use the recommended subtask count from the report (unless overridden)
|
- The `expand` command will use the recommended subtask count from the report (unless overridden)
|
||||||
- It will use the tailored expansion prompt from the report (unless a custom prompt is provided)
|
- It will use the tailored expansion prompt from the report (unless a custom prompt is provided)
|
||||||
- When using `--all`, tasks are sorted by complexity score (highest first)
|
- When using `--all`, tasks are sorted by complexity score (highest first)
|
||||||
- The `--research` flag is preserved from the complexity analysis to expansion
|
- The `--research` flag is preserved from the complexity analysis to expansion
|
||||||
|
|
||||||
The output report structure is:
|
The output report structure is:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"meta": {
|
"meta": {
|
||||||
"generatedAt": "2023-06-15T12:34:56.789Z",
|
"generatedAt": "2023-06-15T12:34:56.789Z",
|
||||||
"tasksAnalyzed": 20,
|
"tasksAnalyzed": 20,
|
||||||
"thresholdScore": 5,
|
"thresholdScore": 5,
|
||||||
"projectName": "Your Project Name",
|
"projectName": "Your Project Name",
|
||||||
"usedResearch": true
|
"usedResearch": true
|
||||||
},
|
},
|
||||||
"complexityAnalysis": [
|
"complexityAnalysis": [
|
||||||
{
|
{
|
||||||
"taskId": 8,
|
"taskId": 8,
|
||||||
"taskTitle": "Develop Implementation Drift Handling",
|
"taskTitle": "Develop Implementation Drift Handling",
|
||||||
"complexityScore": 9.5,
|
"complexityScore": 9.5,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 6,
|
||||||
"expansionPrompt": "Create subtasks that handle detecting...",
|
"expansionPrompt": "Create subtasks that handle detecting...",
|
||||||
"reasoning": "This task requires sophisticated logic...",
|
"reasoning": "This task requires sophisticated logic...",
|
||||||
"expansionCommand": "node scripts/dev.js expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
|
"expansionCommand": "node scripts/dev.js expand --id=8 --num=6 --prompt=\"Create subtasks...\" --research"
|
||||||
},
|
}
|
||||||
// More tasks sorted by complexity score (highest first)
|
// More tasks sorted by complexity score (highest first)
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -457,16 +474,19 @@ This command is particularly useful when you need to examine a specific task in
|
|||||||
The script now includes improved error handling throughout all commands:
|
The script now includes improved error handling throughout all commands:
|
||||||
|
|
||||||
1. **Detailed Validation**:
|
1. **Detailed Validation**:
|
||||||
|
|
||||||
- Required parameters (like task IDs and prompts) are validated early
|
- Required parameters (like task IDs and prompts) are validated early
|
||||||
- File existence is checked with customized errors for common scenarios
|
- File existence is checked with customized errors for common scenarios
|
||||||
- Parameter type conversion is handled with clear error messages
|
- Parameter type conversion is handled with clear error messages
|
||||||
|
|
||||||
2. **Contextual Error Messages**:
|
2. **Contextual Error Messages**:
|
||||||
|
|
||||||
- Task not found errors include suggestions to run the list command
|
- Task not found errors include suggestions to run the list command
|
||||||
- API key errors include reminders to check environment variables
|
- API key errors include reminders to check environment variables
|
||||||
- Invalid ID format errors show the expected format
|
- Invalid ID format errors show the expected format
|
||||||
|
|
||||||
3. **Command-Specific Help Displays**:
|
3. **Command-Specific Help Displays**:
|
||||||
|
|
||||||
- When validation fails, detailed help for the specific command is shown
|
- When validation fails, detailed help for the specific command is shown
|
||||||
- Help displays include usage examples and parameter descriptions
|
- Help displays include usage examples and parameter descriptions
|
||||||
- Formatted in clear, color-coded boxes with examples
|
- Formatted in clear, color-coded boxes with examples
|
||||||
@@ -481,11 +501,13 @@ The script now includes improved error handling throughout all commands:
|
|||||||
The script now automatically checks for updates without slowing down execution:
|
The script now automatically checks for updates without slowing down execution:
|
||||||
|
|
||||||
1. **Background Version Checking**:
|
1. **Background Version Checking**:
|
||||||
|
|
||||||
- Non-blocking version checks run in the background while commands execute
|
- Non-blocking version checks run in the background while commands execute
|
||||||
- Actual command execution isn't delayed by version checking
|
- Actual command execution isn't delayed by version checking
|
||||||
- Update notifications appear after command completion
|
- Update notifications appear after command completion
|
||||||
|
|
||||||
2. **Update Notifications**:
|
2. **Update Notifications**:
|
||||||
|
|
||||||
- When a newer version is available, a notification is displayed
|
- When a newer version is available, a notification is displayed
|
||||||
- Notifications include current version, latest version, and update command
|
- Notifications include current version, latest version, and update command
|
||||||
- Formatted in an attention-grabbing box with clear instructions
|
- Formatted in an attention-grabbing box with clear instructions
|
||||||
@@ -516,6 +538,7 @@ node scripts/dev.js add-subtask --parent=5 --title="Login API route" --skip-gene
|
|||||||
```
|
```
|
||||||
|
|
||||||
Key features:
|
Key features:
|
||||||
|
|
||||||
- Create new subtasks with detailed properties or convert existing tasks
|
- Create new subtasks with detailed properties or convert existing tasks
|
||||||
- Define dependencies between subtasks
|
- Define dependencies between subtasks
|
||||||
- Set custom status for new subtasks
|
- Set custom status for new subtasks
|
||||||
@@ -538,6 +561,7 @@ node scripts/dev.js remove-subtask --id=5.2 --skip-generate
|
|||||||
```
|
```
|
||||||
|
|
||||||
Key features:
|
Key features:
|
||||||
|
|
||||||
- Remove subtasks individually or in batches
|
- Remove subtasks individually or in batches
|
||||||
- Optionally convert subtasks to standalone tasks
|
- Optionally convert subtasks to standalone tasks
|
||||||
- Control whether task files are regenerated
|
- Control whether task files are regenerated
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
// Add at the very beginning of the file
|
// Add at the very beginning of the file
|
||||||
if (process.env.DEBUG === '1') {
|
if (process.env.DEBUG === '1') {
|
||||||
console.error('DEBUG - dev.js received args:', process.argv.slice(2));
|
console.error('DEBUG - dev.js received args:', process.argv.slice(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
import { runCLI } from './modules/commands.js';
|
import { runCLI } from './modules/commands.js';
|
||||||
|
|||||||
1473
scripts/init.js
1473
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
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user