Compare commits
1 Commits
v0.15.0-rc
...
crunchyman
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9435c19d47 |
5
.changeset/beige-rats-accept.md
Normal file
5
.changeset/beige-rats-accept.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
- Add support for Google Gemini models via Vercel AI SDK integration.
|
||||
@@ -1,15 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Added comprehensive Ollama model validation and interactive setup support
|
||||
|
||||
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
|
||||
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
|
||||
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
|
||||
- **Robust Error Handling**:
|
||||
- Detects when Ollama server is not running and provides clear error messages
|
||||
- Validates model existence and lists available alternatives when model not found
|
||||
- Graceful fallback behavior for connection issues
|
||||
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
|
||||
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
|
||||
5
.changeset/blue-spies-kick.md
Normal file
5
.changeset/blue-spies-kick.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Add xAI provider and Grok models support
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Adds and updates supported AI models with costs:
|
||||
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
|
||||
- Added Mistral models: Devstral Small, Mistral Nemo
|
||||
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
|
||||
- Updated Gemini model to latest 2.5 Flash preview version
|
||||
8
.changeset/cuddly-zebras-matter.md
Normal file
8
.changeset/cuddly-zebras-matter.md
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
feat(expand): Enhance `expand` and `expand-all` commands
|
||||
|
||||
- Integrate `task-complexity-report.json` to automatically determine the number of subtasks and use tailored prompts for expansion based on prior analysis. You no longer need to try copy-pasting the recommended prompt. If it exists, it will use it for you. You can just run `task-master update --id=[id of task] --research` and it will use that prompt automatically. No extra prompt needed.
|
||||
- Change default behavior to *append* new subtasks to existing ones. Use the `--force` flag to clear existing subtasks before expanding. This is helpful if you need to add more subtasks to a task but you want to do it by the batch from a given prompt. Use force if you want to start fresh with a task's subtasks.
|
||||
@@ -1,15 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
|
||||
|
||||
- Research current technologies and best practices relevant to the project
|
||||
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
|
||||
- Include specific library recommendations with version numbers
|
||||
- Provide more detailed implementation guidance based on industry standards
|
||||
- Create more accurate dependency relationships between tasks
|
||||
|
||||
This results in higher quality, more actionable tasks with minimal additional effort.
|
||||
|
||||
*NOTE* That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
|
||||
7
.changeset/easy-toys-wash.md
Normal file
7
.changeset/easy-toys-wash.md
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Adds support for the OpenRouter AI provider. Users can now configure models available through OpenRouter (requiring an `OPENROUTER_API_KEY`) via the `task-master models` command, granting access to a wide range of additional LLMs.
|
||||
- IMPORTANT FYI ABOUT OPENROUTER: Taskmaster relies on AI SDK, which itself relies on tool use. It looks like **free** models sometimes do not include tool use. For example, Gemini 2.5 pro (free) failed via OpenRouter (no tool use) but worked fine on the paid version of the model. Custom model support for Open Router is considered experimental and likely will not be further improved for some time.
|
||||
|
||||
5
.changeset/every-stars-sell.md
Normal file
5
.changeset/every-stars-sell.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Add integration for Roo Code
|
||||
13
.changeset/fine-signs-add.md
Normal file
13
.changeset/fine-signs-add.md
Normal file
@@ -0,0 +1,13 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Improve and adjust `init` command for robustness and updated dependencies.
|
||||
|
||||
- **Update Initialization Dependencies:** Ensure newly initialized projects (`task-master init`) include all required AI SDK dependencies (`@ai-sdk/*`, `ai`, provider wrappers) in their `package.json` for out-of-the-box AI feature compatibility. Remove unnecessary dependencies (e.g., `uuid`) from the init template.
|
||||
- **Silence `npm install` during `init`:** Prevent `npm install` output from interfering with non-interactive/MCP initialization by suppressing its stdio in silent mode.
|
||||
- **Improve Conditional Model Setup:** Reliably skip interactive `models --setup` during non-interactive `init` runs (e.g., `init -y` or MCP) by checking `isSilentMode()` instead of passing flags.
|
||||
- **Refactor `init.js`:** Remove internal `isInteractive` flag logic.
|
||||
- **Update `init` Instructions:** Tweak the "Getting Started" text displayed after `init`.
|
||||
- **Fix MCP Server Launch:** Update `.cursor/mcp.json` template to use `node ./mcp-server/server.js` instead of `npx task-master-mcp`.
|
||||
- **Update Default Model:** Change the default main model in the `.taskmasterconfig` template.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically:
|
||||
- Analyzes your existing tasks to find those most relevant to your new task's description.
|
||||
- Provides the AI with detailed context from these relevant tasks.
|
||||
|
||||
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
|
||||
5
.changeset/gentle-views-jump.md
Normal file
5
.changeset/gentle-views-jump.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fixes an issue with add-task which did not use the manually defined properties and still needlessly hit the AI endpoint.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Enhance analyze-complexity to support analyzing specific task IDs.
|
||||
- You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks.
|
||||
- The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
|
||||
5
.changeset/mighty-mirrors-watch.md
Normal file
5
.changeset/mighty-mirrors-watch.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Adds model management and new configuration file .taskmasterconfig which houses the models used for main, research and fallback. Adds models command and setter flags. Adds a --setup flag with an interactive setup. We should be calling this during init. Shows a table of active and available models when models is called without flags. Includes SWE scores and token costs, which are manually entered into the supported_models.json, the new place where models are defined for support. Config-manager.js is the core module responsible for managing the new config."
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fixes issue with force/append flag combinations for parse-prd.
|
||||
5
.changeset/neat-donkeys-shave.md
Normal file
5
.changeset/neat-donkeys-shave.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fixes an issue that prevented remove-subtask with comma separated tasks/subtasks from being deleted (only the first ID was being deleted). Closes #140
|
||||
10
.changeset/nine-rocks-sink.md
Normal file
10
.changeset/nine-rocks-sink.md
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Improves next command to be subtask-aware
|
||||
- The logic for determining the "next task" (findNextTask function, used by task-master next and the next_task MCP tool) has been significantly improved. Previously, it only considered top-level tasks, making its recommendation less useful when a parent task containing subtasks was already marked 'in-progress'.
|
||||
- The updated logic now prioritizes finding the next available subtask within any 'in-progress' parent task, considering subtask dependencies and priority.
|
||||
- If no suitable subtask is found within active parent tasks, it falls back to recommending the next eligible top-level task based on the original criteria (status, dependencies, priority).
|
||||
|
||||
This change makes the next command much more relevant and helpful during the implementation phase of complex tasks.
|
||||
11
.changeset/ninety-ghosts-relax.md
Normal file
11
.changeset/ninety-ghosts-relax.md
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Adds custom model ID support for Ollama and OpenRouter providers.
|
||||
- Adds the `--ollama` and `--openrouter` flags to `task-master models --set-<role>` command to set models for those providers outside of the support models list.
|
||||
- Updated `task-master models --setup` interactive mode with options to explicitly enter custom Ollama or OpenRouter model IDs.
|
||||
- Implemented live validation against OpenRouter API (`/api/v1/models`) when setting a custom OpenRouter model ID (via flag or setup).
|
||||
- Refined logic to prioritize explicit provider flags/choices over internal model list lookups in case of ID conflicts.
|
||||
- Added warnings when setting custom/unvalidated models.
|
||||
- We obviously don't recommend going with a custom, unproven model. If you do and find performance is good, please let us know so we can add it to the list of supported models.
|
||||
5
.changeset/ninety-wombats-pull.md
Normal file
5
.changeset/ninety-wombats-pull.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Add `--status` flag to `show` command to filter displayed subtasks.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
|
||||
7
.changeset/public-cooks-fetch.md
Normal file
7
.changeset/public-cooks-fetch.md
Normal file
@@ -0,0 +1,7 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Integrate OpenAI as a new AI provider.
|
||||
- Enhance `models` command/tool to display API key status.
|
||||
- Implement model-specific `maxTokens` override based on `supported-models.json` to save you if you use an incorrect max token value.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
|
||||
9
.changeset/tricky-papayas-hang.md
Normal file
9
.changeset/tricky-papayas-hang.md
Normal file
@@ -0,0 +1,9 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
Tweaks Perplexity AI calls for research mode to max out input tokens and get day-fresh information
|
||||
- Forces temp at 0.1 for highly deterministic output, no variations
|
||||
- Adds a system prompt to further improve the output
|
||||
- Correctly uses the maximum input tokens (8,719, used 8,700) for perplexity
|
||||
- Specificies to use a high degree of research across the web
|
||||
- Specifies to use information that is as fresh as today; this support stuff like capturing brand new announcements like new GPT models and being able to query for those in research. 🔥
|
||||
@@ -1,6 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add next task to set task status response
|
||||
Status: DONE
|
||||
5
.changeset/violet-papayas-see.md
Normal file
5
.changeset/violet-papayas-see.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Fix --task to --num-tasks in ui + related tests - issue #324
|
||||
9
.changeset/violet-parrots-march.md
Normal file
9
.changeset/violet-parrots-march.md
Normal file
@@ -0,0 +1,9 @@
|
||||
---
|
||||
'task-master-ai': patch
|
||||
---
|
||||
|
||||
Adds a 'models' CLI and MCP command to get the current model configuration, available models, and gives the ability to set main/research/fallback models."
|
||||
- In the CLI, `task-master models` shows the current models config. Using the `--setup` flag launches an interactive set up that allows you to easily select the models you want to use for each of the three roles. Use `q` during the interactive setup to cancel the setup.
|
||||
- In the MCP, responses are simplified in RESTful format (instead of the full CLI output). The agent can use the `models` tool with different arguments, including `listAvailableModels` to get available models. Run without arguments, it will return the current configuration. Arguments are available to set the model for each of the three roles. This allows you to manage Taskmaster AI providers and models directly from either the CLI or MCP or both.
|
||||
- Updated the CLI help menu when you run `task-master` to include missing commands and .taskmasterconfig information.
|
||||
- Adds `--research` flag to `add-task` so you can hit up Perplexity right from the add-task flow, rather than having to add a task and then update it.
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
'task-master-ai': minor
|
||||
---
|
||||
|
||||
Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
|
||||
|
||||
**Usage:**
|
||||
- CLI command: `task-master move --from=<id> --to=<id>`
|
||||
- MCP tool: `move_task` with parameters:
|
||||
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
|
||||
- `to`: ID of destination (e.g., "7" or "7.3")
|
||||
- `file` (optional): Custom path to tasks.json
|
||||
|
||||
**Example scenarios:**
|
||||
- Move task to become subtask: `--from="5" --to="7"`
|
||||
- Move subtask to standalone task: `--from="5.2" --to="7"`
|
||||
- Move subtask to different parent: `--from="5.2" --to="7.3"`
|
||||
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
|
||||
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
|
||||
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
|
||||
|
||||
**Multiple Task Support:**
|
||||
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
|
||||
|
||||
**Validation Features:**
|
||||
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
|
||||
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
|
||||
- Validates source tasks exist before attempting to move them
|
||||
- Ensures proper parent-child relationships are maintained
|
||||
@@ -25,7 +25,6 @@ This document outlines the architecture and usage patterns for interacting with
|
||||
* Implements **retry logic** for specific API errors (`_attemptProviderCallWithRetries`).
|
||||
* Resolves API keys automatically via `_resolveApiKey` (using `resolveEnvVariable`).
|
||||
* Maps requests to the correct provider implementation (in `src/ai-providers/`) via `PROVIDER_FUNCTIONS`.
|
||||
* Returns a structured object containing the primary AI result (`mainResult`) and telemetry data (`telemetryData`). See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for details on how this telemetry data is propagated and handled.
|
||||
|
||||
* **Provider Implementations (`src/ai-providers/*.js`):**
|
||||
* Contain provider-specific wrappers around Vercel AI SDK functions (`generateText`, `generateObject`).
|
||||
|
||||
@@ -42,7 +42,6 @@ alwaysApply: false
|
||||
- Resolves API keys (from `.env` or `session.env`).
|
||||
- Implements fallback and retry logic.
|
||||
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
|
||||
- Telemetry data generated by the AI service layer is propagated upwards through core logic, direct functions, and MCP tools. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the detailed integration pattern.
|
||||
|
||||
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
|
||||
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.
|
||||
@@ -66,9 +65,8 @@ alwaysApply: false
|
||||
- **[`mcp-server/`](mdc:mcp-server/): MCP Server Integration**
|
||||
- **Purpose**: Provides MCP interface using FastMCP.
|
||||
- **Responsibilities** (See also: [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)):
|
||||
- Registers tools (`mcp-server/src/tools/*.js`). Tool `execute` methods **should be wrapped** with the `withNormalizedProjectRoot` HOF (from `tools/utils.js`) to ensure consistent path handling.
|
||||
- The HOF provides a normalized `args.projectRoot` to the `execute` method.
|
||||
- Tool `execute` methods call **direct function wrappers** (`mcp-server/src/core/direct-functions/*.js`), passing the normalized `projectRoot` and other args.
|
||||
- Registers tools (`mcp-server/src/tools/*.js`).
|
||||
- Tool `execute` methods call **direct function wrappers** (`mcp-server/src/core/direct-functions/*.js`).
|
||||
- Direct functions use path utilities (`mcp-server/src/core/utils/`) to resolve paths based on `projectRoot` from session.
|
||||
- Direct functions implement silent mode, logger wrappers, and call core logic functions from `scripts/modules/`.
|
||||
- Manages MCP caching and response formatting.
|
||||
|
||||
@@ -49,7 +49,6 @@ Task Master offers two primary ways to interact:
|
||||
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
|
||||
- Respect dependency chains and task priorities when selecting work
|
||||
- Report progress regularly using `get_tasks` / `task-master list`
|
||||
- Reorganize tasks as needed using `move_task` / `task-master move --from=<id> --to=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to change task hierarchy or ordering
|
||||
|
||||
## Task Complexity Analysis
|
||||
|
||||
@@ -117,7 +116,7 @@ Taskmaster configuration is managed through two main mechanisms:
|
||||
* For MCP/Cursor integration, configure these keys in the `env` section of `.cursor/mcp.json`.
|
||||
* Available keys/variables: See `assets/env.example` or the Configuration section in the command reference (previously linked to `taskmaster.mdc`).
|
||||
|
||||
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `TASKMASTER_LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
|
||||
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
|
||||
**If AI commands FAIL in MCP** verify that the API key for the selected provider is present in the `env` section of `.cursor/mcp.json`.
|
||||
**If AI commands FAIL in CLI** verify that the API key for the selected provider is present in the `.env` file in the root of the project.
|
||||
|
||||
@@ -155,25 +154,6 @@ Taskmaster configuration is managed through two main mechanisms:
|
||||
- Task files are automatically regenerated after dependency changes
|
||||
- Dependencies are visualized with status indicators in task listings and files
|
||||
|
||||
## Task Reorganization
|
||||
|
||||
- Use `move_task` / `task-master move --from=<id> --to=<id>` to move tasks or subtasks within the hierarchy
|
||||
- This command supports several use cases:
|
||||
- Moving a standalone task to become a subtask (e.g., `--from=5 --to=7`)
|
||||
- Moving a subtask to become a standalone task (e.g., `--from=5.2 --to=7`)
|
||||
- Moving a subtask to a different parent (e.g., `--from=5.2 --to=7.3`)
|
||||
- Reordering subtasks within the same parent (e.g., `--from=5.2 --to=5.4`)
|
||||
- Moving a task to a new, non-existent ID position (e.g., `--from=5 --to=25`)
|
||||
- Moving multiple tasks at once using comma-separated IDs (e.g., `--from=10,11,12 --to=16,17,18`)
|
||||
- The system includes validation to prevent data loss:
|
||||
- Allows moving to non-existent IDs by creating placeholder tasks
|
||||
- Prevents moving to existing task IDs that have content (to avoid overwriting)
|
||||
- Validates source tasks exist before attempting to move them
|
||||
- The system maintains proper parent-child relationships and dependency integrity
|
||||
- Task files are automatically regenerated after the move operation
|
||||
- This provides greater flexibility in organizing and refining your task structure as project understanding evolves
|
||||
- This is especially useful when dealing with potential merge conflicts arising from teams creating tasks on separate branches. Solve these conflicts very easily by moving your tasks and keeping theirs.
|
||||
|
||||
## Iterative Subtask Implementation
|
||||
|
||||
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:
|
||||
|
||||
@@ -3,6 +3,7 @@ description: Glossary of other Cursor rules
|
||||
globs: **/*
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Glossary of Task Master Cursor Rules
|
||||
|
||||
This file provides a quick reference to the purpose of each rule file located in the `.cursor/rules` directory.
|
||||
@@ -22,5 +23,4 @@ This file provides a quick reference to the purpose of each rule file located in
|
||||
- **[`tests.mdc`](mdc:.cursor/rules/tests.mdc)**: Guidelines for implementing and maintaining tests for Task Master CLI.
|
||||
- **[`ui.mdc`](mdc:.cursor/rules/ui.mdc)**: Guidelines for implementing and maintaining user interface components.
|
||||
- **[`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)**: Guidelines for implementing utility functions.
|
||||
- **[`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc)**: Guidelines for integrating AI usage telemetry across Task Master.
|
||||
|
||||
|
||||
@@ -188,70 +188,58 @@ execute: async (args, { log, session }) => {
|
||||
- **args**: Validated parameters.
|
||||
- **context**: Contains `{ log, session }` from FastMCP. (Removed `reportProgress`).
|
||||
|
||||
### Standard Tool Execution Pattern with Path Normalization (Updated)
|
||||
### Standard Tool Execution Pattern
|
||||
|
||||
To ensure consistent handling of project paths across different client environments (Windows, macOS, Linux, WSL) and input formats (e.g., `file:///...`, URI encoded paths), all MCP tool `execute` methods that require access to the project root **MUST** be wrapped with the `withNormalizedProjectRoot` Higher-Order Function (HOF).
|
||||
The `execute` method within each MCP tool (in `mcp-server/src/tools/*.js`) should follow this standard pattern:
|
||||
|
||||
This HOF, defined in [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js), performs the following before calling the tool's core logic:
|
||||
|
||||
1. **Determines the Raw Root:** It prioritizes `args.projectRoot` if provided by the client, otherwise it calls `getRawProjectRootFromSession` to extract the path from the session.
|
||||
2. **Normalizes the Path:** It uses the `normalizeProjectRoot` helper to decode URIs, strip `file://` prefixes, fix potential Windows drive letter prefixes (e.g., `/C:/`), convert backslashes (`\`) to forward slashes (`/`), and resolve the path to an absolute path suitable for the server's OS.
|
||||
3. **Injects Normalized Path:** It updates the `args` object by replacing the original `projectRoot` (or adding it) with the normalized, absolute path.
|
||||
4. **Executes Original Logic:** It calls the original `execute` function body, passing the updated `args` object.
|
||||
|
||||
**Implementation Example:**
|
||||
1. **Log Entry**: Log the start of the tool execution with relevant arguments.
|
||||
2. **Get Project Root**: Use the `getProjectRootFromSession(session, log)` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) to extract the project root path from the client session. Fall back to `args.projectRoot` if the session doesn't provide a root.
|
||||
3. **Call Direct Function**: Invoke the corresponding `*Direct` function wrapper (e.g., `listTasksDirect` from [`task-master-core.js`](mdc:mcp-server/src/core/task-master-core.js)), passing an updated `args` object that includes the resolved `projectRoot`. Crucially, the third argument (context) passed to the direct function should **only include `{ log, session }`**. **Do NOT pass `reportProgress`**.
|
||||
```javascript
|
||||
// Example call (applies to both AI and non-AI direct functions now)
|
||||
const result = await someDirectFunction(
|
||||
{ ...args, projectRoot }, // Args including resolved root
|
||||
log, // MCP logger
|
||||
{ session } // Context containing session
|
||||
);
|
||||
```
|
||||
4. **Handle Result**: Receive the result object (`{ success, data/error, fromCache }`) from the `*Direct` function.
|
||||
5. **Format Response**: Pass this result object to the `handleApiResult` utility (from [`tools/utils.js`](mdc:mcp-server/src/tools/utils.js)) for standardized MCP response formatting and error handling.
|
||||
6. **Return**: Return the formatted response object provided by `handleApiResult`.
|
||||
|
||||
```javascript
|
||||
// In mcp-server/src/tools/your-tool.js
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot // <<< Import HOF
|
||||
} from './utils.js';
|
||||
import { yourDirectFunction } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js'; // If needed
|
||||
|
||||
export function registerYourTool(server) {
|
||||
server.addTool({
|
||||
name: "your_tool",
|
||||
description: "...".
|
||||
parameters: z.object({
|
||||
// ... other parameters ...
|
||||
projectRoot: z.string().optional().describe('...') // projectRoot is optional here, HOF handles fallback
|
||||
}),
|
||||
// Wrap the entire execute function
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
// args.projectRoot is now guaranteed to be normalized and absolute
|
||||
const { /* other args */, projectRoot } = args;
|
||||
// Example execute method structure for a tool calling an AI-based direct function
|
||||
import { getProjectRootFromSession, handleApiResult, createErrorResponse } from './utils.js';
|
||||
import { someAIDirectFunction } from '../core/task-master-core.js';
|
||||
|
||||
// ... inside server.addTool({...})
|
||||
execute: async (args, { log, session }) => { // Note: reportProgress is omitted here
|
||||
try {
|
||||
log.info(`Executing your_tool with normalized root: ${projectRoot}`);
|
||||
log.info(`Starting AI tool execution with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Resolve paths using the normalized projectRoot
|
||||
let tasksPath = findTasksJsonPath({ projectRoot, file: args.file }, log);
|
||||
// 1. Get Project Root
|
||||
let rootFolder = getProjectRootFromSession(session, log);
|
||||
if (!rootFolder && args.projectRoot) { // Fallback if needed
|
||||
rootFolder = args.projectRoot;
|
||||
log.info(`Using project root from args as fallback: ${rootFolder}`);
|
||||
}
|
||||
|
||||
// Call direct function, passing normalized projectRoot if needed by direct func
|
||||
const result = await yourDirectFunction(
|
||||
{
|
||||
/* other args */,
|
||||
projectRoot // Pass it if direct function needs it
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
// 2. Call AI-Based Direct Function (passing only log and session in context)
|
||||
const result = await someAIDirectFunction({
|
||||
...args,
|
||||
projectRoot: rootFolder // Ensure projectRoot is explicitly passed
|
||||
}, log, { session }); // Pass session here, NO reportProgress
|
||||
|
||||
// 3. Handle and Format Response
|
||||
return handleApiResult(result, log);
|
||||
|
||||
} catch (error) {
|
||||
log.error(`Error in your_tool: ${error.message}`);
|
||||
log.error(`Error during AI tool execution: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
}) // End HOF wrap
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
By using this HOF, the core logic within the `execute` method and any downstream functions (like `findTasksJsonPath` or direct functions) can reliably expect `args.projectRoot` to be a clean, absolute path suitable for the server environment.
|
||||
|
||||
### Project Initialization Tool
|
||||
|
||||
The `initialize_project` tool allows integrated clients like Cursor to set up a new Task Master project:
|
||||
@@ -522,8 +510,3 @@ Follow these steps to add MCP support for an existing Task Master command (see [
|
||||
// Add more functions as implemented
|
||||
};
|
||||
```
|
||||
|
||||
## Telemetry Integration
|
||||
|
||||
- Direct functions calling core logic that involves AI should receive and pass through `telemetryData` within their successful `data` payload. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the standard pattern.
|
||||
- MCP tools use `handleApiResult`, which ensures the `data` object (potentially including `telemetryData`) from the direct function is correctly included in the final response.
|
||||
|
||||
@@ -3,6 +3,7 @@ description: Guidelines for integrating new features into the Task Master CLI
|
||||
globs: scripts/modules/*.js
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Task Master Feature Integration Guidelines
|
||||
|
||||
## Feature Placement Decision Process
|
||||
@@ -195,8 +196,6 @@ The standard pattern for adding a feature follows this workflow:
|
||||
- ✅ **DO**: If an MCP tool fails with vague errors (e.g., JSON parsing issues like `Unexpected token ... is not valid JSON`), **try running the equivalent CLI command directly in the terminal** (e.g., `task-master expand --all`). CLI output often provides much more specific error messages (like missing function definitions or stack traces from the core logic) that pinpoint the root cause.
|
||||
- ❌ **DON'T**: Rely solely on MCP logs if the error is unclear; use the CLI as a complementary debugging tool for core logic issues.
|
||||
|
||||
- **Telemetry Integration**: Ensure AI calls correctly handle and propagate `telemetryData` as described in [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc).
|
||||
|
||||
```javascript
|
||||
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
|
||||
/**
|
||||
@@ -524,24 +523,14 @@ Integrating Task Master commands with the MCP server (for use by tools like Curs
|
||||
|
||||
4. **Create MCP Tool (`mcp-server/src/tools/`)**:
|
||||
- Create a new file (e.g., `your-command.js`) using **kebab-case**.
|
||||
- Import `zod`, `handleApiResult`, **`withNormalizedProjectRoot` HOF**, and your `yourCommandDirect` function.
|
||||
- Import `zod`, `handleApiResult`, `createErrorResponse`, **`getProjectRootFromSession`**, and your `yourCommandDirect` function.
|
||||
- Implement `registerYourCommandTool(server)`.
|
||||
- **Define parameters**: Make `projectRoot` optional (`z.string().optional().describe(...)`) as the HOF handles fallback.
|
||||
- Consider if this operation should run in the background using `AsyncOperationManager`.
|
||||
- Implement the standard `execute` method **wrapped with `withNormalizedProjectRoot`**:
|
||||
```javascript
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
// args.projectRoot is now normalized
|
||||
const { projectRoot /*, other args */ } = args;
|
||||
// ... resolve tasks path if needed using normalized projectRoot ...
|
||||
const result = await yourCommandDirect(
|
||||
{ /* other args */, projectRoot /* if needed by direct func */ },
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
return handleApiResult(result, log);
|
||||
})
|
||||
```
|
||||
- Define the tool `name` using **snake_case** (e.g., `your_command`).
|
||||
- Define the `parameters` using `zod`. **Crucially, define `projectRoot` as optional**: `projectRoot: z.string().optional().describe(...)`. Include `file` if applicable.
|
||||
- Implement the standard `async execute(args, { log, reportProgress, session })` method:
|
||||
- Get `rootFolder` using `getProjectRootFromSession` (with fallback to `args.projectRoot`).
|
||||
- Call `yourCommandDirect({ ...args, projectRoot: rootFolder }, log)`.
|
||||
- Pass the result to `handleApiResult(result, log, 'Error Message')`.
|
||||
|
||||
5. **Register Tool**: Import and call `registerYourCommandTool` in `mcp-server/src/tools/index.js`.
|
||||
|
||||
@@ -629,3 +618,8 @@ When implementing project initialization commands:
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
@@ -79,7 +79,6 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* **Usage (CLI):** Run without flags to view current configuration and available models. Use set flags to update specific roles. Use `--setup` for guided configuration, including custom models. To set a custom model via flags, use `--set-<role>=<model_id>` along with either `--ollama` or `--openrouter`.
|
||||
* **Notes:** Configuration is stored in `.taskmasterconfig` in the project root. This command/tool modifies that file. Use `listAvailableModels` or `task-master models` to see internally supported models. OpenRouter custom models are validated against their live API. Ollama custom models are not validated live.
|
||||
* **API note:** API keys for selected AI providers (based on their model) need to exist in the mcp.json file to be accessible in MCP context. The API keys must be present in the local .env file for the CLI to be able to read them.
|
||||
* **Model costs:** The costs in supported models are expressed in dollars. An input/output value of 3 is $3.00. A value of 0.8 is $0.80.
|
||||
* **Warning:** DO NOT MANUALLY EDIT THE .taskmasterconfig FILE. Use the included commands either in the MCP or CLI format as needed. Always prioritize MCP tools when available and use the CLI as a fallback.
|
||||
|
||||
---
|
||||
@@ -269,36 +268,11 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Delete unnecessary subtasks or promote a subtask to a top-level task.
|
||||
|
||||
### 17. Move Task (`move_task`)
|
||||
|
||||
* **MCP Tool:** `move_task`
|
||||
* **CLI Command:** `task-master move [options]`
|
||||
* **Description:** `Move a task or subtask to a new position within the task hierarchy.`
|
||||
* **Key Parameters/Options:**
|
||||
* `from`: `Required. ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated for multiple tasks.` (CLI: `--from <id>`)
|
||||
* `to`: `Required. ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated.` (CLI: `--to <id>`)
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Reorganize tasks by moving them within the hierarchy. Supports various scenarios like:
|
||||
* Moving a task to become a subtask
|
||||
* Moving a subtask to become a standalone task
|
||||
* Moving a subtask to a different parent
|
||||
* Reordering subtasks within the same parent
|
||||
* Moving a task to a new, non-existent ID (automatically creates placeholders)
|
||||
* Moving multiple tasks at once with comma-separated IDs
|
||||
* **Validation Features:**
|
||||
* Allows moving tasks to non-existent destination IDs (creates placeholder tasks)
|
||||
* Prevents moving to existing task IDs that already have content (to avoid overwriting)
|
||||
* Validates that source tasks exist before attempting to move them
|
||||
* Maintains proper parent-child relationships
|
||||
* **Example CLI:** `task-master move --from=5.2 --to=7.3` to move subtask 5.2 to become subtask 7.3.
|
||||
* **Example Multi-Move:** `task-master move --from=10,11,12 --to=16,17,18` to move multiple tasks to new positions.
|
||||
* **Common Use:** Resolving merge conflicts in tasks.json when multiple team members create tasks on different branches.
|
||||
|
||||
---
|
||||
|
||||
## Dependency Management
|
||||
|
||||
### 18. Add Dependency (`add_dependency`)
|
||||
### 17. Add Dependency (`add_dependency`)
|
||||
|
||||
* **MCP Tool:** `add_dependency`
|
||||
* **CLI Command:** `task-master add-dependency [options]`
|
||||
@@ -309,7 +283,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`)
|
||||
* **Usage:** Establish the correct order of execution between tasks.
|
||||
|
||||
### 19. Remove Dependency (`remove_dependency`)
|
||||
### 18. Remove Dependency (`remove_dependency`)
|
||||
|
||||
* **MCP Tool:** `remove_dependency`
|
||||
* **CLI Command:** `task-master remove-dependency [options]`
|
||||
@@ -320,7 +294,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Update task relationships when the order of execution changes.
|
||||
|
||||
### 20. Validate Dependencies (`validate_dependencies`)
|
||||
### 19. Validate Dependencies (`validate_dependencies`)
|
||||
|
||||
* **MCP Tool:** `validate_dependencies`
|
||||
* **CLI Command:** `task-master validate-dependencies [options]`
|
||||
@@ -329,7 +303,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
||||
* **Usage:** Audit the integrity of your task dependencies.
|
||||
|
||||
### 21. Fix Dependencies (`fix_dependencies`)
|
||||
### 20. Fix Dependencies (`fix_dependencies`)
|
||||
|
||||
* **MCP Tool:** `fix_dependencies`
|
||||
* **CLI Command:** `task-master fix-dependencies [options]`
|
||||
@@ -342,7 +316,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
|
||||
## Analysis & Reporting
|
||||
|
||||
### 22. Analyze Project Complexity (`analyze_project_complexity`)
|
||||
### 21. Analyze Project Complexity (`analyze_project_complexity`)
|
||||
|
||||
* **MCP Tool:** `analyze_project_complexity`
|
||||
* **CLI Command:** `task-master analyze-complexity [options]`
|
||||
@@ -355,7 +329,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
* **Usage:** Used before breaking down tasks to identify which ones need the most attention.
|
||||
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||
|
||||
### 23. View Complexity Report (`complexity_report`)
|
||||
### 22. View Complexity Report (`complexity_report`)
|
||||
|
||||
* **MCP Tool:** `complexity_report`
|
||||
* **CLI Command:** `task-master complexity-report [options]`
|
||||
@@ -368,7 +342,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
||||
|
||||
## File Management
|
||||
|
||||
### 24. Generate Task Files (`generate`)
|
||||
### 23. Generate Task Files (`generate`)
|
||||
|
||||
* **MCP Tool:** `generate`
|
||||
* **CLI Command:** `task-master generate [options]`
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
---
|
||||
description: Guidelines for integrating AI usage telemetry across Task Master.
|
||||
globs: scripts/modules/**/*.js,mcp-server/src/**/*.js
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# AI Usage Telemetry Integration
|
||||
|
||||
This document outlines the standard pattern for capturing, propagating, and handling AI usage telemetry data (cost, tokens, model, etc.) across the Task Master stack. This ensures consistent telemetry for both CLI and MCP interactions.
|
||||
|
||||
## Overview
|
||||
|
||||
Telemetry data is generated within the unified AI service layer ([`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)) and then passed upwards through the calling functions.
|
||||
|
||||
- **Data Source**: [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js) (specifically its `generateTextService`, `generateObjectService`, etc.) returns an object like `{ mainResult: AI_CALL_OUTPUT, telemetryData: TELEMETRY_OBJECT }`.
|
||||
- **`telemetryData` Object Structure**:
|
||||
```json
|
||||
{
|
||||
"timestamp": "ISO_STRING_DATE",
|
||||
"userId": "USER_ID_FROM_CONFIG",
|
||||
"commandName": "invoking_command_or_tool_name",
|
||||
"modelUsed": "ai_model_id",
|
||||
"providerName": "ai_provider_name",
|
||||
"inputTokens": NUMBER,
|
||||
"outputTokens": NUMBER,
|
||||
"totalTokens": NUMBER,
|
||||
"totalCost": NUMBER, // e.g., 0.012414
|
||||
"currency": "USD" // e.g., "USD"
|
||||
}
|
||||
```
|
||||
|
||||
## Integration Pattern by Layer
|
||||
|
||||
The key principle is that each layer receives telemetry data from the layer below it (if applicable) and passes it to the layer above it, or handles it for display in the case of the CLI.
|
||||
|
||||
### 1. Core Logic Functions (e.g., in `scripts/modules/task-manager/`)
|
||||
|
||||
Functions in this layer that invoke AI services are responsible for handling the `telemetryData` they receive from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
|
||||
|
||||
- **Actions**:
|
||||
1. Call the appropriate AI service function (e.g., `generateObjectService`).
|
||||
- Pass `commandName` (e.g., `add-task`, `expand-task`) and `outputType` (e.g., `cli` or `mcp`) in the `params` object to the AI service. The `outputType` can be derived from context (e.g., presence of `mcpLog`).
|
||||
2. The AI service returns an object, e.g., `aiServiceResponse = { mainResult: {/*AI output*/}, telemetryData: {/*telemetry data*/} }`.
|
||||
3. Extract `aiServiceResponse.mainResult` for the core processing.
|
||||
4. **Must return an object that includes `aiServiceResponse.telemetryData`**.
|
||||
Example: `return { operationSpecificData: /*...*/, telemetryData: aiServiceResponse.telemetryData };`
|
||||
|
||||
- **CLI Output Handling (If Applicable)**:
|
||||
- If the core function also handles CLI output (e.g., it has an `outputFormat` parameter that can be `'text'` or `'cli'`):
|
||||
1. Check if `outputFormat === 'text'` (or `'cli'`).
|
||||
2. If so, and if `aiServiceResponse.telemetryData` is available, call `displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli')` from [`scripts/modules/ui.js`](mdc:scripts/modules/ui.js).
|
||||
- This ensures telemetry is displayed directly to CLI users after the main command output.
|
||||
|
||||
- **Example Snippet (Core Logic in `scripts/modules/task-manager/someAiAction.js`)**:
|
||||
```javascript
|
||||
import { generateObjectService } from '../ai-services-unified.js';
|
||||
import { displayAiUsageSummary } from '../ui.js';
|
||||
|
||||
async function performAiRelatedAction(params, context, outputFormat = 'text') {
|
||||
const { commandNameFromContext, /* other context vars */ } = context;
|
||||
let aiServiceResponse = null;
|
||||
|
||||
try {
|
||||
aiServiceResponse = await generateObjectService({
|
||||
// ... other parameters for AI service ...
|
||||
commandName: commandNameFromContext || 'default-action-name',
|
||||
outputType: context.mcpLog ? 'mcp' : 'cli' // Derive outputType
|
||||
});
|
||||
|
||||
const usefulAiOutput = aiServiceResponse.mainResult.object;
|
||||
// ... do work with usefulAiOutput ...
|
||||
|
||||
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
|
||||
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
|
||||
}
|
||||
|
||||
return {
|
||||
actionData: /* results of processing */,
|
||||
telemetryData: aiServiceResponse.telemetryData
|
||||
};
|
||||
} catch (error) {
|
||||
// ... handle error ...
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Direct Function Wrappers (in `mcp-server/src/core/direct-functions/`)
|
||||
|
||||
These functions adapt core logic for the MCP server, ensuring structured responses.
|
||||
|
||||
- **Actions**:
|
||||
1. Call the corresponding core logic function.
|
||||
- Pass necessary context (e.g., `session`, `mcpLog`, `projectRoot`).
|
||||
- Provide the `commandName` (typically derived from the MCP tool name) and `outputType: 'mcp'` in the context object passed to the core function.
|
||||
- If the core function supports an `outputFormat` parameter, pass `'json'` to suppress CLI-specific UI.
|
||||
2. The core logic function returns an object (e.g., `coreResult = { actionData: ..., telemetryData: ... }`).
|
||||
3. Include `coreResult.telemetryData` as a field within the `data` object of the successful response returned by the direct function.
|
||||
|
||||
- **Example Snippet (Direct Function `someAiActionDirect.js`)**:
|
||||
```javascript
|
||||
import { performAiRelatedAction } from '../../../../scripts/modules/task-manager/someAiAction.js'; // Core function
|
||||
import { createLogWrapper } from '../../tools/utils.js'; // MCP Log wrapper
|
||||
|
||||
export async function someAiActionDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
// ... prepare arguments for core function from args, including args.projectRoot ...
|
||||
|
||||
try {
|
||||
const coreResult = await performAiRelatedAction(
|
||||
{ /* parameters for core function */ },
|
||||
{ // Context for core function
|
||||
session,
|
||||
mcpLog: createLogWrapper(log),
|
||||
projectRoot: args.projectRoot,
|
||||
commandNameFromContext: 'mcp_tool_some_ai_action', // Example command name
|
||||
outputType: 'mcp'
|
||||
},
|
||||
'json' // Request 'json' output format from core function
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
operationSpecificData: coreResult.actionData,
|
||||
telemetryData: coreResult.telemetryData // Pass telemetry through
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
// ... error handling, return { success: false, error: ... } ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. MCP Tools (in `mcp-server/src/tools/`)
|
||||
|
||||
These are the exposed endpoints for MCP clients.
|
||||
|
||||
- **Actions**:
|
||||
1. Call the corresponding direct function wrapper.
|
||||
2. The direct function returns an object structured like `{ success: true, data: { operationSpecificData: ..., telemetryData: ... } }` (or an error object).
|
||||
3. Pass this entire result object to `handleApiResult(result, log)` from [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
|
||||
4. `handleApiResult` ensures that the `data` field from the direct function's response (which correctly includes `telemetryData`) is part of the final MCP response.
|
||||
|
||||
- **Example Snippet (MCP Tool `some_ai_action.js`)**:
|
||||
```javascript
|
||||
import { someAiActionDirect } from '../core/task-master-core.js';
|
||||
import { handleApiResult, withNormalizedProjectRoot } from './utils.js';
|
||||
// ... zod for parameters ...
|
||||
|
||||
export function registerSomeAiActionTool(server) {
|
||||
server.addTool({
|
||||
name: "some_ai_action",
|
||||
// ... description, parameters ...
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
try {
|
||||
const resultFromDirectFunction = await someAiActionDirect(
|
||||
{ /* args including projectRoot */ },
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
return handleApiResult(resultFromDirectFunction, log); // This passes the nested telemetryData through
|
||||
} catch (error) {
|
||||
// ... error handling ...
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 4. CLI Commands (`scripts/modules/commands.js`)
|
||||
|
||||
These define the command-line interface.
|
||||
|
||||
- **Actions**:
|
||||
1. Call the appropriate core logic function.
|
||||
2. Pass `outputFormat: 'text'` (or ensure the core function defaults to text-based output for CLI).
|
||||
3. The core logic function (as per Section 1) is responsible for calling `displayAiUsageSummary` if telemetry data is available and it's in CLI mode.
|
||||
4. The command action itself **should not** call `displayAiUsageSummary` if the core logic function already handles this. This avoids duplicate display.
|
||||
|
||||
- **Example Snippet (CLI Command in `commands.js`)**:
|
||||
```javascript
|
||||
// In scripts/modules/commands.js
|
||||
import { performAiRelatedAction } from './task-manager/someAiAction.js'; // Core function
|
||||
|
||||
programInstance
|
||||
.command('some-cli-ai-action')
|
||||
// ... .option() ...
|
||||
.action(async (options) => {
|
||||
try {
|
||||
const projectRoot = findProjectRoot() || '.'; // Example root finding
|
||||
// ... prepare parameters for core function from command options ...
|
||||
await performAiRelatedAction(
|
||||
{ /* parameters for core function */ },
|
||||
{ // Context for core function
|
||||
projectRoot,
|
||||
commandNameFromContext: 'some-cli-ai-action',
|
||||
outputType: 'cli'
|
||||
},
|
||||
'text' // Explicitly request text output format for CLI
|
||||
);
|
||||
// Core function handles displayAiUsageSummary internally for 'text' outputFormat
|
||||
} catch (error) {
|
||||
// ... error handling ...
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Summary Flow
|
||||
|
||||
The telemetry data flows as follows:
|
||||
|
||||
1. **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)**: Generates `telemetryData` and returns `{ mainResult, telemetryData }`.
|
||||
2. **Core Logic Function**:
|
||||
* Receives `{ mainResult, telemetryData }`.
|
||||
* Uses `mainResult`.
|
||||
* If CLI (`outputFormat: 'text'`), calls `displayAiUsageSummary(telemetryData)`.
|
||||
* Returns `{ operationSpecificData, telemetryData }`.
|
||||
3. **Direct Function Wrapper**:
|
||||
* Receives `{ operationSpecificData, telemetryData }` from core logic.
|
||||
* Returns `{ success: true, data: { operationSpecificData, telemetryData } }`.
|
||||
4. **MCP Tool**:
|
||||
* Receives direct function response.
|
||||
* `handleApiResult` ensures the final MCP response to the client is `{ success: true, data: { operationSpecificData, telemetryData } }`.
|
||||
5. **CLI Command**:
|
||||
* Calls core logic with `outputFormat: 'text'`. Display is handled by core logic.
|
||||
|
||||
This pattern ensures telemetry is captured and appropriately handled/exposed across all interaction modes.
|
||||
@@ -428,69 +428,36 @@ Taskmaster configuration (excluding API keys) is primarily managed through the `
|
||||
|
||||
## MCP Server Tool Utilities (`mcp-server/src/tools/utils.js`)
|
||||
|
||||
These utilities specifically support the implementation and execution of MCP tools.
|
||||
|
||||
- **`normalizeProjectRoot(rawPath, log)`**:
|
||||
- **Purpose**: Takes a raw project root path (potentially URI encoded, with `file://` prefix, Windows slashes) and returns a normalized, absolute path suitable for the server's OS.
|
||||
- **Logic**: Decodes URI, strips `file://`, handles Windows drive prefix (`/C:/`), replaces `\` with `/`, uses `path.resolve()`.
|
||||
- **Usage**: Used internally by `withNormalizedProjectRoot` HOF.
|
||||
|
||||
- **`getRawProjectRootFromSession(session, log)`**:
|
||||
- **Purpose**: Extracts the *raw* project root URI string from the session object (`session.roots[0].uri` or `session.roots.roots[0].uri`) without performing normalization.
|
||||
- **Usage**: Used internally by `withNormalizedProjectRoot` HOF as a fallback if `args.projectRoot` isn't provided.
|
||||
|
||||
- **`withNormalizedProjectRoot(executeFn)`**:
|
||||
- **Purpose**: A Higher-Order Function (HOF) designed to wrap a tool's `execute` method.
|
||||
- **Logic**:
|
||||
1. Determines the raw project root (from `args.projectRoot` or `getRawProjectRootFromSession`).
|
||||
2. Normalizes the raw path using `normalizeProjectRoot`.
|
||||
3. Injects the normalized, absolute path back into the `args` object as `args.projectRoot`.
|
||||
4. Calls the original `executeFn` with the updated `args`.
|
||||
- **Usage**: Should wrap the `execute` function of *every* MCP tool that needs a reliable, normalized project root path.
|
||||
- **Example**:
|
||||
```javascript
|
||||
// In mcp-server/src/tools/your-tool.js
|
||||
import { withNormalizedProjectRoot } from './utils.js';
|
||||
|
||||
export function registerYourTool(server) {
|
||||
server.addTool({
|
||||
// ... name, description, parameters ...
|
||||
execute: withNormalizedProjectRoot(async (args, context) => {
|
||||
// args.projectRoot is now normalized here
|
||||
const { projectRoot /*, other args */ } = args;
|
||||
// ... rest of tool logic using normalized projectRoot ...
|
||||
})
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
- **`handleApiResult(result, log, errorPrefix, processFunction)`**:
|
||||
- **Purpose**: Standardizes the formatting of responses returned by direct functions (`{ success, data/error, fromCache }`) into the MCP response format.
|
||||
- **Usage**: Call this at the end of the tool's `execute` method, passing the result from the direct function call.
|
||||
|
||||
- **`createContentResponse(content)` / `createErrorResponse(errorMessage)`**:
|
||||
- **Purpose**: Helper functions to create the basic MCP response structure for success or error messages.
|
||||
- **Usage**: Used internally by `handleApiResult` and potentially directly for simple responses.
|
||||
|
||||
- **`createLogWrapper(log)`**:
|
||||
- **Purpose**: Creates a logger object wrapper with standard methods (`info`, `warn`, `error`, `debug`, `success`) mapping to the passed MCP `log` object's methods. Ensures compatibility when passing loggers to core functions.
|
||||
- **Usage**: Used within direct functions before passing the `log` object down to core logic that expects the standard method names.
|
||||
|
||||
- **`getCachedOrExecute({ cacheKey, actionFn, log })`**:
|
||||
- **Purpose**: Utility for implementing caching within direct functions. Checks cache for `cacheKey`; if miss, executes `actionFn`, caches successful result, and returns.
|
||||
- **Usage**: Wrap the core logic execution within a direct function call.
|
||||
|
||||
- **`processMCPResponseData(taskOrData, fieldsToRemove)`**:
|
||||
- **Purpose**: Utility to filter potentially sensitive or large fields (like `details`, `testStrategy`) from task objects before sending the response back via MCP.
|
||||
- **Usage**: Passed as the default `processFunction` to `handleApiResult`.
|
||||
- **Purpose**: These utilities specifically support the MCP server tools ([`mcp-server/src/tools/*.js`](mdc:mcp-server/src/tools/*.js)), handling MCP communication patterns, response formatting, caching integration, and the CLI fallback mechanism.
|
||||
- **Refer to [`mcp.mdc`](mdc:.cursor/rules/mcp.mdc)** for detailed usage patterns within the MCP tool `execute` methods and direct function wrappers.
|
||||
|
||||
- **`getProjectRootFromSession(session, log)`**:
|
||||
- **Purpose**: Legacy function to extract *and normalize* the project root from the session. Replaced by the HOF pattern but potentially still used.
|
||||
- **Recommendation**: Prefer using the `withNormalizedProjectRoot` HOF in tools instead of calling this directly.
|
||||
- ✅ **DO**: Call this utility **within the MCP tool's `execute` method** to extract the project root path from the `session` object.
|
||||
- Decodes the `file://` URI and handles potential errors.
|
||||
- Returns the project path string or `null`.
|
||||
- The returned path should then be passed in the `args` object when calling the corresponding `*Direct` function (e.g., `yourDirectFunction({ ...args, projectRoot: rootFolder }, log)`).
|
||||
|
||||
- **`executeTaskMasterCommand(...)`**:
|
||||
- **Purpose**: Executes `task-master` CLI command as a fallback.
|
||||
- **Recommendation**: Deprecated for most uses; prefer direct function calls.
|
||||
- **`handleApiResult(result, log, errorPrefix, processFunction)`**:
|
||||
- ✅ **DO**: Call this from the MCP tool's `execute` method after receiving the result from the `*Direct` function wrapper.
|
||||
- Takes the standard `{ success, data/error, fromCache }` object.
|
||||
- Formats the standard MCP success or error response, including the `fromCache` flag.
|
||||
- Uses `processMCPResponseData` by default to filter response data.
|
||||
|
||||
- **`executeTaskMasterCommand(command, log, args, projectRootRaw)`**:
|
||||
- Executes a Task Master CLI command as a child process.
|
||||
- Handles fallback between global `task-master` and local `node scripts/dev.js`.
|
||||
- ❌ **DON'T**: Use this as the primary method for MCP tools. Prefer direct function calls via `*Direct` wrappers.
|
||||
|
||||
- **`processMCPResponseData(taskOrData, fieldsToRemove)`**:
|
||||
- Filters task data (e.g., removing `details`, `testStrategy`) before sending to the MCP client. Called by `handleApiResult`.
|
||||
|
||||
- **`createContentResponse(content)` / `createErrorResponse(errorMessage)`**:
|
||||
- Formatters for standard MCP success/error responses.
|
||||
|
||||
- **`getCachedOrExecute({ cacheKey, actionFn, log })`**:
|
||||
- ✅ **DO**: Use this utility *inside direct function wrappers* to implement caching.
|
||||
- Checks cache, executes `actionFn` on miss, stores result.
|
||||
- Returns standard `{ success, data/error, fromCache: boolean }`.
|
||||
|
||||
## Export Organization
|
||||
|
||||
|
||||
62
.github/workflows/pre-release.yml
vendored
62
.github/workflows/pre-release.yml
vendored
@@ -1,62 +0,0 @@
|
||||
name: Pre-Release (RC)
|
||||
|
||||
on:
|
||||
workflow_dispatch: # Allows manual triggering from GitHub UI/API
|
||||
|
||||
concurrency: pre-release-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
rc:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'npm'
|
||||
|
||||
- name: Cache node_modules
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
*/*/node_modules
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-node-
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
timeout-minutes: 2
|
||||
|
||||
- name: Enter RC mode
|
||||
run: |
|
||||
npx changeset pre exit || true
|
||||
npx changeset pre enter rc
|
||||
|
||||
- name: Version RC packages
|
||||
run: npx changeset version
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Create Release Candidate Pull Request or Publish Release Candidate to npm
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
publish: npm run release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Exit RC mode
|
||||
run: npx changeset pre exit
|
||||
|
||||
- name: Commit & Push changes
|
||||
uses: actions-js/push@master
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: ${{ github.ref }}
|
||||
message: 'chore: rc version bump'
|
||||
3
.github/workflows/release.yml
vendored
3
.github/workflows/release.yml
vendored
@@ -33,9 +33,6 @@ jobs:
|
||||
run: npm ci
|
||||
timeout-minutes: 2
|
||||
|
||||
- name: Exit pre-release mode (safety check)
|
||||
run: npx changeset pre exit || true
|
||||
|
||||
- name: Create Release Pull Request or Publish to npm
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -61,6 +61,3 @@ dist
|
||||
*.debug
|
||||
init-debug.log
|
||||
dev-debug.log
|
||||
|
||||
# NPMRC
|
||||
.npmrc
|
||||
|
||||
@@ -2,20 +2,20 @@
|
||||
"models": {
|
||||
"main": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-sonnet-4-20250514",
|
||||
"maxTokens": 50000,
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 100000,
|
||||
"temperature": 0.2
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"provider": "xai",
|
||||
"modelId": "grok-3",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 128000,
|
||||
"modelId": "claude-3-5-sonnet-20241022",
|
||||
"maxTokens": 120000,
|
||||
"temperature": 0.2
|
||||
}
|
||||
},
|
||||
@@ -26,7 +26,6 @@
|
||||
"defaultPriority": "medium",
|
||||
"projectName": "Taskmaster",
|
||||
"ollamaBaseUrl": "http://localhost:11434/api",
|
||||
"userId": "1234567890",
|
||||
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
|
||||
}
|
||||
}
|
||||
192
CHANGELOG.md
192
CHANGELOG.md
@@ -1,197 +1,5 @@
|
||||
# task-master-ai
|
||||
|
||||
## 0.14.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
|
||||
|
||||
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
|
||||
|
||||
- You can now add it by running `task-master models --setup` and selecting it.
|
||||
- Ollama is a local model provider, so no API key is required.
|
||||
- Ollama models are available at `http://localhost:11434/api` by default.
|
||||
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
|
||||
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
|
||||
|
||||
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Resolve all issues related to MCP
|
||||
|
||||
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
|
||||
|
||||
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
|
||||
|
||||
- Fixes #477
|
||||
|
||||
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
|
||||
|
||||
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
|
||||
|
||||
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
|
||||
|
||||
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add src directory to exports
|
||||
|
||||
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
|
||||
|
||||
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
|
||||
|
||||
- Fixes issues users where having where they were getting stale data
|
||||
|
||||
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
|
||||
|
||||
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
|
||||
|
||||
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
|
||||
|
||||
- Closes #419
|
||||
|
||||
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
|
||||
|
||||
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
|
||||
|
||||
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
|
||||
|
||||
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
|
||||
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
|
||||
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
|
||||
- Ensures a clean, branded help experience with no repeated content.
|
||||
- Fixes #339
|
||||
|
||||
## 0.14.0-rc.1
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
|
||||
|
||||
- You can now add it by running `task-master models --setup` and selecting it.
|
||||
- Ollama is a local model provider, so no API key is required.
|
||||
- Ollama models are available at `http://localhost:11434/api` by default.
|
||||
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
|
||||
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
|
||||
|
||||
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
|
||||
|
||||
## 0.14.0-rc.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
|
||||
|
||||
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
|
||||
|
||||
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
|
||||
|
||||
- Fixes #477
|
||||
|
||||
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
|
||||
|
||||
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
|
||||
|
||||
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
|
||||
|
||||
- Fixes issues users where having where they were getting stale data
|
||||
|
||||
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
|
||||
|
||||
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
|
||||
|
||||
- Closes #419
|
||||
|
||||
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
|
||||
|
||||
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
|
||||
|
||||
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
|
||||
|
||||
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
|
||||
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
|
||||
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
|
||||
- Ensures a clean, branded help experience with no repeated content.
|
||||
- Fixes #339
|
||||
|
||||
## 0.13.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#399](https://github.com/eyaltoledano/claude-task-master/pull/399) [`734a4fd`](https://github.com/eyaltoledano/claude-task-master/commit/734a4fdcfc89c2e089255618cf940561ad13a3c8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
|
||||
|
||||
## 0.13.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ef782ff`](https://github.com/eyaltoledano/claude-task-master/commit/ef782ff5bd4ceb3ed0dc9ea82087aae5f79ac933) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - feat(expand): Enhance `expand` and `expand-all` commands
|
||||
|
||||
- Integrate `task-complexity-report.json` to automatically determine the number of subtasks and use tailored prompts for expansion based on prior analysis. You no longer need to try copy-pasting the recommended prompt. If it exists, it will use it for you. You can just run `task-master update --id=[id of task] --research` and it will use that prompt automatically. No extra prompt needed.
|
||||
- Change default behavior to _append_ new subtasks to existing ones. Use the `--force` flag to clear existing subtasks before expanding. This is helpful if you need to add more subtasks to a task but you want to do it by the batch from a given prompt. Use force if you want to start fresh with a task's subtasks.
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`87d97bb`](https://github.com/eyaltoledano/claude-task-master/commit/87d97bba00d84e905756d46ef96b2d5b984e0f38) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds support for the OpenRouter AI provider. Users can now configure models available through OpenRouter (requiring an `OPENROUTER_API_KEY`) via the `task-master models` command, granting access to a wide range of additional LLMs. - IMPORTANT FYI ABOUT OPENROUTER: Taskmaster relies on AI SDK, which itself relies on tool use. It looks like **free** models sometimes do not include tool use. For example, Gemini 2.5 pro (free) failed via OpenRouter (no tool use) but worked fine on the paid version of the model. Custom model support for Open Router is considered experimental and likely will not be further improved for some time.
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`1ab836f`](https://github.com/eyaltoledano/claude-task-master/commit/1ab836f191cb8969153593a9a0bd47fc9aa4a831) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds model management and new configuration file .taskmasterconfig which houses the models used for main, research and fallback. Adds models command and setter flags. Adds a --setup flag with an interactive setup. We should be calling this during init. Shows a table of active and available models when models is called without flags. Includes SWE scores and token costs, which are manually entered into the supported_models.json, the new place where models are defined for support. Config-manager.js is the core module responsible for managing the new config."
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`c8722b0`](https://github.com/eyaltoledano/claude-task-master/commit/c8722b0a7a443a73b95d1bcd4a0b68e0fce2a1cd) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds custom model ID support for Ollama and OpenRouter providers.
|
||||
|
||||
- Adds the `--ollama` and `--openrouter` flags to `task-master models --set-<role>` command to set models for those providers outside of the support models list.
|
||||
- Updated `task-master models --setup` interactive mode with options to explicitly enter custom Ollama or OpenRouter model IDs.
|
||||
- Implemented live validation against OpenRouter API (`/api/v1/models`) when setting a custom OpenRouter model ID (via flag or setup).
|
||||
- Refined logic to prioritize explicit provider flags/choices over internal model list lookups in case of ID conflicts.
|
||||
- Added warnings when setting custom/unvalidated models.
|
||||
- We obviously don't recommend going with a custom, unproven model. If you do and find performance is good, please let us know so we can add it to the list of supported models.
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`2517bc1`](https://github.com/eyaltoledano/claude-task-master/commit/2517bc112c9a497110f3286ca4bfb4130c9addcb) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Integrate OpenAI as a new AI provider. - Enhance `models` command/tool to display API key status. - Implement model-specific `maxTokens` override based on `supported-models.json` to save you if you use an incorrect max token value.
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`9a48278`](https://github.com/eyaltoledano/claude-task-master/commit/9a482789f7894f57f655fb8d30ba68542bd0df63) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Tweaks Perplexity AI calls for research mode to max out input tokens and get day-fresh information - Forces temp at 0.1 for highly deterministic output, no variations - Adds a system prompt to further improve the output - Correctly uses the maximum input tokens (8,719, used 8,700) for perplexity - Specificies to use a high degree of research across the web - Specifies to use information that is as fresh as today; this support stuff like capturing brand new announcements like new GPT models and being able to query for those in research. 🔥
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`842eaf7`](https://github.com/eyaltoledano/claude-task-master/commit/842eaf722498ddf7307800b4cdcef4ac4fd7e5b0) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - - Add support for Google Gemini models via Vercel AI SDK integration.
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ed79d4f`](https://github.com/eyaltoledano/claude-task-master/commit/ed79d4f4735dfab4124fa189214c0bd5e23a6860) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add xAI provider and Grok models support
|
||||
|
||||
- [#378](https://github.com/eyaltoledano/claude-task-master/pull/378) [`ad89253`](https://github.com/eyaltoledano/claude-task-master/commit/ad89253e313a395637aa48b9f92cc39b1ef94ad8) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Better support for file paths on Windows, Linux & WSL.
|
||||
|
||||
- Standardizes handling of different path formats (URI encoded, Windows, Linux, WSL).
|
||||
- Ensures tools receive a clean, absolute path suitable for the server OS.
|
||||
- Simplifies tool implementation by centralizing normalization logic.
|
||||
|
||||
- [#285](https://github.com/eyaltoledano/claude-task-master/pull/285) [`2acba94`](https://github.com/eyaltoledano/claude-task-master/commit/2acba945c0afee9460d8af18814c87e80f747e9f) Thanks [@neno-is-ooo](https://github.com/neno-is-ooo)! - Add integration for Roo Code
|
||||
|
||||
- [#378](https://github.com/eyaltoledano/claude-task-master/pull/378) [`d63964a`](https://github.com/eyaltoledano/claude-task-master/commit/d63964a10eed9be17856757661ff817ad6bacfdc) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improved update-subtask - Now it has context about the parent task details - It also has context about the subtask before it and the subtask after it (if they exist) - Not passing all subtasks to stay token efficient
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`5f504fa`](https://github.com/eyaltoledano/claude-task-master/commit/5f504fafb8bdaa0043c2d20dee8bbb8ec2040d85) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improve and adjust `init` command for robustness and updated dependencies.
|
||||
|
||||
- **Update Initialization Dependencies:** Ensure newly initialized projects (`task-master init`) include all required AI SDK dependencies (`@ai-sdk/*`, `ai`, provider wrappers) in their `package.json` for out-of-the-box AI feature compatibility. Remove unnecessary dependencies (e.g., `uuid`) from the init template.
|
||||
- **Silence `npm install` during `init`:** Prevent `npm install` output from interfering with non-interactive/MCP initialization by suppressing its stdio in silent mode.
|
||||
- **Improve Conditional Model Setup:** Reliably skip interactive `models --setup` during non-interactive `init` runs (e.g., `init -y` or MCP) by checking `isSilentMode()` instead of passing flags.
|
||||
- **Refactor `init.js`:** Remove internal `isInteractive` flag logic.
|
||||
- **Update `init` Instructions:** Tweak the "Getting Started" text displayed after `init`.
|
||||
- **Fix MCP Server Launch:** Update `.cursor/mcp.json` template to use `node ./mcp-server/server.js` instead of `npx task-master-mcp`.
|
||||
- **Update Default Model:** Change the default main model in the `.taskmasterconfig` template.
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`96aeeff`](https://github.com/eyaltoledano/claude-task-master/commit/96aeeffc195372722c6a07370540e235bfe0e4d8) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue with add-task which did not use the manually defined properties and still needlessly hit the AI endpoint.
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`5aea93d`](https://github.com/eyaltoledano/claude-task-master/commit/5aea93d4c0490c242d7d7042a210611977848e0a) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue that prevented remove-subtask with comma separated tasks/subtasks from being deleted (only the first ID was being deleted). Closes #140
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`66ac9ab`](https://github.com/eyaltoledano/claude-task-master/commit/66ac9ab9f66d006da518d6e8a3244e708af2764d) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improves next command to be subtask-aware - The logic for determining the "next task" (findNextTask function, used by task-master next and the next_task MCP tool) has been significantly improved. Previously, it only considered top-level tasks, making its recommendation less useful when a parent task containing subtasks was already marked 'in-progress'. - The updated logic now prioritizes finding the next available subtask within any 'in-progress' parent task, considering subtask dependencies and priority. - If no suitable subtask is found within active parent tasks, it falls back to recommending the next eligible top-level task based on the original criteria (status, dependencies, priority).
|
||||
|
||||
This change makes the next command much more relevant and helpful during the implementation phase of complex tasks.
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ca7b045`](https://github.com/eyaltoledano/claude-task-master/commit/ca7b0457f1dc65fd9484e92527d9fd6d69db758d) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--status` flag to `show` command to filter displayed subtasks.
|
||||
|
||||
- [#328](https://github.com/eyaltoledano/claude-task-master/pull/328) [`5a2371b`](https://github.com/eyaltoledano/claude-task-master/commit/5a2371b7cc0c76f5e95d43921c1e8cc8081bf14e) Thanks [@knoxgraeme](https://github.com/knoxgraeme)! - Fix --task to --num-tasks in ui + related tests - issue #324
|
||||
|
||||
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`6cb213e`](https://github.com/eyaltoledano/claude-task-master/commit/6cb213ebbd51116ae0688e35b575d09443d17c3b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds a 'models' CLI and MCP command to get the current model configuration, available models, and gives the ability to set main/research/fallback models." - In the CLI, `task-master models` shows the current models config. Using the `--setup` flag launches an interactive set up that allows you to easily select the models you want to use for each of the three roles. Use `q` during the interactive setup to cancel the setup. - In the MCP, responses are simplified in RESTful format (instead of the full CLI output). The agent can use the `models` tool with different arguments, including `listAvailableModels` to get available models. Run without arguments, it will return the current configuration. Arguments are available to set the model for each of the three roles. This allows you to manage Taskmaster AI providers and models directly from either the CLI or MCP or both. - Updated the CLI help menu when you run `task-master` to include missing commands and .taskmasterconfig information. - Adds `--research` flag to `add-task` so you can hit up Perplexity right from the add-task flow, rather than having to add a task and then update it.
|
||||
|
||||
## 0.12.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -47,7 +47,7 @@ npm install task-master-ai
|
||||
task-master init
|
||||
|
||||
# If installed locally
|
||||
npx task-master init
|
||||
npx task-master-init
|
||||
```
|
||||
|
||||
This will prompt you for project details and set up a new project with the necessary files and structure.
|
||||
|
||||
17
README.md
17
README.md
@@ -11,20 +11,8 @@ A task management system for AI-driven development with Claude, designed to work
|
||||
|
||||
## Requirements
|
||||
|
||||
Taskmaster utilizes AI across several commands, and those require a separate API key. You can use a variety of models from different AI providers provided you add your API keys. For example, if you want to use Claude 3.7, you'll need an Anthropic API key.
|
||||
|
||||
You can define 3 types of models to be used: the main model, the research model, and the fallback model (in case either the main or research fail). Whatever model you use, its provider API key must be present in either mcp.json or .env.
|
||||
|
||||
At least one (1) of the following is required:
|
||||
|
||||
- Anthropic API key (Claude API)
|
||||
- OpenAI API key
|
||||
- Google Gemini API key
|
||||
- Perplexity API key (for research model)
|
||||
- xAI API Key (for research or main model)
|
||||
- OpenRouter API Key (for research or main model)
|
||||
|
||||
Using the research model is optional but highly recommended. You will need at least ONE API key. Adding all API keys enables you to seamlessly switch between model providers at will.
|
||||
- OpenAI SDK (for Perplexity API integration, optional)
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -48,8 +36,7 @@ MCP (Model Control Protocol) provides the easiest way to get started with Task M
|
||||
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
|
||||
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
|
||||
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
|
||||
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE",
|
||||
"OLLAMA_API_KEY": "YOUR_OLLAMA_API_KEY_HERE"
|
||||
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-5-sonnet-20240620",
|
||||
"maxTokens": 8192,
|
||||
"modelId": "claude-3.5-sonnet-20240620",
|
||||
"maxTokens": 120000,
|
||||
"temperature": 0.1
|
||||
}
|
||||
},
|
||||
|
||||
@@ -198,7 +198,7 @@ alwaysApply: true
|
||||
- **MAX_TOKENS** (Default: `"4000"`): Maximum tokens for responses (Example: `MAX_TOKENS=8000`)
|
||||
- **TEMPERATURE** (Default: `"0.7"`): Temperature for model responses (Example: `TEMPERATURE=0.5`)
|
||||
- **DEBUG** (Default: `"false"`): Enable debug logging (Example: `DEBUG=true`)
|
||||
- **TASKMASTER_LOG_LEVEL** (Default: `"info"`): Console output level (Example: `TASKMASTER_LOG_LEVEL=debug`)
|
||||
- **LOG_LEVEL** (Default: `"info"`): Console output level (Example: `LOG_LEVEL=debug`)
|
||||
- **DEFAULT_SUBTASKS** (Default: `"3"`): Default subtask count (Example: `DEFAULT_SUBTASKS=5`)
|
||||
- **DEFAULT_PRIORITY** (Default: `"medium"`): Default priority (Example: `DEFAULT_PRIORITY=high`)
|
||||
- **PROJECT_NAME** (Default: `"MCP SaaS MVP"`): Project name in metadata (Example: `PROJECT_NAME=My Awesome Project`)
|
||||
|
||||
413
assets/AGENTS.md
413
assets/AGENTS.md
@@ -1,413 +0,0 @@
|
||||
# Task Master AI - Claude Code Integration Guide
|
||||
|
||||
## Essential Commands
|
||||
|
||||
### Core Workflow Commands
|
||||
|
||||
```bash
|
||||
# Project Setup
|
||||
task-master init # Initialize Task Master in current project
|
||||
task-master parse-prd scripts/prd.txt # Generate tasks from PRD document
|
||||
task-master models --setup # Configure AI models interactively
|
||||
|
||||
# Daily Development Workflow
|
||||
task-master list # Show all tasks with status
|
||||
task-master next # Get next available task to work on
|
||||
task-master show <id> # View detailed task information (e.g., task-master show 1.2)
|
||||
task-master set-status --id=<id> --status=done # Mark task complete
|
||||
|
||||
# Task Management
|
||||
task-master add-task --prompt="description" --research # Add new task with AI assistance
|
||||
task-master expand --id=<id> --research --force # Break task into subtasks
|
||||
task-master update-task --id=<id> --prompt="changes" # Update specific task
|
||||
task-master update --from=<id> --prompt="changes" # Update multiple tasks from ID onwards
|
||||
task-master update-subtask --id=<id> --prompt="notes" # Add implementation notes to subtask
|
||||
|
||||
# Analysis & Planning
|
||||
task-master analyze-complexity --research # Analyze task complexity
|
||||
task-master complexity-report # View complexity analysis
|
||||
task-master expand --all --research # Expand all eligible tasks
|
||||
|
||||
# Dependencies & Organization
|
||||
task-master add-dependency --id=<id> --depends-on=<id> # Add task dependency
|
||||
task-master move --from=<id> --to=<id> # Reorganize task hierarchy
|
||||
task-master validate-dependencies # Check for dependency issues
|
||||
task-master generate # Update task markdown files (usually auto-called)
|
||||
```
|
||||
|
||||
## Key Files & Project Structure
|
||||
|
||||
### Core Files
|
||||
|
||||
- `tasks/tasks.json` - Main task data file (auto-managed)
|
||||
- `.taskmasterconfig` - AI model configuration (use `task-master models` to modify)
|
||||
- `scripts/prd.txt` - Product Requirements Document for parsing
|
||||
- `tasks/*.txt` - Individual task files (auto-generated from tasks.json)
|
||||
- `.env` - API keys for CLI usage
|
||||
|
||||
### Claude Code Integration Files
|
||||
|
||||
- `CLAUDE.md` - Auto-loaded context for Claude Code (this file)
|
||||
- `.claude/settings.json` - Claude Code tool allowlist and preferences
|
||||
- `.claude/commands/` - Custom slash commands for repeated workflows
|
||||
- `.mcp.json` - MCP server configuration (project-specific)
|
||||
|
||||
### Directory Structure
|
||||
|
||||
```
|
||||
project/
|
||||
├── tasks/
|
||||
│ ├── tasks.json # Main task database
|
||||
│ ├── task-1.md # Individual task files
|
||||
│ └── task-2.md
|
||||
├── scripts/
|
||||
│ ├── prd.txt # Product requirements
|
||||
│ └── task-complexity-report.json
|
||||
├── .claude/
|
||||
│ ├── settings.json # Claude Code configuration
|
||||
│ └── commands/ # Custom slash commands
|
||||
├── .taskmasterconfig # AI models & settings
|
||||
├── .env # API keys
|
||||
├── .mcp.json # MCP configuration
|
||||
└── CLAUDE.md # This file - auto-loaded by Claude Code
|
||||
```
|
||||
|
||||
## MCP Integration
|
||||
|
||||
Task Master provides an MCP server that Claude Code can connect to. Configure in `.mcp.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"task-master-ai": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
|
||||
"env": {
|
||||
"ANTHROPIC_API_KEY": "your_key_here",
|
||||
"PERPLEXITY_API_KEY": "your_key_here",
|
||||
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
|
||||
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
|
||||
"XAI_API_KEY": "XAI_API_KEY_HERE",
|
||||
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
|
||||
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
|
||||
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
|
||||
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Essential MCP Tools
|
||||
|
||||
```javascript
|
||||
help; // = shows available taskmaster commands
|
||||
// Project setup
|
||||
initialize_project; // = task-master init
|
||||
parse_prd; // = task-master parse-prd
|
||||
|
||||
// Daily workflow
|
||||
get_tasks; // = task-master list
|
||||
next_task; // = task-master next
|
||||
get_task; // = task-master show <id>
|
||||
set_task_status; // = task-master set-status
|
||||
|
||||
// Task management
|
||||
add_task; // = task-master add-task
|
||||
expand_task; // = task-master expand
|
||||
update_task; // = task-master update-task
|
||||
update_subtask; // = task-master update-subtask
|
||||
update; // = task-master update
|
||||
|
||||
// Analysis
|
||||
analyze_project_complexity; // = task-master analyze-complexity
|
||||
complexity_report; // = task-master complexity-report
|
||||
```
|
||||
|
||||
## Claude Code Workflow Integration
|
||||
|
||||
### Standard Development Workflow
|
||||
|
||||
#### 1. Project Initialization
|
||||
|
||||
```bash
|
||||
# Initialize Task Master
|
||||
task-master init
|
||||
|
||||
# Create or obtain PRD, then parse it
|
||||
task-master parse-prd scripts/prd.txt
|
||||
|
||||
# Analyze complexity and expand tasks
|
||||
task-master analyze-complexity --research
|
||||
task-master expand --all --research
|
||||
```
|
||||
|
||||
If tasks already exist, another PRD can be parsed (with new information only!) using parse-prd with --append flag. This will add the generated tasks to the existing list of tasks..
|
||||
|
||||
#### 2. Daily Development Loop
|
||||
|
||||
```bash
|
||||
# Start each session
|
||||
task-master next # Find next available task
|
||||
task-master show <id> # Review task details
|
||||
|
||||
# During implementation, check in code context into the tasks and subtasks
|
||||
task-master update-subtask --id=<id> --prompt="implementation notes..."
|
||||
|
||||
# Complete tasks
|
||||
task-master set-status --id=<id> --status=done
|
||||
```
|
||||
|
||||
#### 3. Multi-Claude Workflows
|
||||
|
||||
For complex projects, use multiple Claude Code sessions:
|
||||
|
||||
```bash
|
||||
# Terminal 1: Main implementation
|
||||
cd project && claude
|
||||
|
||||
# Terminal 2: Testing and validation
|
||||
cd project-test-worktree && claude
|
||||
|
||||
# Terminal 3: Documentation updates
|
||||
cd project-docs-worktree && claude
|
||||
```
|
||||
|
||||
### Custom Slash Commands
|
||||
|
||||
Create `.claude/commands/taskmaster-next.md`:
|
||||
|
||||
```markdown
|
||||
Find the next available Task Master task and show its details.
|
||||
|
||||
Steps:
|
||||
|
||||
1. Run `task-master next` to get the next task
|
||||
2. If a task is available, run `task-master show <id>` for full details
|
||||
3. Provide a summary of what needs to be implemented
|
||||
4. Suggest the first implementation step
|
||||
```
|
||||
|
||||
Create `.claude/commands/taskmaster-complete.md`:
|
||||
|
||||
```markdown
|
||||
Complete a Task Master task: $ARGUMENTS
|
||||
|
||||
Steps:
|
||||
|
||||
1. Review the current task with `task-master show $ARGUMENTS`
|
||||
2. Verify all implementation is complete
|
||||
3. Run any tests related to this task
|
||||
4. Mark as complete: `task-master set-status --id=$ARGUMENTS --status=done`
|
||||
5. Show the next available task with `task-master next`
|
||||
```
|
||||
|
||||
## Tool Allowlist Recommendations
|
||||
|
||||
Add to `.claude/settings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"allowedTools": [
|
||||
"Edit",
|
||||
"Bash(task-master *)",
|
||||
"Bash(git commit:*)",
|
||||
"Bash(git add:*)",
|
||||
"Bash(npm run *)",
|
||||
"mcp__task_master_ai__*"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration & Setup
|
||||
|
||||
### API Keys Required
|
||||
|
||||
At least **one** of these API keys must be configured:
|
||||
|
||||
- `ANTHROPIC_API_KEY` (Claude models) - **Recommended**
|
||||
- `PERPLEXITY_API_KEY` (Research features) - **Highly recommended**
|
||||
- `OPENAI_API_KEY` (GPT models)
|
||||
- `GOOGLE_API_KEY` (Gemini models)
|
||||
- `MISTRAL_API_KEY` (Mistral models)
|
||||
- `OPENROUTER_API_KEY` (Multiple models)
|
||||
- `XAI_API_KEY` (Grok models)
|
||||
|
||||
An API key is required for any provider used across any of the 3 roles defined in the `models` command.
|
||||
|
||||
### Model Configuration
|
||||
|
||||
```bash
|
||||
# Interactive setup (recommended)
|
||||
task-master models --setup
|
||||
|
||||
# Set specific models
|
||||
task-master models --set-main claude-3-5-sonnet-20241022
|
||||
task-master models --set-research perplexity-llama-3.1-sonar-large-128k-online
|
||||
task-master models --set-fallback gpt-4o-mini
|
||||
```
|
||||
|
||||
## Task Structure & IDs
|
||||
|
||||
### Task ID Format
|
||||
|
||||
- Main tasks: `1`, `2`, `3`, etc.
|
||||
- Subtasks: `1.1`, `1.2`, `2.1`, etc.
|
||||
- Sub-subtasks: `1.1.1`, `1.1.2`, etc.
|
||||
|
||||
### Task Status Values
|
||||
|
||||
- `pending` - Ready to work on
|
||||
- `in-progress` - Currently being worked on
|
||||
- `done` - Completed and verified
|
||||
- `deferred` - Postponed
|
||||
- `cancelled` - No longer needed
|
||||
- `blocked` - Waiting on external factors
|
||||
|
||||
### Task Fields
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "1.2",
|
||||
"title": "Implement user authentication",
|
||||
"description": "Set up JWT-based auth system",
|
||||
"status": "pending",
|
||||
"priority": "high",
|
||||
"dependencies": ["1.1"],
|
||||
"details": "Use bcrypt for hashing, JWT for tokens...",
|
||||
"testStrategy": "Unit tests for auth functions, integration tests for login flow",
|
||||
"subtasks": []
|
||||
}
|
||||
```
|
||||
|
||||
## Claude Code Best Practices with Task Master
|
||||
|
||||
### Context Management
|
||||
|
||||
- Use `/clear` between different tasks to maintain focus
|
||||
- This CLAUDE.md file is automatically loaded for context
|
||||
- Use `task-master show <id>` to pull specific task context when needed
|
||||
|
||||
### Iterative Implementation
|
||||
|
||||
1. `task-master show <subtask-id>` - Understand requirements
|
||||
2. Explore codebase and plan implementation
|
||||
3. `task-master update-subtask --id=<id> --prompt="detailed plan"` - Log plan
|
||||
4. `task-master set-status --id=<id> --status=in-progress` - Start work
|
||||
5. Implement code following logged plan
|
||||
6. `task-master update-subtask --id=<id> --prompt="what worked/didn't work"` - Log progress
|
||||
7. `task-master set-status --id=<id> --status=done` - Complete task
|
||||
|
||||
### Complex Workflows with Checklists
|
||||
|
||||
For large migrations or multi-step processes:
|
||||
|
||||
1. Create a markdown PRD file describing the new changes: `touch task-migration-checklist.md` (prds can be .txt or .md)
|
||||
2. Use Taskmaster to parse the new prd with `task-master parse-prd --append` (also available in MCP)
|
||||
3. Use Taskmaster to expand the newly generated tasks into subtasks. Consdier using `analyze-complexity` with the correct --to and --from IDs (the new ids) to identify the ideal subtask amounts for each task. Then expand them.
|
||||
4. Work through items systematically, checking them off as completed
|
||||
5. Use `task-master update-subtask` to log progress on each task/subtask and/or updating/researching them before/during implementation if getting stuck
|
||||
|
||||
### Git Integration
|
||||
|
||||
Task Master works well with `gh` CLI:
|
||||
|
||||
```bash
|
||||
# Create PR for completed task
|
||||
gh pr create --title "Complete task 1.2: User authentication" --body "Implements JWT auth system as specified in task 1.2"
|
||||
|
||||
# Reference task in commits
|
||||
git commit -m "feat: implement JWT auth (task 1.2)"
|
||||
```
|
||||
|
||||
### Parallel Development with Git Worktrees
|
||||
|
||||
```bash
|
||||
# Create worktrees for parallel task development
|
||||
git worktree add ../project-auth feature/auth-system
|
||||
git worktree add ../project-api feature/api-refactor
|
||||
|
||||
# Run Claude Code in each worktree
|
||||
cd ../project-auth && claude # Terminal 1: Auth work
|
||||
cd ../project-api && claude # Terminal 2: API work
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### AI Commands Failing
|
||||
|
||||
```bash
|
||||
# Check API keys are configured
|
||||
cat .env # For CLI usage
|
||||
|
||||
# Verify model configuration
|
||||
task-master models
|
||||
|
||||
# Test with different model
|
||||
task-master models --set-fallback gpt-4o-mini
|
||||
```
|
||||
|
||||
### MCP Connection Issues
|
||||
|
||||
- Check `.mcp.json` configuration
|
||||
- Verify Node.js installation
|
||||
- Use `--mcp-debug` flag when starting Claude Code
|
||||
- Use CLI as fallback if MCP unavailable
|
||||
|
||||
### Task File Sync Issues
|
||||
|
||||
```bash
|
||||
# Regenerate task files from tasks.json
|
||||
task-master generate
|
||||
|
||||
# Fix dependency issues
|
||||
task-master fix-dependencies
|
||||
```
|
||||
|
||||
DO NOT RE-INITIALIZE. That will not do anything beyond re-adding the same Taskmaster core files.
|
||||
|
||||
## Important Notes
|
||||
|
||||
### AI-Powered Operations
|
||||
|
||||
These commands make AI calls and may take up to a minute:
|
||||
|
||||
- `parse_prd` / `task-master parse-prd`
|
||||
- `analyze_project_complexity` / `task-master analyze-complexity`
|
||||
- `expand_task` / `task-master expand`
|
||||
- `expand_all` / `task-master expand --all`
|
||||
- `add_task` / `task-master add-task`
|
||||
- `update` / `task-master update`
|
||||
- `update_task` / `task-master update-task`
|
||||
- `update_subtask` / `task-master update-subtask`
|
||||
|
||||
### File Management
|
||||
|
||||
- Never manually edit `tasks.json` - use commands instead
|
||||
- Never manually edit `.taskmasterconfig` - use `task-master models`
|
||||
- Task markdown files in `tasks/` are auto-generated
|
||||
- Run `task-master generate` after manual changes to tasks.json
|
||||
|
||||
### Claude Code Session Management
|
||||
|
||||
- Use `/clear` frequently to maintain focused context
|
||||
- Create custom slash commands for repeated Task Master workflows
|
||||
- Configure tool allowlist to streamline permissions
|
||||
- Use headless mode for automation: `claude -p "task-master next"`
|
||||
|
||||
### Multi-Task Updates
|
||||
|
||||
- Use `update --from=<id>` to update multiple future tasks
|
||||
- Use `update-task --id=<id>` for single task updates
|
||||
- Use `update-subtask --id=<id>` for implementation logging
|
||||
|
||||
### Research Mode
|
||||
|
||||
- Add `--research` flag for research-based AI enhancement
|
||||
- Requires a research model API key like Perplexity (`PERPLEXITY_API_KEY`) in environment
|
||||
- Provides more informed task creation and updates
|
||||
- Recommended for complex technical tasks
|
||||
|
||||
---
|
||||
|
||||
_This guide ensures Claude Code has immediate access to Task Master's essential functionality for agentic development workflows._
|
||||
@@ -1,9 +1,8 @@
|
||||
# API Keys (Required to enable respective provider)
|
||||
ANTHROPIC_API_KEY="your_anthropic_api_key_here" # Required: Format: sk-ant-api03-...
|
||||
PERPLEXITY_API_KEY="your_perplexity_api_key_here" # Optional: Format: pplx-...
|
||||
OPENAI_API_KEY="your_openai_api_key_here" # Optional, for OpenAI/OpenRouter models. Format: sk-proj-...
|
||||
GOOGLE_API_KEY="your_google_api_key_here" # Optional, for Google Gemini models.
|
||||
MISTRAL_API_KEY="your_mistral_key_here" # Optional, for Mistral AI models.
|
||||
XAI_API_KEY="YOUR_XAI_KEY_HERE" # Optional, for xAI AI models.
|
||||
AZURE_OPENAI_API_KEY="your_azure_key_here" # Optional, for Azure OpenAI models (requires endpoint in .taskmasterconfig).
|
||||
OLLAMA_API_KEY="your_ollama_api_key_here" # Optional: For remote Ollama servers that require authentication.
|
||||
ANTHROPIC_API_KEY=your_anthropic_api_key_here # Required: Format: sk-ant-api03-...
|
||||
PERPLEXITY_API_KEY=your_perplexity_api_key_here # Optional: Format: pplx-...
|
||||
OPENAI_API_KEY=your_openai_api_key_here # Optional, for OpenAI/OpenRouter models. Format: sk-proj-...
|
||||
GOOGLE_API_KEY=your_google_api_key_here # Optional, for Google Gemini models.
|
||||
MISTRAL_API_KEY=your_mistral_key_here # Optional, for Mistral AI models.
|
||||
XAI_API_KEY=YOUR_XAI_KEY_HERE # Optional, for xAI AI models.
|
||||
AZURE_OPENAI_API_KEY=your_azure_key_here # Optional, for Azure OpenAI models (requires endpoint in .taskmasterconfig).
|
||||
@@ -39,7 +39,7 @@
|
||||
{
|
||||
"slug": "debug",
|
||||
"name": "Debug",
|
||||
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
|
||||
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mdode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
|
||||
"customInstructions": "Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.",
|
||||
"groups": [
|
||||
"read",
|
||||
|
||||
@@ -31,7 +31,7 @@ Task Master configuration is now managed through two primary methods:
|
||||
- Create a `.env` file in your project root for CLI usage.
|
||||
- See `assets/env.example` for required key names.
|
||||
|
||||
**Important:** Settings like `MODEL`, `MAX_TOKENS`, `TEMPERATURE`, `TASKMASTER_LOG_LEVEL`, etc., are **no longer set via `.env`**. Use `task-master models --setup` instead.
|
||||
**Important:** Settings like `MODEL`, `MAX_TOKENS`, `TEMPERATURE`, `LOG_LEVEL`, etc., are **no longer set via `.env`**. Use `task-master models --setup` instead.
|
||||
|
||||
## How It Works
|
||||
|
||||
@@ -200,7 +200,7 @@ Notes:
|
||||
|
||||
## Logging
|
||||
|
||||
The script supports different logging levels controlled by the `TASKMASTER_LOG_LEVEL` environment variable:
|
||||
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
|
||||
|
||||
- `debug`: Detailed information, typically useful for troubleshooting
|
||||
- `info`: Confirmation that things are working as expected (default)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,368 +0,0 @@
|
||||
We want to refine how Task Master handles AI model token limits to be more precise, by:
|
||||
|
||||
1. Distinguishing between `maxInputTokens` and `maxOutputTokens` in the configuration.
|
||||
2. Dynamically adjusting the `maxOutputTokens` for an API call based on the actual prompt length to stay within the model's total context window (or respecting separate input/output limits if the API and model support that).
|
||||
3. Ensuring that `ai-services-unified.js` uses these more granular limits.
|
||||
|
||||
This is a good improvement for both cost control and preventing errors.
|
||||
|
||||
Here's a plan:
|
||||
|
||||
**Phase 1: Configuration and Core Logic Updates**
|
||||
|
||||
1. **Update `.taskmasterconfig` Structure:**
|
||||
- I'll modify the `models` section in your `.taskmasterconfig`. For each role (`main`, `research`, `fallback`), `maxTokens` will be replaced with `maxInputTokens` and `maxOutputTokens`.
|
||||
- We'll need to decide on reasonable default values for these new fields. We can look at the current `maxTokens` and the model's known limits to make an initial guess.
|
||||
2. **Update `MODEL_MAP` in `ai-services-unified.js`:**
|
||||
- This array already stores cost data. We need to ensure it also stores the _absolute_ maximum input and output tokens for each model listed (e.g., `model_max_input_tokens`, `model_max_output_tokens`). If these fields are not present, they will need to be added. The values in `.taskmasterconfig` will then represent user-defined operational limits, which should ideally be validated against these absolute maximums.
|
||||
3. **Update `config-manager.js`:**
|
||||
- Getter functions like `getParametersForRole` will be updated to fetch `maxInputTokens` and `maxOutputTokens` instead of the singular `maxTokens`.
|
||||
- New getters might be needed if we want to access the model's absolute limits directly from `MODEL_MAP` via `config-manager.js`.
|
||||
4. **Update `ai-services-unified.js` (`_unifiedServiceRunner`):**
|
||||
- **Token Counting:** This is a crucial step. Before an API call, we need to estimate the token count of the combined `systemPrompt` and `userPrompt`.
|
||||
- The Vercel AI SDK or the individual provider SDKs might offer utilities for this. For example, some SDKs expose a `tokenizer` or a way to count tokens for a given string.
|
||||
- If a direct utility isn't available through the Vercel SDK for the specific provider, we might need to use a library like `tiktoken` for OpenAI/Anthropic models or investigate provider-specific tokenization. This could be complex as tokenization varies between models.
|
||||
- For now, let's assume we can get a reasonable estimate.
|
||||
- **Dynamic Output Token Calculation & Validation:**
|
||||
- Retrieve `configured_max_input_tokens` and `configured_max_output_tokens` from `config-manager.js` for the current role.
|
||||
- Retrieve `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
|
||||
- Let `prompt_tokens = countTokens(systemPrompt + userPrompt)`.
|
||||
- **Input Validation:** If `prompt_tokens > configured_max_input_tokens` OR `prompt_tokens > model_absolute_max_input_tokens`, throw an error. (We might also consider auto-truncation strategies in the future, but an error is safer to start).
|
||||
- **Output Calculation:** The `max_tokens` parameter sent to the API (which typically refers to the _max number of tokens to generate_) should be `configured_max_output_tokens`. We also need to ensure this doesn't violate the model's absolute output limit.
|
||||
- Some models have a _total_ context window (input + output). If this is the case for a model, the `max_tokens` parameter for the API call might need to be `min(configured_max_output_tokens, model_absolute_total_tokens - prompt_tokens)`. However, many modern APIs handle separate input and output limits, simplifying this. We'll aim to pass `configured_max_output_tokens` as the API's `max_tokens` parameter, assuming the input validation has passed.
|
||||
- **API Call Parameter:** Update the `callParams` to use the correctly determined `max_tokens` for generation (which will be our `configured_max_output_tokens`).
|
||||
|
||||
**Phase 2: Error Handling and Refinements**
|
||||
|
||||
1. **Enhanced Error Handling:** Provide clear error messages if prompt tokens exceed input limits, or if API calls fail due to token issues despite our calculations.
|
||||
2. **Validation:** Add validation (perhaps in `config-manager.js` or when `task-master models --setup` is run) to ensure `configured_max_input_tokens` and `configured_max_output_tokens` in `.taskmasterconfig` do not exceed the `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
|
||||
|
||||
Let's start by inspecting `scripts/modules/config-manager.js` to see how parameters and `MODEL_MAP` are currently handled. This will inform the changes needed for `.taskmasterconfig` and `ai-services-unified.js`.
|
||||
|
||||
I will now read `scripts/modules/config-manager.js`.
|
||||
|
||||
Okay, I've reviewed `scripts/modules/config-manager.js`. Here's what I've gathered and how it impacts the plan:
|
||||
|
||||
- **`MODEL_MAP` Source:** `MODEL_MAP` is loaded from `supported-models.json`. This is excellent, as it means we can update the model capabilities (including new token limits) in a structured JSON file.
|
||||
- **Configuration Loading:** `_loadAndValidateConfig` handles loading `.taskmasterconfig` and merging it with `DEFAULTS`.
|
||||
- **Getters:** There are specific getters for `maxTokens` for each role (e.g., `getMainMaxTokens`). We will need to update these.
|
||||
- **`getParametersForRole`:** This function already exists and is a good candidate for returning the new `maxInputTokens` and `maxOutputTokens`.
|
||||
|
||||
Here's the refined plan:
|
||||
|
||||
**Phase 1: Configuration and Data Structures**
|
||||
|
||||
1. **Update `supported-models.json`:**
|
||||
|
||||
- For each model entry in `supported-models.json`, we need to add `maxInputTokens` and `maxOutputTokens` fields. These should reflect the _absolute maximums_ for that specific model.
|
||||
- Example entry change:
|
||||
|
||||
```json
|
||||
// Before
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
"name": "Claude 3.7 Sonnet (Preview)",
|
||||
"context_window": 200000, // This might be total context
|
||||
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
|
||||
}
|
||||
|
||||
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
"name": "Claude 3.7 Sonnet (Preview)",
|
||||
"maxInputTokens": 190000, // Example
|
||||
"maxOutputTokens": 8192, // Example, often smaller for generation
|
||||
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
|
||||
}
|
||||
```
|
||||
|
||||
- I will need to find the official input/output token limits for the models currently in your `MODEL_MAP`. If you have this information handy, it would speed things up. Otherwise, I can make educated guesses or search for them.
|
||||
|
||||
2. **Update `.taskmasterconfig` (Defaults and User File):**
|
||||
- In `scripts/modules/config-manager.js`, modify the `DEFAULTS` object. For each role (`main`, `research`, `fallback`), replace `maxTokens` with:
|
||||
- `maxInputTokens`: A sensible default (e.g., a large portion of the model's capability, but user-configurable).
|
||||
- `maxOutputTokens`: A sensible default for generation (e.g., 4096 or 8192).
|
||||
- You will then need to manually update your existing `.taskmasterconfig` file to reflect this new structure. I can provide the snippet for you to paste.
|
||||
3. **Update `config-manager.js`:**
|
||||
- Modify `getParametersForRole(role, explicitRoot = null)`:
|
||||
- It currently fetches `maxTokens` and `temperature`.
|
||||
- Update it to fetch `maxInputTokens`, `maxOutputTokens`, and `temperature` from the loaded config for the given role.
|
||||
- Remove the role-specific `getMaxTokens` functions (e.g., `getMainMaxTokens`, `getResearchMaxTokens`, `getFallbackMaxTokens`). The `getParametersForRole` will be the central way to get these.
|
||||
- (Optional, for later validation) Consider adding a new function `getModelCapabilities(providerName, modelId)` that reads from `MODEL_MAP` to return the absolute `maxInputTokens` and `maxOutputTokens` for a given model. This would be useful for validating the user's settings in `.taskmasterconfig`.
|
||||
|
||||
**Phase 2: Core Logic in `ai-services-unified.js`**
|
||||
|
||||
1. **Token Counting (`_unifiedServiceRunner`):**
|
||||
|
||||
- This is the most complex part. We need a reliable way to count tokens for the prompts.
|
||||
- **Strategy 1 (Ideal):** Leverage Vercel AI SDK. The SDK might provide a way to get a tokenizer for the active model or a utility function. We'll need to investigate its capabilities.
|
||||
- **Strategy 2 (Fallback):** Use a library like `tiktoken` for models compatible with OpenAI's tokenization (many are, including some Anthropic models). For other models, we might need provider-specific tokenizers or make estimations (less ideal).
|
||||
- **Initial Approach:** Let's try to find a Vercel AI SDK utility first. If not, we'll start with `tiktoken` as a common case and acknowledge that other models might need specific handling later.
|
||||
- The function `_unifiedServiceRunner` will call this token counting utility:
|
||||
|
||||
```javascript
|
||||
// Placeholder for token counting
|
||||
function countTokens(text, modelId /* or providerName */) {
|
||||
// ... implementation using SDK or library ...
|
||||
// This is a simplification; actual tokenization is model-specific.
|
||||
// For now, a rough estimate might be (text.length / 4) as a placeholder
|
||||
// if a proper tokenizer isn't immediately available.
|
||||
if (!text) return 0;
|
||||
return Math.ceil(text.length / 3.5); // Very rough general estimate
|
||||
}
|
||||
|
||||
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
|
||||
```
|
||||
|
||||
2. **Dynamic Output Token Calculation & Validation (`_unifiedServiceRunner`):**
|
||||
|
||||
- Fetch parameters using the updated `getParametersForRole` from `config-manager.js`:
|
||||
```javascript
|
||||
const roleParams = getParametersForRole(
|
||||
currentRole,
|
||||
effectiveProjectRoot
|
||||
);
|
||||
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
|
||||
```
|
||||
- Fetch model's absolute limits from `MODEL_MAP` (we'll need a helper in `config-manager.js` or do it directly in `ai-services-unified.js` for now):
|
||||
```javascript
|
||||
// Simplified; ideally use a robust getter from config-manager
|
||||
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
|
||||
(m) => m.id === modelId
|
||||
);
|
||||
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
|
||||
const modelAbsoluteMaxOutput =
|
||||
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
|
||||
```
|
||||
- **Input Validation:**
|
||||
```javascript
|
||||
if (promptTokens > roleParams.maxInputTokens) {
|
||||
throw new Error(
|
||||
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
|
||||
);
|
||||
}
|
||||
if (promptTokens > modelAbsoluteMaxInput) {
|
||||
throw new Error(
|
||||
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
|
||||
);
|
||||
}
|
||||
```
|
||||
- **API Call Parameter (`max_tokens` for generation):**
|
||||
The `max_tokens` parameter passed to the provider's API call should be `roleParams.maxOutputTokens`. We must also ensure this doesn't exceed the model's absolute output capability.
|
||||
|
||||
```javascript
|
||||
const apiMaxOutputTokens = Math.min(
|
||||
roleParams.maxOutputTokens,
|
||||
modelAbsoluteMaxOutput
|
||||
);
|
||||
|
||||
const callParams = {
|
||||
apiKey,
|
||||
modelId,
|
||||
// Use apiMaxOutputTokens for the actual API call
|
||||
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
|
||||
temperature: roleParams.temperature,
|
||||
messages,
|
||||
baseUrl,
|
||||
...(serviceType === 'generateObject' && { schema, objectName }),
|
||||
...restApiParams
|
||||
};
|
||||
```
|
||||
|
||||
3. **Update `logAiUsage`:**
|
||||
- The cost calculation in `logAiUsage` seems correct as it already uses `inputCost` and `outputCost` per 1M tokens. This part should remain compatible.
|
||||
|
||||
**Next Steps:**
|
||||
|
||||
1. **Modify `supported-models.json`:** I need the content of this file to propose the new `maxInputTokens` and `maxOutputTokens` fields. Please provide it.
|
||||
2. **Decide on Tokenizer Strategy:** What are your thoughts on the token counting? Are you aware of any utilities within Vercel AI SDK for this, or should we plan to integrate `tiktoken` initially?
|
||||
|
||||
Once I have the content of `supported-models.json`, I can draft the changes for it and then proceed to `config-manager.js` and `.taskmasterconfig`.
|
||||
|
||||
```json
|
||||
// Before
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
"name": "Claude 3.7 Sonnet (Preview)",
|
||||
"context_window": 200000, // This might be total context
|
||||
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
|
||||
}
|
||||
|
||||
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
"name": "Claude 3.7 Sonnet (Preview)",
|
||||
"maxInputTokens": 190000, // Example
|
||||
"maxOutputTokens": 8192, // Example, often smaller for generation
|
||||
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Placeholder for token counting
|
||||
function countTokens(text, modelId /* or providerName */) {
|
||||
// ... implementation using SDK or library ...
|
||||
// This is a simplification; actual tokenization is model-specific.
|
||||
// For now, a rough estimate might be (text.length / 4) as a placeholder
|
||||
// if a proper tokenizer isn't immediately available.
|
||||
if (!text) return 0;
|
||||
return Math.ceil(text.length / 3.5); // Very rough general estimate
|
||||
}
|
||||
|
||||
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
|
||||
```
|
||||
|
||||
```javascript
|
||||
const roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
|
||||
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Simplified; ideally use a robust getter from config-manager
|
||||
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
|
||||
(m) => m.id === modelId
|
||||
);
|
||||
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
|
||||
const modelAbsoluteMaxOutput =
|
||||
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
|
||||
```
|
||||
|
||||
```javascript
|
||||
if (promptTokens > roleParams.maxInputTokens) {
|
||||
throw new Error(
|
||||
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
|
||||
);
|
||||
}
|
||||
if (promptTokens > modelAbsoluteMaxInput) {
|
||||
throw new Error(
|
||||
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
const apiMaxOutputTokens = Math.min(
|
||||
roleParams.maxOutputTokens,
|
||||
modelAbsoluteMaxOutput
|
||||
);
|
||||
|
||||
const callParams = {
|
||||
apiKey,
|
||||
modelId,
|
||||
// Use apiMaxOutputTokens for the actual API call
|
||||
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
|
||||
temperature: roleParams.temperature,
|
||||
messages,
|
||||
baseUrl,
|
||||
...(serviceType === 'generateObject' && { schema, objectName }),
|
||||
...restApiParams
|
||||
};
|
||||
```
|
||||
|
||||
Okay, I have the contents of `supported-models.json`.
|
||||
|
||||
It seems many models have a `max_tokens` field, which I assume is the _total context window_. Some don't have it, and for others (like OpenAI `gpt-4o`), the listed `max_tokens` (16384) is known to be its _output_ token limit when using the Chat Completions API, while the context window is much larger (128k). This highlights the complexity: `max_tokens` in `supported-models.json` is used inconsistently.
|
||||
|
||||
**Revised Plan for `supported-models.json` and Token Definitions:**
|
||||
|
||||
To bring clarity, we'll introduce two new fields and ensure their meaning is consistent:
|
||||
|
||||
- `contextWindowTokens`: The total number of tokens the model can process (input + output). This would replace the current ambiguous `max_tokens`.
|
||||
- `maxOutputTokens`: The maximum number of tokens the model can _generate_ in a single response. This is often smaller than the total context window, especially for larger models.
|
||||
|
||||
If a model _only_ specifies a total context window, we'll have to make a reasonable assumption for `maxOutputTokens` (e.g., 4096 or 8192, or a fraction of the total context window). If it only specifies an output token limit (like some OpenAI models in certain API modes), we'll need to find its total context window.
|
||||
|
||||
**Updated `supported-models.json` Structure (Example):**
|
||||
|
||||
```json
|
||||
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
"swe_score": 0.623,
|
||||
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"contextWindowTokens": 200000, // From Anthropic's documentation
|
||||
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
|
||||
}
|
||||
|
||||
// For a model like OpenAI GPT-4o
|
||||
{
|
||||
"id": "gpt-4o",
|
||||
"swe_score": 0.332,
|
||||
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"contextWindowTokens": 128000, // Official context window
|
||||
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
|
||||
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
|
||||
}
|
||||
```
|
||||
|
||||
I will proceed to generate the updated `supported-models.json` content. This will be a significant change. I will make my best effort to find the correct `contextWindowTokens` and `maxOutputTokens` for each model. If official numbers are ambiguous or not readily available, I'll use sensible defaults and add a comment.
|
||||
|
||||
**Regarding Tokenizer Strategy:**
|
||||
|
||||
- **Vercel AI SDK:** The `ai` package (Vercel AI SDK) itself is a lightweight wrapper. Tokenization is usually handled by the underlying provider-specific SDKs (e.g., `@anthropic-ai/sdk`, `openai`). The Vercel SDK doesn't provide a universal tokenizer.
|
||||
- **Provider SDKs:**
|
||||
- `@anthropic-ai/sdk`: Does not expose a public tokenizer directly. Anthropic recommends counting based on their guidelines (roughly 3.5 chars/token for English).
|
||||
- `openai` (for Node.js): The `gpt-3-encoder` or `tiktoken` libraries are commonly used. `tiktoken` is more current.
|
||||
- **`tiktoken`:** This is a good general-purpose library for OpenAI models and those that use compatible tokenization (many models fine-tuned from Llama, etc., might be close). It supports various encodings.
|
||||
- **Recommendation:**
|
||||
1. Start by integrating `tiktoken`. We can select the encoding based on the provider or even specific model if needed (e.g., `cl100k_base` for gpt-4, gpt-3.5-turbo, DALL-E models).
|
||||
2. For providers where `tiktoken` is not accurate (e.g., Google's Gemini, Perplexity if they have proprietary tokenizers), we might have to rely on character-based estimations (e.g., `length / N`) as a rougher guide or investigate if their specific SDKs offer token counting.
|
||||
3. The Vercel AI SDK's `experimental_streamObject` and other functions _might_ internally handle some aspects of token counting for request preparation, but we need explicit counting for our logic _before_ the call.
|
||||
|
||||
For now, let's assume we'll add a `countTokens` utility that uses `tiktoken` for OpenAI and Anthropic (as Anthropic's guidance is character-based but `cl100k_base` is often a decent proxy for their tokenization for rough estimates, though not perfect), and a character-based fallback for others.
|
||||
|
||||
I will now generate the proposed changes for `scripts/modules/supported-models.json`. This will be a large diff.
|
||||
|
||||
After this, we'll move to:
|
||||
|
||||
1. Updating `.taskmasterconfig` defaults in `config-manager.js` and providing you the snippet for your user file.
|
||||
2. Updating `config-manager.js` getters.
|
||||
3. Implementing the logic in `ai-services-unified.js`.
|
||||
|
||||
```json
|
||||
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
"swe_score": 0.623,
|
||||
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"contextWindowTokens": 200000, // From Anthropic's documentation
|
||||
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
|
||||
}
|
||||
|
||||
// For a model like OpenAI GPT-4o
|
||||
{
|
||||
"id": "gpt-4o",
|
||||
"swe_score": 0.332,
|
||||
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"contextWindowTokens": 128000, // Official context window
|
||||
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
|
||||
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
|
||||
{
|
||||
"id": "claude-3-7-sonnet-20250219",
|
||||
"swe_score": 0.623,
|
||||
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"contextWindowTokens": 200000, // From Anthropic's documentation
|
||||
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
|
||||
}
|
||||
|
||||
// For a model like OpenAI GPT-4o
|
||||
{
|
||||
"id": "gpt-4o",
|
||||
"swe_score": 0.332,
|
||||
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
|
||||
"allowed_roles": ["main", "fallback"],
|
||||
"contextWindowTokens": 128000, // Official context window
|
||||
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
|
||||
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
|
||||
}
|
||||
```
|
||||
@@ -187,32 +187,6 @@ task-master validate-dependencies
|
||||
task-master fix-dependencies
|
||||
```
|
||||
|
||||
## Move Tasks
|
||||
|
||||
```bash
|
||||
# Move a task or subtask to a new position
|
||||
task-master move --from=<id> --to=<id>
|
||||
|
||||
# Examples:
|
||||
# Move task to become a subtask
|
||||
task-master move --from=5 --to=7
|
||||
|
||||
# Move subtask to become a standalone task
|
||||
task-master move --from=5.2 --to=7
|
||||
|
||||
# Move subtask to a different parent
|
||||
task-master move --from=5.2 --to=7.3
|
||||
|
||||
# Reorder subtasks within the same parent
|
||||
task-master move --from=5.2 --to=5.4
|
||||
|
||||
# Move a task to a new ID position (creates placeholder if doesn't exist)
|
||||
task-master move --from=5 --to=25
|
||||
|
||||
# Move multiple tasks at once (must have the same number of IDs)
|
||||
task-master move --from=10,11,12 --to=16,17,18
|
||||
```
|
||||
|
||||
## Add a New Task
|
||||
|
||||
```bash
|
||||
|
||||
@@ -15,15 +15,13 @@ Taskmaster uses two primary methods for configuration:
|
||||
"provider": "anthropic",
|
||||
"modelId": "claude-3-7-sonnet-20250219",
|
||||
"maxTokens": 64000,
|
||||
"temperature": 0.2,
|
||||
"baseUrl": "https://api.anthropic.com/v1"
|
||||
"temperature": 0.2
|
||||
},
|
||||
"research": {
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1,
|
||||
"baseUrl": "https://api.perplexity.ai/v1"
|
||||
"temperature": 0.1
|
||||
},
|
||||
"fallback": {
|
||||
"provider": "anthropic",
|
||||
@@ -58,9 +56,8 @@ Taskmaster uses two primary methods for configuration:
|
||||
- `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key (also requires `AZURE_OPENAI_ENDPOINT`).
|
||||
- `OPENROUTER_API_KEY`: Your OpenRouter API key.
|
||||
- `XAI_API_KEY`: Your X-AI API key.
|
||||
- **Optional Endpoint Overrides:**
|
||||
- **Per-role `baseUrl` in `.taskmasterconfig`:** You can add a `baseUrl` property to any model role (`main`, `research`, `fallback`) to override the default API endpoint for that provider. If omitted, the provider's standard endpoint is used.
|
||||
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key (can also be set as `baseUrl` for the Azure model role).
|
||||
- **Optional Endpoint Overrides (in .taskmasterconfig):**
|
||||
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key.
|
||||
- `OLLAMA_BASE_URL`: Override the default Ollama API URL (Default: `http://localhost:11434/api`).
|
||||
|
||||
**Important:** Settings like model ID selections (`main`, `research`, `fallback`), `maxTokens`, `temperature`, `logLevel`, `defaultSubtasks`, `defaultPriority`, and `projectName` are **managed in `.taskmasterconfig`**, not environment variables.
|
||||
|
||||
@@ -30,7 +30,7 @@ I need to regenerate the subtasks for task 3 with a different approach. Can you
|
||||
## Handling changes
|
||||
|
||||
```
|
||||
I've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||
```
|
||||
|
||||
## Completing work
|
||||
@@ -40,34 +40,6 @@ I've finished implementing the authentication system described in task 2. All te
|
||||
Please mark it as complete and tell me what I should work on next.
|
||||
```
|
||||
|
||||
## Reorganizing tasks
|
||||
|
||||
```
|
||||
I think subtask 5.2 would fit better as part of task 7. Can you move it there?
|
||||
```
|
||||
|
||||
(Agent runs: `task-master move --from=5.2 --to=7.3`)
|
||||
|
||||
```
|
||||
Task 8 should actually be a subtask of task 4. Can you reorganize this?
|
||||
```
|
||||
|
||||
(Agent runs: `task-master move --from=8 --to=4.1`)
|
||||
|
||||
```
|
||||
I just merged the main branch and there's a conflict in tasks.json. My teammates created tasks 10-15 on their branch while I created tasks 10-12 on my branch. Can you help me resolve this by moving my tasks?
|
||||
```
|
||||
|
||||
(Agent runs:
|
||||
|
||||
```bash
|
||||
task-master move --from=10 --to=16
|
||||
task-master move --from=11 --to=17
|
||||
task-master move --from=12 --to=18
|
||||
```
|
||||
|
||||
)
|
||||
|
||||
## Analyzing complexity
|
||||
|
||||
```
|
||||
|
||||
@@ -89,7 +89,7 @@ Initialize a new project:
|
||||
task-master init
|
||||
|
||||
# If installed locally
|
||||
npx task-master init
|
||||
npx task-master-init
|
||||
```
|
||||
|
||||
This will prompt you for project details and set up a new project with the necessary files and structure.
|
||||
@@ -268,61 +268,7 @@ task-master update --from=4 --prompt="Update to use MongoDB, researching best pr
|
||||
|
||||
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
|
||||
|
||||
### 6. Reorganizing Tasks
|
||||
|
||||
If you need to reorganize your task structure:
|
||||
|
||||
```
|
||||
I think subtask 5.2 would fit better as part of task 7 instead. Can you move it there?
|
||||
```
|
||||
|
||||
The agent will execute:
|
||||
|
||||
```bash
|
||||
task-master move --from=5.2 --to=7.3
|
||||
```
|
||||
|
||||
You can reorganize tasks in various ways:
|
||||
|
||||
- Moving a standalone task to become a subtask: `--from=5 --to=7`
|
||||
- Moving a subtask to become a standalone task: `--from=5.2 --to=7`
|
||||
- Moving a subtask to a different parent: `--from=5.2 --to=7.3`
|
||||
- Reordering subtasks within the same parent: `--from=5.2 --to=5.4`
|
||||
- Moving a task to a new ID position: `--from=5 --to=25` (even if task 25 doesn't exist yet)
|
||||
- Moving multiple tasks at once: `--from=10,11,12 --to=16,17,18` (must have same number of IDs, Taskmaster will look through each position)
|
||||
|
||||
When moving tasks to new IDs:
|
||||
|
||||
- The system automatically creates placeholder tasks for non-existent destination IDs
|
||||
- This prevents accidental data loss during reorganization
|
||||
- Any tasks that depend on moved tasks will have their dependencies updated
|
||||
- When moving a parent task, all its subtasks are automatically moved with it and renumbered
|
||||
|
||||
This is particularly useful as your project understanding evolves and you need to refine your task structure.
|
||||
|
||||
### 7. Resolving Merge Conflicts with Tasks
|
||||
|
||||
When working with a team, you might encounter merge conflicts in your tasks.json file if multiple team members create tasks on different branches. The move command makes resolving these conflicts straightforward:
|
||||
|
||||
```
|
||||
I just merged the main branch and there's a conflict with tasks.json. My teammates created tasks 10-15 while I created tasks 10-12 on my branch. Can you help me resolve this?
|
||||
```
|
||||
|
||||
The agent will help you:
|
||||
|
||||
1. Keep your teammates' tasks (10-15)
|
||||
2. Move your tasks to new positions to avoid conflicts:
|
||||
|
||||
```bash
|
||||
# Move your tasks to new positions (e.g., 16-18)
|
||||
task-master move --from=10 --to=16
|
||||
task-master move --from=11 --to=17
|
||||
task-master move --from=12 --to=18
|
||||
```
|
||||
|
||||
This approach preserves everyone's work while maintaining a clean task structure, making it much easier to handle task conflicts than trying to manually merge JSON files.
|
||||
|
||||
### 8. Breaking Down Complex Tasks
|
||||
### 6. Breaking Down Complex Tasks
|
||||
|
||||
For complex tasks that need more granularity:
|
||||
|
||||
|
||||
131
llms-install.md
131
llms-install.md
@@ -1,131 +0,0 @@
|
||||
``# Taskmaster AI Installation Guide
|
||||
|
||||
This guide helps AI assistants install and configure Taskmaster for users in their development projects.
|
||||
|
||||
## What is Taskmaster?
|
||||
|
||||
Taskmaster is an AI-driven task management system designed for development workflows. It helps break down projects into manageable tasks, track dependencies, and maintain development momentum through structured, AI-enhanced planning.
|
||||
|
||||
## Installation Steps
|
||||
|
||||
### Step 1: Add MCP Configuration
|
||||
|
||||
Add the following configuration to the user's MCP settings file (`.cursor/mcp.json` for Cursor, or equivalent for other editors):
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"taskmaster-ai": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
|
||||
"env": {
|
||||
"ANTHROPIC_API_KEY": "user_will_add_their_key_here",
|
||||
"PERPLEXITY_API_KEY": "user_will_add_their_key_here",
|
||||
"OPENAI_API_KEY": "user_will_add_their_key_here",
|
||||
"GOOGLE_API_KEY": "user_will_add_their_key_here",
|
||||
"MISTRAL_API_KEY": "user_will_add_their_key_here",
|
||||
"OPENROUTER_API_KEY": "user_will_add_their_key_here",
|
||||
"XAI_API_KEY": "user_will_add_their_key_here"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: API Key Requirements
|
||||
|
||||
Inform the user they need **at least one** API key from the following providers:
|
||||
|
||||
- **Anthropic** (for Claude models) - Recommended
|
||||
- **OpenAI** (for GPT models)
|
||||
- **Google** (for Gemini models)
|
||||
- **Perplexity** (for research features) - Highly recommended
|
||||
- **Mistral** (for Mistral models)
|
||||
- **OpenRouter** (access to multiple models)
|
||||
- **xAI** (for Grok models)
|
||||
|
||||
The user will be able to define 3 separate roles (can be the same provider or separate providers) for main AI operations, research operations (research providers/models only), and a fallback model in case of errors.
|
||||
|
||||
### Step 3: Initialize Project
|
||||
|
||||
Once the MCP server is configured and API keys are added, initialize Taskmaster in the user's project:
|
||||
|
||||
> Can you initialize Task Master in my project?
|
||||
|
||||
This will run the `initialize_project` tool to set up the basic file structure.
|
||||
|
||||
### Step 4: Create Initial Tasks
|
||||
|
||||
Users have two options for creating initial tasks:
|
||||
|
||||
**Option A: Parse a PRD (Recommended)**
|
||||
If they have a Product Requirements Document:
|
||||
|
||||
> Can you parse my PRD file at [path/to/prd.txt] to generate initial tasks?
|
||||
|
||||
If the user does not have a PRD, the AI agent can help them create one and store it in scripts/prd.txt for parsing.
|
||||
|
||||
**Option B: Start from scratch**
|
||||
|
||||
> Can you help me add my first task: [describe the task]
|
||||
|
||||
## Common Usage Patterns
|
||||
|
||||
### Daily Workflow
|
||||
|
||||
> What's the next task I should work on?
|
||||
> Can you show me the details for task [ID]?
|
||||
> Can you mark task [ID] as done?
|
||||
|
||||
### Task Management
|
||||
|
||||
> Can you break down task [ID] into subtasks?
|
||||
> Can you add a new task: [description]
|
||||
> Can you analyze the complexity of my tasks?
|
||||
|
||||
### Project Organization
|
||||
|
||||
> Can you show me all my pending tasks?
|
||||
> Can you move task [ID] to become a subtask of [parent ID]?
|
||||
> Can you update task [ID] with this new information: [details]
|
||||
|
||||
## Verification Steps
|
||||
|
||||
After installation, verify everything is working:
|
||||
|
||||
1. **Check MCP Connection**: The AI should be able to access Task Master tools
|
||||
2. **Test Basic Commands**: Try `get_tasks` to list current tasks
|
||||
3. **Verify API Keys**: Ensure AI-powered commands work (like `add_task`)
|
||||
|
||||
Note: An API key fallback exists that allows the MCP server to read API keys from `.env` instead of the MCP JSON config. It is recommended to have keys in both places in case the MCP server is unable to read keys from its environment for whatever reason.
|
||||
|
||||
When adding keys to `.env` only, the `models` tool will explain that the keys are not OK for MCP. Despite this, the fallback should kick in and the API keys will be read from the `.env` file.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**If MCP server doesn't start:**
|
||||
|
||||
- Verify the JSON configuration is valid
|
||||
- Check that Node.js is installed
|
||||
- Ensure API keys are properly formatted
|
||||
|
||||
**If AI commands fail:**
|
||||
|
||||
- Verify at least one API key is configured
|
||||
- Check API key permissions and quotas
|
||||
- Try using a different model via the `models` tool
|
||||
|
||||
## CLI Fallback
|
||||
|
||||
Taskmaster is also available via CLI commands, by installing with `npm install task-master-ai@latest` in a terminal. Running `task-master help` will show all available commands, which offer a 1:1 experience with the MCP server. As the AI agent, you should refer to the system prompts and rules provided to you to identify Taskmaster-specific rules that help you understand how and when to use it.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Once installed, users can:
|
||||
|
||||
- Create new tasks with `add-task` or parse a PRD (scripts/prd.txt) into tasks with `parse-prd`
|
||||
- Set up model preferences with `models` tool
|
||||
- Expand tasks into subtasks with `expand-all` and `expand-task`
|
||||
- Explore advanced features like research mode and complexity analysis
|
||||
|
||||
For detailed documentation, refer to the Task Master docs directory.``
|
||||
@@ -23,21 +23,13 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
* @param {string} [args.priority='medium'] - Task priority (high, medium, low)
|
||||
* @param {string} [args.tasksJsonPath] - Path to the tasks.json file (resolved by tool)
|
||||
* @param {boolean} [args.research=false] - Whether to use research capabilities for task creation
|
||||
* @param {string} [args.projectRoot] - Project root path
|
||||
* @param {Object} log - Logger object
|
||||
* @param {Object} context - Additional context (session)
|
||||
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
|
||||
*/
|
||||
export async function addTaskDirect(args, log, context = {}) {
|
||||
// Destructure expected args (including research and projectRoot)
|
||||
const {
|
||||
tasksJsonPath,
|
||||
prompt,
|
||||
dependencies,
|
||||
priority,
|
||||
research,
|
||||
projectRoot
|
||||
} = args;
|
||||
// Destructure expected args (including research)
|
||||
const { tasksJsonPath, prompt, dependencies, priority, research } = args;
|
||||
const { session } = context; // Destructure session from context
|
||||
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
@@ -94,7 +86,6 @@ export async function addTaskDirect(args, log, context = {}) {
|
||||
|
||||
let manualTaskData = null;
|
||||
let newTaskId;
|
||||
let telemetryData;
|
||||
|
||||
if (isManualCreation) {
|
||||
// Create manual task data object
|
||||
@@ -110,25 +101,19 @@ export async function addTaskDirect(args, log, context = {}) {
|
||||
);
|
||||
|
||||
// Call the addTask function with manual task data
|
||||
const result = await addTask(
|
||||
newTaskId = await addTask(
|
||||
tasksPath,
|
||||
null, // prompt is null for manual creation
|
||||
taskDependencies,
|
||||
taskPriority,
|
||||
{
|
||||
session,
|
||||
mcpLog,
|
||||
projectRoot,
|
||||
commandName: 'add-task',
|
||||
outputType: 'mcp'
|
||||
mcpLog
|
||||
},
|
||||
'json', // outputFormat
|
||||
manualTaskData, // Pass the manual task data
|
||||
false, // research flag is false for manual creation
|
||||
projectRoot // Pass projectRoot
|
||||
false // research flag is false for manual creation
|
||||
);
|
||||
newTaskId = result.newTaskId;
|
||||
telemetryData = result.telemetryData;
|
||||
} else {
|
||||
// AI-driven task creation
|
||||
log.info(
|
||||
@@ -136,24 +121,19 @@ export async function addTaskDirect(args, log, context = {}) {
|
||||
);
|
||||
|
||||
// Call the addTask function, passing the research flag
|
||||
const result = await addTask(
|
||||
newTaskId = await addTask(
|
||||
tasksPath,
|
||||
prompt, // Use the prompt for AI creation
|
||||
taskDependencies,
|
||||
taskPriority,
|
||||
{
|
||||
session,
|
||||
mcpLog,
|
||||
projectRoot,
|
||||
commandName: 'add-task',
|
||||
outputType: 'mcp'
|
||||
mcpLog
|
||||
},
|
||||
'json', // outputFormat
|
||||
null, // manualTaskData is null for AI creation
|
||||
research // Pass the research flag
|
||||
);
|
||||
newTaskId = result.newTaskId;
|
||||
telemetryData = result.telemetryData;
|
||||
}
|
||||
|
||||
// Restore normal logging
|
||||
@@ -163,8 +143,7 @@ export async function addTaskDirect(args, log, context = {}) {
|
||||
success: true,
|
||||
data: {
|
||||
taskId: newTaskId,
|
||||
message: `Successfully added new task #${newTaskId}`,
|
||||
telemetryData: telemetryData
|
||||
message: `Successfully added new task #${newTaskId}`
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
|
||||
@@ -18,29 +18,15 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
|
||||
* @param {string} args.outputPath - Explicit absolute path to save the report.
|
||||
* @param {string|number} [args.threshold] - Minimum complexity score to recommend expansion (1-10)
|
||||
* @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis
|
||||
* @param {string} [args.ids] - Comma-separated list of task IDs to analyze
|
||||
* @param {number} [args.from] - Starting task ID in a range to analyze
|
||||
* @param {number} [args.to] - Ending task ID in a range to analyze
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} log - Logger object
|
||||
* @param {Object} [context={}] - Context object containing session data
|
||||
* @param {Object} [context.session] - MCP session object
|
||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||
*/
|
||||
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
const {
|
||||
tasksJsonPath,
|
||||
outputPath,
|
||||
threshold,
|
||||
research,
|
||||
projectRoot,
|
||||
ids,
|
||||
from,
|
||||
to
|
||||
} = args;
|
||||
|
||||
const logWrapper = createLogWrapper(log);
|
||||
const { session } = context; // Extract session
|
||||
// Destructure expected args
|
||||
const { tasksJsonPath, outputPath, model, threshold, research } = args; // Model is ignored by core function now
|
||||
|
||||
// --- Initial Checks (remain the same) ---
|
||||
try {
|
||||
@@ -70,51 +56,39 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
log.info(`Analyzing task complexity from: ${tasksPath}`);
|
||||
log.info(`Output report will be saved to: ${resolvedOutputPath}`);
|
||||
|
||||
if (ids) {
|
||||
log.info(`Analyzing specific task IDs: ${ids}`);
|
||||
} else if (from || to) {
|
||||
const fromStr = from !== undefined ? from : 'first';
|
||||
const toStr = to !== undefined ? to : 'last';
|
||||
log.info(`Analyzing tasks in range: ${fromStr} to ${toStr}`);
|
||||
}
|
||||
|
||||
if (research) {
|
||||
log.info('Using research role for complexity analysis');
|
||||
}
|
||||
|
||||
// Prepare options for the core function - REMOVED mcpLog and session here
|
||||
const coreOptions = {
|
||||
file: tasksJsonPath,
|
||||
output: outputPath,
|
||||
// Prepare options for the core function
|
||||
const options = {
|
||||
file: tasksPath,
|
||||
output: resolvedOutputPath,
|
||||
// model: model, // No longer needed
|
||||
threshold: threshold,
|
||||
research: research === true, // Ensure boolean
|
||||
projectRoot: projectRoot, // Pass projectRoot here
|
||||
id: ids, // Pass the ids parameter to the core function as 'id'
|
||||
from: from, // Pass from parameter
|
||||
to: to // Pass to parameter
|
||||
research: research === true // Ensure boolean
|
||||
};
|
||||
// --- End Initial Checks ---
|
||||
|
||||
// --- Silent Mode and Logger Wrapper ---
|
||||
// --- Silent Mode and Logger Wrapper (remain the same) ---
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) {
|
||||
enableSilentMode(); // Still enable silent mode as a backup
|
||||
enableSilentMode();
|
||||
}
|
||||
|
||||
let report;
|
||||
let coreResult;
|
||||
// Create logger wrapper using the utility
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
let report; // To store the result from the core function
|
||||
|
||||
try {
|
||||
// --- Call Core Function (Pass context separately) ---
|
||||
// Pass coreOptions as the first argument
|
||||
// Pass context object { session, mcpLog } as the second argument
|
||||
coreResult = await analyzeTaskComplexity(coreOptions, {
|
||||
session,
|
||||
mcpLog: logWrapper,
|
||||
commandName: 'analyze-complexity',
|
||||
outputType: 'mcp'
|
||||
// --- Call Core Function (Updated Context Passing) ---
|
||||
// Call the core function, passing options and the context object { session, mcpLog }
|
||||
report = await analyzeTaskComplexity(options, {
|
||||
session, // Pass the session object
|
||||
mcpLog // Pass the logger wrapper
|
||||
});
|
||||
report = coreResult.report;
|
||||
// --- End Core Function Call ---
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Error in analyzeTaskComplexity core function: ${error.message}`
|
||||
@@ -126,7 +100,7 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'ANALYZE_CORE_ERROR',
|
||||
code: 'ANALYZE_CORE_ERROR', // More specific error code
|
||||
message: `Error running core complexity analysis: ${error.message}`
|
||||
}
|
||||
};
|
||||
@@ -150,13 +124,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
!coreResult ||
|
||||
!coreResult.report ||
|
||||
typeof coreResult.report !== 'object'
|
||||
) {
|
||||
// The core function now returns the report object directly
|
||||
if (!report || !report.complexityAnalysis) {
|
||||
log.error(
|
||||
'Core analysis function returned an invalid or undefined response.'
|
||||
'Core analyzeTaskComplexity function did not return a valid report object.'
|
||||
);
|
||||
return {
|
||||
success: false,
|
||||
@@ -168,10 +139,7 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
}
|
||||
|
||||
try {
|
||||
// Ensure complexityAnalysis exists and is an array
|
||||
const analysisArray = Array.isArray(coreResult.report.complexityAnalysis)
|
||||
? coreResult.report.complexityAnalysis
|
||||
: [];
|
||||
const analysisArray = report.complexityAnalysis; // Already an array
|
||||
|
||||
// Count tasks by complexity (remains the same)
|
||||
const highComplexityTasks = analysisArray.filter(
|
||||
@@ -187,16 +155,16 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: `Task complexity analysis complete. Report saved to ${outputPath}`,
|
||||
reportPath: outputPath,
|
||||
message: `Task complexity analysis complete. Report saved to ${resolvedOutputPath}`,
|
||||
reportPath: resolvedOutputPath,
|
||||
reportSummary: {
|
||||
taskCount: analysisArray.length,
|
||||
highComplexityTasks,
|
||||
mediumComplexityTasks,
|
||||
lowComplexityTasks
|
||||
},
|
||||
fullReport: coreResult.report,
|
||||
telemetryData: coreResult.telemetryData
|
||||
}
|
||||
// Include the full report data if needed by the client
|
||||
// fullReport: report
|
||||
}
|
||||
};
|
||||
} catch (parseError) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for displaying the complexity report with error handling and caching.
|
||||
@@ -85,20 +86,30 @@ export async function complexityReportDirect(args, log) {
|
||||
|
||||
// Use the caching utility
|
||||
try {
|
||||
const result = await coreActionFn();
|
||||
log.info('complexityReportDirect completed');
|
||||
return result;
|
||||
const result = await getCachedOrExecute({
|
||||
cacheKey,
|
||||
actionFn: coreActionFn,
|
||||
log
|
||||
});
|
||||
log.info(
|
||||
`complexityReportDirect completed. From cache: ${result.fromCache}`
|
||||
);
|
||||
return result; // Returns { success, data/error, fromCache }
|
||||
} catch (error) {
|
||||
// Catch unexpected errors from getCachedOrExecute itself
|
||||
// Ensure silent mode is disabled
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Unexpected error during complexityReport: ${error.message}`);
|
||||
log.error(
|
||||
`Unexpected error during getCachedOrExecute for complexityReport: ${error.message}`
|
||||
);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UNEXPECTED_ERROR',
|
||||
message: error.message
|
||||
}
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -17,15 +17,14 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
* @param {boolean} [args.research] - Enable research-backed subtask generation
|
||||
* @param {string} [args.prompt] - Additional context to guide subtask generation
|
||||
* @param {boolean} [args.force] - Force regeneration of subtasks for tasks that already have them
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} log - Logger object from FastMCP
|
||||
* @param {Object} context - Context object containing session
|
||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||
*/
|
||||
export async function expandAllTasksDirect(args, log, context = {}) {
|
||||
const { session } = context; // Extract session
|
||||
// Destructure expected args, including projectRoot
|
||||
const { tasksJsonPath, num, research, prompt, force, projectRoot } = args;
|
||||
// Destructure expected args
|
||||
const { tasksJsonPath, num, research, prompt, force } = args;
|
||||
|
||||
// Create logger wrapper using the utility
|
||||
const mcpLog = createLogWrapper(log);
|
||||
@@ -44,7 +43,7 @@ export async function expandAllTasksDirect(args, log, context = {}) {
|
||||
enableSilentMode(); // Enable silent mode for the core function call
|
||||
try {
|
||||
log.info(
|
||||
`Calling core expandAllTasks with args: ${JSON.stringify({ num, research, prompt, force, projectRoot })}`
|
||||
`Calling core expandAllTasks with args: ${JSON.stringify({ num, research, prompt, force })}`
|
||||
);
|
||||
|
||||
// Parse parameters (ensure correct types)
|
||||
@@ -53,28 +52,22 @@ export async function expandAllTasksDirect(args, log, context = {}) {
|
||||
const additionalContext = prompt || '';
|
||||
const forceFlag = force === true;
|
||||
|
||||
// Call the core function, passing options and the context object { session, mcpLog, projectRoot }
|
||||
// Call the core function, passing options and the context object { session, mcpLog }
|
||||
const result = await expandAllTasks(
|
||||
tasksJsonPath,
|
||||
numSubtasks,
|
||||
useResearch,
|
||||
additionalContext,
|
||||
forceFlag,
|
||||
{ session, mcpLog, projectRoot }
|
||||
{ session, mcpLog }
|
||||
);
|
||||
|
||||
// Core function now returns a summary object including the *aggregated* telemetryData
|
||||
// Core function now returns a summary object
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: `Expand all operation completed. Expanded: ${result.expandedCount}, Failed: ${result.failedCount}, Skipped: ${result.skippedCount}`,
|
||||
details: {
|
||||
expandedCount: result.expandedCount,
|
||||
failedCount: result.failedCount,
|
||||
skippedCount: result.skippedCount,
|
||||
tasksToExpand: result.tasksToExpand
|
||||
},
|
||||
telemetryData: result.telemetryData // Pass the aggregated object
|
||||
details: result // Include the full result details
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
|
||||
@@ -25,7 +25,6 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
* @param {boolean} [args.research] - Enable research role for subtask generation.
|
||||
* @param {string} [args.prompt] - Additional context to guide subtask generation.
|
||||
* @param {boolean} [args.force] - Force expansion even if subtasks exist.
|
||||
* @param {string} [args.projectRoot] - Project root directory.
|
||||
* @param {Object} log - Logger object
|
||||
* @param {Object} context - Context object containing session
|
||||
* @param {Object} [context.session] - MCP Session object
|
||||
@@ -33,8 +32,8 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
*/
|
||||
export async function expandTaskDirect(args, log, context = {}) {
|
||||
const { session } = context; // Extract session
|
||||
// Destructure expected args, including projectRoot
|
||||
const { tasksJsonPath, id, num, research, prompt, force, projectRoot } = args;
|
||||
// Destructure expected args
|
||||
const { tasksJsonPath, id, num, research, prompt, force } = args;
|
||||
|
||||
// Log session root data for debugging
|
||||
log.info(
|
||||
@@ -185,28 +184,20 @@ export async function expandTaskDirect(args, log, context = {}) {
|
||||
// Create logger wrapper using the utility
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
let wasSilent; // Declare wasSilent outside the try block
|
||||
// Process the request
|
||||
try {
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
wasSilent = isSilentMode(); // Assign inside the try block
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) enableSilentMode();
|
||||
|
||||
// Call the core expandTask function with the wrapped logger and projectRoot
|
||||
const coreResult = await expandTask(
|
||||
// Call the core expandTask function with the wrapped logger
|
||||
const result = await expandTask(
|
||||
tasksPath,
|
||||
taskId,
|
||||
numSubtasks,
|
||||
useResearch,
|
||||
additionalContext,
|
||||
{
|
||||
mcpLog,
|
||||
session,
|
||||
projectRoot,
|
||||
commandName: 'expand-task',
|
||||
outputType: 'mcp'
|
||||
},
|
||||
forceFlag
|
||||
{ mcpLog, session }
|
||||
);
|
||||
|
||||
// Restore normal logging
|
||||
@@ -221,17 +212,16 @@ export async function expandTaskDirect(args, log, context = {}) {
|
||||
? updatedTask.subtasks.length - subtasksCountBefore
|
||||
: 0;
|
||||
|
||||
// Return the result, including telemetryData
|
||||
// Return the result
|
||||
log.info(
|
||||
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
task: coreResult.task,
|
||||
task: updatedTask,
|
||||
subtasksAdded,
|
||||
hasExistingSubtasks,
|
||||
telemetryData: coreResult.telemetryData
|
||||
hasExistingSubtasks
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
disableSilentMode
|
||||
// isSilentMode // Not used directly here
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { getProjectRootFromSession } from '../../tools/utils.js'; // Adjust path if necessary
|
||||
import os from 'os'; // Import os module for home directory check
|
||||
|
||||
/**
|
||||
@@ -15,32 +16,60 @@ import os from 'os'; // Import os module for home directory check
|
||||
* @returns {Promise<{success: boolean, data?: any, error?: {code: string, message: string}}>} - Standard result object.
|
||||
*/
|
||||
export async function initializeProjectDirect(args, log, context = {}) {
|
||||
const { session } = context; // Keep session if core logic needs it
|
||||
const { session } = context;
|
||||
const homeDir = os.homedir();
|
||||
let targetDirectory = null;
|
||||
|
||||
log.info(
|
||||
`CONTEXT received in direct function: ${context ? JSON.stringify(Object.keys(context)) : 'MISSING or Falsy'}`
|
||||
);
|
||||
log.info(
|
||||
`SESSION extracted in direct function: ${session ? 'Exists' : 'MISSING or Falsy'}`
|
||||
);
|
||||
log.info(`Args received in direct function: ${JSON.stringify(args)}`);
|
||||
|
||||
// --- Determine Target Directory ---
|
||||
// TRUST the projectRoot passed from the tool layer via args
|
||||
// The HOF in the tool layer already normalized and validated it came from a reliable source (args or session)
|
||||
const targetDirectory = args.projectRoot;
|
||||
|
||||
// --- Validate the targetDirectory (basic sanity checks) ---
|
||||
// 1. Prioritize projectRoot passed directly in args
|
||||
// Ensure it's not null, '/', or the home directory
|
||||
if (
|
||||
!targetDirectory ||
|
||||
typeof targetDirectory !== 'string' || // Ensure it's a string
|
||||
targetDirectory === '/' ||
|
||||
targetDirectory === homeDir
|
||||
args.projectRoot &&
|
||||
args.projectRoot !== '/' &&
|
||||
args.projectRoot !== homeDir
|
||||
) {
|
||||
log.error(
|
||||
`Invalid target directory received from tool layer: '${targetDirectory}'`
|
||||
log.info(`Using projectRoot directly from args: ${args.projectRoot}`);
|
||||
targetDirectory = args.projectRoot;
|
||||
} else {
|
||||
// 2. If args.projectRoot is missing or invalid, THEN try session (as a fallback)
|
||||
log.warn(
|
||||
`args.projectRoot ('${args.projectRoot}') is missing or invalid. Attempting to derive from session.`
|
||||
);
|
||||
const sessionDerivedPath = getProjectRootFromSession(session, log);
|
||||
// Validate the session-derived path as well
|
||||
if (
|
||||
sessionDerivedPath &&
|
||||
sessionDerivedPath !== '/' &&
|
||||
sessionDerivedPath !== homeDir
|
||||
) {
|
||||
log.info(
|
||||
`Using project root derived from session: ${sessionDerivedPath}`
|
||||
);
|
||||
targetDirectory = sessionDerivedPath;
|
||||
} else {
|
||||
log.error(
|
||||
`Could not determine a valid project root. args.projectRoot='${args.projectRoot}', sessionDerivedPath='${sessionDerivedPath}'`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Validate the final targetDirectory
|
||||
if (!targetDirectory) {
|
||||
// This error now covers cases where neither args.projectRoot nor session provided a valid path
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'INVALID_TARGET_DIRECTORY',
|
||||
message: `Cannot initialize project: Invalid target directory '${targetDirectory}' received. Please ensure a valid workspace/folder is open or specified.`,
|
||||
details: `Received args.projectRoot: ${args.projectRoot}` // Show what was received
|
||||
message: `Cannot initialize project: Could not determine a valid target directory. Please ensure a workspace/folder is open or specify projectRoot.`,
|
||||
details: `Attempted args.projectRoot: ${args.projectRoot}`
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
@@ -57,12 +86,11 @@ export async function initializeProjectDirect(args, log, context = {}) {
|
||||
log.info(
|
||||
`Temporarily changing CWD to ${targetDirectory} for initialization.`
|
||||
);
|
||||
process.chdir(targetDirectory); // Change CWD to the HOF-provided root
|
||||
process.chdir(targetDirectory); // Change CWD to the *validated* targetDirectory
|
||||
|
||||
enableSilentMode();
|
||||
enableSilentMode(); // Enable silent mode BEFORE calling the core function
|
||||
try {
|
||||
// Construct options ONLY from the relevant flags in args
|
||||
// The core initializeProject operates in the current CWD, which we just set
|
||||
// Always force yes: true when called via MCP to avoid interactive prompts
|
||||
const options = {
|
||||
aliases: args.addAliases,
|
||||
skipInstall: args.skipInstall,
|
||||
@@ -72,11 +100,12 @@ export async function initializeProjectDirect(args, log, context = {}) {
|
||||
log.info(`Initializing project with options: ${JSON.stringify(options)}`);
|
||||
const result = await initializeProject(options); // Call core logic
|
||||
|
||||
// Format success result for handleApiResult
|
||||
resultData = {
|
||||
message: 'Project initialized successfully.',
|
||||
next_step:
|
||||
'Now that the project is initialized, the next step is to create the tasks by parsing a PRD. This will create the tasks folder and the initial task files (tasks folder will be created when parse-prd is run). The parse-prd tool will require a prd.txt file as input (typically found in the project root directory, scripts/ directory). You can create a prd.txt file by asking the user about their idea, and then using the scripts/example_prd.txt file as a template to genrate a prd.txt file in scripts/. You may skip all of this if the user already has a prd.txt file. You can THEN use the parse-prd tool to create the tasks. So: step 1 after initialization is to create a prd.txt file in scripts/prd.txt or confirm the user already has one. Step 2 is to use the parse-prd tool to create the tasks. Do not bother looking for tasks after initialization, just use the parse-prd tool to create the tasks after creating a prd.txt from which to parse the tasks. You do NOT need to reinitialize the project to parse-prd.',
|
||||
...result
|
||||
...result // Include details returned by initializeProject
|
||||
};
|
||||
success = true;
|
||||
log.info(
|
||||
@@ -91,11 +120,12 @@ export async function initializeProjectDirect(args, log, context = {}) {
|
||||
};
|
||||
success = false;
|
||||
} finally {
|
||||
disableSilentMode();
|
||||
disableSilentMode(); // ALWAYS disable silent mode in finally
|
||||
log.info(`Restoring original CWD: ${originalCwd}`);
|
||||
process.chdir(originalCwd);
|
||||
process.chdir(originalCwd); // Change back to original CWD
|
||||
}
|
||||
|
||||
// Return in format expected by handleApiResult
|
||||
if (success) {
|
||||
return { success: true, data: resultData, fromCache: false };
|
||||
} else {
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
import { listTasks } from '../../../../scripts/modules/task-manager.js';
|
||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
@@ -18,7 +19,7 @@ import {
|
||||
*/
|
||||
export async function listTasksDirect(args, log) {
|
||||
// Destructure the explicit tasksJsonPath from args
|
||||
const { tasksJsonPath, reportPath, status, withSubtasks } = args;
|
||||
const { tasksJsonPath, status, withSubtasks } = args;
|
||||
|
||||
if (!tasksJsonPath) {
|
||||
log.error('listTasksDirect called without tasksJsonPath');
|
||||
@@ -35,6 +36,7 @@ export async function listTasksDirect(args, log) {
|
||||
// Use the explicit tasksJsonPath for cache key
|
||||
const statusFilter = status || 'all';
|
||||
const withSubtasksFilter = withSubtasks || false;
|
||||
const cacheKey = `listTasks:${tasksJsonPath}:${statusFilter}:${withSubtasksFilter}`;
|
||||
|
||||
// Define the action function to be executed on cache miss
|
||||
const coreListTasksAction = async () => {
|
||||
@@ -49,7 +51,6 @@ export async function listTasksDirect(args, log) {
|
||||
const resultData = listTasks(
|
||||
tasksJsonPath,
|
||||
statusFilter,
|
||||
reportPath,
|
||||
withSubtasksFilter,
|
||||
'json'
|
||||
);
|
||||
@@ -64,7 +65,6 @@ export async function listTasksDirect(args, log) {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
log.info(
|
||||
`Core listTasks function retrieved ${resultData.tasks.length} tasks`
|
||||
);
|
||||
@@ -88,19 +88,25 @@ export async function listTasksDirect(args, log) {
|
||||
}
|
||||
};
|
||||
|
||||
// Use the caching utility
|
||||
try {
|
||||
const result = await coreListTasksAction();
|
||||
log.info('listTasksDirect completed');
|
||||
return result;
|
||||
const result = await getCachedOrExecute({
|
||||
cacheKey,
|
||||
actionFn: coreListTasksAction,
|
||||
log
|
||||
});
|
||||
log.info(`listTasksDirect completed. From cache: ${result.fromCache}`);
|
||||
return result; // Returns { success, data/error, fromCache }
|
||||
} catch (error) {
|
||||
log.error(`Unexpected error during listTasks: ${error.message}`);
|
||||
// Catch unexpected errors from getCachedOrExecute itself (though unlikely)
|
||||
log.error(
|
||||
`Unexpected error during getCachedOrExecute for listTasks: ${error.message}`
|
||||
);
|
||||
console.error(error.stack);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UNEXPECTED_ERROR',
|
||||
message: error.message
|
||||
}
|
||||
error: { code: 'CACHE_UTIL_ERROR', message: error.message },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
/**
|
||||
* Direct function wrapper for moveTask
|
||||
*/
|
||||
|
||||
import { moveTask } from '../../../../scripts/modules/task-manager.js';
|
||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
|
||||
/**
|
||||
* Move a task or subtask to a new position
|
||||
* @param {Object} args - Function arguments
|
||||
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file
|
||||
* @param {string} args.sourceId - ID of the task/subtask to move (e.g., '5' or '5.2')
|
||||
* @param {string} args.destinationId - ID of the destination (e.g., '7' or '7.3')
|
||||
* @param {string} args.file - Alternative path to the tasks.json file
|
||||
* @param {string} args.projectRoot - Project root directory
|
||||
* @param {Object} log - Logger object
|
||||
* @returns {Promise<{success: boolean, data?: Object, error?: Object}>}
|
||||
*/
|
||||
export async function moveTaskDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
|
||||
// Validate required parameters
|
||||
if (!args.sourceId) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Source ID is required',
|
||||
code: 'MISSING_SOURCE_ID'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (!args.destinationId) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
message: 'Destination ID is required',
|
||||
code: 'MISSING_DESTINATION_ID'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
// Find tasks.json path if not provided
|
||||
let tasksPath = args.tasksJsonPath || args.file;
|
||||
if (!tasksPath) {
|
||||
if (!args.projectRoot) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
message:
|
||||
'Project root is required if tasksJsonPath is not provided',
|
||||
code: 'MISSING_PROJECT_ROOT'
|
||||
}
|
||||
};
|
||||
}
|
||||
tasksPath = findTasksJsonPath(args, log);
|
||||
}
|
||||
|
||||
// Enable silent mode to prevent console output during MCP operation
|
||||
enableSilentMode();
|
||||
|
||||
// Call the core moveTask function, always generate files
|
||||
const result = await moveTask(
|
||||
tasksPath,
|
||||
args.sourceId,
|
||||
args.destinationId,
|
||||
true
|
||||
);
|
||||
|
||||
// Restore console output
|
||||
disableSilentMode();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
movedTask: result.movedTask,
|
||||
message: `Successfully moved task/subtask ${args.sourceId} to ${args.destinationId}`
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
// Restore console output in case of error
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Failed to move task: ${error.message}`);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
message: error.message,
|
||||
code: 'MOVE_TASK_ERROR'
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,8 @@
|
||||
*/
|
||||
|
||||
import { findNextTask } from '../../../../scripts/modules/task-manager.js';
|
||||
import {
|
||||
readJSON,
|
||||
readComplexityReport
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { readJSON } from '../../../../scripts/modules/utils.js';
|
||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
@@ -23,7 +21,7 @@ import {
|
||||
*/
|
||||
export async function nextTaskDirect(args, log) {
|
||||
// Destructure expected args
|
||||
const { tasksJsonPath, reportPath } = args;
|
||||
const { tasksJsonPath } = args;
|
||||
|
||||
if (!tasksJsonPath) {
|
||||
log.error('nextTaskDirect called without tasksJsonPath');
|
||||
@@ -37,6 +35,9 @@ export async function nextTaskDirect(args, log) {
|
||||
};
|
||||
}
|
||||
|
||||
// Generate cache key using the provided task path
|
||||
const cacheKey = `nextTask:${tasksJsonPath}`;
|
||||
|
||||
// Define the action function to be executed on cache miss
|
||||
const coreNextTaskAction = async () => {
|
||||
try {
|
||||
@@ -58,11 +59,8 @@ export async function nextTaskDirect(args, log) {
|
||||
};
|
||||
}
|
||||
|
||||
// Read the complexity report
|
||||
const complexityReport = readComplexityReport(reportPath);
|
||||
|
||||
// Find the next task
|
||||
const nextTask = findNextTask(data.tasks, complexityReport);
|
||||
const nextTask = findNextTask(data.tasks);
|
||||
|
||||
if (!nextTask) {
|
||||
log.info(
|
||||
@@ -73,34 +71,24 @@ export async function nextTaskDirect(args, log) {
|
||||
data: {
|
||||
message:
|
||||
'No eligible next task found. All tasks are either completed or have unsatisfied dependencies',
|
||||
nextTask: null
|
||||
nextTask: null,
|
||||
allTasks: data.tasks
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Check if it's a subtask
|
||||
const isSubtask =
|
||||
typeof nextTask.id === 'string' && nextTask.id.includes('.');
|
||||
|
||||
const taskOrSubtask = isSubtask ? 'subtask' : 'task';
|
||||
|
||||
const additionalAdvice = isSubtask
|
||||
? 'Subtasks can be updated with timestamped details as you implement them. This is useful for tracking progress, marking milestones and insights (of successful or successive falures in attempting to implement the subtask). Research can be used when updating the subtask to collect up-to-date information, and can be helpful to solve a repeating problem the agent is unable to solve. It is a good idea to get-task the parent task to collect the overall context of the task, and to get-task the subtask to collect the specific details of the subtask.'
|
||||
: 'Tasks can be updated to reflect a change in the direction of the task, or to reformulate the task per your prompt. Research can be used when updating the task to collect up-to-date information. It is best to update subtasks as you work on them, and to update the task for more high-level changes that may affect pending subtasks or the general direction of the task.';
|
||||
|
||||
// Restore normal logging
|
||||
disableSilentMode();
|
||||
|
||||
// Return the next task data with the full tasks array for reference
|
||||
log.info(
|
||||
`Successfully found next task ${nextTask.id}: ${nextTask.title}. Is subtask: ${isSubtask}`
|
||||
`Successfully found next task ${nextTask.id}: ${nextTask.title}`
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
nextTask,
|
||||
isSubtask,
|
||||
nextSteps: `When ready to work on the ${taskOrSubtask}, use set-status to set the status to "in progress" ${additionalAdvice}`
|
||||
allTasks: data.tasks
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -120,11 +108,18 @@ export async function nextTaskDirect(args, log) {
|
||||
|
||||
// Use the caching utility
|
||||
try {
|
||||
const result = await coreNextTaskAction();
|
||||
log.info(`nextTaskDirect completed.`);
|
||||
return result;
|
||||
const result = await getCachedOrExecute({
|
||||
cacheKey,
|
||||
actionFn: coreNextTaskAction,
|
||||
log
|
||||
});
|
||||
log.info(`nextTaskDirect completed. From cache: ${result.fromCache}`);
|
||||
return result; // Returns { success, data/error, fromCache }
|
||||
} catch (error) {
|
||||
log.error(`Unexpected error during nextTask: ${error.message}`);
|
||||
// Catch unexpected errors from getCachedOrExecute itself
|
||||
log.error(
|
||||
`Unexpected error during getCachedOrExecute for nextTask: ${error.message}`
|
||||
);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
|
||||
@@ -8,11 +8,9 @@ import fs from 'fs';
|
||||
import { parsePRD } from '../../../../scripts/modules/task-manager.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
import { getDefaultNumTasks } from '../../../../scripts/modules/config-manager.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for parsing PRD documents and generating tasks.
|
||||
@@ -23,171 +21,177 @@ import { getDefaultNumTasks } from '../../../../scripts/modules/config-manager.j
|
||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||
*/
|
||||
export async function parsePRDDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
// Extract projectRoot from args
|
||||
const {
|
||||
input: inputArg,
|
||||
output: outputArg,
|
||||
numTasks: numTasksArg,
|
||||
force,
|
||||
append,
|
||||
research,
|
||||
projectRoot
|
||||
} = args;
|
||||
const { session } = context; // Only extract session
|
||||
|
||||
// Create the standard logger wrapper
|
||||
const logWrapper = createLogWrapper(log);
|
||||
try {
|
||||
log.info(`Parsing PRD document with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// --- Input Validation and Path Resolution ---
|
||||
if (!projectRoot) {
|
||||
logWrapper.error('parsePRDDirect requires a projectRoot argument.');
|
||||
// Validate required parameters
|
||||
if (!args.projectRoot) {
|
||||
const errorMessage = 'Project root is required for parsePRDDirect';
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_PROJECT_ROOT', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
if (!args.input) {
|
||||
const errorMessage = 'Input file path is required for parsePRDDirect';
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_INPUT_PATH', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
if (!args.output) {
|
||||
const errorMessage = 'Output file path is required for parsePRDDirect';
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_OUTPUT_PATH', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve input path (expecting absolute path or path relative to project root)
|
||||
const projectRoot = args.projectRoot;
|
||||
const inputPath = path.isAbsolute(args.input)
|
||||
? args.input
|
||||
: path.resolve(projectRoot, args.input);
|
||||
|
||||
// Verify input file exists
|
||||
if (!fs.existsSync(inputPath)) {
|
||||
const errorMessage = `Input file not found: ${inputPath}`;
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'MISSING_ARGUMENT',
|
||||
message: 'projectRoot is required.'
|
||||
}
|
||||
};
|
||||
}
|
||||
if (!inputArg) {
|
||||
logWrapper.error('parsePRDDirect called without input path');
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_ARGUMENT', message: 'Input path is required' }
|
||||
code: 'INPUT_FILE_NOT_FOUND',
|
||||
message: errorMessage,
|
||||
details: `Checked path: ${inputPath}\nProject root: ${projectRoot}\nInput argument: ${args.input}`
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve input and output paths relative to projectRoot
|
||||
const inputPath = path.resolve(projectRoot, inputArg);
|
||||
const outputPath = outputArg
|
||||
? path.resolve(projectRoot, outputArg)
|
||||
: path.resolve(projectRoot, 'tasks', 'tasks.json'); // Default output path
|
||||
|
||||
// Check if input file exists
|
||||
if (!fs.existsSync(inputPath)) {
|
||||
const errorMsg = `Input PRD file not found at resolved path: ${inputPath}`;
|
||||
logWrapper.error(errorMsg);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'FILE_NOT_FOUND', message: errorMsg }
|
||||
};
|
||||
}
|
||||
// Resolve output path (expecting absolute path or path relative to project root)
|
||||
const outputPath = path.isAbsolute(args.output)
|
||||
? args.output
|
||||
: path.resolve(projectRoot, args.output);
|
||||
|
||||
// Ensure output directory exists
|
||||
const outputDir = path.dirname(outputPath);
|
||||
try {
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
logWrapper.info(`Creating output directory: ${outputDir}`);
|
||||
log.info(`Creating output directory: ${outputDir}`);
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
} catch (dirError) {
|
||||
logWrapper.error(
|
||||
`Failed to create output directory ${outputDir}: ${dirError.message}`
|
||||
);
|
||||
// Return an error response immediately if dir creation fails
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'DIRECTORY_CREATION_ERROR',
|
||||
message: `Failed to create output directory: ${dirError.message}`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let numTasks = getDefaultNumTasks(projectRoot);
|
||||
if (numTasksArg) {
|
||||
// Parse number of tasks - handle both string and number values
|
||||
let numTasks = 10; // Default
|
||||
if (args.numTasks) {
|
||||
numTasks =
|
||||
typeof numTasksArg === 'string' ? parseInt(numTasksArg, 10) : numTasksArg;
|
||||
if (isNaN(numTasks) || numTasks <= 0) {
|
||||
// Ensure positive number
|
||||
numTasks = getDefaultNumTasks(projectRoot); // Fallback to default if parsing fails or invalid
|
||||
logWrapper.warn(
|
||||
`Invalid numTasks value: ${numTasksArg}. Using default: ${numTasks}`
|
||||
);
|
||||
typeof args.numTasks === 'string'
|
||||
? parseInt(args.numTasks, 10)
|
||||
: args.numTasks;
|
||||
if (isNaN(numTasks)) {
|
||||
numTasks = 10; // Fallback to default if parsing fails
|
||||
log.warn(`Invalid numTasks value: ${args.numTasks}. Using default: 10`);
|
||||
}
|
||||
}
|
||||
|
||||
if (append) {
|
||||
logWrapper.info('Append mode enabled.');
|
||||
if (force) {
|
||||
logWrapper.warn(
|
||||
'Both --force and --append flags were provided. --force takes precedence; append mode will be ignored.'
|
||||
);
|
||||
}
|
||||
}
|
||||
// Extract the append flag from args
|
||||
const append = Boolean(args.append) === true;
|
||||
|
||||
if (research) {
|
||||
logWrapper.info(
|
||||
'Research mode enabled. Using Perplexity AI for enhanced PRD analysis.'
|
||||
);
|
||||
}
|
||||
|
||||
logWrapper.info(
|
||||
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, Research: ${research}, ProjectRoot: ${projectRoot}`
|
||||
// Log key parameters including append flag
|
||||
log.info(
|
||||
`Preparing to parse PRD from ${inputPath} and output to ${outputPath} with ${numTasks} tasks, append mode: ${append}`
|
||||
);
|
||||
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) {
|
||||
// --- Logger Wrapper ---
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
// Prepare options for the core function
|
||||
const options = {
|
||||
mcpLog,
|
||||
session
|
||||
};
|
||||
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
enableSilentMode();
|
||||
try {
|
||||
// Make sure the output directory exists
|
||||
const outputDir = path.dirname(outputPath);
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
log.info(`Creating output directory: ${outputDir}`);
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
try {
|
||||
// Call the core parsePRD function
|
||||
const result = await parsePRD(
|
||||
// Execute core parsePRD function with AI client
|
||||
const tasksDataResult = await parsePRD(
|
||||
inputPath,
|
||||
outputPath,
|
||||
numTasks,
|
||||
{
|
||||
session,
|
||||
mcpLog: logWrapper,
|
||||
projectRoot,
|
||||
force,
|
||||
append,
|
||||
research,
|
||||
commandName: 'parse-prd',
|
||||
outputType: 'mcp'
|
||||
session,
|
||||
append
|
||||
},
|
||||
'json'
|
||||
aiClient,
|
||||
modelConfig
|
||||
);
|
||||
|
||||
// Adjust check for the new return structure
|
||||
if (result && result.success) {
|
||||
const successMsg = `Successfully parsed PRD and generated tasks in ${result.tasksPath}`;
|
||||
logWrapper.success(successMsg);
|
||||
// Since parsePRD doesn't return a value but writes to a file, we'll read the result
|
||||
// to return it to the caller
|
||||
if (fs.existsSync(outputPath)) {
|
||||
const tasksData = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
||||
const actionVerb = append ? 'appended' : 'generated';
|
||||
const message = `Successfully ${actionVerb} ${tasksData.tasks?.length || 0} tasks from PRD`;
|
||||
|
||||
if (!tasksDataResult || !tasksDataResult.tasks || !tasksData) {
|
||||
throw new Error(
|
||||
'Core parsePRD function did not return valid task data.'
|
||||
);
|
||||
}
|
||||
|
||||
log.info(message);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: successMsg,
|
||||
outputPath: result.tasksPath,
|
||||
telemetryData: result.telemetryData
|
||||
}
|
||||
message,
|
||||
taskCount: tasksDataResult.tasks?.length || 0,
|
||||
outputPath,
|
||||
appended: append
|
||||
},
|
||||
fromCache: false // This operation always modifies state and should never be cached
|
||||
};
|
||||
} else {
|
||||
// Handle case where core function didn't return expected success structure
|
||||
logWrapper.error(
|
||||
'Core parsePRD function did not return a successful structure.'
|
||||
);
|
||||
const errorMessage = `Tasks file was not created at ${outputPath}`;
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'CORE_FUNCTION_ERROR',
|
||||
message:
|
||||
result?.message ||
|
||||
'Core function failed to parse PRD or returned unexpected result.'
|
||||
}
|
||||
error: { code: 'OUTPUT_FILE_NOT_CREATED', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
logWrapper.error(`Error executing core parsePRD: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'PARSE_PRD_CORE_ERROR',
|
||||
message: error.message || 'Unknown error parsing PRD'
|
||||
}
|
||||
};
|
||||
} finally {
|
||||
if (!wasSilent && isSilentMode()) {
|
||||
// Always restore normal logging
|
||||
disableSilentMode();
|
||||
}
|
||||
} catch (error) {
|
||||
// Make sure to restore normal logging even if there's an error
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Error parsing PRD: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: error.code || 'PARSE_PRD_ERROR', // Use error code if available
|
||||
message: error.message || 'Unknown error parsing PRD'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { nextTaskDirect } from './next-task.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for setTaskStatus with error handling.
|
||||
*
|
||||
@@ -19,7 +19,7 @@ import { nextTaskDirect } from './next-task.js';
|
||||
*/
|
||||
export async function setTaskStatusDirect(args, log) {
|
||||
// Destructure expected args, including the resolved tasksJsonPath
|
||||
const { tasksJsonPath, id, status, complexityReportPath } = args;
|
||||
const { tasksJsonPath, id, status } = args;
|
||||
try {
|
||||
log.info(`Setting task status with args: ${JSON.stringify(args)}`);
|
||||
|
||||
@@ -85,39 +85,6 @@ export async function setTaskStatusDirect(args, log) {
|
||||
},
|
||||
fromCache: false // This operation always modifies state and should never be cached
|
||||
};
|
||||
|
||||
// If the task was completed, attempt to fetch the next task
|
||||
if (result.data.status === 'done') {
|
||||
try {
|
||||
log.info(`Attempting to fetch next task for task ${taskId}`);
|
||||
const nextResult = await nextTaskDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
reportPath: complexityReportPath
|
||||
},
|
||||
log
|
||||
);
|
||||
|
||||
if (nextResult.success) {
|
||||
log.info(
|
||||
`Successfully retrieved next task: ${nextResult.data.nextTask}`
|
||||
);
|
||||
result.data = {
|
||||
...result.data,
|
||||
nextTask: nextResult.data.nextTask,
|
||||
isNextSubtask: nextResult.data.isSubtask,
|
||||
nextSteps: nextResult.data.nextSteps
|
||||
};
|
||||
} else {
|
||||
log.warn(
|
||||
`Failed to retrieve next task: ${nextResult.error?.message || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
} catch (nextErr) {
|
||||
log.error(`Error retrieving next task: ${nextErr.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
log.error(`Error setting task status: ${error.message}`);
|
||||
|
||||
@@ -3,103 +3,151 @@
|
||||
* Direct function implementation for showing task details
|
||||
*/
|
||||
|
||||
import { findTaskById } from '../../../../scripts/modules/utils.js';
|
||||
import { readJSON } from '../../../../scripts/modules/utils.js';
|
||||
import { getCachedOrExecute } from '../../tools/utils.js';
|
||||
import {
|
||||
findTaskById,
|
||||
readComplexityReport,
|
||||
readJSON
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for getting task details.
|
||||
* Direct function wrapper for showing task details with error handling and caching.
|
||||
*
|
||||
* @param {Object} args - Command arguments.
|
||||
* @param {string} args.id - Task ID to show.
|
||||
* @param {string} [args.file] - Optional path to the tasks file (passed to findTasksJsonPath).
|
||||
* @param {string} args.reportPath - Explicit path to the complexity report file.
|
||||
* @param {Object} args - Command arguments
|
||||
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
|
||||
* @param {string} args.id - The ID of the task or subtask to show.
|
||||
* @param {string} [args.status] - Optional status to filter subtasks by.
|
||||
* @param {string} args.projectRoot - Absolute path to the project root directory (already normalized by tool).
|
||||
* @param {Object} log - Logger object.
|
||||
* @param {Object} context - Context object containing session data.
|
||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||
* @param {Object} log - Logger object
|
||||
* @returns {Promise<Object>} - Task details result { success: boolean, data?: any, error?: { code: string, message: string }, fromCache: boolean }
|
||||
*/
|
||||
export async function showTaskDirect(args, log) {
|
||||
// Destructure session from context if needed later, otherwise ignore
|
||||
// const { session } = context;
|
||||
// Destructure projectRoot and other args. projectRoot is assumed normalized.
|
||||
const { id, file, reportPath, status, projectRoot } = args;
|
||||
// Destructure expected args
|
||||
const { tasksJsonPath, id, status } = args;
|
||||
|
||||
log.info(
|
||||
`Showing task direct function. ID: ${id}, File: ${file}, Status Filter: ${status}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
|
||||
// --- Path Resolution using the passed (already normalized) projectRoot ---
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
// Use the projectRoot passed directly from args
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: projectRoot, file: file },
|
||||
log
|
||||
);
|
||||
log.info(`Resolved tasks path: ${tasksJsonPath}`);
|
||||
} catch (error) {
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
if (!tasksJsonPath) {
|
||||
log.error('showTaskDirect called without tasksJsonPath');
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'TASKS_FILE_NOT_FOUND',
|
||||
message: `Failed to find tasks.json: ${error.message}`
|
||||
}
|
||||
code: 'MISSING_ARGUMENT',
|
||||
message: 'tasksJsonPath is required'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
// --- End Path Resolution ---
|
||||
|
||||
// --- Rest of the function remains the same, using tasksJsonPath ---
|
||||
try {
|
||||
const tasksData = readJSON(tasksJsonPath);
|
||||
if (!tasksData || !tasksData.tasks) {
|
||||
// Validate task ID
|
||||
const taskId = id;
|
||||
if (!taskId) {
|
||||
log.error('Task ID is required');
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'INVALID_TASKS_DATA', message: 'Invalid tasks data' }
|
||||
error: {
|
||||
code: 'INPUT_VALIDATION_ERROR',
|
||||
message: 'Task ID is required'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
const complexityReport = readComplexityReport(reportPath);
|
||||
// Generate cache key using the provided task path, ID, and status filter
|
||||
const cacheKey = `showTask:${tasksJsonPath}:${taskId}:${status || 'all'}`;
|
||||
|
||||
// Define the action function to be executed on cache miss
|
||||
const coreShowTaskAction = async () => {
|
||||
try {
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
enableSilentMode();
|
||||
|
||||
log.info(
|
||||
`Retrieving task details for ID: ${taskId} from ${tasksJsonPath}${status ? ` (filtering by status: ${status})` : ''}`
|
||||
);
|
||||
|
||||
// Read tasks data using the provided path
|
||||
const data = readJSON(tasksJsonPath);
|
||||
if (!data || !data.tasks) {
|
||||
disableSilentMode(); // Disable before returning
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'INVALID_TASKS_FILE',
|
||||
message: `No valid tasks found in ${tasksJsonPath}`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Find the specific task, passing the status filter
|
||||
const { task, originalSubtaskCount } = findTaskById(
|
||||
tasksData.tasks,
|
||||
id,
|
||||
complexityReport,
|
||||
data.tasks,
|
||||
taskId,
|
||||
status
|
||||
);
|
||||
|
||||
if (!task) {
|
||||
disableSilentMode(); // Disable before returning
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'TASK_NOT_FOUND',
|
||||
message: `Task or subtask with ID ${id} not found`
|
||||
message: `Task with ID ${taskId} not found${status ? ` or no subtasks match status '${status}'` : ''}`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
log.info(`Successfully retrieved task ${id}.`);
|
||||
// Restore normal logging
|
||||
disableSilentMode();
|
||||
|
||||
const returnData = { ...task };
|
||||
if (originalSubtaskCount !== null) {
|
||||
returnData._originalSubtaskCount = originalSubtaskCount;
|
||||
returnData._subtaskFilter = status;
|
||||
// Return the task data, the original subtask count (if applicable),
|
||||
// and the full tasks array for reference (needed for formatDependenciesWithStatus function in UI)
|
||||
log.info(
|
||||
`Successfully found task ${taskId}${status ? ` (with status filter: ${status})` : ''}`
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
task,
|
||||
originalSubtaskCount,
|
||||
allTasks: data.tasks
|
||||
}
|
||||
|
||||
return { success: true, data: returnData };
|
||||
};
|
||||
} catch (error) {
|
||||
log.error(`Error showing task ${id}: ${error.message}`);
|
||||
// Make sure to restore normal logging even if there's an error
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Error showing task: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'TASK_OPERATION_ERROR',
|
||||
message: error.message
|
||||
code: 'CORE_FUNCTION_ERROR',
|
||||
message: error.message || 'Failed to show task details'
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Use the caching utility
|
||||
try {
|
||||
const result = await getCachedOrExecute({
|
||||
cacheKey,
|
||||
actionFn: coreShowTaskAction,
|
||||
log
|
||||
});
|
||||
log.info(`showTaskDirect completed. From cache: ${result.fromCache}`);
|
||||
return result; // Returns { success, data/error, fromCache }
|
||||
} catch (error) {
|
||||
// Catch unexpected errors from getCachedOrExecute itself
|
||||
disableSilentMode();
|
||||
log.error(
|
||||
`Unexpected error during getCachedOrExecute for showTask: ${error.message}`
|
||||
);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UNEXPECTED_ERROR',
|
||||
message: error.message
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,40 +6,29 @@
|
||||
import { updateSubtaskById } from '../../../../scripts/modules/task-manager.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for updateSubtaskById with error handling.
|
||||
*
|
||||
* @param {Object} args - Command arguments containing id, prompt, useResearch, tasksJsonPath, and projectRoot.
|
||||
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
|
||||
* @param {string} args.id - Subtask ID in format "parent.sub".
|
||||
* @param {string} args.prompt - Information to append to the subtask.
|
||||
* @param {boolean} [args.research] - Whether to use research role.
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} args - Command arguments containing id, prompt, useResearch and tasksJsonPath.
|
||||
* @param {Object} log - Logger object.
|
||||
* @param {Object} context - Context object containing session data.
|
||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||
*/
|
||||
export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
// Destructure expected args, including projectRoot
|
||||
const { tasksJsonPath, id, prompt, research, projectRoot } = args;
|
||||
|
||||
const logWrapper = createLogWrapper(log);
|
||||
const { session } = context; // Only extract session, not reportProgress
|
||||
const { tasksJsonPath, id, prompt, research } = args;
|
||||
|
||||
try {
|
||||
logWrapper.info(
|
||||
`Updating subtask by ID via direct function. ID: ${id}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Check if tasksJsonPath was provided
|
||||
if (!tasksJsonPath) {
|
||||
const errorMessage = 'tasksJsonPath is required but was not provided.';
|
||||
logWrapper.error(errorMessage);
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_ARGUMENT', message: errorMessage },
|
||||
@@ -47,22 +36,22 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// Basic validation for ID format (e.g., '5.2')
|
||||
if (!id || typeof id !== 'string' || !id.includes('.')) {
|
||||
// Check required parameters (id and prompt)
|
||||
if (!id) {
|
||||
const errorMessage =
|
||||
'Invalid subtask ID format. Must be in format "parentId.subtaskId" (e.g., "5.2").';
|
||||
logWrapper.error(errorMessage);
|
||||
'No subtask ID specified. Please provide a subtask ID to update.';
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'INVALID_SUBTASK_ID', message: errorMessage },
|
||||
error: { code: 'MISSING_SUBTASK_ID', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
if (!prompt) {
|
||||
const errorMessage =
|
||||
'No prompt specified. Please provide the information to append.';
|
||||
logWrapper.error(errorMessage);
|
||||
'No prompt specified. Please provide a prompt with information to add to the subtask.';
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
||||
@@ -95,87 +84,80 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||
|
||||
// Use the provided path
|
||||
const tasksPath = tasksJsonPath;
|
||||
|
||||
// Get research flag
|
||||
const useResearch = research === true;
|
||||
|
||||
log.info(
|
||||
`Updating subtask with ID ${subtaskIdStr} with prompt "${prompt}" and research: ${useResearch}`
|
||||
);
|
||||
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) {
|
||||
enableSilentMode();
|
||||
}
|
||||
|
||||
try {
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
enableSilentMode();
|
||||
|
||||
// Create the logger wrapper using the utility function
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
// Execute core updateSubtaskById function
|
||||
const coreResult = await updateSubtaskById(
|
||||
// Pass both session and logWrapper as mcpLog to ensure outputFormat is 'json'
|
||||
const updatedSubtask = await updateSubtaskById(
|
||||
tasksPath,
|
||||
subtaskIdStr,
|
||||
prompt,
|
||||
useResearch,
|
||||
{
|
||||
mcpLog: logWrapper,
|
||||
session,
|
||||
projectRoot,
|
||||
commandName: 'update-subtask',
|
||||
outputType: 'mcp'
|
||||
},
|
||||
'json'
|
||||
mcpLog
|
||||
}
|
||||
);
|
||||
|
||||
if (!coreResult || coreResult.updatedSubtask === null) {
|
||||
const message = `Subtask ${id} or its parent task not found.`;
|
||||
logWrapper.error(message);
|
||||
// Restore normal logging
|
||||
disableSilentMode();
|
||||
|
||||
// Handle the case where the subtask couldn't be updated (e.g., already marked as done)
|
||||
if (!updatedSubtask) {
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'SUBTASK_NOT_FOUND', message: message },
|
||||
error: {
|
||||
code: 'SUBTASK_UPDATE_FAILED',
|
||||
message:
|
||||
'Failed to update subtask. It may be marked as completed, or another error occurred.'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
// Subtask updated successfully
|
||||
const successMessage = `Successfully updated subtask with ID ${subtaskIdStr}`;
|
||||
logWrapper.success(successMessage);
|
||||
// Return the updated subtask information
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: `Successfully updated subtask with ID ${subtaskIdStr}`,
|
||||
subtaskId: subtaskIdStr,
|
||||
parentId: subtaskIdStr.split('.')[0],
|
||||
subtask: coreResult.updatedSubtask,
|
||||
subtask: updatedSubtask,
|
||||
tasksPath,
|
||||
useResearch,
|
||||
telemetryData: coreResult.telemetryData
|
||||
useResearch
|
||||
},
|
||||
fromCache: false
|
||||
fromCache: false // This operation always modifies state and should never be cached
|
||||
};
|
||||
} catch (error) {
|
||||
logWrapper.error(`Error updating subtask by ID: ${error.message}`);
|
||||
// Make sure to restore normal logging even if there's an error
|
||||
disableSilentMode();
|
||||
throw error; // Rethrow to be caught by outer catch block
|
||||
}
|
||||
} catch (error) {
|
||||
// Ensure silent mode is disabled
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Error updating subtask by ID: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UPDATE_SUBTASK_CORE_ERROR',
|
||||
code: 'UPDATE_SUBTASK_ERROR',
|
||||
message: error.message || 'Unknown error updating subtask'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
} finally {
|
||||
if (!wasSilent && isSilentMode()) {
|
||||
disableSilentMode();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logWrapper.error(
|
||||
`Setup error in updateSubtaskByIdDirect: ${error.message}`
|
||||
);
|
||||
if (isSilentMode()) disableSilentMode();
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'DIRECT_FUNCTION_SETUP_ERROR',
|
||||
message: error.message || 'Unknown setup error'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,40 +6,30 @@
|
||||
import { updateTaskById } from '../../../../scripts/modules/task-manager.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for updateTaskById with error handling.
|
||||
*
|
||||
* @param {Object} args - Command arguments containing id, prompt, useResearch, tasksJsonPath, and projectRoot.
|
||||
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
|
||||
* @param {string} args.id - Task ID (or subtask ID like "1.2").
|
||||
* @param {string} args.prompt - New information/context prompt.
|
||||
* @param {boolean} [args.research] - Whether to use research role.
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} args - Command arguments containing id, prompt, useResearch and tasksJsonPath.
|
||||
* @param {Object} log - Logger object.
|
||||
* @param {Object} context - Context object containing session data.
|
||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||
*/
|
||||
export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
// Destructure expected args, including projectRoot
|
||||
const { tasksJsonPath, id, prompt, research, projectRoot } = args;
|
||||
|
||||
const logWrapper = createLogWrapper(log);
|
||||
const { session } = context; // Only extract session, not reportProgress
|
||||
// Destructure expected args, including the resolved tasksJsonPath
|
||||
const { tasksJsonPath, id, prompt, research } = args;
|
||||
|
||||
try {
|
||||
logWrapper.info(
|
||||
`Updating task by ID via direct function. ID: ${id}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Check if tasksJsonPath was provided
|
||||
if (!tasksJsonPath) {
|
||||
const errorMessage = 'tasksJsonPath is required but was not provided.';
|
||||
logWrapper.error(errorMessage);
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_ARGUMENT', message: errorMessage },
|
||||
@@ -51,7 +41,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
if (!id) {
|
||||
const errorMessage =
|
||||
'No task ID specified. Please provide a task ID to update.';
|
||||
logWrapper.error(errorMessage);
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_TASK_ID', message: errorMessage },
|
||||
@@ -62,7 +52,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
if (!prompt) {
|
||||
const errorMessage =
|
||||
'No prompt specified. Please provide a prompt with new information for the task update.';
|
||||
logWrapper.error(errorMessage);
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
||||
@@ -81,7 +71,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
taskId = parseInt(id, 10);
|
||||
if (isNaN(taskId)) {
|
||||
const errorMessage = `Invalid task ID: ${id}. Task ID must be a positive integer or subtask ID (e.g., "5.2").`;
|
||||
logWrapper.error(errorMessage);
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'INVALID_TASK_ID', message: errorMessage },
|
||||
@@ -99,88 +89,66 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
// Get research flag
|
||||
const useResearch = research === true;
|
||||
|
||||
logWrapper.info(
|
||||
log.info(
|
||||
`Updating task with ID ${taskId} with prompt "${prompt}" and research: ${useResearch}`
|
||||
);
|
||||
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) {
|
||||
enableSilentMode();
|
||||
}
|
||||
|
||||
try {
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
enableSilentMode();
|
||||
|
||||
// Create the logger wrapper using the utility function
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
// Execute core updateTaskById function with proper parameters
|
||||
const coreResult = await updateTaskById(
|
||||
await updateTaskById(
|
||||
tasksPath,
|
||||
taskId,
|
||||
prompt,
|
||||
useResearch,
|
||||
{
|
||||
mcpLog: logWrapper,
|
||||
session,
|
||||
projectRoot,
|
||||
commandName: 'update-task',
|
||||
outputType: 'mcp'
|
||||
mcpLog, // Pass the wrapped logger
|
||||
session
|
||||
},
|
||||
'json'
|
||||
);
|
||||
|
||||
// Check if the core function returned null or an object without success
|
||||
if (!coreResult || coreResult.updatedTask === null) {
|
||||
// Core function logs the reason, just return success with info
|
||||
const message = `Task ${taskId} was not updated (likely already completed).`;
|
||||
logWrapper.info(message);
|
||||
// Since updateTaskById doesn't return a value but modifies the tasks file,
|
||||
// we'll return a success message
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: message,
|
||||
taskId: taskId,
|
||||
updated: false,
|
||||
telemetryData: coreResult?.telemetryData
|
||||
message: `Successfully updated task with ID ${taskId} based on the prompt`,
|
||||
taskId,
|
||||
tasksPath: tasksPath, // Return the used path
|
||||
useResearch
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
// Task was updated successfully
|
||||
const successMessage = `Successfully updated task with ID ${taskId} based on the prompt`;
|
||||
logWrapper.success(successMessage);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: successMessage,
|
||||
taskId: taskId,
|
||||
tasksPath: tasksPath,
|
||||
useResearch: useResearch,
|
||||
updated: true,
|
||||
updatedTask: coreResult.updatedTask,
|
||||
telemetryData: coreResult.telemetryData
|
||||
},
|
||||
fromCache: false
|
||||
fromCache: false // This operation always modifies state and should never be cached
|
||||
};
|
||||
} catch (error) {
|
||||
logWrapper.error(`Error updating task by ID: ${error.message}`);
|
||||
log.error(`Error updating task by ID: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UPDATE_TASK_CORE_ERROR',
|
||||
code: 'UPDATE_TASK_ERROR',
|
||||
message: error.message || 'Unknown error updating task'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
} finally {
|
||||
if (!wasSilent && isSilentMode()) {
|
||||
// Make sure to restore normal logging even if there's an error
|
||||
disableSilentMode();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logWrapper.error(`Setup error in updateTaskByIdDirect: ${error.message}`);
|
||||
if (isSilentMode()) disableSilentMode();
|
||||
// Ensure silent mode is disabled
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Error updating task by ID: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'DIRECT_FUNCTION_SETUP_ERROR',
|
||||
message: error.message || 'Unknown setup error'
|
||||
code: 'UPDATE_TASK_ERROR',
|
||||
message: error.message || 'Unknown error updating task'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
|
||||
@@ -1,126 +1,128 @@
|
||||
/**
|
||||
* update-tasks.js
|
||||
* Direct function implementation for updating tasks based on new context
|
||||
* Direct function implementation for updating tasks based on new context/prompt
|
||||
*/
|
||||
|
||||
import path from 'path';
|
||||
import { updateTasks } from '../../../../scripts/modules/task-manager.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for updating tasks based on new context.
|
||||
* Direct function wrapper for updating tasks based on new context/prompt.
|
||||
*
|
||||
* @param {Object} args - Command arguments containing projectRoot, from, prompt, research options.
|
||||
* @param {Object} args - Command arguments containing from, prompt, research and tasksJsonPath.
|
||||
* @param {Object} log - Logger object.
|
||||
* @param {Object} context - Context object containing session data.
|
||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||
*/
|
||||
export async function updateTasksDirect(args, log, context = {}) {
|
||||
const { session } = context;
|
||||
const { from, prompt, research, file: fileArg, projectRoot } = args;
|
||||
const { session } = context; // Extract session
|
||||
const { tasksJsonPath, from, prompt, research } = args;
|
||||
|
||||
// Create the standard logger wrapper
|
||||
const logWrapper = createLogWrapper(log);
|
||||
const logWrapper = {
|
||||
info: (message, ...args) => log.info(message, ...args),
|
||||
warn: (message, ...args) => log.warn(message, ...args),
|
||||
error: (message, ...args) => log.error(message, ...args),
|
||||
debug: (message, ...args) => log.debug && log.debug(message, ...args),
|
||||
success: (message, ...args) => log.info(message, ...args)
|
||||
};
|
||||
|
||||
// --- Input Validation ---
|
||||
if (!projectRoot) {
|
||||
logWrapper.error('updateTasksDirect requires a projectRoot argument.');
|
||||
// --- Input Validation (Keep existing checks) ---
|
||||
if (!tasksJsonPath) {
|
||||
log.error('updateTasksDirect called without tasksJsonPath');
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'MISSING_ARGUMENT',
|
||||
message: 'projectRoot is required.'
|
||||
}
|
||||
error: { code: 'MISSING_ARGUMENT', message: 'tasksJsonPath is required' },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
if (args.id !== undefined && from === undefined) {
|
||||
// Keep 'from' vs 'id' check
|
||||
const errorMessage =
|
||||
"Use 'from' parameter, not 'id', or use 'update_task' tool.";
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'PARAMETER_MISMATCH', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
if (!from) {
|
||||
logWrapper.error('updateTasksDirect called without from ID');
|
||||
log.error('Missing from ID.');
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'MISSING_ARGUMENT',
|
||||
message: 'Starting task ID (from) is required'
|
||||
}
|
||||
error: { code: 'MISSING_FROM_ID', message: 'No from ID specified.' },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
if (!prompt) {
|
||||
logWrapper.error('updateTasksDirect called without prompt');
|
||||
log.error('Missing prompt.');
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_PROMPT', message: 'No prompt specified.' },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
let fromId;
|
||||
try {
|
||||
fromId = parseInt(from, 10);
|
||||
if (isNaN(fromId) || fromId <= 0) throw new Error();
|
||||
} catch {
|
||||
log.error(`Invalid from ID: ${from}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'MISSING_ARGUMENT',
|
||||
message: 'Update prompt is required'
|
||||
}
|
||||
code: 'INVALID_FROM_ID',
|
||||
message: `Invalid from ID: ${from}. Must be a positive integer.`
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
const useResearch = research === true;
|
||||
// --- End Input Validation ---
|
||||
|
||||
// Resolve tasks file path
|
||||
const tasksFile = fileArg
|
||||
? path.resolve(projectRoot, fileArg)
|
||||
: path.resolve(projectRoot, 'tasks', 'tasks.json');
|
||||
|
||||
logWrapper.info(
|
||||
`Updating tasks via direct function. From: ${from}, Research: ${research}, File: ${tasksFile}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
log.info(`Updating tasks from ID ${fromId}. Research: ${useResearch}`);
|
||||
|
||||
enableSilentMode(); // Enable silent mode
|
||||
try {
|
||||
// Call the core updateTasks function
|
||||
const result = await updateTasks(
|
||||
tasksFile,
|
||||
from,
|
||||
// Create logger wrapper using the utility
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
// Execute core updateTasks function, passing session context
|
||||
await updateTasks(
|
||||
tasksJsonPath,
|
||||
fromId,
|
||||
prompt,
|
||||
research,
|
||||
{
|
||||
session,
|
||||
mcpLog: logWrapper,
|
||||
projectRoot
|
||||
},
|
||||
'json'
|
||||
useResearch,
|
||||
// Pass context with logger wrapper and session
|
||||
{ mcpLog, session },
|
||||
'json' // Explicitly request JSON format for MCP
|
||||
);
|
||||
|
||||
if (result && result.success && Array.isArray(result.updatedTasks)) {
|
||||
logWrapper.success(
|
||||
`Successfully updated ${result.updatedTasks.length} tasks.`
|
||||
);
|
||||
// Since updateTasks modifies file and doesn't return data, create success message
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: `Successfully updated ${result.updatedTasks.length} tasks.`,
|
||||
tasksFile,
|
||||
updatedCount: result.updatedTasks.length,
|
||||
telemetryData: result.telemetryData
|
||||
}
|
||||
message: `Successfully initiated update for tasks from ID ${fromId} based on the prompt.`,
|
||||
fromId,
|
||||
tasksPath: tasksJsonPath,
|
||||
useResearch
|
||||
},
|
||||
fromCache: false // Modifies state
|
||||
};
|
||||
} else {
|
||||
// Handle case where core function didn't return expected success structure
|
||||
logWrapper.error(
|
||||
'Core updateTasks function did not return a successful structure.'
|
||||
);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'CORE_FUNCTION_ERROR',
|
||||
message:
|
||||
result?.message ||
|
||||
'Core function failed to update tasks or returned unexpected result.'
|
||||
}
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
logWrapper.error(`Error executing core updateTasks: ${error.message}`);
|
||||
log.error(`Error executing core updateTasks: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UPDATE_TASKS_CORE_ERROR',
|
||||
message: error.message || 'Unknown error updating tasks'
|
||||
}
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
} finally {
|
||||
disableSilentMode(); // Ensure silent mode is disabled
|
||||
|
||||
@@ -28,9 +28,8 @@ import { fixDependenciesDirect } from './direct-functions/fix-dependencies.js';
|
||||
import { complexityReportDirect } from './direct-functions/complexity-report.js';
|
||||
import { addDependencyDirect } from './direct-functions/add-dependency.js';
|
||||
import { removeTaskDirect } from './direct-functions/remove-task.js';
|
||||
import { initializeProjectDirect } from './direct-functions/initialize-project.js';
|
||||
import { initializeProjectDirect } from './direct-functions/initialize-project-direct.js';
|
||||
import { modelsDirect } from './direct-functions/models.js';
|
||||
import { moveTaskDirect } from './direct-functions/move-task.js';
|
||||
|
||||
// Re-export utility functions
|
||||
export { findTasksJsonPath } from './utils/path-utils.js';
|
||||
@@ -61,8 +60,7 @@ export const directFunctions = new Map([
|
||||
['addDependencyDirect', addDependencyDirect],
|
||||
['removeTaskDirect', removeTaskDirect],
|
||||
['initializeProjectDirect', initializeProjectDirect],
|
||||
['modelsDirect', modelsDirect],
|
||||
['moveTaskDirect', moveTaskDirect]
|
||||
['modelsDirect', modelsDirect]
|
||||
]);
|
||||
|
||||
// Re-export all direct function implementations
|
||||
@@ -91,6 +89,5 @@ export {
|
||||
addDependencyDirect,
|
||||
removeTaskDirect,
|
||||
initializeProjectDirect,
|
||||
modelsDirect,
|
||||
moveTaskDirect
|
||||
modelsDirect
|
||||
};
|
||||
|
||||
@@ -339,49 +339,6 @@ export function findPRDDocumentPath(projectRoot, explicitPath, log) {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function findComplexityReportPath(projectRoot, explicitPath, log) {
|
||||
// If explicit path is provided, check if it exists
|
||||
if (explicitPath) {
|
||||
const fullPath = path.isAbsolute(explicitPath)
|
||||
? explicitPath
|
||||
: path.resolve(projectRoot, explicitPath);
|
||||
|
||||
if (fs.existsSync(fullPath)) {
|
||||
log.info(`Using provided PRD document path: ${fullPath}`);
|
||||
return fullPath;
|
||||
} else {
|
||||
log.warn(
|
||||
`Provided PRD document path not found: ${fullPath}, will search for alternatives`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Common locations and file patterns for PRD documents
|
||||
const commonLocations = [
|
||||
'', // Project root
|
||||
'scripts/'
|
||||
];
|
||||
|
||||
const commonFileNames = [
|
||||
'complexity-report.json',
|
||||
'task-complexity-report.json'
|
||||
];
|
||||
|
||||
// Check all possible combinations
|
||||
for (const location of commonLocations) {
|
||||
for (const fileName of commonFileNames) {
|
||||
const potentialPath = path.join(projectRoot, location, fileName);
|
||||
if (fs.existsSync(potentialPath)) {
|
||||
log.info(`Found PRD document at: ${potentialPath}`);
|
||||
return potentialPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.warn(`No PRD document found in common locations within ${projectRoot}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the tasks output directory path
|
||||
* @param {string} projectRoot - The project root directory
|
||||
|
||||
@@ -7,8 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
getProjectRootFromSession,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { addDependencyDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -36,16 +35,28 @@ export function registerAddDependencyTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Adding dependency for task ${args.id} to depend on ${args.dependsOn}`
|
||||
);
|
||||
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -81,6 +92,6 @@ export function registerAddDependencyTool(server) {
|
||||
log.error(`Error in addDependency tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { addSubtaskDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -60,15 +60,24 @@ export function registerAddSubtaskTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Adding subtask with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -104,6 +113,6 @@ export function registerAddSubtaskTool(server) {
|
||||
log.error(`Error in addSubtask tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
createErrorResponse,
|
||||
handleApiResult,
|
||||
withNormalizedProjectRoot
|
||||
withProjectContext,
|
||||
handleApiResult
|
||||
} from './utils.js';
|
||||
import { addTaskDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -63,11 +63,13 @@ export function registerAddTaskTool(server) {
|
||||
.optional()
|
||||
.describe('Whether to use research capabilities for task creation')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: withProjectContext(async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Starting add-task with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Note: projectRoot is now guaranteed to be normalized by withProjectContext
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
@@ -81,10 +83,12 @@ export function registerAddTaskTool(server) {
|
||||
);
|
||||
}
|
||||
|
||||
// Call the direct functionP
|
||||
// Call the direct function
|
||||
const result = await addTaskDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
prompt: args.prompt,
|
||||
title: args.title,
|
||||
description: args.description,
|
||||
@@ -92,13 +96,13 @@ export function registerAddTaskTool(server) {
|
||||
testStrategy: args.testStrategy,
|
||||
dependencies: args.dependencies,
|
||||
priority: args.priority,
|
||||
research: args.research,
|
||||
projectRoot: args.projectRoot
|
||||
research: args.research
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
// Return the result
|
||||
return handleApiResult(result, log);
|
||||
} catch (error) {
|
||||
log.error(`Error in add-task tool: ${error.message}`);
|
||||
|
||||
@@ -4,149 +4,121 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import path from 'path';
|
||||
import fs from 'fs'; // Import fs for directory check/creation
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
} from './utils.js';
|
||||
import { analyzeTaskComplexityDirect } from '../core/task-master-core.js'; // Assuming core functions are exported via task-master-core.js
|
||||
import { handleApiResult, createErrorResponse } from './utils.js';
|
||||
import { analyzeTaskComplexityDirect } from '../core/direct-functions/analyze-task-complexity.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
/**
|
||||
* Register the analyze_project_complexity tool
|
||||
* Register the analyze tool with the MCP server
|
||||
* @param {Object} server - FastMCP server instance
|
||||
*/
|
||||
export function registerAnalyzeProjectComplexityTool(server) {
|
||||
export function registerAnalyzeTool(server) {
|
||||
server.addTool({
|
||||
name: 'analyze_project_complexity',
|
||||
description:
|
||||
'Analyze task complexity and generate expansion recommendations.',
|
||||
'Analyze task complexity and generate expansion recommendations',
|
||||
parameters: z.object({
|
||||
threshold: z.coerce // Use coerce for number conversion from string if needed
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(10)
|
||||
.optional()
|
||||
.default(5) // Default threshold
|
||||
.describe('Complexity score threshold (1-10) to recommend expansion.'),
|
||||
research: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe('Use Perplexity AI for research-backed analysis.'),
|
||||
output: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Output file path relative to project root (default: scripts/task-complexity-report.json).'
|
||||
'Output file path relative to project root (default: scripts/task-complexity-report.json)'
|
||||
),
|
||||
threshold: z.coerce
|
||||
.number()
|
||||
.min(1)
|
||||
.max(10)
|
||||
.optional()
|
||||
.describe(
|
||||
'Minimum complexity score to recommend expansion (1-10) (default: 5)'
|
||||
),
|
||||
file: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Path to the tasks file relative to project root (default: tasks/tasks.json).'
|
||||
'Absolute path to the tasks file in the /tasks folder inside the project root (default: tasks/tasks.json)'
|
||||
),
|
||||
ids: z
|
||||
.string()
|
||||
research: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
'Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").'
|
||||
),
|
||||
from: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe('Starting task ID in a range to analyze.'),
|
||||
to: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe('Ending task ID in a range to analyze.'),
|
||||
.default(false)
|
||||
.describe('Use research role for complexity analysis'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
const toolName = 'analyze_project_complexity'; // Define tool name for logging
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Executing ${toolName} tool with args: ${JSON.stringify(args)}`
|
||||
`Executing analyze_project_complexity tool with args: ${JSON.stringify(args)}`
|
||||
);
|
||||
|
||||
const rootFolder = args.projectRoot;
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse('projectRoot is required.');
|
||||
}
|
||||
if (!path.isAbsolute(rootFolder)) {
|
||||
return createErrorResponse('projectRoot must be an absolute path.');
|
||||
}
|
||||
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
log.info(`${toolName}: Resolved tasks path: ${tasksJsonPath}`);
|
||||
} catch (error) {
|
||||
log.error(`${toolName}: Error finding tasks.json: ${error.message}`);
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json within project root '${args.projectRoot}': ${error.message}`
|
||||
`Failed to find tasks.json within project root '${rootFolder}': ${error.message}`
|
||||
);
|
||||
}
|
||||
|
||||
const outputPath = args.output
|
||||
? path.resolve(args.projectRoot, args.output)
|
||||
: path.resolve(
|
||||
args.projectRoot,
|
||||
'scripts',
|
||||
'task-complexity-report.json'
|
||||
);
|
||||
? path.resolve(rootFolder, args.output)
|
||||
: path.resolve(rootFolder, 'scripts', 'task-complexity-report.json');
|
||||
|
||||
log.info(`${toolName}: Report output path: ${outputPath}`);
|
||||
|
||||
// Ensure output directory exists
|
||||
const outputDir = path.dirname(outputPath);
|
||||
try {
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
log.info(`${toolName}: Created output directory: ${outputDir}`);
|
||||
log.info(`Created output directory: ${outputDir}`);
|
||||
}
|
||||
} catch (dirError) {
|
||||
log.error(
|
||||
`${toolName}: Failed to create output directory ${outputDir}: ${dirError.message}`
|
||||
`Failed to create output directory ${outputDir}: ${dirError.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Failed to create output directory: ${dirError.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Call Direct Function - Pass projectRoot in first arg object
|
||||
const result = await analyzeTaskComplexityDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
outputPath: outputPath,
|
||||
threshold: args.threshold,
|
||||
research: args.research,
|
||||
projectRoot: args.projectRoot,
|
||||
ids: args.ids,
|
||||
from: args.from,
|
||||
to: args.to
|
||||
research: args.research
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
// 4. Handle Result
|
||||
log.info(
|
||||
`${toolName}: Direct function result: success=${result.success}`
|
||||
if (result.success) {
|
||||
log.info(`Tool analyze_project_complexity finished successfully.`);
|
||||
} else {
|
||||
log.error(
|
||||
`Tool analyze_project_complexity failed: ${result.error?.message || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
|
||||
return handleApiResult(result, log, 'Error analyzing task complexity');
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
log.error(`Critical error in analyze tool execute: ${error.message}`);
|
||||
return createErrorResponse(`Internal tool error: ${error.message}`);
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { clearSubtasksDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -41,15 +41,26 @@ export function registerClearSubtasksTool(server) {
|
||||
message: "Either 'id' or 'all' parameter must be provided",
|
||||
path: ['id', 'all']
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Clearing subtasks with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -61,11 +72,14 @@ export function registerClearSubtasksTool(server) {
|
||||
|
||||
const result = await clearSubtasksDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
all: args.all
|
||||
},
|
||||
log
|
||||
// Remove context object as clearSubtasksDirect likely doesn't need session/reportProgress
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
@@ -79,6 +93,6 @@ export function registerClearSubtasksTool(server) {
|
||||
log.error(`Error in clearSubtasks tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { complexityReportDirect } from '../core/task-master-core.js';
|
||||
import path from 'path';
|
||||
@@ -31,24 +31,34 @@ export function registerComplexityReportTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Getting complexity report with args: ${JSON.stringify(args)}`
|
||||
);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
const reportPath = args.file
|
||||
? path.resolve(args.projectRoot, args.file)
|
||||
: path.resolve(
|
||||
args.projectRoot,
|
||||
'scripts',
|
||||
'task-complexity-report.json'
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to the complexity report file
|
||||
// Default to scripts/task-complexity-report.json relative to root
|
||||
const reportPath = args.file
|
||||
? path.resolve(rootFolder, args.file)
|
||||
: path.resolve(rootFolder, 'scripts', 'task-complexity-report.json');
|
||||
|
||||
const result = await complexityReportDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
reportPath: reportPath
|
||||
// No other args specific to this tool
|
||||
},
|
||||
log
|
||||
);
|
||||
@@ -74,6 +84,6 @@ export function registerComplexityReportTool(server) {
|
||||
`Failed to retrieve complexity report: ${error.message}`
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { expandAllTasksDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -59,16 +59,25 @@ export function registerExpandAllTool(server) {
|
||||
'Absolute path to the project root directory (derived from session if possible)'
|
||||
)
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Tool expand_all execution started with args: ${JSON.stringify(args)}`
|
||||
);
|
||||
|
||||
const rootFolder = getProjectRootFromSession(session, log);
|
||||
if (!rootFolder) {
|
||||
log.error('Could not determine project root from session.');
|
||||
return createErrorResponse(
|
||||
'Could not determine project root from session.'
|
||||
);
|
||||
}
|
||||
log.info(`Project root determined: ${rootFolder}`);
|
||||
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
log.info(`Resolved tasks.json path: ${tasksJsonPath}`);
|
||||
@@ -85,8 +94,7 @@ export function registerExpandAllTool(server) {
|
||||
num: args.num,
|
||||
research: args.research,
|
||||
prompt: args.prompt,
|
||||
force: args.force,
|
||||
projectRoot: args.projectRoot
|
||||
force: args.force
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
@@ -104,6 +112,6 @@ export function registerExpandAllTool(server) {
|
||||
`An unexpected error occurred: ${error.message}`
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { expandTaskDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -47,15 +47,28 @@ export function registerExpandTaskTool(server) {
|
||||
.default(false)
|
||||
.describe('Force expansion even if subtasks exist')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Starting expand-task with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
log.info(`Project root resolved to: ${rootFolder}`);
|
||||
|
||||
// Resolve the path to tasks.json using the utility
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -65,25 +78,29 @@ export function registerExpandTaskTool(server) {
|
||||
);
|
||||
}
|
||||
|
||||
// Call direct function with only session in the context, not reportProgress
|
||||
// Use the pattern recommended in the MCP guidelines
|
||||
const result = await expandTaskDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
num: args.num,
|
||||
research: args.research,
|
||||
prompt: args.prompt,
|
||||
force: args.force,
|
||||
projectRoot: args.projectRoot
|
||||
force: args.force // Need to add force to parameters
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
); // Only pass session, NOT reportProgress
|
||||
|
||||
// Return the result
|
||||
return handleApiResult(result, log, 'Error expanding task');
|
||||
} catch (error) {
|
||||
log.error(`Error in expand-task tool: ${error.message}`);
|
||||
log.error(`Error in expand task tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { fixDependenciesDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -26,15 +26,24 @@ export function registerFixDependenciesTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Fixing dependencies with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -62,6 +71,6 @@ export function registerFixDependenciesTool(server) {
|
||||
log.error(`Error in fixDependencies tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { generateTaskFilesDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -32,15 +32,26 @@ export function registerGenerateTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Generating task files with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -50,14 +61,17 @@ export function registerGenerateTool(server) {
|
||||
);
|
||||
}
|
||||
|
||||
// Determine output directory: use explicit arg or default to tasks.json directory
|
||||
const outputDir = args.output
|
||||
? path.resolve(args.projectRoot, args.output)
|
||||
? path.resolve(rootFolder, args.output) // Resolve relative to root if needed
|
||||
: path.dirname(tasksJsonPath);
|
||||
|
||||
const result = await generateTaskFilesDirect(
|
||||
{
|
||||
// Pass the explicitly resolved paths
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
outputDir: outputDir
|
||||
// No other args specific to this tool
|
||||
},
|
||||
log
|
||||
);
|
||||
@@ -75,6 +89,6 @@ export function registerGenerateTool(server) {
|
||||
log.error(`Error in generate tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,13 +7,10 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { showTaskDirect } from '../core/task-master-core.js';
|
||||
import {
|
||||
findTasksJsonPath,
|
||||
findComplexityReportPath
|
||||
} from '../core/utils/path-utils.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Custom processor function that removes allTasks from the response
|
||||
@@ -24,10 +21,8 @@ function processTaskResponse(data) {
|
||||
if (!data) return data;
|
||||
|
||||
// If we have the expected structure with task and allTasks
|
||||
if (typeof data === 'object' && data !== null && data.id && data.title) {
|
||||
// If the data itself looks like the task object, return it
|
||||
return data;
|
||||
} else if (data.task) {
|
||||
if (data.task) {
|
||||
// Return only the task object, removing the allTasks array
|
||||
return data.task;
|
||||
}
|
||||
|
||||
@@ -49,39 +44,44 @@ export function registerShowTaskTool(server) {
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Filter subtasks by status (e.g., 'pending', 'done')"),
|
||||
file: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Path to the tasks file relative to project root'),
|
||||
complexityReport: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Path to the complexity report file (relative to project root or absolute)'
|
||||
),
|
||||
file: z.string().optional().describe('Absolute path to the tasks file'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Absolute path to the project root directory (Optional, usually from session)'
|
||||
)
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log }) => {
|
||||
const { id, file, status, projectRoot } = args;
|
||||
execute: async (args, { log, session }) => {
|
||||
// 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
|
||||
|
||||
try {
|
||||
log.info(
|
||||
`Getting task details for ID: ${id}${status ? ` (filtering subtasks by status: ${status})` : ''} in root: ${projectRoot}`
|
||||
`Getting task details for ID: ${args.id}${args.status ? ` (filtering subtasks by status: ${args.status})` : ''}`
|
||||
);
|
||||
|
||||
// Resolve the path to tasks.json using the NORMALIZED projectRoot from args
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
log.info(`Attempting to use project root: ${rootFolder}`); // Log the final resolved root
|
||||
|
||||
log.info(`Root folder: ${rootFolder}`); // Log the final resolved root
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: projectRoot, file: file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
log.info(`Resolved tasks path: ${tasksJsonPath}`);
|
||||
} catch (error) {
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
@@ -89,26 +89,13 @@ export function registerShowTaskTool(server) {
|
||||
);
|
||||
}
|
||||
|
||||
// Call the direct function, passing the normalized projectRoot
|
||||
// Resolve the path to complexity report
|
||||
let complexityReportPath;
|
||||
try {
|
||||
complexityReportPath = findComplexityReportPath(
|
||||
projectRoot,
|
||||
args.complexityReport,
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Error finding complexity report: ${error.message}`);
|
||||
}
|
||||
log.info(`Attempting to use tasks file path: ${tasksJsonPath}`);
|
||||
|
||||
const result = await showTaskDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
reportPath: complexityReportPath,
|
||||
// Pass other relevant args
|
||||
id: id,
|
||||
status: status,
|
||||
projectRoot: projectRoot
|
||||
id: args.id,
|
||||
status: args.status
|
||||
},
|
||||
log
|
||||
);
|
||||
@@ -121,7 +108,7 @@ export function registerShowTaskTool(server) {
|
||||
log.error(`Failed to get task: ${result.error.message}`);
|
||||
}
|
||||
|
||||
// Use our custom processor function
|
||||
// Use our custom processor function to remove allTasks from the response
|
||||
return handleApiResult(
|
||||
result,
|
||||
log,
|
||||
@@ -129,9 +116,9 @@ export function registerShowTaskTool(server) {
|
||||
processTaskResponse
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Error in get-task tool: ${error.message}\n${error.stack}`);
|
||||
log.error(`Error in get-task tool: ${error.message}\n${error.stack}`); // Add stack trace
|
||||
return createErrorResponse(`Failed to get task: ${error.message}`);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,13 +7,10 @@ import { z } from 'zod';
|
||||
import {
|
||||
createErrorResponse,
|
||||
handleApiResult,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { listTasksDirect } from '../core/task-master-core.js';
|
||||
import {
|
||||
findTasksJsonPath,
|
||||
findComplexityReportPath
|
||||
} from '../core/utils/path-utils.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Register the getTasks tool with the MCP server
|
||||
@@ -41,51 +38,45 @@ export function registerListTasksTool(server) {
|
||||
.describe(
|
||||
'Path to the tasks file (relative to project root or absolute)'
|
||||
),
|
||||
complexityReport: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Path to the complexity report file (relative to project root or absolute)'
|
||||
),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Getting tasks with filters: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
// Use the error message from findTasksJsonPath for better context
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json: ${error.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to complexity report
|
||||
let complexityReportPath;
|
||||
try {
|
||||
complexityReportPath = findComplexityReportPath(
|
||||
args.projectRoot,
|
||||
args.complexityReport,
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Error finding complexity report: ${error.message}`);
|
||||
}
|
||||
const result = await listTasksDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
status: args.status,
|
||||
withSubtasks: args.withSubtasks,
|
||||
reportPath: complexityReportPath
|
||||
withSubtasks: args.withSubtasks
|
||||
},
|
||||
log
|
||||
);
|
||||
@@ -98,7 +89,7 @@ export function registerListTasksTool(server) {
|
||||
log.error(`Error getting tasks: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import { registerExpandTaskTool } from './expand-task.js';
|
||||
import { registerAddTaskTool } from './add-task.js';
|
||||
import { registerAddSubtaskTool } from './add-subtask.js';
|
||||
import { registerRemoveSubtaskTool } from './remove-subtask.js';
|
||||
import { registerAnalyzeProjectComplexityTool } from './analyze.js';
|
||||
import { registerAnalyzeTool } from './analyze.js';
|
||||
import { registerClearSubtasksTool } from './clear-subtasks.js';
|
||||
import { registerExpandAllTool } from './expand-all.js';
|
||||
import { registerRemoveDependencyTool } from './remove-dependency.js';
|
||||
@@ -28,7 +28,6 @@ import { registerAddDependencyTool } from './add-dependency.js';
|
||||
import { registerRemoveTaskTool } from './remove-task.js';
|
||||
import { registerInitializeProjectTool } from './initialize-project.js';
|
||||
import { registerModelsTool } from './models.js';
|
||||
import { registerMoveTaskTool } from './move-task.js';
|
||||
|
||||
/**
|
||||
* Register all Task Master tools with the MCP server
|
||||
@@ -62,10 +61,9 @@ export function registerTaskMasterTools(server) {
|
||||
registerRemoveTaskTool(server);
|
||||
registerRemoveSubtaskTool(server);
|
||||
registerClearSubtasksTool(server);
|
||||
registerMoveTaskTool(server);
|
||||
|
||||
// Group 5: Task Analysis & Expansion
|
||||
registerAnalyzeProjectComplexityTool(server);
|
||||
registerAnalyzeTool(server);
|
||||
registerExpandTaskTool(server);
|
||||
registerExpandAllTool(server);
|
||||
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
createErrorResponse,
|
||||
handleApiResult,
|
||||
withNormalizedProjectRoot
|
||||
} from './utils.js';
|
||||
import { createErrorResponse, handleApiResult } from './utils.js';
|
||||
import { initializeProjectDirect } from '../core/task-master-core.js';
|
||||
|
||||
export function registerInitializeProjectTool(server) {
|
||||
@@ -37,10 +33,19 @@ export function registerInitializeProjectTool(server) {
|
||||
'The root directory for the project. ALWAYS SET THIS TO THE PROJECT ROOT DIRECTORY. IF NOT SET, THE TOOL WILL NOT WORK.'
|
||||
)
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, context) => {
|
||||
execute: async (args, context) => {
|
||||
const { log } = context;
|
||||
const session = context.session;
|
||||
|
||||
log.info(
|
||||
'>>> Full Context Received by Tool:',
|
||||
JSON.stringify(context, null, 2)
|
||||
);
|
||||
log.info(`Context received in tool function: ${context}`);
|
||||
log.info(
|
||||
`Session received in tool function: ${session ? session : 'undefined'}`
|
||||
);
|
||||
|
||||
try {
|
||||
log.info(
|
||||
`Executing initialize_project tool with args: ${JSON.stringify(args)}`
|
||||
@@ -54,6 +59,6 @@ export function registerInitializeProjectTool(server) {
|
||||
log.error(errorMessage, error);
|
||||
return createErrorResponse(errorMessage, { details: error.stack });
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
getProjectRootFromSession,
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
createErrorResponse
|
||||
} from './utils.js';
|
||||
import { modelsDirect } from '../core/task-master-core.js';
|
||||
|
||||
@@ -42,9 +42,7 @@ export function registerModelsTool(server) {
|
||||
listAvailableModels: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
'List all available models not currently in use. Input/output costs values are in dollars (3 is $3.00).'
|
||||
),
|
||||
.describe('List all available models not currently in use.'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.optional()
|
||||
@@ -58,22 +56,34 @@ export function registerModelsTool(server) {
|
||||
.optional()
|
||||
.describe('Indicates the set model ID is a custom Ollama model.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Starting models tool with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Call the direct function
|
||||
const result = await modelsDirect(
|
||||
{ ...args, projectRoot: args.projectRoot },
|
||||
{ ...args, projectRoot: rootFolder },
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
// Handle and return the result
|
||||
return handleApiResult(result, log);
|
||||
} catch (error) {
|
||||
log.error(`Error in models tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
/**
|
||||
* tools/move-task.js
|
||||
* Tool for moving tasks or subtasks to a new position
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
} from './utils.js';
|
||||
import { moveTaskDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Register the moveTask tool with the MCP server
|
||||
* @param {Object} server - FastMCP server instance
|
||||
*/
|
||||
export function registerMoveTaskTool(server) {
|
||||
server.addTool({
|
||||
name: 'move_task',
|
||||
description: 'Move a task or subtask to a new position',
|
||||
parameters: z.object({
|
||||
from: z
|
||||
.string()
|
||||
.describe(
|
||||
'ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")'
|
||||
),
|
||||
to: z
|
||||
.string()
|
||||
.describe(
|
||||
'ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated'
|
||||
),
|
||||
file: z.string().optional().describe('Custom path to tasks.json file'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Root directory of the project (typically derived from session)'
|
||||
)
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
try {
|
||||
// Find tasks.json path if not provided
|
||||
let tasksJsonPath = args.file;
|
||||
|
||||
if (!tasksJsonPath) {
|
||||
tasksJsonPath = findTasksJsonPath(args, log);
|
||||
}
|
||||
|
||||
// Parse comma-separated IDs
|
||||
const fromIds = args.from.split(',').map((id) => id.trim());
|
||||
const toIds = args.to.split(',').map((id) => id.trim());
|
||||
|
||||
// Validate matching IDs count
|
||||
if (fromIds.length !== toIds.length) {
|
||||
return createErrorResponse(
|
||||
'The number of source and destination IDs must match',
|
||||
'MISMATCHED_ID_COUNT'
|
||||
);
|
||||
}
|
||||
|
||||
// If moving multiple tasks
|
||||
if (fromIds.length > 1) {
|
||||
const results = [];
|
||||
// Move tasks one by one, only generate files on the last move
|
||||
for (let i = 0; i < fromIds.length; i++) {
|
||||
const fromId = fromIds[i];
|
||||
const toId = toIds[i];
|
||||
|
||||
// Skip if source and destination are the same
|
||||
if (fromId === toId) {
|
||||
log.info(`Skipping ${fromId} -> ${toId} (same ID)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const shouldGenerateFiles = i === fromIds.length - 1;
|
||||
const result = await moveTaskDirect(
|
||||
{
|
||||
sourceId: fromId,
|
||||
destinationId: toId,
|
||||
tasksJsonPath,
|
||||
projectRoot: args.projectRoot
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
log.error(
|
||||
`Failed to move ${fromId} to ${toId}: ${result.error.message}`
|
||||
);
|
||||
} else {
|
||||
results.push(result.data);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
moves: results,
|
||||
message: `Successfully moved ${results.length} tasks`
|
||||
}
|
||||
};
|
||||
} else {
|
||||
// Moving a single task
|
||||
return handleApiResult(
|
||||
await moveTaskDirect(
|
||||
{
|
||||
sourceId: args.from,
|
||||
destinationId: args.to,
|
||||
tasksJsonPath,
|
||||
projectRoot: args.projectRoot
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
),
|
||||
log
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
return createErrorResponse(
|
||||
`Failed to move task: ${error.message}`,
|
||||
'MOVE_TASK_ERROR'
|
||||
);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -7,13 +7,10 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { nextTaskDirect } from '../core/task-master-core.js';
|
||||
import {
|
||||
findTasksJsonPath,
|
||||
findComplexityReportPath
|
||||
} from '../core/utils/path-utils.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Register the next-task tool with the MCP server
|
||||
@@ -26,25 +23,30 @@ export function registerNextTaskTool(server) {
|
||||
'Find the next task to work on based on dependencies and status',
|
||||
parameters: z.object({
|
||||
file: z.string().optional().describe('Absolute path to the tasks file'),
|
||||
complexityReport: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Path to the complexity report file (relative to project root or absolute)'
|
||||
),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Finding next task with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -54,21 +56,11 @@ export function registerNextTaskTool(server) {
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to complexity report
|
||||
let complexityReportPath;
|
||||
try {
|
||||
complexityReportPath = findComplexityReportPath(
|
||||
args.projectRoot,
|
||||
args.complexityReport,
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Error finding complexity report: ${error.message}`);
|
||||
}
|
||||
const result = await nextTaskDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
reportPath: complexityReportPath
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath
|
||||
// No other args specific to this tool
|
||||
},
|
||||
log
|
||||
);
|
||||
@@ -88,6 +80,6 @@ export function registerNextTaskTool(server) {
|
||||
log.error(`Error in nextTask tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,16 +4,16 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import path from 'path';
|
||||
import {
|
||||
getProjectRootFromSession,
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
createErrorResponse
|
||||
} from './utils.js';
|
||||
import { parsePRDDirect } from '../core/task-master-core.js';
|
||||
import { resolveProjectPaths } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Register the parse_prd tool
|
||||
* Register the parsePRD tool with the MCP server
|
||||
* @param {Object} server - FastMCP server instance
|
||||
*/
|
||||
export function registerParsePRDTool(server) {
|
||||
@@ -42,58 +42,72 @@ export function registerParsePRDTool(server) {
|
||||
force: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe('Overwrite existing output file without prompting.'),
|
||||
.describe('Allow overwriting an existing tasks.json file.'),
|
||||
append: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe('Append generated tasks to existing file.'),
|
||||
research: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe(
|
||||
'Use the research model for research-backed task generation, providing more comprehensive, accurate and up-to-date task details.'
|
||||
'Append new tasks to existing tasks.json instead of overwriting'
|
||||
),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
.describe('The directory of the project. Must be absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
const toolName = 'parse_prd';
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Executing ${toolName} tool with args: ${JSON.stringify(args)}`
|
||||
log.info(`Parsing PRD with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve input (PRD) and output (tasks.json) paths using the utility
|
||||
const { projectRoot, prdPath, tasksJsonPath } = resolveProjectPaths(
|
||||
rootFolder,
|
||||
args,
|
||||
log
|
||||
);
|
||||
|
||||
// Call Direct Function - Pass relevant args including projectRoot
|
||||
// Check if PRD path was found (resolveProjectPaths returns null if not found and not provided)
|
||||
if (!prdPath) {
|
||||
return createErrorResponse(
|
||||
'No PRD document found or provided. Please ensure a PRD file exists (e.g., PRD.md) or provide a valid input file path.'
|
||||
);
|
||||
}
|
||||
|
||||
// Call the direct function with fully resolved paths
|
||||
const result = await parsePRDDirect(
|
||||
{
|
||||
input: args.input,
|
||||
output: args.output,
|
||||
projectRoot: projectRoot,
|
||||
input: prdPath,
|
||||
output: tasksJsonPath,
|
||||
numTasks: args.numTasks,
|
||||
force: args.force,
|
||||
append: args.append,
|
||||
research: args.research,
|
||||
projectRoot: args.projectRoot
|
||||
append: args.append
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
log.info(
|
||||
`${toolName}: Direct function result: success=${result.success}`
|
||||
if (result.success) {
|
||||
log.info(`Successfully parsed PRD: ${result.data.message}`);
|
||||
} else {
|
||||
log.error(
|
||||
`Failed to parse PRD: ${result.error?.message || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
|
||||
return handleApiResult(result, log, 'Error parsing PRD');
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
log.error(`Error in parse-prd tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { removeDependencyDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -33,17 +33,28 @@ export function registerRemoveDependencyTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Removing dependency for task ${args.id} from ${args.dependsOn} with args: ${JSON.stringify(args)}`
|
||||
);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -55,7 +66,9 @@ export function registerRemoveDependencyTool(server) {
|
||||
|
||||
const result = await removeDependencyDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
dependsOn: args.dependsOn
|
||||
},
|
||||
@@ -73,6 +86,6 @@ export function registerRemoveDependencyTool(server) {
|
||||
log.error(`Error in removeDependency tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { removeSubtaskDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -46,15 +46,26 @@ export function registerRemoveSubtaskTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Removing subtask with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -66,7 +77,9 @@ export function registerRemoveSubtaskTool(server) {
|
||||
|
||||
const result = await removeSubtaskDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
convert: args.convert,
|
||||
skipGenerate: args.skipGenerate
|
||||
@@ -85,6 +98,6 @@ export function registerRemoveSubtaskTool(server) {
|
||||
log.error(`Error in removeSubtask tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { removeTaskDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -35,15 +35,28 @@ export function registerRemoveTaskTool(server) {
|
||||
.optional()
|
||||
.describe('Whether to skip confirmation prompt (default: false)')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Removing task(s) with ID(s): ${args.id}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
log.info(`Using project root: ${rootFolder}`);
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -55,6 +68,7 @@ export function registerRemoveTaskTool(server) {
|
||||
|
||||
log.info(`Using tasks file path: ${tasksJsonPath}`);
|
||||
|
||||
// Assume client has already handled confirmation if needed
|
||||
const result = await removeTaskDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
@@ -74,6 +88,6 @@ export function registerRemoveTaskTool(server) {
|
||||
log.error(`Error in remove-task tool: ${error.message}`);
|
||||
return createErrorResponse(`Failed to remove task: ${error.message}`);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,17 +7,10 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import {
|
||||
setTaskStatusDirect,
|
||||
nextTaskDirect
|
||||
} from '../core/task-master-core.js';
|
||||
import {
|
||||
findTasksJsonPath,
|
||||
findComplexityReportPath
|
||||
} from '../core/utils/path-utils.js';
|
||||
import { TASK_STATUS_OPTIONS } from '../../../src/constants/task-status.js';
|
||||
import { setTaskStatusDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Register the setTaskStatus tool with the MCP server
|
||||
@@ -34,30 +27,35 @@ export function registerSetTaskStatusTool(server) {
|
||||
"Task ID or subtask ID (e.g., '15', '15.2'). Can be comma-separated to update multiple tasks/subtasks at once."
|
||||
),
|
||||
status: z
|
||||
.enum(TASK_STATUS_OPTIONS)
|
||||
.string()
|
||||
.describe(
|
||||
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
|
||||
),
|
||||
file: z.string().optional().describe('Absolute path to the tasks file'),
|
||||
complexityReport: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Path to the complexity report file (relative to project root or absolute)'
|
||||
),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log }) => {
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Setting status of task(s) ${args.id} to: ${args.status}`);
|
||||
|
||||
// Use args.projectRoot directly (guaranteed by withNormalizedProjectRoot)
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -67,27 +65,19 @@ export function registerSetTaskStatusTool(server) {
|
||||
);
|
||||
}
|
||||
|
||||
let complexityReportPath;
|
||||
try {
|
||||
complexityReportPath = findComplexityReportPath(
|
||||
args.projectRoot,
|
||||
args.complexityReport,
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Error finding complexity report: ${error.message}`);
|
||||
}
|
||||
|
||||
// Call the direct function with the resolved path
|
||||
const result = await setTaskStatusDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
status: args.status,
|
||||
complexityReportPath
|
||||
status: args.status
|
||||
},
|
||||
log
|
||||
);
|
||||
|
||||
// Log the result
|
||||
if (result.success) {
|
||||
log.info(
|
||||
`Successfully updated status for task(s) ${args.id} to "${args.status}": ${result.data.message}`
|
||||
@@ -98,6 +88,7 @@ export function registerSetTaskStatusTool(server) {
|
||||
);
|
||||
}
|
||||
|
||||
// Format and return the result
|
||||
return handleApiResult(result, log, 'Error setting task status');
|
||||
} catch (error) {
|
||||
log.error(`Error in setTaskStatus tool: ${error.message}`);
|
||||
@@ -105,6 +96,6 @@ export function registerSetTaskStatusTool(server) {
|
||||
`Error setting task status: ${error.message}`
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { updateSubtaskByIdDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -37,19 +37,30 @@ export function registerUpdateSubtaskTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
const toolName = 'update_subtask';
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`${toolName}: Error finding tasks.json: ${error.message}`);
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json: ${error.message}`
|
||||
);
|
||||
@@ -57,11 +68,12 @@ export function registerUpdateSubtaskTool(server) {
|
||||
|
||||
const result = await updateSubtaskByIdDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
prompt: args.prompt,
|
||||
research: args.research,
|
||||
projectRoot: args.projectRoot
|
||||
research: args.research
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
@@ -77,13 +89,9 @@ export function registerUpdateSubtaskTool(server) {
|
||||
|
||||
return handleApiResult(result, log, 'Error updating subtask');
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
log.error(`Error in update_subtask tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { updateTaskByIdDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
@@ -23,7 +23,7 @@ export function registerUpdateTaskTool(server) {
|
||||
'Updates a single task by ID with new information or context provided in the prompt.',
|
||||
parameters: z.object({
|
||||
id: z
|
||||
.string() // ID can be number or string like "1.2"
|
||||
.string()
|
||||
.describe(
|
||||
"ID of the task (e.g., '15') to update. Subtasks are supported using the update-subtask tool."
|
||||
),
|
||||
@@ -39,53 +39,61 @@ export function registerUpdateTaskTool(server) {
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
const toolName = 'update_task';
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Executing ${toolName} tool with args: ${JSON.stringify(args)}`
|
||||
);
|
||||
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: args.projectRoot, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
log.info(`${toolName}: Resolved tasks path: ${tasksJsonPath}`);
|
||||
} catch (error) {
|
||||
log.error(`${toolName}: Error finding tasks.json: ${error.message}`);
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json: ${error.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Call Direct Function - Include projectRoot
|
||||
const result = await updateTaskByIdDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
prompt: args.prompt,
|
||||
research: args.research,
|
||||
projectRoot: args.projectRoot
|
||||
research: args.research
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
// 4. Handle Result
|
||||
log.info(
|
||||
`${toolName}: Direct function result: success=${result.success}`
|
||||
if (result.success) {
|
||||
log.info(`Successfully updated task with ID ${args.id}`);
|
||||
} else {
|
||||
log.error(
|
||||
`Failed to update task: ${result.error?.message || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
|
||||
return handleApiResult(result, log, 'Error updating task');
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
log.error(`Error in update_task tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,13 +4,10 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
withNormalizedProjectRoot
|
||||
} from './utils.js';
|
||||
import { handleApiResult, createErrorResponse } from './utils.js';
|
||||
import { updateTasksDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* Register the update tool with the MCP server
|
||||
@@ -34,61 +31,58 @@ export function registerUpdateTool(server) {
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe('Use Perplexity AI for research-backed updates'),
|
||||
file: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Path to the tasks file relative to project root'),
|
||||
file: z.string().optional().describe('Absolute path to the tasks file'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'The directory of the project. (Optional, usually from session)'
|
||||
)
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||
const toolName = 'update';
|
||||
const { from, prompt, research, file, projectRoot } = args;
|
||||
|
||||
execute: async (args, { log, session }) => {
|
||||
try {
|
||||
log.info(
|
||||
`Executing ${toolName} tool with normalized root: ${projectRoot}`
|
||||
);
|
||||
log.info(`Executing update tool with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// 1. Get Project Root
|
||||
const rootFolder = args.projectRoot;
|
||||
if (!rootFolder || !path.isAbsolute(rootFolder)) {
|
||||
return createErrorResponse(
|
||||
'projectRoot is required and must be absolute.'
|
||||
);
|
||||
}
|
||||
log.info(`Project root: ${rootFolder}`);
|
||||
|
||||
// 2. Resolve Path
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath({ projectRoot, file }, log);
|
||||
log.info(`${toolName}: Resolved tasks path: ${tasksJsonPath}`);
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
log.info(`Resolved tasks path: ${tasksJsonPath}`);
|
||||
} catch (error) {
|
||||
log.error(`${toolName}: Error finding tasks.json: ${error.message}`);
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json within project root '${projectRoot}': ${error.message}`
|
||||
`Failed to find tasks.json: ${error.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Call Direct Function
|
||||
const result = await updateTasksDirect(
|
||||
{
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
from: from,
|
||||
prompt: prompt,
|
||||
research: research,
|
||||
projectRoot: projectRoot
|
||||
from: args.from,
|
||||
prompt: args.prompt,
|
||||
research: args.research
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
);
|
||||
|
||||
log.info(
|
||||
`${toolName}: Direct function result: success=${result.success}`
|
||||
);
|
||||
// 4. Handle Result
|
||||
log.info(`updateTasksDirect result: success=${result.success}`);
|
||||
return handleApiResult(result, log, 'Error updating tasks');
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
log.error(`Critical error in update tool execute: ${error.message}`);
|
||||
return createErrorResponse(`Internal tool error: ${error.message}`);
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user