Compare commits
63 Commits
crunchyman
...
v0.15.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1e45ff50e | ||
|
|
1513858da4 | ||
|
|
59dcf4bd64 | ||
|
|
a09ba021c5 | ||
|
|
e906166141 | ||
|
|
231e569e84 | ||
|
|
09add37423 | ||
|
|
91fc779714 | ||
|
|
8c69c0aafd | ||
|
|
43ad75c7fa | ||
|
|
a59dd037cf | ||
|
|
3293c7858b | ||
|
|
b371808524 | ||
|
|
86d8f00af8 | ||
|
|
0c55ce0165 | ||
|
|
5a91941913 | ||
|
|
04af16de27 | ||
|
|
edf0f23005 | ||
|
|
e0e1155260 | ||
|
|
70f4054f26 | ||
|
|
34c769bcd0 | ||
|
|
34df2c8bbd | ||
|
|
5e9bc28abe | ||
|
|
d2e64318e2 | ||
|
|
4c835264ac | ||
|
|
c882f89a8c | ||
|
|
20e1b72a17 | ||
|
|
db631f43a5 | ||
|
|
3b9402f1f8 | ||
|
|
c8c0fc2a57 | ||
|
|
60b8e97a1c | ||
|
|
3a6d6dd671 | ||
|
|
f4a83ec047 | ||
|
|
0699f64299 | ||
|
|
60b8f5faa3 | ||
|
|
cd6e42249e | ||
|
|
fcd80623b6 | ||
|
|
026815353f | ||
|
|
8a3b611fc2 | ||
|
|
6ba42b53dc | ||
|
|
3e304232ab | ||
|
|
70fa5b0031 | ||
|
|
314c0de8c4 | ||
|
|
58b417a8ce | ||
|
|
a8dabf4485 | ||
|
|
bc19bc7927 | ||
|
|
da636f6681 | ||
|
|
ca5ec03cd8 | ||
|
|
79a41543d5 | ||
|
|
9f4bac8d6a | ||
|
|
e53d5e1577 | ||
|
|
59230c4d91 | ||
|
|
04b6a3cb21 | ||
|
|
37178ff1b9 | ||
|
|
bbc8b9cc1f | ||
|
|
c955431753 | ||
|
|
21c3cb8cda | ||
|
|
ab84afd036 | ||
|
|
f89d2aacc0 | ||
|
|
0288311965 | ||
|
|
8ae772086d | ||
|
|
2b3ae8bf89 | ||
|
|
245c3cb398 |
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Resolve all issues related to MCP
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix CLI --force flag for parse-prd command
|
|
||||||
|
|
||||||
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
|
|
||||||
|
|
||||||
- Fixes #477
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': minor
|
|
||||||
---
|
|
||||||
|
|
||||||
.taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Task Master no longer tells you to update when you're already up to date
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
{
|
|
||||||
"mode": "exit",
|
|
||||||
"tag": "rc",
|
|
||||||
"initialVersions": {
|
|
||||||
"task-master-ai": "0.13.2"
|
|
||||||
},
|
|
||||||
"changesets": [
|
|
||||||
"beige-doodles-type",
|
|
||||||
"red-oranges-attend",
|
|
||||||
"red-suns-wash"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Add src directory to exports
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix the error handling of task status settings
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Remove caching layer from MCP direct functions for task listing, next task, and complexity report
|
|
||||||
|
|
||||||
- Fixes issues users where having where they were getting stale data
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix for issue #409 LOG_LEVEL Pydantic validation error
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix initial .env.example to work out of the box
|
|
||||||
|
|
||||||
- Closes #419
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix default fallback model and maxTokens in Taskmaster initialization
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix bug when updating tasks on the MCP server (#412)
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
---
|
|
||||||
'task-master-ai': patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Fix duplicate output on CLI help screen
|
|
||||||
|
|
||||||
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
|
|
||||||
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
|
|
||||||
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
|
|
||||||
- Ensures a clean, branded help experience with no repeated content.
|
|
||||||
- Fixes #339
|
|
||||||
@@ -25,6 +25,7 @@ This document outlines the architecture and usage patterns for interacting with
|
|||||||
* Implements **retry logic** for specific API errors (`_attemptProviderCallWithRetries`).
|
* Implements **retry logic** for specific API errors (`_attemptProviderCallWithRetries`).
|
||||||
* Resolves API keys automatically via `_resolveApiKey` (using `resolveEnvVariable`).
|
* Resolves API keys automatically via `_resolveApiKey` (using `resolveEnvVariable`).
|
||||||
* Maps requests to the correct provider implementation (in `src/ai-providers/`) via `PROVIDER_FUNCTIONS`.
|
* 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`):**
|
* **Provider Implementations (`src/ai-providers/*.js`):**
|
||||||
* Contain provider-specific wrappers around Vercel AI SDK functions (`generateText`, `generateObject`).
|
* Contain provider-specific wrappers around Vercel AI SDK functions (`generateText`, `generateObject`).
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ alwaysApply: false
|
|||||||
- Resolves API keys (from `.env` or `session.env`).
|
- Resolves API keys (from `.env` or `session.env`).
|
||||||
- Implements fallback and retry logic.
|
- Implements fallback and retry logic.
|
||||||
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
|
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
|
||||||
|
- Telemetry data generated by the AI service layer is propagated upwards through core logic, direct functions, and MCP tools. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the detailed integration pattern.
|
||||||
|
|
||||||
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
|
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
|
||||||
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.
|
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ Task Master offers two primary ways to interact:
|
|||||||
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
|
- 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
|
- Respect dependency chains and task priorities when selecting work
|
||||||
- Report progress regularly using `get_tasks` / `task-master list`
|
- 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
|
## Task Complexity Analysis
|
||||||
|
|
||||||
@@ -154,6 +155,25 @@ Taskmaster configuration is managed through two main mechanisms:
|
|||||||
- Task files are automatically regenerated after dependency changes
|
- Task files are automatically regenerated after dependency changes
|
||||||
- Dependencies are visualized with status indicators in task listings and files
|
- 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
|
## Iterative Subtask Implementation
|
||||||
|
|
||||||
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:
|
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ description: Glossary of other Cursor rules
|
|||||||
globs: **/*
|
globs: **/*
|
||||||
alwaysApply: true
|
alwaysApply: true
|
||||||
---
|
---
|
||||||
|
|
||||||
# Glossary of Task Master Cursor Rules
|
# 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.
|
This file provides a quick reference to the purpose of each rule file located in the `.cursor/rules` directory.
|
||||||
@@ -23,4 +22,5 @@ This file provides a quick reference to the purpose of each rule file located in
|
|||||||
- **[`tests.mdc`](mdc:.cursor/rules/tests.mdc)**: Guidelines for implementing and maintaining tests for Task Master CLI.
|
- **[`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.
|
- **[`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.
|
- **[`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.
|
||||||
|
|
||||||
|
|||||||
@@ -522,3 +522,8 @@ Follow these steps to add MCP support for an existing Task Master command (see [
|
|||||||
// Add more functions as implemented
|
// 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,7 +3,6 @@ description: Guidelines for integrating new features into the Task Master CLI
|
|||||||
globs: scripts/modules/*.js
|
globs: scripts/modules/*.js
|
||||||
alwaysApply: false
|
alwaysApply: false
|
||||||
---
|
---
|
||||||
|
|
||||||
# Task Master Feature Integration Guidelines
|
# Task Master Feature Integration Guidelines
|
||||||
|
|
||||||
## Feature Placement Decision Process
|
## Feature Placement Decision Process
|
||||||
@@ -196,6 +195,8 @@ The standard pattern for adding a feature follows this workflow:
|
|||||||
- ✅ **DO**: If an MCP tool fails with vague errors (e.g., JSON parsing issues like `Unexpected token ... is not valid JSON`), **try running the equivalent CLI command directly in the terminal** (e.g., `task-master expand --all`). CLI output often provides much more specific error messages (like missing function definitions or stack traces from the core logic) that pinpoint the root cause.
|
- ✅ **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.
|
- ❌ **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
|
```javascript
|
||||||
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
|
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -269,11 +269,36 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
|
* `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.
|
* **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
|
## Dependency Management
|
||||||
|
|
||||||
### 17. Add Dependency (`add_dependency`)
|
### 18. Add Dependency (`add_dependency`)
|
||||||
|
|
||||||
* **MCP Tool:** `add_dependency`
|
* **MCP Tool:** `add_dependency`
|
||||||
* **CLI Command:** `task-master add-dependency [options]`
|
* **CLI Command:** `task-master add-dependency [options]`
|
||||||
@@ -284,7 +309,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>`)
|
* `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.
|
* **Usage:** Establish the correct order of execution between tasks.
|
||||||
|
|
||||||
### 18. Remove Dependency (`remove_dependency`)
|
### 19. Remove Dependency (`remove_dependency`)
|
||||||
|
|
||||||
* **MCP Tool:** `remove_dependency`
|
* **MCP Tool:** `remove_dependency`
|
||||||
* **CLI Command:** `task-master remove-dependency [options]`
|
* **CLI Command:** `task-master remove-dependency [options]`
|
||||||
@@ -295,7 +320,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>`)
|
* `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.
|
* **Usage:** Update task relationships when the order of execution changes.
|
||||||
|
|
||||||
### 19. Validate Dependencies (`validate_dependencies`)
|
### 20. Validate Dependencies (`validate_dependencies`)
|
||||||
|
|
||||||
* **MCP Tool:** `validate_dependencies`
|
* **MCP Tool:** `validate_dependencies`
|
||||||
* **CLI Command:** `task-master validate-dependencies [options]`
|
* **CLI Command:** `task-master validate-dependencies [options]`
|
||||||
@@ -304,7 +329,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>`)
|
* `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.
|
* **Usage:** Audit the integrity of your task dependencies.
|
||||||
|
|
||||||
### 20. Fix Dependencies (`fix_dependencies`)
|
### 21. Fix Dependencies (`fix_dependencies`)
|
||||||
|
|
||||||
* **MCP Tool:** `fix_dependencies`
|
* **MCP Tool:** `fix_dependencies`
|
||||||
* **CLI Command:** `task-master fix-dependencies [options]`
|
* **CLI Command:** `task-master fix-dependencies [options]`
|
||||||
@@ -317,7 +342,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
|
|
||||||
## Analysis & Reporting
|
## Analysis & Reporting
|
||||||
|
|
||||||
### 21. Analyze Project Complexity (`analyze_project_complexity`)
|
### 22. Analyze Project Complexity (`analyze_project_complexity`)
|
||||||
|
|
||||||
* **MCP Tool:** `analyze_project_complexity`
|
* **MCP Tool:** `analyze_project_complexity`
|
||||||
* **CLI Command:** `task-master analyze-complexity [options]`
|
* **CLI Command:** `task-master analyze-complexity [options]`
|
||||||
@@ -330,7 +355,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.
|
* **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.
|
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
|
||||||
|
|
||||||
### 22. View Complexity Report (`complexity_report`)
|
### 23. View Complexity Report (`complexity_report`)
|
||||||
|
|
||||||
* **MCP Tool:** `complexity_report`
|
* **MCP Tool:** `complexity_report`
|
||||||
* **CLI Command:** `task-master complexity-report [options]`
|
* **CLI Command:** `task-master complexity-report [options]`
|
||||||
@@ -343,7 +368,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
|
|||||||
|
|
||||||
## File Management
|
## File Management
|
||||||
|
|
||||||
### 23. Generate Task Files (`generate`)
|
### 24. Generate Task Files (`generate`)
|
||||||
|
|
||||||
* **MCP Tool:** `generate`
|
* **MCP Tool:** `generate`
|
||||||
* **CLI Command:** `task-master generate [options]`
|
* **CLI Command:** `task-master generate [options]`
|
||||||
|
|||||||
228
.cursor/rules/telemetry.mdc
Normal file
228
.cursor/rules/telemetry.mdc
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
---
|
||||||
|
description: Guidelines for integrating AI usage telemetry across Task Master.
|
||||||
|
globs: scripts/modules/**/*.js,mcp-server/src/**/*.js
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# AI Usage Telemetry Integration
|
||||||
|
|
||||||
|
This document outlines the standard pattern for capturing, propagating, and handling AI usage telemetry data (cost, tokens, model, etc.) across the Task Master stack. This ensures consistent telemetry for both CLI and MCP interactions.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Telemetry data is generated within the unified AI service layer ([`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)) and then passed upwards through the calling functions.
|
||||||
|
|
||||||
|
- **Data Source**: [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js) (specifically its `generateTextService`, `generateObjectService`, etc.) returns an object like `{ mainResult: AI_CALL_OUTPUT, telemetryData: TELEMETRY_OBJECT }`.
|
||||||
|
- **`telemetryData` Object Structure**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"timestamp": "ISO_STRING_DATE",
|
||||||
|
"userId": "USER_ID_FROM_CONFIG",
|
||||||
|
"commandName": "invoking_command_or_tool_name",
|
||||||
|
"modelUsed": "ai_model_id",
|
||||||
|
"providerName": "ai_provider_name",
|
||||||
|
"inputTokens": NUMBER,
|
||||||
|
"outputTokens": NUMBER,
|
||||||
|
"totalTokens": NUMBER,
|
||||||
|
"totalCost": NUMBER, // e.g., 0.012414
|
||||||
|
"currency": "USD" // e.g., "USD"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Integration Pattern by Layer
|
||||||
|
|
||||||
|
The key principle is that each layer receives telemetry data from the layer below it (if applicable) and passes it to the layer above it, or handles it for display in the case of the CLI.
|
||||||
|
|
||||||
|
### 1. Core Logic Functions (e.g., in `scripts/modules/task-manager/`)
|
||||||
|
|
||||||
|
Functions in this layer that invoke AI services are responsible for handling the `telemetryData` they receive from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
|
||||||
|
|
||||||
|
- **Actions**:
|
||||||
|
1. Call the appropriate AI service function (e.g., `generateObjectService`).
|
||||||
|
- Pass `commandName` (e.g., `add-task`, `expand-task`) and `outputType` (e.g., `cli` or `mcp`) in the `params` object to the AI service. The `outputType` can be derived from context (e.g., presence of `mcpLog`).
|
||||||
|
2. The AI service returns an object, e.g., `aiServiceResponse = { mainResult: {/*AI output*/}, telemetryData: {/*telemetry data*/} }`.
|
||||||
|
3. Extract `aiServiceResponse.mainResult` for the core processing.
|
||||||
|
4. **Must return an object that includes `aiServiceResponse.telemetryData`**.
|
||||||
|
Example: `return { operationSpecificData: /*...*/, telemetryData: aiServiceResponse.telemetryData };`
|
||||||
|
|
||||||
|
- **CLI Output Handling (If Applicable)**:
|
||||||
|
- If the core function also handles CLI output (e.g., it has an `outputFormat` parameter that can be `'text'` or `'cli'`):
|
||||||
|
1. Check if `outputFormat === 'text'` (or `'cli'`).
|
||||||
|
2. If so, and if `aiServiceResponse.telemetryData` is available, call `displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli')` from [`scripts/modules/ui.js`](mdc:scripts/modules/ui.js).
|
||||||
|
- This ensures telemetry is displayed directly to CLI users after the main command output.
|
||||||
|
|
||||||
|
- **Example Snippet (Core Logic in `scripts/modules/task-manager/someAiAction.js`)**:
|
||||||
|
```javascript
|
||||||
|
import { generateObjectService } from '../ai-services-unified.js';
|
||||||
|
import { displayAiUsageSummary } from '../ui.js';
|
||||||
|
|
||||||
|
async function performAiRelatedAction(params, context, outputFormat = 'text') {
|
||||||
|
const { commandNameFromContext, /* other context vars */ } = context;
|
||||||
|
let aiServiceResponse = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
aiServiceResponse = await generateObjectService({
|
||||||
|
// ... other parameters for AI service ...
|
||||||
|
commandName: commandNameFromContext || 'default-action-name',
|
||||||
|
outputType: context.mcpLog ? 'mcp' : 'cli' // Derive outputType
|
||||||
|
});
|
||||||
|
|
||||||
|
const usefulAiOutput = aiServiceResponse.mainResult.object;
|
||||||
|
// ... do work with usefulAiOutput ...
|
||||||
|
|
||||||
|
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
|
||||||
|
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
actionData: /* results of processing */,
|
||||||
|
telemetryData: aiServiceResponse.telemetryData
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// ... handle error ...
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Direct Function Wrappers (in `mcp-server/src/core/direct-functions/`)
|
||||||
|
|
||||||
|
These functions adapt core logic for the MCP server, ensuring structured responses.
|
||||||
|
|
||||||
|
- **Actions**:
|
||||||
|
1. Call the corresponding core logic function.
|
||||||
|
- Pass necessary context (e.g., `session`, `mcpLog`, `projectRoot`).
|
||||||
|
- Provide the `commandName` (typically derived from the MCP tool name) and `outputType: 'mcp'` in the context object passed to the core function.
|
||||||
|
- If the core function supports an `outputFormat` parameter, pass `'json'` to suppress CLI-specific UI.
|
||||||
|
2. The core logic function returns an object (e.g., `coreResult = { actionData: ..., telemetryData: ... }`).
|
||||||
|
3. Include `coreResult.telemetryData` as a field within the `data` object of the successful response returned by the direct function.
|
||||||
|
|
||||||
|
- **Example Snippet (Direct Function `someAiActionDirect.js`)**:
|
||||||
|
```javascript
|
||||||
|
import { performAiRelatedAction } from '../../../../scripts/modules/task-manager/someAiAction.js'; // Core function
|
||||||
|
import { createLogWrapper } from '../../tools/utils.js'; // MCP Log wrapper
|
||||||
|
|
||||||
|
export async function someAiActionDirect(args, log, context = {}) {
|
||||||
|
const { session } = context;
|
||||||
|
// ... prepare arguments for core function from args, including args.projectRoot ...
|
||||||
|
|
||||||
|
try {
|
||||||
|
const coreResult = await performAiRelatedAction(
|
||||||
|
{ /* parameters for core function */ },
|
||||||
|
{ // Context for core function
|
||||||
|
session,
|
||||||
|
mcpLog: createLogWrapper(log),
|
||||||
|
projectRoot: args.projectRoot,
|
||||||
|
commandNameFromContext: 'mcp_tool_some_ai_action', // Example command name
|
||||||
|
outputType: 'mcp'
|
||||||
|
},
|
||||||
|
'json' // Request 'json' output format from core function
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
operationSpecificData: coreResult.actionData,
|
||||||
|
telemetryData: coreResult.telemetryData // Pass telemetry through
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// ... error handling, return { success: false, error: ... } ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. MCP Tools (in `mcp-server/src/tools/`)
|
||||||
|
|
||||||
|
These are the exposed endpoints for MCP clients.
|
||||||
|
|
||||||
|
- **Actions**:
|
||||||
|
1. Call the corresponding direct function wrapper.
|
||||||
|
2. The direct function returns an object structured like `{ success: true, data: { operationSpecificData: ..., telemetryData: ... } }` (or an error object).
|
||||||
|
3. Pass this entire result object to `handleApiResult(result, log)` from [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
|
||||||
|
4. `handleApiResult` ensures that the `data` field from the direct function's response (which correctly includes `telemetryData`) is part of the final MCP response.
|
||||||
|
|
||||||
|
- **Example Snippet (MCP Tool `some_ai_action.js`)**:
|
||||||
|
```javascript
|
||||||
|
import { someAiActionDirect } from '../core/task-master-core.js';
|
||||||
|
import { handleApiResult, withNormalizedProjectRoot } from './utils.js';
|
||||||
|
// ... zod for parameters ...
|
||||||
|
|
||||||
|
export function registerSomeAiActionTool(server) {
|
||||||
|
server.addTool({
|
||||||
|
name: "some_ai_action",
|
||||||
|
// ... description, parameters ...
|
||||||
|
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
|
||||||
|
try {
|
||||||
|
const resultFromDirectFunction = await someAiActionDirect(
|
||||||
|
{ /* args including projectRoot */ },
|
||||||
|
log,
|
||||||
|
{ session }
|
||||||
|
);
|
||||||
|
return handleApiResult(resultFromDirectFunction, log); // This passes the nested telemetryData through
|
||||||
|
} catch (error) {
|
||||||
|
// ... error handling ...
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. CLI Commands (`scripts/modules/commands.js`)
|
||||||
|
|
||||||
|
These define the command-line interface.
|
||||||
|
|
||||||
|
- **Actions**:
|
||||||
|
1. Call the appropriate core logic function.
|
||||||
|
2. Pass `outputFormat: 'text'` (or ensure the core function defaults to text-based output for CLI).
|
||||||
|
3. The core logic function (as per Section 1) is responsible for calling `displayAiUsageSummary` if telemetry data is available and it's in CLI mode.
|
||||||
|
4. The command action itself **should not** call `displayAiUsageSummary` if the core logic function already handles this. This avoids duplicate display.
|
||||||
|
|
||||||
|
- **Example Snippet (CLI Command in `commands.js`)**:
|
||||||
|
```javascript
|
||||||
|
// In scripts/modules/commands.js
|
||||||
|
import { performAiRelatedAction } from './task-manager/someAiAction.js'; // Core function
|
||||||
|
|
||||||
|
programInstance
|
||||||
|
.command('some-cli-ai-action')
|
||||||
|
// ... .option() ...
|
||||||
|
.action(async (options) => {
|
||||||
|
try {
|
||||||
|
const projectRoot = findProjectRoot() || '.'; // Example root finding
|
||||||
|
// ... prepare parameters for core function from command options ...
|
||||||
|
await performAiRelatedAction(
|
||||||
|
{ /* parameters for core function */ },
|
||||||
|
{ // Context for core function
|
||||||
|
projectRoot,
|
||||||
|
commandNameFromContext: 'some-cli-ai-action',
|
||||||
|
outputType: 'cli'
|
||||||
|
},
|
||||||
|
'text' // Explicitly request text output format for CLI
|
||||||
|
);
|
||||||
|
// Core function handles displayAiUsageSummary internally for 'text' outputFormat
|
||||||
|
} catch (error) {
|
||||||
|
// ... error handling ...
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Summary Flow
|
||||||
|
|
||||||
|
The telemetry data flows as follows:
|
||||||
|
|
||||||
|
1. **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)**: Generates `telemetryData` and returns `{ mainResult, telemetryData }`.
|
||||||
|
2. **Core Logic Function**:
|
||||||
|
* Receives `{ mainResult, telemetryData }`.
|
||||||
|
* Uses `mainResult`.
|
||||||
|
* If CLI (`outputFormat: 'text'`), calls `displayAiUsageSummary(telemetryData)`.
|
||||||
|
* Returns `{ operationSpecificData, telemetryData }`.
|
||||||
|
3. **Direct Function Wrapper**:
|
||||||
|
* Receives `{ operationSpecificData, telemetryData }` from core logic.
|
||||||
|
* Returns `{ success: true, data: { operationSpecificData, telemetryData } }`.
|
||||||
|
4. **MCP Tool**:
|
||||||
|
* Receives direct function response.
|
||||||
|
* `handleApiResult` ensures the final MCP response to the client is `{ success: true, data: { operationSpecificData, telemetryData } }`.
|
||||||
|
5. **CLI Command**:
|
||||||
|
* Calls core logic with `outputFormat: 'text'`. Display is handled by core logic.
|
||||||
|
|
||||||
|
This pattern ensures telemetry is captured and appropriately handled/exposed across all interaction modes.
|
||||||
@@ -1,31 +1,32 @@
|
|||||||
{
|
{
|
||||||
"models": {
|
"models": {
|
||||||
"main": {
|
"main": {
|
||||||
"provider": "anthropic",
|
"provider": "anthropic",
|
||||||
"modelId": "claude-3-7-sonnet-20250219",
|
"modelId": "claude-sonnet-4-20250514",
|
||||||
"maxTokens": 100000,
|
"maxTokens": 50000,
|
||||||
"temperature": 0.2
|
"temperature": 0.2
|
||||||
},
|
},
|
||||||
"research": {
|
"research": {
|
||||||
"provider": "perplexity",
|
"provider": "perplexity",
|
||||||
"modelId": "sonar-pro",
|
"modelId": "sonar-pro",
|
||||||
"maxTokens": 8700,
|
"maxTokens": 8700,
|
||||||
"temperature": 0.1
|
"temperature": 0.1
|
||||||
},
|
},
|
||||||
"fallback": {
|
"fallback": {
|
||||||
"provider": "anthropic",
|
"provider": "anthropic",
|
||||||
"modelId": "claude-3-7-sonnet-20250219",
|
"modelId": "claude-3-7-sonnet-20250219",
|
||||||
"maxTokens": 120000,
|
"maxTokens": 128000,
|
||||||
"temperature": 0.2
|
"temperature": 0.2
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"global": {
|
"global": {
|
||||||
"logLevel": "info",
|
"logLevel": "info",
|
||||||
"debug": false,
|
"debug": false,
|
||||||
"defaultSubtasks": 5,
|
"defaultSubtasks": 5,
|
||||||
"defaultPriority": "medium",
|
"defaultPriority": "medium",
|
||||||
"projectName": "Taskmaster",
|
"projectName": "Taskmaster",
|
||||||
"ollamaBaseUrl": "http://localhost:11434/api",
|
"ollamaBaseUrl": "http://localhost:11434/api",
|
||||||
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
|
"userId": "1234567890",
|
||||||
}
|
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
294
CHANGELOG.md
294
CHANGELOG.md
@@ -1,5 +1,299 @@
|
|||||||
# task-master-ai
|
# task-master-ai
|
||||||
|
|
||||||
|
## 0.15.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
|
||||||
|
|
||||||
|
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
|
||||||
|
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
|
||||||
|
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
|
||||||
|
- **Robust Error Handling**:
|
||||||
|
- Detects when Ollama server is not running and provides clear error messages
|
||||||
|
- Validates model existence and lists available alternatives when model not found
|
||||||
|
- Graceful fallback behavior for connection issues
|
||||||
|
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
|
||||||
|
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
|
||||||
|
|
||||||
|
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
|
||||||
|
- Added Mistral models: Devstral Small, Mistral Nemo
|
||||||
|
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
|
||||||
|
- Updated Gemini model to latest 2.5 Flash preview version
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
|
||||||
|
|
||||||
|
- Research current technologies and best practices relevant to the project
|
||||||
|
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
|
||||||
|
- Include specific library recommendations with version numbers
|
||||||
|
- Provide more detailed implementation guidance based on industry standards
|
||||||
|
- Create more accurate dependency relationships between tasks
|
||||||
|
|
||||||
|
This results in higher quality, more actionable tasks with minimal additional effort.
|
||||||
|
|
||||||
|
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
|
||||||
|
|
||||||
|
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
|
||||||
|
|
||||||
|
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
|
||||||
|
Status: DONE
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
|
||||||
|
|
||||||
|
**Usage:**
|
||||||
|
|
||||||
|
- CLI command: `task-master move --from=<id> --to=<id>`
|
||||||
|
- MCP tool: `move_task` with parameters:
|
||||||
|
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
|
||||||
|
- `to`: ID of destination (e.g., "7" or "7.3")
|
||||||
|
- `file` (optional): Custom path to tasks.json
|
||||||
|
|
||||||
|
**Example scenarios:**
|
||||||
|
|
||||||
|
- Move task to become subtask: `--from="5" --to="7"`
|
||||||
|
- Move subtask to standalone task: `--from="5.2" --to="7"`
|
||||||
|
- Move subtask to different parent: `--from="5.2" --to="7.3"`
|
||||||
|
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
|
||||||
|
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
|
||||||
|
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
|
||||||
|
|
||||||
|
**Multiple Task Support:**
|
||||||
|
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
|
||||||
|
|
||||||
|
**Validation Features:**
|
||||||
|
|
||||||
|
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
|
||||||
|
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
|
||||||
|
- Validates source tasks exist before attempting to move them
|
||||||
|
- Ensures proper parent-child relationships are maintained
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
|
||||||
|
|
||||||
|
## 0.15.0-rc.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
|
||||||
|
|
||||||
|
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
|
||||||
|
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
|
||||||
|
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
|
||||||
|
- **Robust Error Handling**:
|
||||||
|
- Detects when Ollama server is not running and provides clear error messages
|
||||||
|
- Validates model existence and lists available alternatives when model not found
|
||||||
|
- Graceful fallback behavior for connection issues
|
||||||
|
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
|
||||||
|
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
|
||||||
|
|
||||||
|
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
|
||||||
|
- Added Mistral models: Devstral Small, Mistral Nemo
|
||||||
|
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
|
||||||
|
- Updated Gemini model to latest 2.5 Flash preview version
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
|
||||||
|
|
||||||
|
- Research current technologies and best practices relevant to the project
|
||||||
|
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
|
||||||
|
- Include specific library recommendations with version numbers
|
||||||
|
- Provide more detailed implementation guidance based on industry standards
|
||||||
|
- Create more accurate dependency relationships between tasks
|
||||||
|
|
||||||
|
This results in higher quality, more actionable tasks with minimal additional effort.
|
||||||
|
|
||||||
|
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
|
||||||
|
|
||||||
|
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
|
||||||
|
|
||||||
|
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
|
||||||
|
Status: DONE
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
|
||||||
|
|
||||||
|
**Usage:**
|
||||||
|
|
||||||
|
- CLI command: `task-master move --from=<id> --to=<id>`
|
||||||
|
- MCP tool: `move_task` with parameters:
|
||||||
|
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
|
||||||
|
- `to`: ID of destination (e.g., "7" or "7.3")
|
||||||
|
- `file` (optional): Custom path to tasks.json
|
||||||
|
|
||||||
|
**Example scenarios:**
|
||||||
|
|
||||||
|
- Move task to become subtask: `--from="5" --to="7"`
|
||||||
|
- Move subtask to standalone task: `--from="5.2" --to="7"`
|
||||||
|
- Move subtask to different parent: `--from="5.2" --to="7.3"`
|
||||||
|
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
|
||||||
|
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
|
||||||
|
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
|
||||||
|
|
||||||
|
**Multiple Task Support:**
|
||||||
|
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
|
||||||
|
|
||||||
|
**Validation Features:**
|
||||||
|
|
||||||
|
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
|
||||||
|
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
|
||||||
|
- Validates source tasks exist before attempting to move them
|
||||||
|
- Ensures proper parent-child relationships are maintained
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
|
||||||
|
|
||||||
|
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
|
||||||
|
|
||||||
|
## 0.14.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
|
||||||
|
|
||||||
|
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
|
||||||
|
|
||||||
|
- You can now add it by running `task-master models --setup` and selecting it.
|
||||||
|
- Ollama is a local model provider, so no API key is required.
|
||||||
|
- Ollama models are available at `http://localhost:11434/api` by default.
|
||||||
|
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
|
||||||
|
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
|
||||||
|
|
||||||
|
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Resolve all issues related to MCP
|
||||||
|
|
||||||
|
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
|
||||||
|
|
||||||
|
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
|
||||||
|
|
||||||
|
- Fixes #477
|
||||||
|
|
||||||
|
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
|
||||||
|
|
||||||
|
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
|
||||||
|
|
||||||
|
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
|
||||||
|
|
||||||
|
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add src directory to exports
|
||||||
|
|
||||||
|
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
|
||||||
|
|
||||||
|
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
|
||||||
|
|
||||||
|
- Fixes issues users where having where they were getting stale data
|
||||||
|
|
||||||
|
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
|
||||||
|
|
||||||
|
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
|
||||||
|
|
||||||
|
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
|
||||||
|
|
||||||
|
- Closes #419
|
||||||
|
|
||||||
|
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
|
||||||
|
|
||||||
|
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
|
||||||
|
|
||||||
|
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
|
||||||
|
|
||||||
|
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
|
||||||
|
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
|
||||||
|
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
|
||||||
|
- Ensures a clean, branded help experience with no repeated content.
|
||||||
|
- Fixes #339
|
||||||
|
|
||||||
|
## 0.14.0-rc.1
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
|
||||||
|
|
||||||
|
- You can now add it by running `task-master models --setup` and selecting it.
|
||||||
|
- Ollama is a local model provider, so no API key is required.
|
||||||
|
- Ollama models are available at `http://localhost:11434/api` by default.
|
||||||
|
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
|
||||||
|
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
|
||||||
|
|
||||||
|
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
|
||||||
|
|
||||||
|
## 0.14.0-rc.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
|
||||||
|
|
||||||
|
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
|
||||||
|
|
||||||
|
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
|
||||||
|
|
||||||
|
- Fixes #477
|
||||||
|
|
||||||
|
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
|
||||||
|
|
||||||
|
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
|
||||||
|
|
||||||
|
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
|
||||||
|
|
||||||
|
- Fixes issues users where having where they were getting stale data
|
||||||
|
|
||||||
|
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
|
||||||
|
|
||||||
|
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
|
||||||
|
|
||||||
|
- Closes #419
|
||||||
|
|
||||||
|
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
|
||||||
|
|
||||||
|
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
|
||||||
|
|
||||||
|
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
|
||||||
|
|
||||||
|
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
|
||||||
|
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
|
||||||
|
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
|
||||||
|
- Ensures a clean, branded help experience with no repeated content.
|
||||||
|
- Fixes #339
|
||||||
|
|
||||||
## 0.13.1
|
## 0.13.1
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
17
README.md
17
README.md
@@ -11,8 +11,20 @@ A task management system for AI-driven development with Claude, designed to work
|
|||||||
|
|
||||||
## Requirements
|
## 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)
|
- Anthropic API key (Claude API)
|
||||||
- OpenAI SDK (for Perplexity API integration, optional)
|
- OpenAI API key
|
||||||
|
- Google Gemini API key
|
||||||
|
- Perplexity API key (for research model)
|
||||||
|
- xAI API Key (for research or main model)
|
||||||
|
- OpenRouter API Key (for research or main model)
|
||||||
|
|
||||||
|
Using the research model is optional but highly recommended. You will need at least ONE API key. Adding all API keys enables you to seamlessly switch between model providers at will.
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
@@ -36,7 +48,8 @@ MCP (Model Control Protocol) provides the easiest way to get started with Task M
|
|||||||
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
|
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
|
||||||
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
|
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
|
||||||
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
|
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
|
||||||
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE"
|
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE",
|
||||||
|
"OLLAMA_API_KEY": "YOUR_OLLAMA_API_KEY_HERE"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
413
assets/AGENTS.md
Normal file
413
assets/AGENTS.md
Normal file
@@ -0,0 +1,413 @@
|
|||||||
|
# Task Master AI - Claude Code Integration Guide
|
||||||
|
|
||||||
|
## Essential Commands
|
||||||
|
|
||||||
|
### Core Workflow Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Project Setup
|
||||||
|
task-master init # Initialize Task Master in current project
|
||||||
|
task-master parse-prd scripts/prd.txt # Generate tasks from PRD document
|
||||||
|
task-master models --setup # Configure AI models interactively
|
||||||
|
|
||||||
|
# Daily Development Workflow
|
||||||
|
task-master list # Show all tasks with status
|
||||||
|
task-master next # Get next available task to work on
|
||||||
|
task-master show <id> # View detailed task information (e.g., task-master show 1.2)
|
||||||
|
task-master set-status --id=<id> --status=done # Mark task complete
|
||||||
|
|
||||||
|
# Task Management
|
||||||
|
task-master add-task --prompt="description" --research # Add new task with AI assistance
|
||||||
|
task-master expand --id=<id> --research --force # Break task into subtasks
|
||||||
|
task-master update-task --id=<id> --prompt="changes" # Update specific task
|
||||||
|
task-master update --from=<id> --prompt="changes" # Update multiple tasks from ID onwards
|
||||||
|
task-master update-subtask --id=<id> --prompt="notes" # Add implementation notes to subtask
|
||||||
|
|
||||||
|
# Analysis & Planning
|
||||||
|
task-master analyze-complexity --research # Analyze task complexity
|
||||||
|
task-master complexity-report # View complexity analysis
|
||||||
|
task-master expand --all --research # Expand all eligible tasks
|
||||||
|
|
||||||
|
# Dependencies & Organization
|
||||||
|
task-master add-dependency --id=<id> --depends-on=<id> # Add task dependency
|
||||||
|
task-master move --from=<id> --to=<id> # Reorganize task hierarchy
|
||||||
|
task-master validate-dependencies # Check for dependency issues
|
||||||
|
task-master generate # Update task markdown files (usually auto-called)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Files & Project Structure
|
||||||
|
|
||||||
|
### Core Files
|
||||||
|
|
||||||
|
- `tasks/tasks.json` - Main task data file (auto-managed)
|
||||||
|
- `.taskmasterconfig` - AI model configuration (use `task-master models` to modify)
|
||||||
|
- `scripts/prd.txt` - Product Requirements Document for parsing
|
||||||
|
- `tasks/*.txt` - Individual task files (auto-generated from tasks.json)
|
||||||
|
- `.env` - API keys for CLI usage
|
||||||
|
|
||||||
|
### Claude Code Integration Files
|
||||||
|
|
||||||
|
- `CLAUDE.md` - Auto-loaded context for Claude Code (this file)
|
||||||
|
- `.claude/settings.json` - Claude Code tool allowlist and preferences
|
||||||
|
- `.claude/commands/` - Custom slash commands for repeated workflows
|
||||||
|
- `.mcp.json` - MCP server configuration (project-specific)
|
||||||
|
|
||||||
|
### Directory Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
project/
|
||||||
|
├── tasks/
|
||||||
|
│ ├── tasks.json # Main task database
|
||||||
|
│ ├── task-1.md # Individual task files
|
||||||
|
│ └── task-2.md
|
||||||
|
├── scripts/
|
||||||
|
│ ├── prd.txt # Product requirements
|
||||||
|
│ └── task-complexity-report.json
|
||||||
|
├── .claude/
|
||||||
|
│ ├── settings.json # Claude Code configuration
|
||||||
|
│ └── commands/ # Custom slash commands
|
||||||
|
├── .taskmasterconfig # AI models & settings
|
||||||
|
├── .env # API keys
|
||||||
|
├── .mcp.json # MCP configuration
|
||||||
|
└── CLAUDE.md # This file - auto-loaded by Claude Code
|
||||||
|
```
|
||||||
|
|
||||||
|
## MCP Integration
|
||||||
|
|
||||||
|
Task Master provides an MCP server that Claude Code can connect to. Configure in `.mcp.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"task-master-ai": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
|
||||||
|
"env": {
|
||||||
|
"ANTHROPIC_API_KEY": "your_key_here",
|
||||||
|
"PERPLEXITY_API_KEY": "your_key_here",
|
||||||
|
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
|
||||||
|
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
|
||||||
|
"XAI_API_KEY": "XAI_API_KEY_HERE",
|
||||||
|
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
|
||||||
|
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
|
||||||
|
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
|
||||||
|
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Essential MCP Tools
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
help; // = shows available taskmaster commands
|
||||||
|
// Project setup
|
||||||
|
initialize_project; // = task-master init
|
||||||
|
parse_prd; // = task-master parse-prd
|
||||||
|
|
||||||
|
// Daily workflow
|
||||||
|
get_tasks; // = task-master list
|
||||||
|
next_task; // = task-master next
|
||||||
|
get_task; // = task-master show <id>
|
||||||
|
set_task_status; // = task-master set-status
|
||||||
|
|
||||||
|
// Task management
|
||||||
|
add_task; // = task-master add-task
|
||||||
|
expand_task; // = task-master expand
|
||||||
|
update_task; // = task-master update-task
|
||||||
|
update_subtask; // = task-master update-subtask
|
||||||
|
update; // = task-master update
|
||||||
|
|
||||||
|
// Analysis
|
||||||
|
analyze_project_complexity; // = task-master analyze-complexity
|
||||||
|
complexity_report; // = task-master complexity-report
|
||||||
|
```
|
||||||
|
|
||||||
|
## Claude Code Workflow Integration
|
||||||
|
|
||||||
|
### Standard Development Workflow
|
||||||
|
|
||||||
|
#### 1. Project Initialization
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Initialize Task Master
|
||||||
|
task-master init
|
||||||
|
|
||||||
|
# Create or obtain PRD, then parse it
|
||||||
|
task-master parse-prd scripts/prd.txt
|
||||||
|
|
||||||
|
# Analyze complexity and expand tasks
|
||||||
|
task-master analyze-complexity --research
|
||||||
|
task-master expand --all --research
|
||||||
|
```
|
||||||
|
|
||||||
|
If tasks already exist, another PRD can be parsed (with new information only!) using parse-prd with --append flag. This will add the generated tasks to the existing list of tasks..
|
||||||
|
|
||||||
|
#### 2. Daily Development Loop
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Start each session
|
||||||
|
task-master next # Find next available task
|
||||||
|
task-master show <id> # Review task details
|
||||||
|
|
||||||
|
# During implementation, check in code context into the tasks and subtasks
|
||||||
|
task-master update-subtask --id=<id> --prompt="implementation notes..."
|
||||||
|
|
||||||
|
# Complete tasks
|
||||||
|
task-master set-status --id=<id> --status=done
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. Multi-Claude Workflows
|
||||||
|
|
||||||
|
For complex projects, use multiple Claude Code sessions:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Terminal 1: Main implementation
|
||||||
|
cd project && claude
|
||||||
|
|
||||||
|
# Terminal 2: Testing and validation
|
||||||
|
cd project-test-worktree && claude
|
||||||
|
|
||||||
|
# Terminal 3: Documentation updates
|
||||||
|
cd project-docs-worktree && claude
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom Slash Commands
|
||||||
|
|
||||||
|
Create `.claude/commands/taskmaster-next.md`:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
Find the next available Task Master task and show its details.
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
|
||||||
|
1. Run `task-master next` to get the next task
|
||||||
|
2. If a task is available, run `task-master show <id>` for full details
|
||||||
|
3. Provide a summary of what needs to be implemented
|
||||||
|
4. Suggest the first implementation step
|
||||||
|
```
|
||||||
|
|
||||||
|
Create `.claude/commands/taskmaster-complete.md`:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
Complete a Task Master task: $ARGUMENTS
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
|
||||||
|
1. Review the current task with `task-master show $ARGUMENTS`
|
||||||
|
2. Verify all implementation is complete
|
||||||
|
3. Run any tests related to this task
|
||||||
|
4. Mark as complete: `task-master set-status --id=$ARGUMENTS --status=done`
|
||||||
|
5. Show the next available task with `task-master next`
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tool Allowlist Recommendations
|
||||||
|
|
||||||
|
Add to `.claude/settings.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"allowedTools": [
|
||||||
|
"Edit",
|
||||||
|
"Bash(task-master *)",
|
||||||
|
"Bash(git commit:*)",
|
||||||
|
"Bash(git add:*)",
|
||||||
|
"Bash(npm run *)",
|
||||||
|
"mcp__task_master_ai__*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration & Setup
|
||||||
|
|
||||||
|
### API Keys Required
|
||||||
|
|
||||||
|
At least **one** of these API keys must be configured:
|
||||||
|
|
||||||
|
- `ANTHROPIC_API_KEY` (Claude models) - **Recommended**
|
||||||
|
- `PERPLEXITY_API_KEY` (Research features) - **Highly recommended**
|
||||||
|
- `OPENAI_API_KEY` (GPT models)
|
||||||
|
- `GOOGLE_API_KEY` (Gemini models)
|
||||||
|
- `MISTRAL_API_KEY` (Mistral models)
|
||||||
|
- `OPENROUTER_API_KEY` (Multiple models)
|
||||||
|
- `XAI_API_KEY` (Grok models)
|
||||||
|
|
||||||
|
An API key is required for any provider used across any of the 3 roles defined in the `models` command.
|
||||||
|
|
||||||
|
### Model Configuration
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Interactive setup (recommended)
|
||||||
|
task-master models --setup
|
||||||
|
|
||||||
|
# Set specific models
|
||||||
|
task-master models --set-main claude-3-5-sonnet-20241022
|
||||||
|
task-master models --set-research perplexity-llama-3.1-sonar-large-128k-online
|
||||||
|
task-master models --set-fallback gpt-4o-mini
|
||||||
|
```
|
||||||
|
|
||||||
|
## Task Structure & IDs
|
||||||
|
|
||||||
|
### Task ID Format
|
||||||
|
|
||||||
|
- Main tasks: `1`, `2`, `3`, etc.
|
||||||
|
- Subtasks: `1.1`, `1.2`, `2.1`, etc.
|
||||||
|
- Sub-subtasks: `1.1.1`, `1.1.2`, etc.
|
||||||
|
|
||||||
|
### Task Status Values
|
||||||
|
|
||||||
|
- `pending` - Ready to work on
|
||||||
|
- `in-progress` - Currently being worked on
|
||||||
|
- `done` - Completed and verified
|
||||||
|
- `deferred` - Postponed
|
||||||
|
- `cancelled` - No longer needed
|
||||||
|
- `blocked` - Waiting on external factors
|
||||||
|
|
||||||
|
### Task Fields
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "1.2",
|
||||||
|
"title": "Implement user authentication",
|
||||||
|
"description": "Set up JWT-based auth system",
|
||||||
|
"status": "pending",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": ["1.1"],
|
||||||
|
"details": "Use bcrypt for hashing, JWT for tokens...",
|
||||||
|
"testStrategy": "Unit tests for auth functions, integration tests for login flow",
|
||||||
|
"subtasks": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Claude Code Best Practices with Task Master
|
||||||
|
|
||||||
|
### Context Management
|
||||||
|
|
||||||
|
- Use `/clear` between different tasks to maintain focus
|
||||||
|
- This CLAUDE.md file is automatically loaded for context
|
||||||
|
- Use `task-master show <id>` to pull specific task context when needed
|
||||||
|
|
||||||
|
### Iterative Implementation
|
||||||
|
|
||||||
|
1. `task-master show <subtask-id>` - Understand requirements
|
||||||
|
2. Explore codebase and plan implementation
|
||||||
|
3. `task-master update-subtask --id=<id> --prompt="detailed plan"` - Log plan
|
||||||
|
4. `task-master set-status --id=<id> --status=in-progress` - Start work
|
||||||
|
5. Implement code following logged plan
|
||||||
|
6. `task-master update-subtask --id=<id> --prompt="what worked/didn't work"` - Log progress
|
||||||
|
7. `task-master set-status --id=<id> --status=done` - Complete task
|
||||||
|
|
||||||
|
### Complex Workflows with Checklists
|
||||||
|
|
||||||
|
For large migrations or multi-step processes:
|
||||||
|
|
||||||
|
1. Create a markdown PRD file describing the new changes: `touch task-migration-checklist.md` (prds can be .txt or .md)
|
||||||
|
2. Use Taskmaster to parse the new prd with `task-master parse-prd --append` (also available in MCP)
|
||||||
|
3. Use Taskmaster to expand the newly generated tasks into subtasks. Consdier using `analyze-complexity` with the correct --to and --from IDs (the new ids) to identify the ideal subtask amounts for each task. Then expand them.
|
||||||
|
4. Work through items systematically, checking them off as completed
|
||||||
|
5. Use `task-master update-subtask` to log progress on each task/subtask and/or updating/researching them before/during implementation if getting stuck
|
||||||
|
|
||||||
|
### Git Integration
|
||||||
|
|
||||||
|
Task Master works well with `gh` CLI:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create PR for completed task
|
||||||
|
gh pr create --title "Complete task 1.2: User authentication" --body "Implements JWT auth system as specified in task 1.2"
|
||||||
|
|
||||||
|
# Reference task in commits
|
||||||
|
git commit -m "feat: implement JWT auth (task 1.2)"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Parallel Development with Git Worktrees
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create worktrees for parallel task development
|
||||||
|
git worktree add ../project-auth feature/auth-system
|
||||||
|
git worktree add ../project-api feature/api-refactor
|
||||||
|
|
||||||
|
# Run Claude Code in each worktree
|
||||||
|
cd ../project-auth && claude # Terminal 1: Auth work
|
||||||
|
cd ../project-api && claude # Terminal 2: API work
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### AI Commands Failing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Check API keys are configured
|
||||||
|
cat .env # For CLI usage
|
||||||
|
|
||||||
|
# Verify model configuration
|
||||||
|
task-master models
|
||||||
|
|
||||||
|
# Test with different model
|
||||||
|
task-master models --set-fallback gpt-4o-mini
|
||||||
|
```
|
||||||
|
|
||||||
|
### MCP Connection Issues
|
||||||
|
|
||||||
|
- Check `.mcp.json` configuration
|
||||||
|
- Verify Node.js installation
|
||||||
|
- Use `--mcp-debug` flag when starting Claude Code
|
||||||
|
- Use CLI as fallback if MCP unavailable
|
||||||
|
|
||||||
|
### Task File Sync Issues
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Regenerate task files from tasks.json
|
||||||
|
task-master generate
|
||||||
|
|
||||||
|
# Fix dependency issues
|
||||||
|
task-master fix-dependencies
|
||||||
|
```
|
||||||
|
|
||||||
|
DO NOT RE-INITIALIZE. That will not do anything beyond re-adding the same Taskmaster core files.
|
||||||
|
|
||||||
|
## Important Notes
|
||||||
|
|
||||||
|
### AI-Powered Operations
|
||||||
|
|
||||||
|
These commands make AI calls and may take up to a minute:
|
||||||
|
|
||||||
|
- `parse_prd` / `task-master parse-prd`
|
||||||
|
- `analyze_project_complexity` / `task-master analyze-complexity`
|
||||||
|
- `expand_task` / `task-master expand`
|
||||||
|
- `expand_all` / `task-master expand --all`
|
||||||
|
- `add_task` / `task-master add-task`
|
||||||
|
- `update` / `task-master update`
|
||||||
|
- `update_task` / `task-master update-task`
|
||||||
|
- `update_subtask` / `task-master update-subtask`
|
||||||
|
|
||||||
|
### File Management
|
||||||
|
|
||||||
|
- Never manually edit `tasks.json` - use commands instead
|
||||||
|
- Never manually edit `.taskmasterconfig` - use `task-master models`
|
||||||
|
- Task markdown files in `tasks/` are auto-generated
|
||||||
|
- Run `task-master generate` after manual changes to tasks.json
|
||||||
|
|
||||||
|
### Claude Code Session Management
|
||||||
|
|
||||||
|
- Use `/clear` frequently to maintain focused context
|
||||||
|
- Create custom slash commands for repeated Task Master workflows
|
||||||
|
- Configure tool allowlist to streamline permissions
|
||||||
|
- Use headless mode for automation: `claude -p "task-master next"`
|
||||||
|
|
||||||
|
### Multi-Task Updates
|
||||||
|
|
||||||
|
- Use `update --from=<id>` to update multiple future tasks
|
||||||
|
- Use `update-task --id=<id>` for single task updates
|
||||||
|
- Use `update-subtask --id=<id>` for implementation logging
|
||||||
|
|
||||||
|
### Research Mode
|
||||||
|
|
||||||
|
- Add `--research` flag for research-based AI enhancement
|
||||||
|
- Requires a research model API key like Perplexity (`PERPLEXITY_API_KEY`) in environment
|
||||||
|
- Provides more informed task creation and updates
|
||||||
|
- Recommended for complex technical tasks
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
_This guide ensures Claude Code has immediate access to Task Master's essential functionality for agentic development workflows._
|
||||||
@@ -6,3 +6,4 @@ GOOGLE_API_KEY="your_google_api_key_here" # Optional, for Google Gem
|
|||||||
MISTRAL_API_KEY="your_mistral_key_here" # Optional, for Mistral AI models.
|
MISTRAL_API_KEY="your_mistral_key_here" # Optional, for Mistral AI models.
|
||||||
XAI_API_KEY="YOUR_XAI_KEY_HERE" # Optional, for xAI 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).
|
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.
|
||||||
@@ -39,7 +39,7 @@
|
|||||||
{
|
{
|
||||||
"slug": "debug",
|
"slug": "debug",
|
||||||
"name": "Debug",
|
"name": "Debug",
|
||||||
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mdode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
|
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
|
||||||
"customInstructions": "Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.",
|
"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": [
|
"groups": [
|
||||||
"read",
|
"read",
|
||||||
|
|||||||
1798
context/chats/add-task-dependencies-1.md
Normal file
1798
context/chats/add-task-dependencies-1.md
Normal file
File diff suppressed because it is too large
Load Diff
368
context/chats/max-min-tokens.txt.md
Normal file
368
context/chats/max-min-tokens.txt.md
Normal file
@@ -0,0 +1,368 @@
|
|||||||
|
We want to refine how Task Master handles AI model token limits to be more precise, by:
|
||||||
|
|
||||||
|
1. Distinguishing between `maxInputTokens` and `maxOutputTokens` in the configuration.
|
||||||
|
2. Dynamically adjusting the `maxOutputTokens` for an API call based on the actual prompt length to stay within the model's total context window (or respecting separate input/output limits if the API and model support that).
|
||||||
|
3. Ensuring that `ai-services-unified.js` uses these more granular limits.
|
||||||
|
|
||||||
|
This is a good improvement for both cost control and preventing errors.
|
||||||
|
|
||||||
|
Here's a plan:
|
||||||
|
|
||||||
|
**Phase 1: Configuration and Core Logic Updates**
|
||||||
|
|
||||||
|
1. **Update `.taskmasterconfig` Structure:**
|
||||||
|
- I'll modify the `models` section in your `.taskmasterconfig`. For each role (`main`, `research`, `fallback`), `maxTokens` will be replaced with `maxInputTokens` and `maxOutputTokens`.
|
||||||
|
- We'll need to decide on reasonable default values for these new fields. We can look at the current `maxTokens` and the model's known limits to make an initial guess.
|
||||||
|
2. **Update `MODEL_MAP` in `ai-services-unified.js`:**
|
||||||
|
- This array already stores cost data. We need to ensure it also stores the _absolute_ maximum input and output tokens for each model listed (e.g., `model_max_input_tokens`, `model_max_output_tokens`). If these fields are not present, they will need to be added. The values in `.taskmasterconfig` will then represent user-defined operational limits, which should ideally be validated against these absolute maximums.
|
||||||
|
3. **Update `config-manager.js`:**
|
||||||
|
- Getter functions like `getParametersForRole` will be updated to fetch `maxInputTokens` and `maxOutputTokens` instead of the singular `maxTokens`.
|
||||||
|
- New getters might be needed if we want to access the model's absolute limits directly from `MODEL_MAP` via `config-manager.js`.
|
||||||
|
4. **Update `ai-services-unified.js` (`_unifiedServiceRunner`):**
|
||||||
|
- **Token Counting:** This is a crucial step. Before an API call, we need to estimate the token count of the combined `systemPrompt` and `userPrompt`.
|
||||||
|
- The Vercel AI SDK or the individual provider SDKs might offer utilities for this. For example, some SDKs expose a `tokenizer` or a way to count tokens for a given string.
|
||||||
|
- If a direct utility isn't available through the Vercel SDK for the specific provider, we might need to use a library like `tiktoken` for OpenAI/Anthropic models or investigate provider-specific tokenization. This could be complex as tokenization varies between models.
|
||||||
|
- For now, let's assume we can get a reasonable estimate.
|
||||||
|
- **Dynamic Output Token Calculation & Validation:**
|
||||||
|
- Retrieve `configured_max_input_tokens` and `configured_max_output_tokens` from `config-manager.js` for the current role.
|
||||||
|
- Retrieve `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
|
||||||
|
- Let `prompt_tokens = countTokens(systemPrompt + userPrompt)`.
|
||||||
|
- **Input Validation:** If `prompt_tokens > configured_max_input_tokens` OR `prompt_tokens > model_absolute_max_input_tokens`, throw an error. (We might also consider auto-truncation strategies in the future, but an error is safer to start).
|
||||||
|
- **Output Calculation:** The `max_tokens` parameter sent to the API (which typically refers to the _max number of tokens to generate_) should be `configured_max_output_tokens`. We also need to ensure this doesn't violate the model's absolute output limit.
|
||||||
|
- Some models have a _total_ context window (input + output). If this is the case for a model, the `max_tokens` parameter for the API call might need to be `min(configured_max_output_tokens, model_absolute_total_tokens - prompt_tokens)`. However, many modern APIs handle separate input and output limits, simplifying this. We'll aim to pass `configured_max_output_tokens` as the API's `max_tokens` parameter, assuming the input validation has passed.
|
||||||
|
- **API Call Parameter:** Update the `callParams` to use the correctly determined `max_tokens` for generation (which will be our `configured_max_output_tokens`).
|
||||||
|
|
||||||
|
**Phase 2: Error Handling and Refinements**
|
||||||
|
|
||||||
|
1. **Enhanced Error Handling:** Provide clear error messages if prompt tokens exceed input limits, or if API calls fail due to token issues despite our calculations.
|
||||||
|
2. **Validation:** Add validation (perhaps in `config-manager.js` or when `task-master models --setup` is run) to ensure `configured_max_input_tokens` and `configured_max_output_tokens` in `.taskmasterconfig` do not exceed the `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
|
||||||
|
|
||||||
|
Let's start by inspecting `scripts/modules/config-manager.js` to see how parameters and `MODEL_MAP` are currently handled. This will inform the changes needed for `.taskmasterconfig` and `ai-services-unified.js`.
|
||||||
|
|
||||||
|
I will now read `scripts/modules/config-manager.js`.
|
||||||
|
|
||||||
|
Okay, I've reviewed `scripts/modules/config-manager.js`. Here's what I've gathered and how it impacts the plan:
|
||||||
|
|
||||||
|
- **`MODEL_MAP` Source:** `MODEL_MAP` is loaded from `supported-models.json`. This is excellent, as it means we can update the model capabilities (including new token limits) in a structured JSON file.
|
||||||
|
- **Configuration Loading:** `_loadAndValidateConfig` handles loading `.taskmasterconfig` and merging it with `DEFAULTS`.
|
||||||
|
- **Getters:** There are specific getters for `maxTokens` for each role (e.g., `getMainMaxTokens`). We will need to update these.
|
||||||
|
- **`getParametersForRole`:** This function already exists and is a good candidate for returning the new `maxInputTokens` and `maxOutputTokens`.
|
||||||
|
|
||||||
|
Here's the refined plan:
|
||||||
|
|
||||||
|
**Phase 1: Configuration and Data Structures**
|
||||||
|
|
||||||
|
1. **Update `supported-models.json`:**
|
||||||
|
|
||||||
|
- For each model entry in `supported-models.json`, we need to add `maxInputTokens` and `maxOutputTokens` fields. These should reflect the _absolute maximums_ for that specific model.
|
||||||
|
- Example entry change:
|
||||||
|
|
||||||
|
```json
|
||||||
|
// Before
|
||||||
|
{
|
||||||
|
"id": "claude-3-7-sonnet-20250219",
|
||||||
|
"name": "Claude 3.7 Sonnet (Preview)",
|
||||||
|
"context_window": 200000, // This might be total context
|
||||||
|
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
|
||||||
|
{
|
||||||
|
"id": "claude-3-7-sonnet-20250219",
|
||||||
|
"name": "Claude 3.7 Sonnet (Preview)",
|
||||||
|
"maxInputTokens": 190000, // Example
|
||||||
|
"maxOutputTokens": 8192, // Example, often smaller for generation
|
||||||
|
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- I will need to find the official input/output token limits for the models currently in your `MODEL_MAP`. If you have this information handy, it would speed things up. Otherwise, I can make educated guesses or search for them.
|
||||||
|
|
||||||
|
2. **Update `.taskmasterconfig` (Defaults and User File):**
|
||||||
|
- In `scripts/modules/config-manager.js`, modify the `DEFAULTS` object. For each role (`main`, `research`, `fallback`), replace `maxTokens` with:
|
||||||
|
- `maxInputTokens`: A sensible default (e.g., a large portion of the model's capability, but user-configurable).
|
||||||
|
- `maxOutputTokens`: A sensible default for generation (e.g., 4096 or 8192).
|
||||||
|
- You will then need to manually update your existing `.taskmasterconfig` file to reflect this new structure. I can provide the snippet for you to paste.
|
||||||
|
3. **Update `config-manager.js`:**
|
||||||
|
- Modify `getParametersForRole(role, explicitRoot = null)`:
|
||||||
|
- It currently fetches `maxTokens` and `temperature`.
|
||||||
|
- Update it to fetch `maxInputTokens`, `maxOutputTokens`, and `temperature` from the loaded config for the given role.
|
||||||
|
- Remove the role-specific `getMaxTokens` functions (e.g., `getMainMaxTokens`, `getResearchMaxTokens`, `getFallbackMaxTokens`). The `getParametersForRole` will be the central way to get these.
|
||||||
|
- (Optional, for later validation) Consider adding a new function `getModelCapabilities(providerName, modelId)` that reads from `MODEL_MAP` to return the absolute `maxInputTokens` and `maxOutputTokens` for a given model. This would be useful for validating the user's settings in `.taskmasterconfig`.
|
||||||
|
|
||||||
|
**Phase 2: Core Logic in `ai-services-unified.js`**
|
||||||
|
|
||||||
|
1. **Token Counting (`_unifiedServiceRunner`):**
|
||||||
|
|
||||||
|
- This is the most complex part. We need a reliable way to count tokens for the prompts.
|
||||||
|
- **Strategy 1 (Ideal):** Leverage Vercel AI SDK. The SDK might provide a way to get a tokenizer for the active model or a utility function. We'll need to investigate its capabilities.
|
||||||
|
- **Strategy 2 (Fallback):** Use a library like `tiktoken` for models compatible with OpenAI's tokenization (many are, including some Anthropic models). For other models, we might need provider-specific tokenizers or make estimations (less ideal).
|
||||||
|
- **Initial Approach:** Let's try to find a Vercel AI SDK utility first. If not, we'll start with `tiktoken` as a common case and acknowledge that other models might need specific handling later.
|
||||||
|
- The function `_unifiedServiceRunner` will call this token counting utility:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Placeholder for token counting
|
||||||
|
function countTokens(text, modelId /* or providerName */) {
|
||||||
|
// ... implementation using SDK or library ...
|
||||||
|
// This is a simplification; actual tokenization is model-specific.
|
||||||
|
// For now, a rough estimate might be (text.length / 4) as a placeholder
|
||||||
|
// if a proper tokenizer isn't immediately available.
|
||||||
|
if (!text) return 0;
|
||||||
|
return Math.ceil(text.length / 3.5); // Very rough general estimate
|
||||||
|
}
|
||||||
|
|
||||||
|
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Dynamic Output Token Calculation & Validation (`_unifiedServiceRunner`):**
|
||||||
|
|
||||||
|
- Fetch parameters using the updated `getParametersForRole` from `config-manager.js`:
|
||||||
|
```javascript
|
||||||
|
const roleParams = getParametersForRole(
|
||||||
|
currentRole,
|
||||||
|
effectiveProjectRoot
|
||||||
|
);
|
||||||
|
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
|
||||||
|
```
|
||||||
|
- Fetch model's absolute limits from `MODEL_MAP` (we'll need a helper in `config-manager.js` or do it directly in `ai-services-unified.js` for now):
|
||||||
|
```javascript
|
||||||
|
// Simplified; ideally use a robust getter from config-manager
|
||||||
|
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
|
||||||
|
(m) => m.id === modelId
|
||||||
|
);
|
||||||
|
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
|
||||||
|
const modelAbsoluteMaxOutput =
|
||||||
|
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
|
||||||
|
```
|
||||||
|
- **Input Validation:**
|
||||||
|
```javascript
|
||||||
|
if (promptTokens > roleParams.maxInputTokens) {
|
||||||
|
throw new Error(
|
||||||
|
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (promptTokens > modelAbsoluteMaxInput) {
|
||||||
|
throw new Error(
|
||||||
|
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **API Call Parameter (`max_tokens` for generation):**
|
||||||
|
The `max_tokens` parameter passed to the provider's API call should be `roleParams.maxOutputTokens`. We must also ensure this doesn't exceed the model's absolute output capability.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const apiMaxOutputTokens = Math.min(
|
||||||
|
roleParams.maxOutputTokens,
|
||||||
|
modelAbsoluteMaxOutput
|
||||||
|
);
|
||||||
|
|
||||||
|
const callParams = {
|
||||||
|
apiKey,
|
||||||
|
modelId,
|
||||||
|
// Use apiMaxOutputTokens for the actual API call
|
||||||
|
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
|
||||||
|
temperature: roleParams.temperature,
|
||||||
|
messages,
|
||||||
|
baseUrl,
|
||||||
|
...(serviceType === 'generateObject' && { schema, objectName }),
|
||||||
|
...restApiParams
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Update `logAiUsage`:**
|
||||||
|
- The cost calculation in `logAiUsage` seems correct as it already uses `inputCost` and `outputCost` per 1M tokens. This part should remain compatible.
|
||||||
|
|
||||||
|
**Next Steps:**
|
||||||
|
|
||||||
|
1. **Modify `supported-models.json`:** I need the content of this file to propose the new `maxInputTokens` and `maxOutputTokens` fields. Please provide it.
|
||||||
|
2. **Decide on Tokenizer Strategy:** What are your thoughts on the token counting? Are you aware of any utilities within Vercel AI SDK for this, or should we plan to integrate `tiktoken` initially?
|
||||||
|
|
||||||
|
Once I have the content of `supported-models.json`, I can draft the changes for it and then proceed to `config-manager.js` and `.taskmasterconfig`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
// Before
|
||||||
|
{
|
||||||
|
"id": "claude-3-7-sonnet-20250219",
|
||||||
|
"name": "Claude 3.7 Sonnet (Preview)",
|
||||||
|
"context_window": 200000, // This might be total context
|
||||||
|
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
|
||||||
|
{
|
||||||
|
"id": "claude-3-7-sonnet-20250219",
|
||||||
|
"name": "Claude 3.7 Sonnet (Preview)",
|
||||||
|
"maxInputTokens": 190000, // Example
|
||||||
|
"maxOutputTokens": 8192, // Example, often smaller for generation
|
||||||
|
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Placeholder for token counting
|
||||||
|
function countTokens(text, modelId /* or providerName */) {
|
||||||
|
// ... implementation using SDK or library ...
|
||||||
|
// This is a simplification; actual tokenization is model-specific.
|
||||||
|
// For now, a rough estimate might be (text.length / 4) as a placeholder
|
||||||
|
// if a proper tokenizer isn't immediately available.
|
||||||
|
if (!text) return 0;
|
||||||
|
return Math.ceil(text.length / 3.5); // Very rough general estimate
|
||||||
|
}
|
||||||
|
|
||||||
|
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
|
||||||
|
```
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
|
||||||
|
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
|
||||||
|
```
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Simplified; ideally use a robust getter from config-manager
|
||||||
|
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
|
||||||
|
(m) => m.id === modelId
|
||||||
|
);
|
||||||
|
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
|
||||||
|
const modelAbsoluteMaxOutput =
|
||||||
|
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
|
||||||
|
```
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
if (promptTokens > roleParams.maxInputTokens) {
|
||||||
|
throw new Error(
|
||||||
|
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (promptTokens > modelAbsoluteMaxInput) {
|
||||||
|
throw new Error(
|
||||||
|
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const apiMaxOutputTokens = Math.min(
|
||||||
|
roleParams.maxOutputTokens,
|
||||||
|
modelAbsoluteMaxOutput
|
||||||
|
);
|
||||||
|
|
||||||
|
const callParams = {
|
||||||
|
apiKey,
|
||||||
|
modelId,
|
||||||
|
// Use apiMaxOutputTokens for the actual API call
|
||||||
|
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
|
||||||
|
temperature: roleParams.temperature,
|
||||||
|
messages,
|
||||||
|
baseUrl,
|
||||||
|
...(serviceType === 'generateObject' && { schema, objectName }),
|
||||||
|
...restApiParams
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Okay, I have the contents of `supported-models.json`.
|
||||||
|
|
||||||
|
It seems many models have a `max_tokens` field, which I assume is the _total context window_. Some don't have it, and for others (like OpenAI `gpt-4o`), the listed `max_tokens` (16384) is known to be its _output_ token limit when using the Chat Completions API, while the context window is much larger (128k). This highlights the complexity: `max_tokens` in `supported-models.json` is used inconsistently.
|
||||||
|
|
||||||
|
**Revised Plan for `supported-models.json` and Token Definitions:**
|
||||||
|
|
||||||
|
To bring clarity, we'll introduce two new fields and ensure their meaning is consistent:
|
||||||
|
|
||||||
|
- `contextWindowTokens`: The total number of tokens the model can process (input + output). This would replace the current ambiguous `max_tokens`.
|
||||||
|
- `maxOutputTokens`: The maximum number of tokens the model can _generate_ in a single response. This is often smaller than the total context window, especially for larger models.
|
||||||
|
|
||||||
|
If a model _only_ specifies a total context window, we'll have to make a reasonable assumption for `maxOutputTokens` (e.g., 4096 or 8192, or a fraction of the total context window). If it only specifies an output token limit (like some OpenAI models in certain API modes), we'll need to find its total context window.
|
||||||
|
|
||||||
|
**Updated `supported-models.json` Structure (Example):**
|
||||||
|
|
||||||
|
```json
|
||||||
|
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
|
||||||
|
{
|
||||||
|
"id": "claude-3-7-sonnet-20250219",
|
||||||
|
"swe_score": 0.623,
|
||||||
|
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"contextWindowTokens": 200000, // From Anthropic's documentation
|
||||||
|
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// For a model like OpenAI GPT-4o
|
||||||
|
{
|
||||||
|
"id": "gpt-4o",
|
||||||
|
"swe_score": 0.332,
|
||||||
|
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"contextWindowTokens": 128000, // Official context window
|
||||||
|
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
|
||||||
|
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
I will proceed to generate the updated `supported-models.json` content. This will be a significant change. I will make my best effort to find the correct `contextWindowTokens` and `maxOutputTokens` for each model. If official numbers are ambiguous or not readily available, I'll use sensible defaults and add a comment.
|
||||||
|
|
||||||
|
**Regarding Tokenizer Strategy:**
|
||||||
|
|
||||||
|
- **Vercel AI SDK:** The `ai` package (Vercel AI SDK) itself is a lightweight wrapper. Tokenization is usually handled by the underlying provider-specific SDKs (e.g., `@anthropic-ai/sdk`, `openai`). The Vercel SDK doesn't provide a universal tokenizer.
|
||||||
|
- **Provider SDKs:**
|
||||||
|
- `@anthropic-ai/sdk`: Does not expose a public tokenizer directly. Anthropic recommends counting based on their guidelines (roughly 3.5 chars/token for English).
|
||||||
|
- `openai` (for Node.js): The `gpt-3-encoder` or `tiktoken` libraries are commonly used. `tiktoken` is more current.
|
||||||
|
- **`tiktoken`:** This is a good general-purpose library for OpenAI models and those that use compatible tokenization (many models fine-tuned from Llama, etc., might be close). It supports various encodings.
|
||||||
|
- **Recommendation:**
|
||||||
|
1. Start by integrating `tiktoken`. We can select the encoding based on the provider or even specific model if needed (e.g., `cl100k_base` for gpt-4, gpt-3.5-turbo, DALL-E models).
|
||||||
|
2. For providers where `tiktoken` is not accurate (e.g., Google's Gemini, Perplexity if they have proprietary tokenizers), we might have to rely on character-based estimations (e.g., `length / N`) as a rougher guide or investigate if their specific SDKs offer token counting.
|
||||||
|
3. The Vercel AI SDK's `experimental_streamObject` and other functions _might_ internally handle some aspects of token counting for request preparation, but we need explicit counting for our logic _before_ the call.
|
||||||
|
|
||||||
|
For now, let's assume we'll add a `countTokens` utility that uses `tiktoken` for OpenAI and Anthropic (as Anthropic's guidance is character-based but `cl100k_base` is often a decent proxy for their tokenization for rough estimates, though not perfect), and a character-based fallback for others.
|
||||||
|
|
||||||
|
I will now generate the proposed changes for `scripts/modules/supported-models.json`. This will be a large diff.
|
||||||
|
|
||||||
|
After this, we'll move to:
|
||||||
|
|
||||||
|
1. Updating `.taskmasterconfig` defaults in `config-manager.js` and providing you the snippet for your user file.
|
||||||
|
2. Updating `config-manager.js` getters.
|
||||||
|
3. Implementing the logic in `ai-services-unified.js`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
|
||||||
|
{
|
||||||
|
"id": "claude-3-7-sonnet-20250219",
|
||||||
|
"swe_score": 0.623,
|
||||||
|
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"contextWindowTokens": 200000, // From Anthropic's documentation
|
||||||
|
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// For a model like OpenAI GPT-4o
|
||||||
|
{
|
||||||
|
"id": "gpt-4o",
|
||||||
|
"swe_score": 0.332,
|
||||||
|
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"contextWindowTokens": 128000, // Official context window
|
||||||
|
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
|
||||||
|
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
|
||||||
|
{
|
||||||
|
"id": "claude-3-7-sonnet-20250219",
|
||||||
|
"swe_score": 0.623,
|
||||||
|
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"contextWindowTokens": 200000, // From Anthropic's documentation
|
||||||
|
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// For a model like OpenAI GPT-4o
|
||||||
|
{
|
||||||
|
"id": "gpt-4o",
|
||||||
|
"swe_score": 0.332,
|
||||||
|
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"contextWindowTokens": 128000, // Official context window
|
||||||
|
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
|
||||||
|
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -187,6 +187,32 @@ task-master validate-dependencies
|
|||||||
task-master fix-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
|
## Add a New Task
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ I need to regenerate the subtasks for task 3 with a different approach. Can you
|
|||||||
## Handling changes
|
## Handling changes
|
||||||
|
|
||||||
```
|
```
|
||||||
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
I've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
|
||||||
```
|
```
|
||||||
|
|
||||||
## Completing work
|
## Completing work
|
||||||
@@ -40,6 +40,34 @@ I've finished implementing the authentication system described in task 2. All te
|
|||||||
Please mark it as complete and tell me what I should work on next.
|
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
|
## Analyzing complexity
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -268,7 +268,61 @@ task-master update --from=4 --prompt="Update to use MongoDB, researching best pr
|
|||||||
|
|
||||||
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
|
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
|
||||||
|
|
||||||
### 6. Breaking Down Complex Tasks
|
### 6. Reorganizing Tasks
|
||||||
|
|
||||||
|
If you need to reorganize your task structure:
|
||||||
|
|
||||||
|
```
|
||||||
|
I think subtask 5.2 would fit better as part of task 7 instead. Can you move it there?
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will execute:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
task-master move --from=5.2 --to=7.3
|
||||||
|
```
|
||||||
|
|
||||||
|
You can reorganize tasks in various ways:
|
||||||
|
|
||||||
|
- Moving a standalone task to become a subtask: `--from=5 --to=7`
|
||||||
|
- Moving a subtask to become a standalone task: `--from=5.2 --to=7`
|
||||||
|
- Moving a subtask to a different parent: `--from=5.2 --to=7.3`
|
||||||
|
- Reordering subtasks within the same parent: `--from=5.2 --to=5.4`
|
||||||
|
- Moving a task to a new ID position: `--from=5 --to=25` (even if task 25 doesn't exist yet)
|
||||||
|
- Moving multiple tasks at once: `--from=10,11,12 --to=16,17,18` (must have same number of IDs, Taskmaster will look through each position)
|
||||||
|
|
||||||
|
When moving tasks to new IDs:
|
||||||
|
|
||||||
|
- The system automatically creates placeholder tasks for non-existent destination IDs
|
||||||
|
- This prevents accidental data loss during reorganization
|
||||||
|
- Any tasks that depend on moved tasks will have their dependencies updated
|
||||||
|
- When moving a parent task, all its subtasks are automatically moved with it and renumbered
|
||||||
|
|
||||||
|
This is particularly useful as your project understanding evolves and you need to refine your task structure.
|
||||||
|
|
||||||
|
### 7. Resolving Merge Conflicts with Tasks
|
||||||
|
|
||||||
|
When working with a team, you might encounter merge conflicts in your tasks.json file if multiple team members create tasks on different branches. The move command makes resolving these conflicts straightforward:
|
||||||
|
|
||||||
|
```
|
||||||
|
I just merged the main branch and there's a conflict with tasks.json. My teammates created tasks 10-15 while I created tasks 10-12 on my branch. Can you help me resolve this?
|
||||||
|
```
|
||||||
|
|
||||||
|
The agent will help you:
|
||||||
|
|
||||||
|
1. Keep your teammates' tasks (10-15)
|
||||||
|
2. Move your tasks to new positions to avoid conflicts:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Move your tasks to new positions (e.g., 16-18)
|
||||||
|
task-master move --from=10 --to=16
|
||||||
|
task-master move --from=11 --to=17
|
||||||
|
task-master move --from=12 --to=18
|
||||||
|
```
|
||||||
|
|
||||||
|
This approach preserves everyone's work while maintaining a clean task structure, making it much easier to handle task conflicts than trying to manually merge JSON files.
|
||||||
|
|
||||||
|
### 8. Breaking Down Complex Tasks
|
||||||
|
|
||||||
For complex tasks that need more granularity:
|
For complex tasks that need more granularity:
|
||||||
|
|
||||||
|
|||||||
131
llms-install.md
Normal file
131
llms-install.md
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
``# Taskmaster AI Installation Guide
|
||||||
|
|
||||||
|
This guide helps AI assistants install and configure Taskmaster for users in their development projects.
|
||||||
|
|
||||||
|
## What is Taskmaster?
|
||||||
|
|
||||||
|
Taskmaster is an AI-driven task management system designed for development workflows. It helps break down projects into manageable tasks, track dependencies, and maintain development momentum through structured, AI-enhanced planning.
|
||||||
|
|
||||||
|
## Installation Steps
|
||||||
|
|
||||||
|
### Step 1: Add MCP Configuration
|
||||||
|
|
||||||
|
Add the following configuration to the user's MCP settings file (`.cursor/mcp.json` for Cursor, or equivalent for other editors):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"taskmaster-ai": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
|
||||||
|
"env": {
|
||||||
|
"ANTHROPIC_API_KEY": "user_will_add_their_key_here",
|
||||||
|
"PERPLEXITY_API_KEY": "user_will_add_their_key_here",
|
||||||
|
"OPENAI_API_KEY": "user_will_add_their_key_here",
|
||||||
|
"GOOGLE_API_KEY": "user_will_add_their_key_here",
|
||||||
|
"MISTRAL_API_KEY": "user_will_add_their_key_here",
|
||||||
|
"OPENROUTER_API_KEY": "user_will_add_their_key_here",
|
||||||
|
"XAI_API_KEY": "user_will_add_their_key_here"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 2: API Key Requirements
|
||||||
|
|
||||||
|
Inform the user they need **at least one** API key from the following providers:
|
||||||
|
|
||||||
|
- **Anthropic** (for Claude models) - Recommended
|
||||||
|
- **OpenAI** (for GPT models)
|
||||||
|
- **Google** (for Gemini models)
|
||||||
|
- **Perplexity** (for research features) - Highly recommended
|
||||||
|
- **Mistral** (for Mistral models)
|
||||||
|
- **OpenRouter** (access to multiple models)
|
||||||
|
- **xAI** (for Grok models)
|
||||||
|
|
||||||
|
The user will be able to define 3 separate roles (can be the same provider or separate providers) for main AI operations, research operations (research providers/models only), and a fallback model in case of errors.
|
||||||
|
|
||||||
|
### Step 3: Initialize Project
|
||||||
|
|
||||||
|
Once the MCP server is configured and API keys are added, initialize Taskmaster in the user's project:
|
||||||
|
|
||||||
|
> Can you initialize Task Master in my project?
|
||||||
|
|
||||||
|
This will run the `initialize_project` tool to set up the basic file structure.
|
||||||
|
|
||||||
|
### Step 4: Create Initial Tasks
|
||||||
|
|
||||||
|
Users have two options for creating initial tasks:
|
||||||
|
|
||||||
|
**Option A: Parse a PRD (Recommended)**
|
||||||
|
If they have a Product Requirements Document:
|
||||||
|
|
||||||
|
> Can you parse my PRD file at [path/to/prd.txt] to generate initial tasks?
|
||||||
|
|
||||||
|
If the user does not have a PRD, the AI agent can help them create one and store it in scripts/prd.txt for parsing.
|
||||||
|
|
||||||
|
**Option B: Start from scratch**
|
||||||
|
|
||||||
|
> Can you help me add my first task: [describe the task]
|
||||||
|
|
||||||
|
## Common Usage Patterns
|
||||||
|
|
||||||
|
### Daily Workflow
|
||||||
|
|
||||||
|
> What's the next task I should work on?
|
||||||
|
> Can you show me the details for task [ID]?
|
||||||
|
> Can you mark task [ID] as done?
|
||||||
|
|
||||||
|
### Task Management
|
||||||
|
|
||||||
|
> Can you break down task [ID] into subtasks?
|
||||||
|
> Can you add a new task: [description]
|
||||||
|
> Can you analyze the complexity of my tasks?
|
||||||
|
|
||||||
|
### Project Organization
|
||||||
|
|
||||||
|
> Can you show me all my pending tasks?
|
||||||
|
> Can you move task [ID] to become a subtask of [parent ID]?
|
||||||
|
> Can you update task [ID] with this new information: [details]
|
||||||
|
|
||||||
|
## Verification Steps
|
||||||
|
|
||||||
|
After installation, verify everything is working:
|
||||||
|
|
||||||
|
1. **Check MCP Connection**: The AI should be able to access Task Master tools
|
||||||
|
2. **Test Basic Commands**: Try `get_tasks` to list current tasks
|
||||||
|
3. **Verify API Keys**: Ensure AI-powered commands work (like `add_task`)
|
||||||
|
|
||||||
|
Note: An API key fallback exists that allows the MCP server to read API keys from `.env` instead of the MCP JSON config. It is recommended to have keys in both places in case the MCP server is unable to read keys from its environment for whatever reason.
|
||||||
|
|
||||||
|
When adding keys to `.env` only, the `models` tool will explain that the keys are not OK for MCP. Despite this, the fallback should kick in and the API keys will be read from the `.env` file.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
**If MCP server doesn't start:**
|
||||||
|
|
||||||
|
- Verify the JSON configuration is valid
|
||||||
|
- Check that Node.js is installed
|
||||||
|
- Ensure API keys are properly formatted
|
||||||
|
|
||||||
|
**If AI commands fail:**
|
||||||
|
|
||||||
|
- Verify at least one API key is configured
|
||||||
|
- Check API key permissions and quotas
|
||||||
|
- Try using a different model via the `models` tool
|
||||||
|
|
||||||
|
## CLI Fallback
|
||||||
|
|
||||||
|
Taskmaster is also available via CLI commands, by installing with `npm install task-master-ai@latest` in a terminal. Running `task-master help` will show all available commands, which offer a 1:1 experience with the MCP server. As the AI agent, you should refer to the system prompts and rules provided to you to identify Taskmaster-specific rules that help you understand how and when to use it.
|
||||||
|
|
||||||
|
## Next Steps
|
||||||
|
|
||||||
|
Once installed, users can:
|
||||||
|
|
||||||
|
- Create new tasks with `add-task` or parse a PRD (scripts/prd.txt) into tasks with `parse-prd`
|
||||||
|
- Set up model preferences with `models` tool
|
||||||
|
- Expand tasks into subtasks with `expand-all` and `expand-task`
|
||||||
|
- Explore advanced features like research mode and complexity analysis
|
||||||
|
|
||||||
|
For detailed documentation, refer to the Task Master docs directory.``
|
||||||
@@ -94,6 +94,7 @@ export async function addTaskDirect(args, log, context = {}) {
|
|||||||
|
|
||||||
let manualTaskData = null;
|
let manualTaskData = null;
|
||||||
let newTaskId;
|
let newTaskId;
|
||||||
|
let telemetryData;
|
||||||
|
|
||||||
if (isManualCreation) {
|
if (isManualCreation) {
|
||||||
// Create manual task data object
|
// Create manual task data object
|
||||||
@@ -109,7 +110,7 @@ export async function addTaskDirect(args, log, context = {}) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Call the addTask function with manual task data
|
// Call the addTask function with manual task data
|
||||||
newTaskId = await addTask(
|
const result = await addTask(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
null, // prompt is null for manual creation
|
null, // prompt is null for manual creation
|
||||||
taskDependencies,
|
taskDependencies,
|
||||||
@@ -117,13 +118,17 @@ export async function addTaskDirect(args, log, context = {}) {
|
|||||||
{
|
{
|
||||||
session,
|
session,
|
||||||
mcpLog,
|
mcpLog,
|
||||||
projectRoot
|
projectRoot,
|
||||||
|
commandName: 'add-task',
|
||||||
|
outputType: 'mcp'
|
||||||
},
|
},
|
||||||
'json', // outputFormat
|
'json', // outputFormat
|
||||||
manualTaskData, // Pass the manual task data
|
manualTaskData, // Pass the manual task data
|
||||||
false, // research flag is false for manual creation
|
false, // research flag is false for manual creation
|
||||||
projectRoot // Pass projectRoot
|
projectRoot // Pass projectRoot
|
||||||
);
|
);
|
||||||
|
newTaskId = result.newTaskId;
|
||||||
|
telemetryData = result.telemetryData;
|
||||||
} else {
|
} else {
|
||||||
// AI-driven task creation
|
// AI-driven task creation
|
||||||
log.info(
|
log.info(
|
||||||
@@ -131,7 +136,7 @@ export async function addTaskDirect(args, log, context = {}) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Call the addTask function, passing the research flag
|
// Call the addTask function, passing the research flag
|
||||||
newTaskId = await addTask(
|
const result = await addTask(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
prompt, // Use the prompt for AI creation
|
prompt, // Use the prompt for AI creation
|
||||||
taskDependencies,
|
taskDependencies,
|
||||||
@@ -139,12 +144,16 @@ export async function addTaskDirect(args, log, context = {}) {
|
|||||||
{
|
{
|
||||||
session,
|
session,
|
||||||
mcpLog,
|
mcpLog,
|
||||||
projectRoot
|
projectRoot,
|
||||||
|
commandName: 'add-task',
|
||||||
|
outputType: 'mcp'
|
||||||
},
|
},
|
||||||
'json', // outputFormat
|
'json', // outputFormat
|
||||||
null, // manualTaskData is null for AI creation
|
null, // manualTaskData is null for AI creation
|
||||||
research // Pass the research flag
|
research // Pass the research flag
|
||||||
);
|
);
|
||||||
|
newTaskId = result.newTaskId;
|
||||||
|
telemetryData = result.telemetryData;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Restore normal logging
|
// Restore normal logging
|
||||||
@@ -154,7 +163,8 @@ export async function addTaskDirect(args, log, context = {}) {
|
|||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
taskId: newTaskId,
|
taskId: newTaskId,
|
||||||
message: `Successfully added new task #${newTaskId}`
|
message: `Successfully added new task #${newTaskId}`,
|
||||||
|
telemetryData: telemetryData
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
|
|||||||
* @param {string} args.outputPath - Explicit absolute path to save the report.
|
* @param {string} args.outputPath - Explicit absolute path to save the report.
|
||||||
* @param {string|number} [args.threshold] - Minimum complexity score to recommend expansion (1-10)
|
* @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 {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 {string} [args.projectRoot] - Project root path.
|
||||||
* @param {Object} log - Logger object
|
* @param {Object} log - Logger object
|
||||||
* @param {Object} [context={}] - Context object containing session data
|
* @param {Object} [context={}] - Context object containing session data
|
||||||
@@ -26,7 +29,16 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
|
|||||||
*/
|
*/
|
||||||
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||||
const { session } = context;
|
const { session } = context;
|
||||||
const { tasksJsonPath, outputPath, threshold, research, projectRoot } = args;
|
const {
|
||||||
|
tasksJsonPath,
|
||||||
|
outputPath,
|
||||||
|
threshold,
|
||||||
|
research,
|
||||||
|
projectRoot,
|
||||||
|
ids,
|
||||||
|
from,
|
||||||
|
to
|
||||||
|
} = args;
|
||||||
|
|
||||||
const logWrapper = createLogWrapper(log);
|
const logWrapper = createLogWrapper(log);
|
||||||
|
|
||||||
@@ -58,6 +70,14 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
|||||||
log.info(`Analyzing task complexity from: ${tasksPath}`);
|
log.info(`Analyzing task complexity from: ${tasksPath}`);
|
||||||
log.info(`Output report will be saved to: ${resolvedOutputPath}`);
|
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) {
|
if (research) {
|
||||||
log.info('Using research role for complexity analysis');
|
log.info('Using research role for complexity analysis');
|
||||||
}
|
}
|
||||||
@@ -68,7 +88,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
|||||||
output: outputPath,
|
output: outputPath,
|
||||||
threshold: threshold,
|
threshold: threshold,
|
||||||
research: research === true, // Ensure boolean
|
research: research === true, // Ensure boolean
|
||||||
projectRoot: projectRoot // Pass projectRoot here
|
projectRoot: projectRoot, // Pass projectRoot here
|
||||||
|
id: ids, // Pass the ids parameter to the core function as 'id'
|
||||||
|
from: from, // Pass from parameter
|
||||||
|
to: to // Pass to parameter
|
||||||
};
|
};
|
||||||
// --- End Initial Checks ---
|
// --- End Initial Checks ---
|
||||||
|
|
||||||
@@ -79,17 +102,19 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let report;
|
let report;
|
||||||
|
let coreResult;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// --- Call Core Function (Pass context separately) ---
|
// --- Call Core Function (Pass context separately) ---
|
||||||
// Pass coreOptions as the first argument
|
// Pass coreOptions as the first argument
|
||||||
// Pass context object { session, mcpLog } as the second argument
|
// Pass context object { session, mcpLog } as the second argument
|
||||||
report = await analyzeTaskComplexity(
|
coreResult = await analyzeTaskComplexity(coreOptions, {
|
||||||
coreOptions, // Pass options object
|
session,
|
||||||
{ session, mcpLog: logWrapper } // Pass context object
|
mcpLog: logWrapper,
|
||||||
// Removed the explicit 'json' format argument, assuming context handling is sufficient
|
commandName: 'analyze-complexity',
|
||||||
// If issues persist, we might need to add an explicit format param to analyzeTaskComplexity
|
outputType: 'mcp'
|
||||||
);
|
});
|
||||||
|
report = coreResult.report;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(
|
log.error(
|
||||||
`Error in analyzeTaskComplexity core function: ${error.message}`
|
`Error in analyzeTaskComplexity core function: ${error.message}`
|
||||||
@@ -125,8 +150,11 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Added a check to ensure report is defined before accessing its properties
|
if (
|
||||||
if (!report || typeof report !== 'object') {
|
!coreResult ||
|
||||||
|
!coreResult.report ||
|
||||||
|
typeof coreResult.report !== 'object'
|
||||||
|
) {
|
||||||
log.error(
|
log.error(
|
||||||
'Core analysis function returned an invalid or undefined response.'
|
'Core analysis function returned an invalid or undefined response.'
|
||||||
);
|
);
|
||||||
@@ -141,8 +169,8 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// Ensure complexityAnalysis exists and is an array
|
// Ensure complexityAnalysis exists and is an array
|
||||||
const analysisArray = Array.isArray(report.complexityAnalysis)
|
const analysisArray = Array.isArray(coreResult.report.complexityAnalysis)
|
||||||
? report.complexityAnalysis
|
? coreResult.report.complexityAnalysis
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
// Count tasks by complexity (remains the same)
|
// Count tasks by complexity (remains the same)
|
||||||
@@ -159,15 +187,16 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Task complexity analysis complete. Report saved to ${outputPath}`, // Use outputPath from args
|
message: `Task complexity analysis complete. Report saved to ${outputPath}`,
|
||||||
reportPath: outputPath, // Use outputPath from args
|
reportPath: outputPath,
|
||||||
reportSummary: {
|
reportSummary: {
|
||||||
taskCount: analysisArray.length,
|
taskCount: analysisArray.length,
|
||||||
highComplexityTasks,
|
highComplexityTasks,
|
||||||
mediumComplexityTasks,
|
mediumComplexityTasks,
|
||||||
lowComplexityTasks
|
lowComplexityTasks
|
||||||
},
|
},
|
||||||
fullReport: report // Now includes the full report
|
fullReport: coreResult.report,
|
||||||
|
telemetryData: coreResult.telemetryData
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (parseError) {
|
} catch (parseError) {
|
||||||
|
|||||||
@@ -63,12 +63,18 @@ export async function expandAllTasksDirect(args, log, context = {}) {
|
|||||||
{ session, mcpLog, projectRoot }
|
{ session, mcpLog, projectRoot }
|
||||||
);
|
);
|
||||||
|
|
||||||
// Core function now returns a summary object
|
// Core function now returns a summary object including the *aggregated* telemetryData
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Expand all operation completed. Expanded: ${result.expandedCount}, Failed: ${result.failedCount}, Skipped: ${result.skippedCount}`,
|
message: `Expand all operation completed. Expanded: ${result.expandedCount}, Failed: ${result.failedCount}, Skipped: ${result.skippedCount}`,
|
||||||
details: result // Include the full result details
|
details: {
|
||||||
|
expandedCount: result.expandedCount,
|
||||||
|
failedCount: result.failedCount,
|
||||||
|
skippedCount: result.skippedCount,
|
||||||
|
tasksToExpand: result.tasksToExpand
|
||||||
|
},
|
||||||
|
telemetryData: result.telemetryData // Pass the aggregated object
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -193,13 +193,19 @@ export async function expandTaskDirect(args, log, context = {}) {
|
|||||||
if (!wasSilent) enableSilentMode();
|
if (!wasSilent) enableSilentMode();
|
||||||
|
|
||||||
// Call the core expandTask function with the wrapped logger and projectRoot
|
// Call the core expandTask function with the wrapped logger and projectRoot
|
||||||
const updatedTaskResult = await expandTask(
|
const coreResult = await expandTask(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
taskId,
|
taskId,
|
||||||
numSubtasks,
|
numSubtasks,
|
||||||
useResearch,
|
useResearch,
|
||||||
additionalContext,
|
additionalContext,
|
||||||
{ mcpLog, session, projectRoot },
|
{
|
||||||
|
mcpLog,
|
||||||
|
session,
|
||||||
|
projectRoot,
|
||||||
|
commandName: 'expand-task',
|
||||||
|
outputType: 'mcp'
|
||||||
|
},
|
||||||
forceFlag
|
forceFlag
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -215,16 +221,17 @@ export async function expandTaskDirect(args, log, context = {}) {
|
|||||||
? updatedTask.subtasks.length - subtasksCountBefore
|
? updatedTask.subtasks.length - subtasksCountBefore
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
// Return the result
|
// Return the result, including telemetryData
|
||||||
log.info(
|
log.info(
|
||||||
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
|
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
task: updatedTask,
|
task: coreResult.task,
|
||||||
subtasksAdded,
|
subtasksAdded,
|
||||||
hasExistingSubtasks
|
hasExistingSubtasks,
|
||||||
|
telemetryData: coreResult.telemetryData
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
*/
|
*/
|
||||||
export async function listTasksDirect(args, log) {
|
export async function listTasksDirect(args, log) {
|
||||||
// Destructure the explicit tasksJsonPath from args
|
// Destructure the explicit tasksJsonPath from args
|
||||||
const { tasksJsonPath, status, withSubtasks } = args;
|
const { tasksJsonPath, reportPath, status, withSubtasks } = args;
|
||||||
|
|
||||||
if (!tasksJsonPath) {
|
if (!tasksJsonPath) {
|
||||||
log.error('listTasksDirect called without tasksJsonPath');
|
log.error('listTasksDirect called without tasksJsonPath');
|
||||||
@@ -49,6 +49,7 @@ export async function listTasksDirect(args, log) {
|
|||||||
const resultData = listTasks(
|
const resultData = listTasks(
|
||||||
tasksJsonPath,
|
tasksJsonPath,
|
||||||
statusFilter,
|
statusFilter,
|
||||||
|
reportPath,
|
||||||
withSubtasksFilter,
|
withSubtasksFilter,
|
||||||
'json'
|
'json'
|
||||||
);
|
);
|
||||||
@@ -63,6 +64,7 @@ export async function listTasksDirect(args, log) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info(
|
log.info(
|
||||||
`Core listTasks function retrieved ${resultData.tasks.length} tasks`
|
`Core listTasks function retrieved ${resultData.tasks.length} tasks`
|
||||||
);
|
);
|
||||||
|
|||||||
99
mcp-server/src/core/direct-functions/move-task.js
Normal file
99
mcp-server/src/core/direct-functions/move-task.js
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
/**
|
||||||
|
* 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,7 +4,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { findNextTask } from '../../../../scripts/modules/task-manager.js';
|
import { findNextTask } from '../../../../scripts/modules/task-manager.js';
|
||||||
import { readJSON } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
readJSON,
|
||||||
|
readComplexityReport
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import {
|
import {
|
||||||
enableSilentMode,
|
enableSilentMode,
|
||||||
disableSilentMode
|
disableSilentMode
|
||||||
@@ -20,7 +23,7 @@ import {
|
|||||||
*/
|
*/
|
||||||
export async function nextTaskDirect(args, log) {
|
export async function nextTaskDirect(args, log) {
|
||||||
// Destructure expected args
|
// Destructure expected args
|
||||||
const { tasksJsonPath } = args;
|
const { tasksJsonPath, reportPath } = args;
|
||||||
|
|
||||||
if (!tasksJsonPath) {
|
if (!tasksJsonPath) {
|
||||||
log.error('nextTaskDirect called without tasksJsonPath');
|
log.error('nextTaskDirect called without tasksJsonPath');
|
||||||
@@ -55,8 +58,11 @@ export async function nextTaskDirect(args, log) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read the complexity report
|
||||||
|
const complexityReport = readComplexityReport(reportPath);
|
||||||
|
|
||||||
// Find the next task
|
// Find the next task
|
||||||
const nextTask = findNextTask(data.tasks);
|
const nextTask = findNextTask(data.tasks, complexityReport);
|
||||||
|
|
||||||
if (!nextTask) {
|
if (!nextTask) {
|
||||||
log.info(
|
log.info(
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ export async function parsePRDDirect(args, log, context = {}) {
|
|||||||
numTasks: numTasksArg,
|
numTasks: numTasksArg,
|
||||||
force,
|
force,
|
||||||
append,
|
append,
|
||||||
|
research,
|
||||||
projectRoot
|
projectRoot
|
||||||
} = args;
|
} = args;
|
||||||
|
|
||||||
@@ -105,19 +106,23 @@ export async function parsePRDDirect(args, log, context = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const useForce = force === true;
|
if (append) {
|
||||||
const useAppend = append === true;
|
|
||||||
if (useAppend) {
|
|
||||||
logWrapper.info('Append mode enabled.');
|
logWrapper.info('Append mode enabled.');
|
||||||
if (useForce) {
|
if (force) {
|
||||||
logWrapper.warn(
|
logWrapper.warn(
|
||||||
'Both --force and --append flags were provided. --force takes precedence; append mode will be ignored.'
|
'Both --force and --append flags were provided. --force takes precedence; append mode will be ignored.'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (research) {
|
||||||
|
logWrapper.info(
|
||||||
|
'Research mode enabled. Using Perplexity AI for enhanced PRD analysis.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
logWrapper.info(
|
logWrapper.info(
|
||||||
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${useForce}, Append: ${useAppend}, ProjectRoot: ${projectRoot}`
|
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, Research: ${research}, ProjectRoot: ${projectRoot}`
|
||||||
);
|
);
|
||||||
|
|
||||||
const wasSilent = isSilentMode();
|
const wasSilent = isSilentMode();
|
||||||
@@ -131,21 +136,29 @@ export async function parsePRDDirect(args, log, context = {}) {
|
|||||||
inputPath,
|
inputPath,
|
||||||
outputPath,
|
outputPath,
|
||||||
numTasks,
|
numTasks,
|
||||||
{ session, mcpLog: logWrapper, projectRoot, useForce, useAppend },
|
{
|
||||||
|
session,
|
||||||
|
mcpLog: logWrapper,
|
||||||
|
projectRoot,
|
||||||
|
force,
|
||||||
|
append,
|
||||||
|
research,
|
||||||
|
commandName: 'parse-prd',
|
||||||
|
outputType: 'mcp'
|
||||||
|
},
|
||||||
'json'
|
'json'
|
||||||
);
|
);
|
||||||
|
|
||||||
// parsePRD returns { success: true, tasks: processedTasks } on success
|
// Adjust check for the new return structure
|
||||||
if (result && result.success && Array.isArray(result.tasks)) {
|
if (result && result.success) {
|
||||||
logWrapper.success(
|
const successMsg = `Successfully parsed PRD and generated tasks in ${result.tasksPath}`;
|
||||||
`Successfully parsed PRD. Generated ${result.tasks.length} tasks.`
|
logWrapper.success(successMsg);
|
||||||
);
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
message: `Successfully parsed PRD and generated ${result.tasks.length} tasks.`,
|
message: successMsg,
|
||||||
outputPath: outputPath,
|
outputPath: result.tasksPath,
|
||||||
taskCount: result.tasks.length
|
telemetryData: result.telemetryData
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
disableSilentMode,
|
disableSilentMode,
|
||||||
isSilentMode
|
isSilentMode
|
||||||
} from '../../../../scripts/modules/utils.js';
|
} from '../../../../scripts/modules/utils.js';
|
||||||
|
import { nextTaskDirect } from './next-task.js';
|
||||||
/**
|
/**
|
||||||
* Direct function wrapper for setTaskStatus with error handling.
|
* Direct function wrapper for setTaskStatus with error handling.
|
||||||
*
|
*
|
||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
*/
|
*/
|
||||||
export async function setTaskStatusDirect(args, log) {
|
export async function setTaskStatusDirect(args, log) {
|
||||||
// Destructure expected args, including the resolved tasksJsonPath
|
// Destructure expected args, including the resolved tasksJsonPath
|
||||||
const { tasksJsonPath, id, status } = args;
|
const { tasksJsonPath, id, status, complexityReportPath } = args;
|
||||||
try {
|
try {
|
||||||
log.info(`Setting task status with args: ${JSON.stringify(args)}`);
|
log.info(`Setting task status with args: ${JSON.stringify(args)}`);
|
||||||
|
|
||||||
@@ -85,6 +85,39 @@ export async function setTaskStatusDirect(args, log) {
|
|||||||
},
|
},
|
||||||
fromCache: false // This operation always modifies state and should never be cached
|
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;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error(`Error setting task status: ${error.message}`);
|
log.error(`Error setting task status: ${error.message}`);
|
||||||
|
|||||||
@@ -3,7 +3,11 @@
|
|||||||
* Direct function implementation for showing task details
|
* Direct function implementation for showing task details
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { findTaskById, readJSON } from '../../../../scripts/modules/utils.js';
|
import {
|
||||||
|
findTaskById,
|
||||||
|
readComplexityReport,
|
||||||
|
readJSON
|
||||||
|
} from '../../../../scripts/modules/utils.js';
|
||||||
import { findTasksJsonPath } from '../utils/path-utils.js';
|
import { findTasksJsonPath } from '../utils/path-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -12,6 +16,7 @@ import { findTasksJsonPath } from '../utils/path-utils.js';
|
|||||||
* @param {Object} args - Command arguments.
|
* @param {Object} args - Command arguments.
|
||||||
* @param {string} args.id - Task ID to show.
|
* @param {string} args.id - Task ID to show.
|
||||||
* @param {string} [args.file] - Optional path to the tasks file (passed to findTasksJsonPath).
|
* @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 {string} [args.status] - Optional status to filter subtasks by.
|
* @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 {string} args.projectRoot - Absolute path to the project root directory (already normalized by tool).
|
||||||
* @param {Object} log - Logger object.
|
* @param {Object} log - Logger object.
|
||||||
@@ -22,7 +27,7 @@ export async function showTaskDirect(args, log) {
|
|||||||
// Destructure session from context if needed later, otherwise ignore
|
// Destructure session from context if needed later, otherwise ignore
|
||||||
// const { session } = context;
|
// const { session } = context;
|
||||||
// Destructure projectRoot and other args. projectRoot is assumed normalized.
|
// Destructure projectRoot and other args. projectRoot is assumed normalized.
|
||||||
const { id, file, status, projectRoot } = args;
|
const { id, file, reportPath, status, projectRoot } = args;
|
||||||
|
|
||||||
log.info(
|
log.info(
|
||||||
`Showing task direct function. ID: ${id}, File: ${file}, Status Filter: ${status}, ProjectRoot: ${projectRoot}`
|
`Showing task direct function. ID: ${id}, File: ${file}, Status Filter: ${status}, ProjectRoot: ${projectRoot}`
|
||||||
@@ -59,9 +64,12 @@ export async function showTaskDirect(args, log) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const complexityReport = readComplexityReport(reportPath);
|
||||||
|
|
||||||
const { task, originalSubtaskCount } = findTaskById(
|
const { task, originalSubtaskCount } = findTaskById(
|
||||||
tasksData.tasks,
|
tasksData.tasks,
|
||||||
id,
|
id,
|
||||||
|
complexityReport,
|
||||||
status
|
status
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -108,18 +108,24 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// Execute core updateSubtaskById function
|
// Execute core updateSubtaskById function
|
||||||
const updatedSubtask = await updateSubtaskById(
|
const coreResult = await updateSubtaskById(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
subtaskIdStr,
|
subtaskIdStr,
|
||||||
prompt,
|
prompt,
|
||||||
useResearch,
|
useResearch,
|
||||||
{ mcpLog: logWrapper, session, projectRoot },
|
{
|
||||||
|
mcpLog: logWrapper,
|
||||||
|
session,
|
||||||
|
projectRoot,
|
||||||
|
commandName: 'update-subtask',
|
||||||
|
outputType: 'mcp'
|
||||||
|
},
|
||||||
'json'
|
'json'
|
||||||
);
|
);
|
||||||
|
|
||||||
if (updatedSubtask === null) {
|
if (!coreResult || coreResult.updatedSubtask === null) {
|
||||||
const message = `Subtask ${id} or its parent task not found.`;
|
const message = `Subtask ${id} or its parent task not found.`;
|
||||||
logWrapper.error(message); // Log as error since it couldn't be found
|
logWrapper.error(message);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: { code: 'SUBTASK_NOT_FOUND', message: message },
|
error: { code: 'SUBTASK_NOT_FOUND', message: message },
|
||||||
@@ -136,9 +142,10 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
|||||||
message: `Successfully updated subtask with ID ${subtaskIdStr}`,
|
message: `Successfully updated subtask with ID ${subtaskIdStr}`,
|
||||||
subtaskId: subtaskIdStr,
|
subtaskId: subtaskIdStr,
|
||||||
parentId: subtaskIdStr.split('.')[0],
|
parentId: subtaskIdStr.split('.')[0],
|
||||||
subtask: updatedSubtask,
|
subtask: coreResult.updatedSubtask,
|
||||||
tasksPath,
|
tasksPath,
|
||||||
useResearch
|
useResearch,
|
||||||
|
telemetryData: coreResult.telemetryData
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// Execute core updateTaskById function with proper parameters
|
// Execute core updateTaskById function with proper parameters
|
||||||
const updatedTask = await updateTaskById(
|
const coreResult = await updateTaskById(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
taskId,
|
taskId,
|
||||||
prompt,
|
prompt,
|
||||||
@@ -118,19 +118,26 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
|||||||
{
|
{
|
||||||
mcpLog: logWrapper,
|
mcpLog: logWrapper,
|
||||||
session,
|
session,
|
||||||
projectRoot
|
projectRoot,
|
||||||
|
commandName: 'update-task',
|
||||||
|
outputType: 'mcp'
|
||||||
},
|
},
|
||||||
'json'
|
'json'
|
||||||
);
|
);
|
||||||
|
|
||||||
// Check if the core function indicated the task wasn't updated (e.g., status was 'done')
|
// Check if the core function returned null or an object without success
|
||||||
if (updatedTask === null) {
|
if (!coreResult || coreResult.updatedTask === null) {
|
||||||
// Core function logs the reason, just return success with info
|
// Core function logs the reason, just return success with info
|
||||||
const message = `Task ${taskId} was not updated (likely already completed).`;
|
const message = `Task ${taskId} was not updated (likely already completed).`;
|
||||||
logWrapper.info(message);
|
logWrapper.info(message);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: { message: message, taskId: taskId, updated: false },
|
data: {
|
||||||
|
message: message,
|
||||||
|
taskId: taskId,
|
||||||
|
updated: false,
|
||||||
|
telemetryData: coreResult?.telemetryData
|
||||||
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -146,7 +153,8 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
|||||||
tasksPath: tasksPath,
|
tasksPath: tasksPath,
|
||||||
useResearch: useResearch,
|
useResearch: useResearch,
|
||||||
updated: true,
|
updated: true,
|
||||||
updatedTask: updatedTask
|
updatedTask: coreResult.updatedTask,
|
||||||
|
telemetryData: coreResult.telemetryData
|
||||||
},
|
},
|
||||||
fromCache: false
|
fromCache: false
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -85,7 +85,6 @@ export async function updateTasksDirect(args, log, context = {}) {
|
|||||||
'json'
|
'json'
|
||||||
);
|
);
|
||||||
|
|
||||||
// updateTasks returns { success: true, updatedTasks: [...] } on success
|
|
||||||
if (result && result.success && Array.isArray(result.updatedTasks)) {
|
if (result && result.success && Array.isArray(result.updatedTasks)) {
|
||||||
logWrapper.success(
|
logWrapper.success(
|
||||||
`Successfully updated ${result.updatedTasks.length} tasks.`
|
`Successfully updated ${result.updatedTasks.length} tasks.`
|
||||||
@@ -95,7 +94,8 @@ export async function updateTasksDirect(args, log, context = {}) {
|
|||||||
data: {
|
data: {
|
||||||
message: `Successfully updated ${result.updatedTasks.length} tasks.`,
|
message: `Successfully updated ${result.updatedTasks.length} tasks.`,
|
||||||
tasksFile,
|
tasksFile,
|
||||||
updatedCount: result.updatedTasks.length
|
updatedCount: result.updatedTasks.length,
|
||||||
|
telemetryData: result.telemetryData
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import { addDependencyDirect } from './direct-functions/add-dependency.js';
|
|||||||
import { removeTaskDirect } from './direct-functions/remove-task.js';
|
import { removeTaskDirect } from './direct-functions/remove-task.js';
|
||||||
import { initializeProjectDirect } from './direct-functions/initialize-project.js';
|
import { initializeProjectDirect } from './direct-functions/initialize-project.js';
|
||||||
import { modelsDirect } from './direct-functions/models.js';
|
import { modelsDirect } from './direct-functions/models.js';
|
||||||
|
import { moveTaskDirect } from './direct-functions/move-task.js';
|
||||||
|
|
||||||
// Re-export utility functions
|
// Re-export utility functions
|
||||||
export { findTasksJsonPath } from './utils/path-utils.js';
|
export { findTasksJsonPath } from './utils/path-utils.js';
|
||||||
@@ -60,7 +61,8 @@ export const directFunctions = new Map([
|
|||||||
['addDependencyDirect', addDependencyDirect],
|
['addDependencyDirect', addDependencyDirect],
|
||||||
['removeTaskDirect', removeTaskDirect],
|
['removeTaskDirect', removeTaskDirect],
|
||||||
['initializeProjectDirect', initializeProjectDirect],
|
['initializeProjectDirect', initializeProjectDirect],
|
||||||
['modelsDirect', modelsDirect]
|
['modelsDirect', modelsDirect],
|
||||||
|
['moveTaskDirect', moveTaskDirect]
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Re-export all direct function implementations
|
// Re-export all direct function implementations
|
||||||
@@ -89,5 +91,6 @@ export {
|
|||||||
addDependencyDirect,
|
addDependencyDirect,
|
||||||
removeTaskDirect,
|
removeTaskDirect,
|
||||||
initializeProjectDirect,
|
initializeProjectDirect,
|
||||||
modelsDirect
|
modelsDirect,
|
||||||
|
moveTaskDirect
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -339,6 +339,49 @@ export function findPRDDocumentPath(projectRoot, explicitPath, log) {
|
|||||||
return null;
|
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
|
* Resolves the tasks output directory path
|
||||||
* @param {string} projectRoot - The project root directory
|
* @param {string} projectRoot - The project root directory
|
||||||
|
|||||||
@@ -49,6 +49,24 @@ export function registerAnalyzeProjectComplexityTool(server) {
|
|||||||
.describe(
|
.describe(
|
||||||
'Path to the tasks file relative to project root (default: tasks/tasks.json).'
|
'Path to the tasks file relative to project root (default: tasks/tasks.json).'
|
||||||
),
|
),
|
||||||
|
ids: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
'Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").'
|
||||||
|
),
|
||||||
|
from: z.coerce
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.describe('Starting task ID in a range to analyze.'),
|
||||||
|
to: z.coerce
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.describe('Ending task ID in a range to analyze.'),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.describe('The directory of the project. Must be an absolute path.')
|
.describe('The directory of the project. Must be an absolute path.')
|
||||||
@@ -107,7 +125,10 @@ export function registerAnalyzeProjectComplexityTool(server) {
|
|||||||
outputPath: outputPath,
|
outputPath: outputPath,
|
||||||
threshold: args.threshold,
|
threshold: args.threshold,
|
||||||
research: args.research,
|
research: args.research,
|
||||||
projectRoot: args.projectRoot
|
projectRoot: args.projectRoot,
|
||||||
|
ids: args.ids,
|
||||||
|
from: args.from,
|
||||||
|
to: args.to
|
||||||
},
|
},
|
||||||
log,
|
log,
|
||||||
{ session }
|
{ session }
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ import {
|
|||||||
withNormalizedProjectRoot
|
withNormalizedProjectRoot
|
||||||
} from './utils.js';
|
} from './utils.js';
|
||||||
import { showTaskDirect } from '../core/task-master-core.js';
|
import { showTaskDirect } from '../core/task-master-core.js';
|
||||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
import {
|
||||||
|
findTasksJsonPath,
|
||||||
|
findComplexityReportPath
|
||||||
|
} from '../core/utils/path-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Custom processor function that removes allTasks from the response
|
* Custom processor function that removes allTasks from the response
|
||||||
@@ -50,6 +53,12 @@ export function registerShowTaskTool(server) {
|
|||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe('Path to the tasks file relative to project root'),
|
.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)'
|
||||||
|
),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
@@ -81,9 +90,22 @@ export function registerShowTaskTool(server) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Call the direct function, passing the normalized projectRoot
|
// 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}`);
|
||||||
|
}
|
||||||
const result = await showTaskDirect(
|
const result = await showTaskDirect(
|
||||||
{
|
{
|
||||||
tasksJsonPath: tasksJsonPath,
|
tasksJsonPath: tasksJsonPath,
|
||||||
|
reportPath: complexityReportPath,
|
||||||
|
// Pass other relevant args
|
||||||
id: id,
|
id: id,
|
||||||
status: status,
|
status: status,
|
||||||
projectRoot: projectRoot
|
projectRoot: projectRoot
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ import {
|
|||||||
withNormalizedProjectRoot
|
withNormalizedProjectRoot
|
||||||
} from './utils.js';
|
} from './utils.js';
|
||||||
import { listTasksDirect } from '../core/task-master-core.js';
|
import { listTasksDirect } from '../core/task-master-core.js';
|
||||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
import {
|
||||||
|
findTasksJsonPath,
|
||||||
|
findComplexityReportPath
|
||||||
|
} from '../core/utils/path-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the getTasks tool with the MCP server
|
* Register the getTasks tool with the MCP server
|
||||||
@@ -38,6 +41,12 @@ export function registerListTasksTool(server) {
|
|||||||
.describe(
|
.describe(
|
||||||
'Path to the tasks file (relative to project root or absolute)'
|
'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
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.describe('The directory of the project. Must be an absolute path.')
|
.describe('The directory of the project. Must be an absolute path.')
|
||||||
@@ -60,11 +69,23 @@ export function registerListTasksTool(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 listTasksDirect(
|
const result = await listTasksDirect(
|
||||||
{
|
{
|
||||||
tasksJsonPath: tasksJsonPath,
|
tasksJsonPath: tasksJsonPath,
|
||||||
status: args.status,
|
status: args.status,
|
||||||
withSubtasks: args.withSubtasks
|
withSubtasks: args.withSubtasks,
|
||||||
|
reportPath: complexityReportPath
|
||||||
},
|
},
|
||||||
log
|
log
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { registerAddDependencyTool } from './add-dependency.js';
|
|||||||
import { registerRemoveTaskTool } from './remove-task.js';
|
import { registerRemoveTaskTool } from './remove-task.js';
|
||||||
import { registerInitializeProjectTool } from './initialize-project.js';
|
import { registerInitializeProjectTool } from './initialize-project.js';
|
||||||
import { registerModelsTool } from './models.js';
|
import { registerModelsTool } from './models.js';
|
||||||
|
import { registerMoveTaskTool } from './move-task.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register all Task Master tools with the MCP server
|
* Register all Task Master tools with the MCP server
|
||||||
@@ -61,6 +62,7 @@ export function registerTaskMasterTools(server) {
|
|||||||
registerRemoveTaskTool(server);
|
registerRemoveTaskTool(server);
|
||||||
registerRemoveSubtaskTool(server);
|
registerRemoveSubtaskTool(server);
|
||||||
registerClearSubtasksTool(server);
|
registerClearSubtasksTool(server);
|
||||||
|
registerMoveTaskTool(server);
|
||||||
|
|
||||||
// Group 5: Task Analysis & Expansion
|
// Group 5: Task Analysis & Expansion
|
||||||
registerAnalyzeProjectComplexityTool(server);
|
registerAnalyzeProjectComplexityTool(server);
|
||||||
|
|||||||
129
mcp-server/src/tools/move-task.js
Normal file
129
mcp-server/src/tools/move-task.js
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
/**
|
||||||
|
* 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'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -10,7 +10,10 @@ import {
|
|||||||
withNormalizedProjectRoot
|
withNormalizedProjectRoot
|
||||||
} from './utils.js';
|
} from './utils.js';
|
||||||
import { nextTaskDirect } from '../core/task-master-core.js';
|
import { nextTaskDirect } from '../core/task-master-core.js';
|
||||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
import {
|
||||||
|
findTasksJsonPath,
|
||||||
|
findComplexityReportPath
|
||||||
|
} from '../core/utils/path-utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register the next-task tool with the MCP server
|
* Register the next-task tool with the MCP server
|
||||||
@@ -23,6 +26,12 @@ export function registerNextTaskTool(server) {
|
|||||||
'Find the next task to work on based on dependencies and status',
|
'Find the next task to work on based on dependencies and status',
|
||||||
parameters: z.object({
|
parameters: z.object({
|
||||||
file: z.string().optional().describe('Absolute path to the tasks file'),
|
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
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.describe('The directory of the project. Must be an absolute path.')
|
.describe('The directory of the project. Must be an absolute path.')
|
||||||
@@ -45,9 +54,21 @@ 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(
|
const result = await nextTaskDirect(
|
||||||
{
|
{
|
||||||
tasksJsonPath: tasksJsonPath
|
tasksJsonPath: tasksJsonPath,
|
||||||
|
reportPath: complexityReportPath
|
||||||
},
|
},
|
||||||
log
|
log
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -49,6 +49,13 @@ export function registerParsePRDTool(server) {
|
|||||||
.optional()
|
.optional()
|
||||||
.default(false)
|
.default(false)
|
||||||
.describe('Append generated tasks to existing file.'),
|
.describe('Append generated tasks to existing file.'),
|
||||||
|
research: z
|
||||||
|
.boolean()
|
||||||
|
.optional()
|
||||||
|
.default(false)
|
||||||
|
.describe(
|
||||||
|
'Use the research model for research-backed task generation, providing more comprehensive, accurate and up-to-date task details.'
|
||||||
|
),
|
||||||
projectRoot: z
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.describe('The directory of the project. Must be an absolute path.')
|
.describe('The directory of the project. Must be an absolute path.')
|
||||||
@@ -68,6 +75,7 @@ export function registerParsePRDTool(server) {
|
|||||||
numTasks: args.numTasks,
|
numTasks: args.numTasks,
|
||||||
force: args.force,
|
force: args.force,
|
||||||
append: args.append,
|
append: args.append,
|
||||||
|
research: args.research,
|
||||||
projectRoot: args.projectRoot
|
projectRoot: args.projectRoot
|
||||||
},
|
},
|
||||||
log,
|
log,
|
||||||
|
|||||||
@@ -9,8 +9,14 @@ import {
|
|||||||
createErrorResponse,
|
createErrorResponse,
|
||||||
withNormalizedProjectRoot
|
withNormalizedProjectRoot
|
||||||
} from './utils.js';
|
} from './utils.js';
|
||||||
import { setTaskStatusDirect } from '../core/task-master-core.js';
|
import {
|
||||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
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 { TASK_STATUS_OPTIONS } from '../../../src/constants/task-status.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -33,6 +39,12 @@ export function registerSetTaskStatusTool(server) {
|
|||||||
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
|
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
|
||||||
),
|
),
|
||||||
file: z.string().optional().describe('Absolute path to the tasks file'),
|
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
|
projectRoot: z
|
||||||
.string()
|
.string()
|
||||||
.describe('The directory of the project. Must be an absolute path.')
|
.describe('The directory of the project. Must be an absolute path.')
|
||||||
@@ -55,11 +67,23 @@ export function registerSetTaskStatusTool(server) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let complexityReportPath;
|
||||||
|
try {
|
||||||
|
complexityReportPath = findComplexityReportPath(
|
||||||
|
args.projectRoot,
|
||||||
|
args.complexityReport,
|
||||||
|
log
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
log.error(`Error finding complexity report: ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
const result = await setTaskStatusDirect(
|
const result = await setTaskStatusDirect(
|
||||||
{
|
{
|
||||||
tasksJsonPath: tasksJsonPath,
|
tasksJsonPath: tasksJsonPath,
|
||||||
id: args.id,
|
id: args.id,
|
||||||
status: args.status
|
status: args.status,
|
||||||
|
complexityReportPath
|
||||||
},
|
},
|
||||||
log
|
log
|
||||||
);
|
);
|
||||||
|
|||||||
6
package-lock.json
generated
6
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "task-master-ai",
|
"name": "task-master-ai",
|
||||||
"version": "0.13.2",
|
"version": "0.14.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "task-master-ai",
|
"name": "task-master-ai",
|
||||||
"version": "0.13.2",
|
"version": "0.14.0",
|
||||||
"license": "MIT WITH Commons-Clause",
|
"license": "MIT WITH Commons-Clause",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ai-sdk/anthropic": "^1.2.10",
|
"@ai-sdk/anthropic": "^1.2.10",
|
||||||
@@ -28,7 +28,7 @@
|
|||||||
"express": "^4.21.2",
|
"express": "^4.21.2",
|
||||||
"fastmcp": "^1.20.5",
|
"fastmcp": "^1.20.5",
|
||||||
"figlet": "^1.8.0",
|
"figlet": "^1.8.0",
|
||||||
"fuse.js": "^7.0.0",
|
"fuse.js": "^7.1.0",
|
||||||
"gradient-string": "^3.0.0",
|
"gradient-string": "^3.0.0",
|
||||||
"helmet": "^8.1.0",
|
"helmet": "^8.1.0",
|
||||||
"inquirer": "^12.5.0",
|
"inquirer": "^12.5.0",
|
||||||
|
|||||||
10
package.json
10
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "task-master-ai",
|
"name": "task-master-ai",
|
||||||
"version": "0.13.2",
|
"version": "0.15.0",
|
||||||
"description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
|
"description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -49,13 +49,16 @@
|
|||||||
"@anthropic-ai/sdk": "^0.39.0",
|
"@anthropic-ai/sdk": "^0.39.0",
|
||||||
"@openrouter/ai-sdk-provider": "^0.4.5",
|
"@openrouter/ai-sdk-provider": "^0.4.5",
|
||||||
"ai": "^4.3.10",
|
"ai": "^4.3.10",
|
||||||
|
"boxen": "^8.0.1",
|
||||||
|
"chalk": "^5.4.1",
|
||||||
|
"cli-table3": "^0.6.5",
|
||||||
"commander": "^11.1.0",
|
"commander": "^11.1.0",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"dotenv": "^16.3.1",
|
"dotenv": "^16.3.1",
|
||||||
"express": "^4.21.2",
|
"express": "^4.21.2",
|
||||||
"fastmcp": "^1.20.5",
|
"fastmcp": "^1.20.5",
|
||||||
"figlet": "^1.8.0",
|
"figlet": "^1.8.0",
|
||||||
"fuse.js": "^7.0.0",
|
"fuse.js": "^7.1.0",
|
||||||
"gradient-string": "^3.0.0",
|
"gradient-string": "^3.0.0",
|
||||||
"helmet": "^8.1.0",
|
"helmet": "^8.1.0",
|
||||||
"inquirer": "^12.5.0",
|
"inquirer": "^12.5.0",
|
||||||
@@ -65,9 +68,6 @@
|
|||||||
"openai": "^4.89.0",
|
"openai": "^4.89.0",
|
||||||
"ora": "^8.2.0",
|
"ora": "^8.2.0",
|
||||||
"uuid": "^11.1.0",
|
"uuid": "^11.1.0",
|
||||||
"boxen": "^8.0.1",
|
|
||||||
"chalk": "^5.4.1",
|
|
||||||
"cli-table3": "^0.6.5",
|
|
||||||
"zod": "^3.23.8"
|
"zod": "^3.23.8"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
|
|||||||
@@ -15,7 +15,11 @@ import {
|
|||||||
getFallbackProvider,
|
getFallbackProvider,
|
||||||
getFallbackModelId,
|
getFallbackModelId,
|
||||||
getParametersForRole,
|
getParametersForRole,
|
||||||
getBaseUrlForRole
|
getUserId,
|
||||||
|
MODEL_MAP,
|
||||||
|
getDebugFlag,
|
||||||
|
getBaseUrlForRole,
|
||||||
|
isApiKeySet
|
||||||
} from './config-manager.js';
|
} from './config-manager.js';
|
||||||
import { log, resolveEnvVariable, findProjectRoot } from './utils.js';
|
import { log, resolveEnvVariable, findProjectRoot } from './utils.js';
|
||||||
|
|
||||||
@@ -25,8 +29,39 @@ import * as google from '../../src/ai-providers/google.js';
|
|||||||
import * as openai from '../../src/ai-providers/openai.js';
|
import * as openai from '../../src/ai-providers/openai.js';
|
||||||
import * as xai from '../../src/ai-providers/xai.js';
|
import * as xai from '../../src/ai-providers/xai.js';
|
||||||
import * as openrouter from '../../src/ai-providers/openrouter.js';
|
import * as openrouter from '../../src/ai-providers/openrouter.js';
|
||||||
|
import * as ollama from '../../src/ai-providers/ollama.js';
|
||||||
// TODO: Import other provider modules when implemented (ollama, etc.)
|
// TODO: Import other provider modules when implemented (ollama, etc.)
|
||||||
|
|
||||||
|
// Helper function to get cost for a specific model
|
||||||
|
function _getCostForModel(providerName, modelId) {
|
||||||
|
if (!MODEL_MAP || !MODEL_MAP[providerName]) {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
`Provider "${providerName}" not found in MODEL_MAP. Cannot determine cost for model ${modelId}.`
|
||||||
|
);
|
||||||
|
return { inputCost: 0, outputCost: 0, currency: 'USD' }; // Default to zero cost
|
||||||
|
}
|
||||||
|
|
||||||
|
const modelData = MODEL_MAP[providerName].find((m) => m.id === modelId);
|
||||||
|
|
||||||
|
if (!modelData || !modelData.cost_per_1m_tokens) {
|
||||||
|
log(
|
||||||
|
'debug',
|
||||||
|
`Cost data not found for model "${modelId}" under provider "${providerName}". Assuming zero cost.`
|
||||||
|
);
|
||||||
|
return { inputCost: 0, outputCost: 0, currency: 'USD' }; // Default to zero cost
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure currency is part of the returned object, defaulting if not present
|
||||||
|
const currency = modelData.cost_per_1m_tokens.currency || 'USD';
|
||||||
|
|
||||||
|
return {
|
||||||
|
inputCost: modelData.cost_per_1m_tokens.input || 0,
|
||||||
|
outputCost: modelData.cost_per_1m_tokens.output || 0,
|
||||||
|
currency: currency
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// --- Provider Function Map ---
|
// --- Provider Function Map ---
|
||||||
// Maps provider names (lowercase) to their respective service functions
|
// Maps provider names (lowercase) to their respective service functions
|
||||||
const PROVIDER_FUNCTIONS = {
|
const PROVIDER_FUNCTIONS = {
|
||||||
@@ -63,6 +98,11 @@ const PROVIDER_FUNCTIONS = {
|
|||||||
generateText: openrouter.generateOpenRouterText,
|
generateText: openrouter.generateOpenRouterText,
|
||||||
streamText: openrouter.streamOpenRouterText,
|
streamText: openrouter.streamOpenRouterText,
|
||||||
generateObject: openrouter.generateOpenRouterObject
|
generateObject: openrouter.generateOpenRouterObject
|
||||||
|
},
|
||||||
|
ollama: {
|
||||||
|
generateText: ollama.generateOllamaText,
|
||||||
|
streamText: ollama.streamOllamaText,
|
||||||
|
generateObject: ollama.generateOllamaObject
|
||||||
}
|
}
|
||||||
// TODO: Add entries for ollama, etc. when implemented
|
// TODO: Add entries for ollama, etc. when implemented
|
||||||
};
|
};
|
||||||
@@ -150,14 +190,10 @@ function _resolveApiKey(providerName, session, projectRoot = null) {
|
|||||||
mistral: 'MISTRAL_API_KEY',
|
mistral: 'MISTRAL_API_KEY',
|
||||||
azure: 'AZURE_OPENAI_API_KEY',
|
azure: 'AZURE_OPENAI_API_KEY',
|
||||||
openrouter: 'OPENROUTER_API_KEY',
|
openrouter: 'OPENROUTER_API_KEY',
|
||||||
xai: 'XAI_API_KEY'
|
xai: 'XAI_API_KEY',
|
||||||
|
ollama: 'OLLAMA_API_KEY'
|
||||||
};
|
};
|
||||||
|
|
||||||
// Double check this -- I have had to use an api key for ollama in the past
|
|
||||||
// if (providerName === 'ollama') {
|
|
||||||
// return null; // Ollama typically doesn't require an API key for basic setup
|
|
||||||
// }
|
|
||||||
|
|
||||||
const envVarName = keyMap[providerName];
|
const envVarName = keyMap[providerName];
|
||||||
if (!envVarName) {
|
if (!envVarName) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -166,6 +202,13 @@ function _resolveApiKey(providerName, session, projectRoot = null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const apiKey = resolveEnvVariable(envVarName, session, projectRoot);
|
const apiKey = resolveEnvVariable(envVarName, session, projectRoot);
|
||||||
|
|
||||||
|
// Special handling for Ollama - API key is optional
|
||||||
|
if (providerName === 'ollama') {
|
||||||
|
return apiKey || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// For all other providers, API key is required
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Required API key ${envVarName} for provider '${providerName}' is not set in environment, session, or .env file.`
|
`Required API key ${envVarName} for provider '${providerName}' is not set in environment, session, or .env file.`
|
||||||
@@ -197,18 +240,22 @@ async function _attemptProviderCallWithRetries(
|
|||||||
|
|
||||||
while (retries <= MAX_RETRIES) {
|
while (retries <= MAX_RETRIES) {
|
||||||
try {
|
try {
|
||||||
log(
|
if (getDebugFlag()) {
|
||||||
'info',
|
log(
|
||||||
`Attempt ${retries + 1}/${MAX_RETRIES + 1} calling ${fnName} (Provider: ${providerName}, Model: ${modelId}, Role: ${attemptRole})`
|
'info',
|
||||||
);
|
`Attempt ${retries + 1}/${MAX_RETRIES + 1} calling ${fnName} (Provider: ${providerName}, Model: ${modelId}, Role: ${attemptRole})`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Call the specific provider function directly
|
// Call the specific provider function directly
|
||||||
const result = await providerApiFn(callParams);
|
const result = await providerApiFn(callParams);
|
||||||
|
|
||||||
log(
|
if (getDebugFlag()) {
|
||||||
'info',
|
log(
|
||||||
`${fnName} succeeded for role ${attemptRole} (Provider: ${providerName}) on attempt ${retries + 1}`
|
'info',
|
||||||
);
|
`${fnName} succeeded for role ${attemptRole} (Provider: ${providerName}) on attempt ${retries + 1}`
|
||||||
|
);
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
log(
|
||||||
@@ -221,13 +268,13 @@ async function _attemptProviderCallWithRetries(
|
|||||||
const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retries - 1);
|
const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retries - 1);
|
||||||
log(
|
log(
|
||||||
'info',
|
'info',
|
||||||
`Retryable error detected. Retrying in ${delay / 1000}s...`
|
`Something went wrong on the provider side. Retrying in ${delay / 1000}s...`
|
||||||
);
|
);
|
||||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||||
} else {
|
} else {
|
||||||
log(
|
log(
|
||||||
'error',
|
'error',
|
||||||
`Non-retryable error or max retries reached for role ${attemptRole} (${fnName} / ${providerName}).`
|
`Something went wrong on the provider side. Max retries reached for role ${attemptRole} (${fnName} / ${providerName}).`
|
||||||
);
|
);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -243,7 +290,15 @@ async function _attemptProviderCallWithRetries(
|
|||||||
* Base logic for unified service functions.
|
* Base logic for unified service functions.
|
||||||
* @param {string} serviceType - Type of service ('generateText', 'streamText', 'generateObject').
|
* @param {string} serviceType - Type of service ('generateText', 'streamText', 'generateObject').
|
||||||
* @param {object} params - Original parameters passed to the service function.
|
* @param {object} params - Original parameters passed to the service function.
|
||||||
|
* @param {string} params.role - The initial client role.
|
||||||
|
* @param {object} [params.session=null] - Optional MCP session object.
|
||||||
* @param {string} [params.projectRoot] - Optional project root path.
|
* @param {string} [params.projectRoot] - Optional project root path.
|
||||||
|
* @param {string} params.commandName - Name of the command invoking the service.
|
||||||
|
* @param {string} params.outputType - 'cli' or 'mcp'.
|
||||||
|
* @param {string} [params.systemPrompt] - Optional system prompt.
|
||||||
|
* @param {string} [params.prompt] - The prompt for the AI.
|
||||||
|
* @param {string} [params.schema] - The Zod schema for the expected object.
|
||||||
|
* @param {string} [params.objectName] - Name for object/tool.
|
||||||
* @returns {Promise<any>} Result from the underlying provider call.
|
* @returns {Promise<any>} Result from the underlying provider call.
|
||||||
*/
|
*/
|
||||||
async function _unifiedServiceRunner(serviceType, params) {
|
async function _unifiedServiceRunner(serviceType, params) {
|
||||||
@@ -255,15 +310,21 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
prompt,
|
prompt,
|
||||||
schema,
|
schema,
|
||||||
objectName,
|
objectName,
|
||||||
|
commandName,
|
||||||
|
outputType,
|
||||||
...restApiParams
|
...restApiParams
|
||||||
} = params;
|
} = params;
|
||||||
log('info', `${serviceType}Service called`, {
|
if (getDebugFlag()) {
|
||||||
role: initialRole,
|
log('info', `${serviceType}Service called`, {
|
||||||
projectRoot
|
role: initialRole,
|
||||||
});
|
commandName,
|
||||||
|
outputType,
|
||||||
|
projectRoot
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Determine the effective project root (passed in or detected)
|
|
||||||
const effectiveProjectRoot = projectRoot || findProjectRoot();
|
const effectiveProjectRoot = projectRoot || findProjectRoot();
|
||||||
|
const userId = getUserId(effectiveProjectRoot);
|
||||||
|
|
||||||
let sequence;
|
let sequence;
|
||||||
if (initialRole === 'main') {
|
if (initialRole === 'main') {
|
||||||
@@ -291,13 +352,13 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
roleParams,
|
roleParams,
|
||||||
providerFnSet,
|
providerFnSet,
|
||||||
providerApiFn,
|
providerApiFn,
|
||||||
baseUrl;
|
baseUrl,
|
||||||
|
providerResponse,
|
||||||
|
telemetryData = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log('info', `New AI service call with role: ${currentRole}`);
|
log('info', `New AI service call with role: ${currentRole}`);
|
||||||
|
|
||||||
// 1. Get Config: Provider, Model, Parameters for the current role
|
|
||||||
// Pass effectiveProjectRoot to config getters
|
|
||||||
if (currentRole === 'main') {
|
if (currentRole === 'main') {
|
||||||
providerName = getMainProvider(effectiveProjectRoot);
|
providerName = getMainProvider(effectiveProjectRoot);
|
||||||
modelId = getMainModelId(effectiveProjectRoot);
|
modelId = getMainModelId(effectiveProjectRoot);
|
||||||
@@ -330,11 +391,24 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pass effectiveProjectRoot to getParametersForRole
|
// Check if API key is set for the current provider and role (excluding 'ollama')
|
||||||
|
if (providerName?.toLowerCase() !== 'ollama') {
|
||||||
|
if (!isApiKeySet(providerName, session, effectiveProjectRoot)) {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
`Skipping role '${currentRole}' (Provider: ${providerName}): API key not set or invalid.`
|
||||||
|
);
|
||||||
|
lastError =
|
||||||
|
lastError ||
|
||||||
|
new Error(
|
||||||
|
`API key for provider '${providerName}' (role: ${currentRole}) is not set.`
|
||||||
|
);
|
||||||
|
continue; // Skip to the next role in the sequence
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
|
roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
|
||||||
baseUrl = getBaseUrlForRole(currentRole, effectiveProjectRoot);
|
baseUrl = getBaseUrlForRole(currentRole, effectiveProjectRoot);
|
||||||
|
|
||||||
// 2. Get Provider Function Set
|
|
||||||
providerFnSet = PROVIDER_FUNCTIONS[providerName?.toLowerCase()];
|
providerFnSet = PROVIDER_FUNCTIONS[providerName?.toLowerCase()];
|
||||||
if (!providerFnSet) {
|
if (!providerFnSet) {
|
||||||
log(
|
log(
|
||||||
@@ -347,7 +421,6 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the original service type to get the function
|
|
||||||
providerApiFn = providerFnSet[serviceType];
|
providerApiFn = providerFnSet[serviceType];
|
||||||
if (typeof providerApiFn !== 'function') {
|
if (typeof providerApiFn !== 'function') {
|
||||||
log(
|
log(
|
||||||
@@ -362,15 +435,12 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Resolve API Key (will throw if required and missing)
|
|
||||||
// Pass effectiveProjectRoot to _resolveApiKey
|
|
||||||
apiKey = _resolveApiKey(
|
apiKey = _resolveApiKey(
|
||||||
providerName?.toLowerCase(),
|
providerName?.toLowerCase(),
|
||||||
session,
|
session,
|
||||||
effectiveProjectRoot
|
effectiveProjectRoot
|
||||||
);
|
);
|
||||||
|
|
||||||
// 4. Construct Messages Array
|
|
||||||
const messages = [];
|
const messages = [];
|
||||||
if (systemPrompt) {
|
if (systemPrompt) {
|
||||||
messages.push({ role: 'system', content: systemPrompt });
|
messages.push({ role: 'system', content: systemPrompt });
|
||||||
@@ -395,14 +465,11 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
// }
|
// }
|
||||||
|
|
||||||
if (prompt) {
|
if (prompt) {
|
||||||
// Ensure prompt exists before adding
|
|
||||||
messages.push({ role: 'user', content: prompt });
|
messages.push({ role: 'user', content: prompt });
|
||||||
} else {
|
} else {
|
||||||
// Throw an error if the prompt is missing, as it's essential
|
|
||||||
throw new Error('User prompt content is missing.');
|
throw new Error('User prompt content is missing.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Prepare call parameters (using messages array)
|
|
||||||
const callParams = {
|
const callParams = {
|
||||||
apiKey,
|
apiKey,
|
||||||
modelId,
|
modelId,
|
||||||
@@ -414,8 +481,7 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
...restApiParams
|
...restApiParams
|
||||||
};
|
};
|
||||||
|
|
||||||
// 6. Attempt the call with retries
|
providerResponse = await _attemptProviderCallWithRetries(
|
||||||
const result = await _attemptProviderCallWithRetries(
|
|
||||||
providerApiFn,
|
providerApiFn,
|
||||||
callParams,
|
callParams,
|
||||||
providerName,
|
providerName,
|
||||||
@@ -423,9 +489,47 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
currentRole
|
currentRole
|
||||||
);
|
);
|
||||||
|
|
||||||
log('info', `${serviceType}Service succeeded using role: ${currentRole}`);
|
if (userId && providerResponse && providerResponse.usage) {
|
||||||
|
try {
|
||||||
|
telemetryData = await logAiUsage({
|
||||||
|
userId,
|
||||||
|
commandName,
|
||||||
|
providerName,
|
||||||
|
modelId,
|
||||||
|
inputTokens: providerResponse.usage.inputTokens,
|
||||||
|
outputTokens: providerResponse.usage.outputTokens,
|
||||||
|
outputType
|
||||||
|
});
|
||||||
|
} catch (telemetryError) {
|
||||||
|
// logAiUsage already logs its own errors and returns null on failure
|
||||||
|
// No need to log again here, telemetryData will remain null
|
||||||
|
}
|
||||||
|
} else if (userId && providerResponse && !providerResponse.usage) {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
`Cannot log telemetry for ${commandName} (${providerName}/${modelId}): AI result missing 'usage' data. (May be expected for streams)`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return result;
|
let finalMainResult;
|
||||||
|
if (serviceType === 'generateText') {
|
||||||
|
finalMainResult = providerResponse.text;
|
||||||
|
} else if (serviceType === 'generateObject') {
|
||||||
|
finalMainResult = providerResponse.object;
|
||||||
|
} else if (serviceType === 'streamText') {
|
||||||
|
finalMainResult = providerResponse;
|
||||||
|
} else {
|
||||||
|
log(
|
||||||
|
'error',
|
||||||
|
`Unknown serviceType in _unifiedServiceRunner: ${serviceType}`
|
||||||
|
);
|
||||||
|
finalMainResult = providerResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
mainResult: finalMainResult,
|
||||||
|
telemetryData: telemetryData
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const cleanMessage = _extractErrorMessage(error);
|
const cleanMessage = _extractErrorMessage(error);
|
||||||
log(
|
log(
|
||||||
@@ -454,9 +558,7 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If loop completes, all roles failed
|
|
||||||
log('error', `All roles in the sequence [${sequence.join(', ')}] failed.`);
|
log('error', `All roles in the sequence [${sequence.join(', ')}] failed.`);
|
||||||
// Throw a new error with the cleaner message from the last failure
|
|
||||||
throw new Error(lastCleanErrorMessage);
|
throw new Error(lastCleanErrorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -470,11 +572,16 @@ async function _unifiedServiceRunner(serviceType, params) {
|
|||||||
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
|
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
|
||||||
* @param {string} params.prompt - The prompt for the AI.
|
* @param {string} params.prompt - The prompt for the AI.
|
||||||
* @param {string} [params.systemPrompt] - Optional system prompt.
|
* @param {string} [params.systemPrompt] - Optional system prompt.
|
||||||
* // Other specific generateText params can be included here.
|
* @param {string} params.commandName - Name of the command invoking the service.
|
||||||
* @returns {Promise<string>} The generated text content.
|
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'.
|
||||||
|
* @returns {Promise<object>} Result object containing generated text and usage data.
|
||||||
*/
|
*/
|
||||||
async function generateTextService(params) {
|
async function generateTextService(params) {
|
||||||
return _unifiedServiceRunner('generateText', params);
|
// Ensure default outputType if not provided
|
||||||
|
const defaults = { outputType: 'cli' };
|
||||||
|
const combinedParams = { ...defaults, ...params };
|
||||||
|
// TODO: Validate commandName exists?
|
||||||
|
return _unifiedServiceRunner('generateText', combinedParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -487,11 +594,18 @@ async function generateTextService(params) {
|
|||||||
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
|
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
|
||||||
* @param {string} params.prompt - The prompt for the AI.
|
* @param {string} params.prompt - The prompt for the AI.
|
||||||
* @param {string} [params.systemPrompt] - Optional system prompt.
|
* @param {string} [params.systemPrompt] - Optional system prompt.
|
||||||
* // Other specific streamText params can be included here.
|
* @param {string} params.commandName - Name of the command invoking the service.
|
||||||
* @returns {Promise<ReadableStream<string>>} A readable stream of text deltas.
|
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'.
|
||||||
|
* @returns {Promise<object>} Result object containing the stream and usage data.
|
||||||
*/
|
*/
|
||||||
async function streamTextService(params) {
|
async function streamTextService(params) {
|
||||||
return _unifiedServiceRunner('streamText', params);
|
const defaults = { outputType: 'cli' };
|
||||||
|
const combinedParams = { ...defaults, ...params };
|
||||||
|
// TODO: Validate commandName exists?
|
||||||
|
// NOTE: Telemetry for streaming might be tricky as usage data often comes at the end.
|
||||||
|
// The current implementation logs *after* the stream is returned.
|
||||||
|
// We might need to adjust how usage is captured/logged for streams.
|
||||||
|
return _unifiedServiceRunner('streamText', combinedParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -507,15 +621,89 @@ async function streamTextService(params) {
|
|||||||
* @param {string} [params.systemPrompt] - Optional system prompt.
|
* @param {string} [params.systemPrompt] - Optional system prompt.
|
||||||
* @param {string} [params.objectName='generated_object'] - Name for object/tool.
|
* @param {string} [params.objectName='generated_object'] - Name for object/tool.
|
||||||
* @param {number} [params.maxRetries=3] - Max retries for object generation.
|
* @param {number} [params.maxRetries=3] - Max retries for object generation.
|
||||||
* @returns {Promise<object>} The generated object matching the schema.
|
* @param {string} params.commandName - Name of the command invoking the service.
|
||||||
|
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'.
|
||||||
|
* @returns {Promise<object>} Result object containing the generated object and usage data.
|
||||||
*/
|
*/
|
||||||
async function generateObjectService(params) {
|
async function generateObjectService(params) {
|
||||||
const defaults = {
|
const defaults = {
|
||||||
objectName: 'generated_object',
|
objectName: 'generated_object',
|
||||||
maxRetries: 3
|
maxRetries: 3,
|
||||||
|
outputType: 'cli'
|
||||||
};
|
};
|
||||||
const combinedParams = { ...defaults, ...params };
|
const combinedParams = { ...defaults, ...params };
|
||||||
|
// TODO: Validate commandName exists?
|
||||||
return _unifiedServiceRunner('generateObject', combinedParams);
|
return _unifiedServiceRunner('generateObject', combinedParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { generateTextService, streamTextService, generateObjectService };
|
// --- Telemetry Function ---
|
||||||
|
/**
|
||||||
|
* Logs AI usage telemetry data.
|
||||||
|
* For now, it just logs to the console. Sending will be implemented later.
|
||||||
|
* @param {object} params - Telemetry parameters.
|
||||||
|
* @param {string} params.userId - Unique user identifier.
|
||||||
|
* @param {string} params.commandName - The command that triggered the AI call.
|
||||||
|
* @param {string} params.providerName - The AI provider used (e.g., 'openai').
|
||||||
|
* @param {string} params.modelId - The specific AI model ID used.
|
||||||
|
* @param {number} params.inputTokens - Number of input tokens.
|
||||||
|
* @param {number} params.outputTokens - Number of output tokens.
|
||||||
|
*/
|
||||||
|
async function logAiUsage({
|
||||||
|
userId,
|
||||||
|
commandName,
|
||||||
|
providerName,
|
||||||
|
modelId,
|
||||||
|
inputTokens,
|
||||||
|
outputTokens,
|
||||||
|
outputType
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
const isMCP = outputType === 'mcp';
|
||||||
|
const timestamp = new Date().toISOString();
|
||||||
|
const totalTokens = (inputTokens || 0) + (outputTokens || 0);
|
||||||
|
|
||||||
|
// Destructure currency along with costs
|
||||||
|
const { inputCost, outputCost, currency } = _getCostForModel(
|
||||||
|
providerName,
|
||||||
|
modelId
|
||||||
|
);
|
||||||
|
|
||||||
|
const totalCost =
|
||||||
|
((inputTokens || 0) / 1_000_000) * inputCost +
|
||||||
|
((outputTokens || 0) / 1_000_000) * outputCost;
|
||||||
|
|
||||||
|
const telemetryData = {
|
||||||
|
timestamp,
|
||||||
|
userId,
|
||||||
|
commandName,
|
||||||
|
modelUsed: modelId, // Consistent field name from requirements
|
||||||
|
providerName, // Keep provider name for context
|
||||||
|
inputTokens: inputTokens || 0,
|
||||||
|
outputTokens: outputTokens || 0,
|
||||||
|
totalTokens,
|
||||||
|
totalCost: parseFloat(totalCost.toFixed(6)),
|
||||||
|
currency // Add currency to the telemetry data
|
||||||
|
};
|
||||||
|
|
||||||
|
if (getDebugFlag()) {
|
||||||
|
log('info', 'AI Usage Telemetry:', telemetryData);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO (Subtask 77.2): Send telemetryData securely to the external endpoint.
|
||||||
|
|
||||||
|
return telemetryData;
|
||||||
|
} catch (error) {
|
||||||
|
log('error', `Failed to log AI usage telemetry: ${error.message}`, {
|
||||||
|
error
|
||||||
|
});
|
||||||
|
// Don't re-throw; telemetry failure shouldn't block core functionality.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
generateTextService,
|
||||||
|
streamTextService,
|
||||||
|
generateObjectService,
|
||||||
|
logAiUsage
|
||||||
|
};
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import chalk from 'chalk';
|
|||||||
import boxen from 'boxen';
|
import boxen from 'boxen';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import https from 'https';
|
import https from 'https';
|
||||||
|
import http from 'http';
|
||||||
import inquirer from 'inquirer';
|
import inquirer from 'inquirer';
|
||||||
import ora from 'ora'; // Import ora
|
import ora from 'ora'; // Import ora
|
||||||
|
|
||||||
@@ -30,7 +31,8 @@ import {
|
|||||||
updateSubtaskById,
|
updateSubtaskById,
|
||||||
removeTask,
|
removeTask,
|
||||||
findTaskById,
|
findTaskById,
|
||||||
taskExists
|
taskExists,
|
||||||
|
moveTask
|
||||||
} from './task-manager.js';
|
} from './task-manager.js';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -47,7 +49,8 @@ import {
|
|||||||
writeConfig,
|
writeConfig,
|
||||||
ConfigurationError,
|
ConfigurationError,
|
||||||
isConfigFilePresent,
|
isConfigFilePresent,
|
||||||
getAvailableModels
|
getAvailableModels,
|
||||||
|
getBaseUrlForRole
|
||||||
} from './config-manager.js';
|
} from './config-manager.js';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -62,7 +65,8 @@ import {
|
|||||||
stopLoadingIndicator,
|
stopLoadingIndicator,
|
||||||
displayModelConfiguration,
|
displayModelConfiguration,
|
||||||
displayAvailableModels,
|
displayAvailableModels,
|
||||||
displayApiKeyStatus
|
displayApiKeyStatus,
|
||||||
|
displayAiUsageSummary
|
||||||
} from './ui.js';
|
} from './ui.js';
|
||||||
|
|
||||||
import { initializeProject } from '../init.js';
|
import { initializeProject } from '../init.js';
|
||||||
@@ -151,6 +155,64 @@ async function runInteractiveSetup(projectRoot) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper function to fetch Ollama models (duplicated for CLI context)
|
||||||
|
function fetchOllamaModelsCLI(baseUrl = 'http://localhost:11434/api') {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
// Parse the base URL to extract hostname, port, and base path
|
||||||
|
const url = new URL(baseUrl);
|
||||||
|
const isHttps = url.protocol === 'https:';
|
||||||
|
const port = url.port || (isHttps ? 443 : 80);
|
||||||
|
const basePath = url.pathname.endsWith('/')
|
||||||
|
? url.pathname.slice(0, -1)
|
||||||
|
: url.pathname;
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
hostname: url.hostname,
|
||||||
|
port: parseInt(port, 10),
|
||||||
|
path: `${basePath}/tags`,
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const requestLib = isHttps ? https : http;
|
||||||
|
const req = requestLib.request(options, (res) => {
|
||||||
|
let data = '';
|
||||||
|
res.on('data', (chunk) => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
res.on('end', () => {
|
||||||
|
if (res.statusCode === 200) {
|
||||||
|
try {
|
||||||
|
const parsedData = JSON.parse(data);
|
||||||
|
resolve(parsedData.models || []); // Return the array of models
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error parsing Ollama response:', e);
|
||||||
|
resolve(null); // Indicate failure
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error(
|
||||||
|
`Ollama API request failed with status code: ${res.statusCode}`
|
||||||
|
);
|
||||||
|
resolve(null); // Indicate failure
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('error', (e) => {
|
||||||
|
console.error('Error fetching Ollama models:', e);
|
||||||
|
resolve(null); // Indicate failure
|
||||||
|
});
|
||||||
|
req.end();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error parsing Ollama base URL:', e);
|
||||||
|
resolve(null); // Indicate failure
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Helper to get choices and default index for a role
|
// Helper to get choices and default index for a role
|
||||||
const getPromptData = (role, allowNone = false) => {
|
const getPromptData = (role, allowNone = false) => {
|
||||||
const currentModel = currentModels[role]; // Use the fetched data
|
const currentModel = currentModels[role]; // Use the fetched data
|
||||||
@@ -178,6 +240,11 @@ async function runInteractiveSetup(projectRoot) {
|
|||||||
value: '__CUSTOM_OPENROUTER__'
|
value: '__CUSTOM_OPENROUTER__'
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const customOllamaOption = {
|
||||||
|
name: '* Custom Ollama model', // Symbol updated
|
||||||
|
value: '__CUSTOM_OLLAMA__'
|
||||||
|
};
|
||||||
|
|
||||||
let choices = [];
|
let choices = [];
|
||||||
let defaultIndex = 0; // Default to 'Cancel'
|
let defaultIndex = 0; // Default to 'Cancel'
|
||||||
|
|
||||||
@@ -223,6 +290,7 @@ async function runInteractiveSetup(projectRoot) {
|
|||||||
}
|
}
|
||||||
commonPrefix.push(cancelOption);
|
commonPrefix.push(cancelOption);
|
||||||
commonPrefix.push(customOpenRouterOption);
|
commonPrefix.push(customOpenRouterOption);
|
||||||
|
commonPrefix.push(customOllamaOption);
|
||||||
|
|
||||||
let prefixLength = commonPrefix.length; // Initial prefix length
|
let prefixLength = commonPrefix.length; // Initial prefix length
|
||||||
|
|
||||||
@@ -353,6 +421,47 @@ async function runInteractiveSetup(projectRoot) {
|
|||||||
setupSuccess = false;
|
setupSuccess = false;
|
||||||
return true; // Continue setup, but mark as failed
|
return true; // Continue setup, but mark as failed
|
||||||
}
|
}
|
||||||
|
} else if (selectedValue === '__CUSTOM_OLLAMA__') {
|
||||||
|
isCustomSelection = true;
|
||||||
|
const { customId } = await inquirer.prompt([
|
||||||
|
{
|
||||||
|
type: 'input',
|
||||||
|
name: 'customId',
|
||||||
|
message: `Enter the custom Ollama Model ID for the ${role} role:`
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
if (!customId) {
|
||||||
|
console.log(chalk.yellow('No custom ID entered. Skipping role.'));
|
||||||
|
return true; // Continue setup, but don't set this role
|
||||||
|
}
|
||||||
|
modelIdToSet = customId;
|
||||||
|
providerHint = 'ollama';
|
||||||
|
// Get the Ollama base URL from config for this role
|
||||||
|
const ollamaBaseUrl = getBaseUrlForRole(role, projectRoot);
|
||||||
|
// Validate against live Ollama list
|
||||||
|
const ollamaModels = await fetchOllamaModelsCLI(ollamaBaseUrl);
|
||||||
|
if (ollamaModels === null) {
|
||||||
|
console.error(
|
||||||
|
chalk.red(
|
||||||
|
`Error: Unable to connect to Ollama server at ${ollamaBaseUrl}. Please ensure Ollama is running and try again.`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
setupSuccess = false;
|
||||||
|
return true; // Continue setup, but mark as failed
|
||||||
|
} else if (!ollamaModels.some((m) => m.model === modelIdToSet)) {
|
||||||
|
console.error(
|
||||||
|
chalk.red(
|
||||||
|
`Error: Model ID "${modelIdToSet}" not found in the Ollama instance. Please verify the model is pulled and available.`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
chalk.yellow(
|
||||||
|
`You can check available models with: curl ${ollamaBaseUrl}/tags`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
setupSuccess = false;
|
||||||
|
return true; // Continue setup, but mark as failed
|
||||||
|
}
|
||||||
} else if (
|
} else if (
|
||||||
selectedValue &&
|
selectedValue &&
|
||||||
typeof selectedValue === 'object' &&
|
typeof selectedValue === 'object' &&
|
||||||
@@ -506,6 +615,10 @@ function registerCommands(programInstance) {
|
|||||||
'--append',
|
'--append',
|
||||||
'Append new tasks to existing tasks.json instead of overwriting'
|
'Append new tasks to existing tasks.json instead of overwriting'
|
||||||
)
|
)
|
||||||
|
.option(
|
||||||
|
'-r, --research',
|
||||||
|
'Use Perplexity AI for research-backed task generation, providing more comprehensive and accurate task breakdown'
|
||||||
|
)
|
||||||
.action(async (file, options) => {
|
.action(async (file, options) => {
|
||||||
// Use input option if file argument not provided
|
// Use input option if file argument not provided
|
||||||
const inputFile = file || options.input;
|
const inputFile = file || options.input;
|
||||||
@@ -514,8 +627,9 @@ function registerCommands(programInstance) {
|
|||||||
const outputPath = options.output;
|
const outputPath = options.output;
|
||||||
const force = options.force || false;
|
const force = options.force || false;
|
||||||
const append = options.append || false;
|
const append = options.append || false;
|
||||||
|
const research = options.research || false;
|
||||||
let useForce = force;
|
let useForce = force;
|
||||||
let useAppend = false;
|
let useAppend = append;
|
||||||
|
|
||||||
// Helper function to check if tasks.json exists and confirm overwrite
|
// Helper function to check if tasks.json exists and confirm overwrite
|
||||||
async function confirmOverwriteIfNeeded() {
|
async function confirmOverwriteIfNeeded() {
|
||||||
@@ -543,10 +657,11 @@ function registerCommands(programInstance) {
|
|||||||
if (!(await confirmOverwriteIfNeeded())) return;
|
if (!(await confirmOverwriteIfNeeded())) return;
|
||||||
|
|
||||||
console.log(chalk.blue(`Generating ${numTasks} tasks...`));
|
console.log(chalk.blue(`Generating ${numTasks} tasks...`));
|
||||||
spinner = ora('Parsing PRD and generating tasks...').start();
|
spinner = ora('Parsing PRD and generating tasks...\n').start();
|
||||||
await parsePRD(defaultPrdPath, outputPath, numTasks, {
|
await parsePRD(defaultPrdPath, outputPath, numTasks, {
|
||||||
useAppend,
|
append: useAppend, // Changed key from useAppend to append
|
||||||
useForce
|
force: useForce, // Changed key from useForce to force
|
||||||
|
research: research
|
||||||
});
|
});
|
||||||
spinner.succeed('Tasks generated successfully!');
|
spinner.succeed('Tasks generated successfully!');
|
||||||
return;
|
return;
|
||||||
@@ -570,13 +685,15 @@ function registerCommands(programInstance) {
|
|||||||
' -o, --output <file> Output file path (default: "tasks/tasks.json")\n' +
|
' -o, --output <file> Output file path (default: "tasks/tasks.json")\n' +
|
||||||
' -n, --num-tasks <number> Number of tasks to generate (default: 10)\n' +
|
' -n, --num-tasks <number> Number of tasks to generate (default: 10)\n' +
|
||||||
' -f, --force Skip confirmation when overwriting existing tasks\n' +
|
' -f, --force Skip confirmation when overwriting existing tasks\n' +
|
||||||
' --append Append new tasks to existing tasks.json instead of overwriting\n\n' +
|
' --append Append new tasks to existing tasks.json instead of overwriting\n' +
|
||||||
|
' -r, --research Use Perplexity AI for research-backed task generation\n\n' +
|
||||||
chalk.cyan('Example:') +
|
chalk.cyan('Example:') +
|
||||||
'\n' +
|
'\n' +
|
||||||
' task-master parse-prd requirements.txt --num-tasks 15\n' +
|
' task-master parse-prd requirements.txt --num-tasks 15\n' +
|
||||||
' task-master parse-prd --input=requirements.txt\n' +
|
' task-master parse-prd --input=requirements.txt\n' +
|
||||||
' task-master parse-prd --force\n' +
|
' task-master parse-prd --force\n' +
|
||||||
' task-master parse-prd requirements_v2.txt --append\n\n' +
|
' task-master parse-prd requirements_v2.txt --append\n' +
|
||||||
|
' task-master parse-prd requirements.txt --research\n\n' +
|
||||||
chalk.yellow('Note: This command will:') +
|
chalk.yellow('Note: This command will:') +
|
||||||
'\n' +
|
'\n' +
|
||||||
' 1. Look for a PRD file at scripts/prd.txt by default\n' +
|
' 1. Look for a PRD file at scripts/prd.txt by default\n' +
|
||||||
@@ -604,11 +721,19 @@ function registerCommands(programInstance) {
|
|||||||
if (append) {
|
if (append) {
|
||||||
console.log(chalk.blue('Appending to existing tasks...'));
|
console.log(chalk.blue('Appending to existing tasks...'));
|
||||||
}
|
}
|
||||||
|
if (research) {
|
||||||
|
console.log(
|
||||||
|
chalk.blue(
|
||||||
|
'Using Perplexity AI for research-backed task generation'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
spinner = ora('Parsing PRD and generating tasks...').start();
|
spinner = ora('Parsing PRD and generating tasks...\n').start();
|
||||||
await parsePRD(inputFile, outputPath, numTasks, {
|
await parsePRD(inputFile, outputPath, numTasks, {
|
||||||
append: useAppend,
|
append: useAppend,
|
||||||
useForce
|
force: useForce,
|
||||||
|
research: research
|
||||||
});
|
});
|
||||||
spinner.succeed('Tasks generated successfully!');
|
spinner.succeed('Tasks generated successfully!');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -1030,6 +1155,8 @@ function registerCommands(programInstance) {
|
|||||||
// set-status command
|
// set-status command
|
||||||
programInstance
|
programInstance
|
||||||
.command('set-status')
|
.command('set-status')
|
||||||
|
.alias('mark')
|
||||||
|
.alias('set')
|
||||||
.description('Set the status of a task')
|
.description('Set the status of a task')
|
||||||
.option(
|
.option(
|
||||||
'-i, --id <id>',
|
'-i, --id <id>',
|
||||||
@@ -1072,10 +1199,16 @@ function registerCommands(programInstance) {
|
|||||||
.command('list')
|
.command('list')
|
||||||
.description('List all tasks')
|
.description('List all tasks')
|
||||||
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
||||||
|
.option(
|
||||||
|
'-r, --report <report>',
|
||||||
|
'Path to the complexity report file',
|
||||||
|
'scripts/task-complexity-report.json'
|
||||||
|
)
|
||||||
.option('-s, --status <status>', 'Filter by status')
|
.option('-s, --status <status>', 'Filter by status')
|
||||||
.option('--with-subtasks', 'Show subtasks for each task')
|
.option('--with-subtasks', 'Show subtasks for each task')
|
||||||
.action(async (options) => {
|
.action(async (options) => {
|
||||||
const tasksPath = options.file;
|
const tasksPath = options.file;
|
||||||
|
const reportPath = options.report;
|
||||||
const statusFilter = options.status;
|
const statusFilter = options.status;
|
||||||
const withSubtasks = options.withSubtasks || false;
|
const withSubtasks = options.withSubtasks || false;
|
||||||
|
|
||||||
@@ -1087,7 +1220,7 @@ function registerCommands(programInstance) {
|
|||||||
console.log(chalk.blue('Including subtasks in listing'));
|
console.log(chalk.blue('Including subtasks in listing'));
|
||||||
}
|
}
|
||||||
|
|
||||||
await listTasks(tasksPath, statusFilter, withSubtasks);
|
await listTasks(tasksPath, statusFilter, reportPath, withSubtasks);
|
||||||
});
|
});
|
||||||
|
|
||||||
// expand command
|
// expand command
|
||||||
@@ -1137,12 +1270,6 @@ function registerCommands(programInstance) {
|
|||||||
{} // Pass empty context for CLI calls
|
{} // Pass empty context for CLI calls
|
||||||
// outputFormat defaults to 'text' in expandAllTasks for CLI
|
// outputFormat defaults to 'text' in expandAllTasks for CLI
|
||||||
);
|
);
|
||||||
// Optional: Display summary from result
|
|
||||||
console.log(chalk.green(`Expansion Summary:`));
|
|
||||||
console.log(chalk.green(` - Attempted: ${result.tasksToExpand}`));
|
|
||||||
console.log(chalk.green(` - Expanded: ${result.expandedCount}`));
|
|
||||||
console.log(chalk.yellow(` - Skipped: ${result.skippedCount}`));
|
|
||||||
console.log(chalk.red(` - Failed: ${result.failedCount}`));
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(
|
console.error(
|
||||||
chalk.red(`Error expanding all tasks: ${error.message}`)
|
chalk.red(`Error expanding all tasks: ${error.message}`)
|
||||||
@@ -1210,6 +1337,12 @@ function registerCommands(programInstance) {
|
|||||||
'-r, --research',
|
'-r, --research',
|
||||||
'Use Perplexity AI for research-backed complexity analysis'
|
'Use Perplexity AI for research-backed complexity analysis'
|
||||||
)
|
)
|
||||||
|
.option(
|
||||||
|
'-i, --id <ids>',
|
||||||
|
'Comma-separated list of specific task IDs to analyze (e.g., "1,3,5")'
|
||||||
|
)
|
||||||
|
.option('--from <id>', 'Starting task ID in a range to analyze')
|
||||||
|
.option('--to <id>', 'Ending task ID in a range to analyze')
|
||||||
.action(async (options) => {
|
.action(async (options) => {
|
||||||
const tasksPath = options.file || 'tasks/tasks.json';
|
const tasksPath = options.file || 'tasks/tasks.json';
|
||||||
const outputPath = options.output;
|
const outputPath = options.output;
|
||||||
@@ -1220,6 +1353,16 @@ function registerCommands(programInstance) {
|
|||||||
console.log(chalk.blue(`Analyzing task complexity from: ${tasksPath}`));
|
console.log(chalk.blue(`Analyzing task complexity from: ${tasksPath}`));
|
||||||
console.log(chalk.blue(`Output report will be saved to: ${outputPath}`));
|
console.log(chalk.blue(`Output report will be saved to: ${outputPath}`));
|
||||||
|
|
||||||
|
if (options.id) {
|
||||||
|
console.log(chalk.blue(`Analyzing specific task IDs: ${options.id}`));
|
||||||
|
} else if (options.from || options.to) {
|
||||||
|
const fromStr = options.from ? options.from : 'first';
|
||||||
|
const toStr = options.to ? options.to : 'last';
|
||||||
|
console.log(
|
||||||
|
chalk.blue(`Analyzing tasks in range: ${fromStr} to ${toStr}`)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (useResearch) {
|
if (useResearch) {
|
||||||
console.log(
|
console.log(
|
||||||
chalk.blue(
|
chalk.blue(
|
||||||
@@ -1272,7 +1415,7 @@ function registerCommands(programInstance) {
|
|||||||
// add-task command
|
// add-task command
|
||||||
programInstance
|
programInstance
|
||||||
.command('add-task')
|
.command('add-task')
|
||||||
.description('Add a new task using AI or manual input')
|
.description('Add a new task using AI, optionally providing manual details')
|
||||||
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
||||||
.option(
|
.option(
|
||||||
'-p, --prompt <prompt>',
|
'-p, --prompt <prompt>',
|
||||||
@@ -1313,74 +1456,70 @@ function registerCommands(programInstance) {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const tasksPath =
|
||||||
|
options.file ||
|
||||||
|
path.join(findProjectRoot() || '.', 'tasks', 'tasks.json') || // Ensure tasksPath is also relative to a found root or current dir
|
||||||
|
'tasks/tasks.json';
|
||||||
|
|
||||||
|
// Correctly determine projectRoot
|
||||||
|
const projectRoot = findProjectRoot();
|
||||||
|
|
||||||
|
let manualTaskData = null;
|
||||||
|
if (isManualCreation) {
|
||||||
|
manualTaskData = {
|
||||||
|
title: options.title,
|
||||||
|
description: options.description,
|
||||||
|
details: options.details || '',
|
||||||
|
testStrategy: options.testStrategy || ''
|
||||||
|
};
|
||||||
|
// Restore specific logging for manual creation
|
||||||
|
console.log(
|
||||||
|
chalk.blue(`Creating task manually with title: "${options.title}"`)
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Restore specific logging for AI creation
|
||||||
|
console.log(
|
||||||
|
chalk.blue(`Creating task with AI using prompt: "${options.prompt}"`)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log dependencies and priority if provided (restored)
|
||||||
|
const dependenciesArray = options.dependencies
|
||||||
|
? options.dependencies.split(',').map((id) => id.trim())
|
||||||
|
: [];
|
||||||
|
if (dependenciesArray.length > 0) {
|
||||||
|
console.log(
|
||||||
|
chalk.blue(`Dependencies: [${dependenciesArray.join(', ')}]`)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (options.priority) {
|
||||||
|
console.log(chalk.blue(`Priority: ${options.priority}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
const context = {
|
||||||
|
projectRoot,
|
||||||
|
commandName: 'add-task',
|
||||||
|
outputType: 'cli'
|
||||||
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Prepare dependencies if provided
|
const { newTaskId, telemetryData } = await addTask(
|
||||||
let dependencies = [];
|
tasksPath,
|
||||||
if (options.dependencies) {
|
options.prompt,
|
||||||
dependencies = options.dependencies
|
dependenciesArray,
|
||||||
.split(',')
|
|
||||||
.map((id) => parseInt(id.trim(), 10));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create manual task data if title and description are provided
|
|
||||||
let manualTaskData = null;
|
|
||||||
if (isManualCreation) {
|
|
||||||
manualTaskData = {
|
|
||||||
title: options.title,
|
|
||||||
description: options.description,
|
|
||||||
details: options.details || '',
|
|
||||||
testStrategy: options.testStrategy || ''
|
|
||||||
};
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
chalk.blue(`Creating task manually with title: "${options.title}"`)
|
|
||||||
);
|
|
||||||
if (dependencies.length > 0) {
|
|
||||||
console.log(
|
|
||||||
chalk.blue(`Dependencies: [${dependencies.join(', ')}]`)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (options.priority) {
|
|
||||||
console.log(chalk.blue(`Priority: ${options.priority}`));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.log(
|
|
||||||
chalk.blue(
|
|
||||||
`Creating task with AI using prompt: "${options.prompt}"`
|
|
||||||
)
|
|
||||||
);
|
|
||||||
if (dependencies.length > 0) {
|
|
||||||
console.log(
|
|
||||||
chalk.blue(`Dependencies: [${dependencies.join(', ')}]`)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (options.priority) {
|
|
||||||
console.log(chalk.blue(`Priority: ${options.priority}`));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pass mcpLog and session for MCP mode
|
|
||||||
const newTaskId = await addTask(
|
|
||||||
options.file,
|
|
||||||
options.prompt, // Pass prompt (will be null/undefined if not provided)
|
|
||||||
dependencies,
|
|
||||||
options.priority,
|
options.priority,
|
||||||
{
|
context,
|
||||||
// For CLI, session context isn't directly available like MCP
|
'text',
|
||||||
// We don't need to pass session here for CLI API key resolution
|
manualTaskData,
|
||||||
// as dotenv loads .env, and utils.resolveEnvVariable checks process.env
|
options.research
|
||||||
},
|
|
||||||
'text', // outputFormat
|
|
||||||
manualTaskData, // Pass the potentially created manualTaskData object
|
|
||||||
options.research || false // Pass the research flag value
|
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log(chalk.green(`✓ Added new task #${newTaskId}`));
|
// addTask handles detailed CLI success logging AND telemetry display when outputFormat is 'text'
|
||||||
console.log(chalk.gray('Next: Complete this task or add more tasks'));
|
// No need to call displayAiUsageSummary here anymore.
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(chalk.red(`Error adding task: ${error.message}`));
|
console.error(chalk.red(`Error adding task: ${error.message}`));
|
||||||
if (error.stack && getDebugFlag()) {
|
if (error.details) {
|
||||||
console.error(error.stack);
|
console.error(chalk.red(error.details));
|
||||||
}
|
}
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
@@ -1393,9 +1532,15 @@ function registerCommands(programInstance) {
|
|||||||
`Show the next task to work on based on dependencies and status${chalk.reset('')}`
|
`Show the next task to work on based on dependencies and status${chalk.reset('')}`
|
||||||
)
|
)
|
||||||
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
||||||
|
.option(
|
||||||
|
'-r, --report <report>',
|
||||||
|
'Path to the complexity report file',
|
||||||
|
'scripts/task-complexity-report.json'
|
||||||
|
)
|
||||||
.action(async (options) => {
|
.action(async (options) => {
|
||||||
const tasksPath = options.file;
|
const tasksPath = options.file;
|
||||||
await displayNextTask(tasksPath);
|
const reportPath = options.report;
|
||||||
|
await displayNextTask(tasksPath, reportPath);
|
||||||
});
|
});
|
||||||
|
|
||||||
// show command
|
// show command
|
||||||
@@ -1408,6 +1553,11 @@ function registerCommands(programInstance) {
|
|||||||
.option('-i, --id <id>', 'Task ID to show')
|
.option('-i, --id <id>', 'Task ID to show')
|
||||||
.option('-s, --status <status>', 'Filter subtasks by status') // ADDED status option
|
.option('-s, --status <status>', 'Filter subtasks by status') // ADDED status option
|
||||||
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
||||||
|
.option(
|
||||||
|
'-r, --report <report>',
|
||||||
|
'Path to the complexity report file',
|
||||||
|
'scripts/task-complexity-report.json'
|
||||||
|
)
|
||||||
.action(async (taskId, options) => {
|
.action(async (taskId, options) => {
|
||||||
const idArg = taskId || options.id;
|
const idArg = taskId || options.id;
|
||||||
const statusFilter = options.status; // ADDED: Capture status filter
|
const statusFilter = options.status; // ADDED: Capture status filter
|
||||||
@@ -1418,8 +1568,9 @@ function registerCommands(programInstance) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const tasksPath = options.file;
|
const tasksPath = options.file;
|
||||||
|
const reportPath = options.report;
|
||||||
// PASS statusFilter to the display function
|
// PASS statusFilter to the display function
|
||||||
await displayTaskById(tasksPath, idArg, statusFilter);
|
await displayTaskById(tasksPath, idArg, reportPath, statusFilter);
|
||||||
});
|
});
|
||||||
|
|
||||||
// add-dependency command
|
// add-dependency command
|
||||||
@@ -2075,7 +2226,7 @@ function registerCommands(programInstance) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Exit with error if any removals failed
|
// Exit with error if any removals failed
|
||||||
if (successfulRemovals.length === 0) {
|
if (result.removedTasks.length === 0) {
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2340,6 +2491,135 @@ Examples:
|
|||||||
return; // Stop execution here
|
return; // Stop execution here
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// move-task command
|
||||||
|
programInstance
|
||||||
|
.command('move')
|
||||||
|
.description('Move a task or subtask to a new position')
|
||||||
|
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
||||||
|
.option(
|
||||||
|
'--from <id>',
|
||||||
|
'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")'
|
||||||
|
)
|
||||||
|
.option(
|
||||||
|
'--to <id>',
|
||||||
|
'ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated'
|
||||||
|
)
|
||||||
|
.action(async (options) => {
|
||||||
|
const tasksPath = options.file;
|
||||||
|
const sourceId = options.from;
|
||||||
|
const destinationId = options.to;
|
||||||
|
|
||||||
|
if (!sourceId || !destinationId) {
|
||||||
|
console.error(
|
||||||
|
chalk.red('Error: Both --from and --to parameters are required')
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
chalk.yellow(
|
||||||
|
'Usage: task-master move --from=<sourceId> --to=<destinationId>'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if we're moving multiple tasks (comma-separated IDs)
|
||||||
|
const sourceIds = sourceId.split(',').map((id) => id.trim());
|
||||||
|
const destinationIds = destinationId.split(',').map((id) => id.trim());
|
||||||
|
|
||||||
|
// Validate that the number of source and destination IDs match
|
||||||
|
if (sourceIds.length !== destinationIds.length) {
|
||||||
|
console.error(
|
||||||
|
chalk.red(
|
||||||
|
'Error: The number of source and destination IDs must match'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
chalk.yellow('Example: task-master move --from=5,6,7 --to=10,11,12')
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If moving multiple tasks
|
||||||
|
if (sourceIds.length > 1) {
|
||||||
|
console.log(
|
||||||
|
chalk.blue(
|
||||||
|
`Moving multiple tasks: ${sourceIds.join(', ')} to ${destinationIds.join(', ')}...`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Read tasks data once to validate destination IDs
|
||||||
|
const tasksData = readJSON(tasksPath);
|
||||||
|
if (!tasksData || !tasksData.tasks) {
|
||||||
|
console.error(
|
||||||
|
chalk.red(`Error: Invalid or missing tasks file at ${tasksPath}`)
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move tasks one by one
|
||||||
|
for (let i = 0; i < sourceIds.length; i++) {
|
||||||
|
const fromId = sourceIds[i];
|
||||||
|
const toId = destinationIds[i];
|
||||||
|
|
||||||
|
// Skip if source and destination are the same
|
||||||
|
if (fromId === toId) {
|
||||||
|
console.log(
|
||||||
|
chalk.yellow(`Skipping ${fromId} -> ${toId} (same ID)`)
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
chalk.blue(`Moving task/subtask ${fromId} to ${toId}...`)
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
await moveTask(
|
||||||
|
tasksPath,
|
||||||
|
fromId,
|
||||||
|
toId,
|
||||||
|
i === sourceIds.length - 1
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
chalk.green(
|
||||||
|
`✓ Successfully moved task/subtask ${fromId} to ${toId}`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
chalk.red(`Error moving ${fromId} to ${toId}: ${error.message}`)
|
||||||
|
);
|
||||||
|
// Continue with the next task rather than exiting
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(chalk.red(`Error: ${error.message}`));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Moving a single task (existing logic)
|
||||||
|
console.log(
|
||||||
|
chalk.blue(`Moving task/subtask ${sourceId} to ${destinationId}...`)
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await moveTask(
|
||||||
|
tasksPath,
|
||||||
|
sourceId,
|
||||||
|
destinationId,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
chalk.green(
|
||||||
|
`✓ Successfully moved task/subtask ${sourceId} to ${destinationId}`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(chalk.red(`Error: ${error.message}`));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return programInstance;
|
return programInstance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -669,6 +669,34 @@ function isConfigFilePresent(explicitRoot = null) {
|
|||||||
return fs.existsSync(configPath);
|
return fs.existsSync(configPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the user ID from the configuration.
|
||||||
|
* @param {string|null} explicitRoot - Optional explicit path to the project root.
|
||||||
|
* @returns {string|null} The user ID or null if not found.
|
||||||
|
*/
|
||||||
|
function getUserId(explicitRoot = null) {
|
||||||
|
const config = getConfig(explicitRoot);
|
||||||
|
if (!config.global) {
|
||||||
|
config.global = {}; // Ensure global object exists
|
||||||
|
}
|
||||||
|
if (!config.global.userId) {
|
||||||
|
config.global.userId = '1234567890';
|
||||||
|
// Attempt to write the updated config.
|
||||||
|
// It's important that writeConfig correctly resolves the path
|
||||||
|
// using explicitRoot, similar to how getConfig does.
|
||||||
|
const success = writeConfig(config, explicitRoot);
|
||||||
|
if (!success) {
|
||||||
|
// Log an error or handle the failure to write,
|
||||||
|
// though for now, we'll proceed with the in-memory default.
|
||||||
|
log(
|
||||||
|
'warning',
|
||||||
|
'Failed to write updated configuration with new userId. Please let the developers know.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return config.global.userId;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a list of all provider names defined in the MODEL_MAP.
|
* Gets a list of all provider names defined in the MODEL_MAP.
|
||||||
* @returns {string[]} An array of provider names.
|
* @returns {string[]} An array of provider names.
|
||||||
@@ -688,8 +716,8 @@ export {
|
|||||||
// Core config access
|
// Core config access
|
||||||
getConfig,
|
getConfig,
|
||||||
writeConfig,
|
writeConfig,
|
||||||
ConfigurationError, // Export custom error type
|
ConfigurationError,
|
||||||
isConfigFilePresent, // Add the new function export
|
isConfigFilePresent,
|
||||||
|
|
||||||
// Validation
|
// Validation
|
||||||
validateProvider,
|
validateProvider,
|
||||||
@@ -722,7 +750,7 @@ export {
|
|||||||
getProjectName,
|
getProjectName,
|
||||||
getOllamaBaseUrl,
|
getOllamaBaseUrl,
|
||||||
getParametersForRole,
|
getParametersForRole,
|
||||||
|
getUserId,
|
||||||
// API Key Checkers (still relevant)
|
// API Key Checkers (still relevant)
|
||||||
isApiKeySet,
|
isApiKeySet,
|
||||||
getMcpApiKeyStatus,
|
getMcpApiKeyStatus,
|
||||||
|
|||||||
@@ -1,5 +1,19 @@
|
|||||||
{
|
{
|
||||||
"anthropic": [
|
"anthropic": [
|
||||||
|
{
|
||||||
|
"id": "claude-sonnet-4-20250514",
|
||||||
|
"swe_score": 0.727,
|
||||||
|
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 120000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "claude-opus-4-20250514",
|
||||||
|
"swe_score": 0.725,
|
||||||
|
"cost_per_1m_tokens": { "input": 15.0, "output": 75.0 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 120000
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "claude-3-7-sonnet-20250219",
|
"id": "claude-3-7-sonnet-20250219",
|
||||||
"swe_score": 0.623,
|
"swe_score": 0.623,
|
||||||
@@ -99,34 +113,39 @@
|
|||||||
],
|
],
|
||||||
"google": [
|
"google": [
|
||||||
{
|
{
|
||||||
"id": "gemini-2.5-pro-exp-03-25",
|
"id": "gemini-2.5-pro-preview-05-06",
|
||||||
"swe_score": 0.638,
|
"swe_score": 0.638,
|
||||||
"cost_per_1m_tokens": null,
|
"cost_per_1m_tokens": null,
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 1048000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "gemini-2.5-pro-preview-03-25",
|
||||||
|
"swe_score": 0.638,
|
||||||
|
"cost_per_1m_tokens": null,
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 1048000
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "gemini-2.5-flash-preview-04-17",
|
"id": "gemini-2.5-flash-preview-04-17",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": null,
|
"cost_per_1m_tokens": null,
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 1048000
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "gemini-2.0-flash",
|
"id": "gemini-2.0-flash",
|
||||||
"swe_score": 0.754,
|
"swe_score": 0.754,
|
||||||
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 1048000
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "gemini-2.0-flash-thinking-experimental",
|
"id": "gemini-2.0-flash-lite",
|
||||||
"swe_score": 0.754,
|
|
||||||
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
|
||||||
"allowed_roles": ["main", "fallback"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "gemini-2.0-pro",
|
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": null,
|
"cost_per_1m_tokens": null,
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 1048000
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"perplexity": [
|
"perplexity": [
|
||||||
@@ -186,43 +205,43 @@
|
|||||||
],
|
],
|
||||||
"ollama": [
|
"ollama": [
|
||||||
{
|
{
|
||||||
"id": "gemma3:27b",
|
"id": "devstral:latest",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "gemma3:12b",
|
"id": "qwen3:latest",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "qwq",
|
"id": "qwen3:14b",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "deepseek-r1",
|
"id": "qwen3:32b",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "mistral-small3.1",
|
"id": "mistral-small3.1:latest",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "llama3.3",
|
"id": "llama3.3:latest",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "phi4",
|
"id": "phi4:latest",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
||||||
"allowed_roles": ["main", "fallback"]
|
"allowed_roles": ["main", "fallback"]
|
||||||
@@ -230,9 +249,16 @@
|
|||||||
],
|
],
|
||||||
"openrouter": [
|
"openrouter": [
|
||||||
{
|
{
|
||||||
"id": "google/gemini-2.0-flash-001",
|
"id": "google/gemini-2.5-flash-preview-05-20",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
|
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 1048576
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "google/gemini-2.5-flash-preview-05-20:thinking",
|
||||||
|
"swe_score": 0,
|
||||||
|
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
|
||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 1048576
|
"max_tokens": 1048576
|
||||||
},
|
},
|
||||||
@@ -258,40 +284,25 @@
|
|||||||
"max_tokens": 64000
|
"max_tokens": 64000
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "deepseek/deepseek-r1:free",
|
"id": "openai/gpt-4.1",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 2, "output": 8 },
|
||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 163840
|
"max_tokens": 1000000
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
"id": "microsoft/mai-ds-r1:free",
|
"id": "openai/gpt-4.1-mini",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0.4, "output": 1.6 },
|
||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 163840
|
"max_tokens": 1000000
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "google/gemini-2.5-pro-preview-03-25",
|
"id": "openai/gpt-4.1-nano",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 1.25, "output": 10 },
|
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
|
||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 65535
|
"max_tokens": 1000000
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "google/gemini-2.5-flash-preview",
|
|
||||||
"swe_score": 0,
|
|
||||||
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
|
||||||
"allowed_roles": ["main"],
|
|
||||||
"max_tokens": 65535
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "google/gemini-2.5-flash-preview:thinking",
|
|
||||||
"swe_score": 0,
|
|
||||||
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
|
|
||||||
"allowed_roles": ["main"],
|
|
||||||
"max_tokens": 65535
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "openai/o3",
|
"id": "openai/o3",
|
||||||
@@ -300,6 +311,20 @@
|
|||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 200000
|
"max_tokens": 200000
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"id": "openai/codex-mini",
|
||||||
|
"swe_score": 0,
|
||||||
|
"cost_per_1m_tokens": { "input": 1.5, "output": 6 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 100000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "openai/gpt-4o-mini",
|
||||||
|
"swe_score": 0,
|
||||||
|
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 100000
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "openai/o4-mini",
|
"id": "openai/o4-mini",
|
||||||
"swe_score": 0.45,
|
"swe_score": 0.45,
|
||||||
@@ -329,46 +354,18 @@
|
|||||||
"max_tokens": 1048576
|
"max_tokens": 1048576
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "google/gemma-3-12b-it:free",
|
"id": "meta-llama/llama-4-maverick",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
"cost_per_1m_tokens": { "input": 0.18, "output": 0.6 },
|
||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 131072
|
"max_tokens": 1000000
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "google/gemma-3-12b-it",
|
"id": "meta-llama/llama-4-scout",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
"cost_per_1m_tokens": { "input": 50, "output": 100 },
|
"cost_per_1m_tokens": { "input": 0.08, "output": 0.3 },
|
||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 131072
|
"max_tokens": 1000000
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "google/gemma-3-27b-it:free",
|
|
||||||
"swe_score": 0,
|
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
|
||||||
"allowed_roles": ["main", "fallback"],
|
|
||||||
"max_tokens": 96000
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "google/gemma-3-27b-it",
|
|
||||||
"swe_score": 0,
|
|
||||||
"cost_per_1m_tokens": { "input": 100, "output": 200 },
|
|
||||||
"allowed_roles": ["main", "fallback"],
|
|
||||||
"max_tokens": 131072
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "qwen/qwq-32b:free",
|
|
||||||
"swe_score": 0,
|
|
||||||
"cost_per_1m_tokens": { "input": 0, "output": 0 },
|
|
||||||
"allowed_roles": ["main", "fallback"],
|
|
||||||
"max_tokens": 40000
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "qwen/qwq-32b",
|
|
||||||
"swe_score": 0,
|
|
||||||
"cost_per_1m_tokens": { "input": 150, "output": 200 },
|
|
||||||
"allowed_roles": ["main", "fallback"],
|
|
||||||
"max_tokens": 131072
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "qwen/qwen-max",
|
"id": "qwen/qwen-max",
|
||||||
@@ -384,6 +381,13 @@
|
|||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 1000000
|
"max_tokens": 1000000
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"id": "qwen/qwen3-235b-a22b",
|
||||||
|
"swe_score": 0,
|
||||||
|
"cost_per_1m_tokens": { "input": 0.14, "output": 2 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 24000
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "mistralai/mistral-small-3.1-24b-instruct:free",
|
"id": "mistralai/mistral-small-3.1-24b-instruct:free",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
@@ -398,6 +402,20 @@
|
|||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 128000
|
"max_tokens": 128000
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"id": "mistralai/devstral-small",
|
||||||
|
"swe_score": 0,
|
||||||
|
"cost_per_1m_tokens": { "input": 0.1, "output": 0.3 },
|
||||||
|
"allowed_roles": ["main"],
|
||||||
|
"max_tokens": 110000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "mistralai/mistral-nemo",
|
||||||
|
"swe_score": 0,
|
||||||
|
"cost_per_1m_tokens": { "input": 0.03, "output": 0.07 },
|
||||||
|
"allowed_roles": ["main", "fallback"],
|
||||||
|
"max_tokens": 100000
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "thudm/glm-4-32b:free",
|
"id": "thudm/glm-4-32b:free",
|
||||||
"swe_score": 0,
|
"swe_score": 0,
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ import updateSubtaskById from './task-manager/update-subtask-by-id.js';
|
|||||||
import removeTask from './task-manager/remove-task.js';
|
import removeTask from './task-manager/remove-task.js';
|
||||||
import taskExists from './task-manager/task-exists.js';
|
import taskExists from './task-manager/task-exists.js';
|
||||||
import isTaskDependentOn from './task-manager/is-task-dependent.js';
|
import isTaskDependentOn from './task-manager/is-task-dependent.js';
|
||||||
|
import moveTask from './task-manager/move-task.js';
|
||||||
|
import { readComplexityReport } from './utils.js';
|
||||||
// Export task manager functions
|
// Export task manager functions
|
||||||
export {
|
export {
|
||||||
parsePRD,
|
parsePRD,
|
||||||
@@ -45,5 +46,7 @@ export {
|
|||||||
removeTask,
|
removeTask,
|
||||||
findTaskById,
|
findTaskById,
|
||||||
taskExists,
|
taskExists,
|
||||||
isTaskDependentOn
|
isTaskDependentOn,
|
||||||
|
moveTask,
|
||||||
|
readComplexityReport
|
||||||
};
|
};
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,10 +1,15 @@
|
|||||||
import chalk from 'chalk';
|
import chalk from 'chalk';
|
||||||
import boxen from 'boxen';
|
import boxen from 'boxen';
|
||||||
import readline from 'readline';
|
import readline from 'readline';
|
||||||
|
import fs from 'fs';
|
||||||
|
|
||||||
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
|
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
|
||||||
|
|
||||||
import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
|
import {
|
||||||
|
startLoadingIndicator,
|
||||||
|
stopLoadingIndicator,
|
||||||
|
displayAiUsageSummary
|
||||||
|
} from '../ui.js';
|
||||||
|
|
||||||
import { generateTextService } from '../ai-services-unified.js';
|
import { generateTextService } from '../ai-services-unified.js';
|
||||||
|
|
||||||
@@ -47,6 +52,9 @@ Do not include any explanatory text, markdown formatting, or code block markers
|
|||||||
* @param {string|number} [options.threshold] - Complexity threshold
|
* @param {string|number} [options.threshold] - Complexity threshold
|
||||||
* @param {boolean} [options.research] - Use research role
|
* @param {boolean} [options.research] - Use research role
|
||||||
* @param {string} [options.projectRoot] - Project root path (for MCP/env fallback).
|
* @param {string} [options.projectRoot] - Project root path (for MCP/env fallback).
|
||||||
|
* @param {string} [options.id] - Comma-separated list of task IDs to analyze specifically
|
||||||
|
* @param {number} [options.from] - Starting task ID in a range to analyze
|
||||||
|
* @param {number} [options.to] - Ending task ID in a range to analyze
|
||||||
* @param {Object} [options._filteredTasksData] - Pre-filtered task data (internal use)
|
* @param {Object} [options._filteredTasksData] - Pre-filtered task data (internal use)
|
||||||
* @param {number} [options._originalTaskCount] - Original task count (internal use)
|
* @param {number} [options._originalTaskCount] - Original task count (internal use)
|
||||||
* @param {Object} context - Context object, potentially containing session and mcpLog
|
* @param {Object} context - Context object, potentially containing session and mcpLog
|
||||||
@@ -61,6 +69,15 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
const thresholdScore = parseFloat(options.threshold || '5');
|
const thresholdScore = parseFloat(options.threshold || '5');
|
||||||
const useResearch = options.research || false;
|
const useResearch = options.research || false;
|
||||||
const projectRoot = options.projectRoot;
|
const projectRoot = options.projectRoot;
|
||||||
|
// New parameters for task ID filtering
|
||||||
|
const specificIds = options.id
|
||||||
|
? options.id
|
||||||
|
.split(',')
|
||||||
|
.map((id) => parseInt(id.trim(), 10))
|
||||||
|
.filter((id) => !isNaN(id))
|
||||||
|
: null;
|
||||||
|
const fromId = options.from !== undefined ? parseInt(options.from, 10) : null;
|
||||||
|
const toId = options.to !== undefined ? parseInt(options.to, 10) : null;
|
||||||
|
|
||||||
const outputFormat = mcpLog ? 'json' : 'text';
|
const outputFormat = mcpLog ? 'json' : 'text';
|
||||||
|
|
||||||
@@ -84,13 +101,14 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
reportLog(`Reading tasks from ${tasksPath}...`, 'info');
|
reportLog(`Reading tasks from ${tasksPath}...`, 'info');
|
||||||
let tasksData;
|
let tasksData;
|
||||||
let originalTaskCount = 0;
|
let originalTaskCount = 0;
|
||||||
|
let originalData = null;
|
||||||
|
|
||||||
if (options._filteredTasksData) {
|
if (options._filteredTasksData) {
|
||||||
tasksData = options._filteredTasksData;
|
tasksData = options._filteredTasksData;
|
||||||
originalTaskCount = options._originalTaskCount || tasksData.tasks.length;
|
originalTaskCount = options._originalTaskCount || tasksData.tasks.length;
|
||||||
if (!options._originalTaskCount) {
|
if (!options._originalTaskCount) {
|
||||||
try {
|
try {
|
||||||
const originalData = readJSON(tasksPath);
|
originalData = readJSON(tasksPath);
|
||||||
if (originalData && originalData.tasks) {
|
if (originalData && originalData.tasks) {
|
||||||
originalTaskCount = originalData.tasks.length;
|
originalTaskCount = originalData.tasks.length;
|
||||||
}
|
}
|
||||||
@@ -99,22 +117,80 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
tasksData = readJSON(tasksPath);
|
originalData = readJSON(tasksPath);
|
||||||
if (
|
if (
|
||||||
!tasksData ||
|
!originalData ||
|
||||||
!tasksData.tasks ||
|
!originalData.tasks ||
|
||||||
!Array.isArray(tasksData.tasks) ||
|
!Array.isArray(originalData.tasks) ||
|
||||||
tasksData.tasks.length === 0
|
originalData.tasks.length === 0
|
||||||
) {
|
) {
|
||||||
throw new Error('No tasks found in the tasks file');
|
throw new Error('No tasks found in the tasks file');
|
||||||
}
|
}
|
||||||
originalTaskCount = tasksData.tasks.length;
|
originalTaskCount = originalData.tasks.length;
|
||||||
|
|
||||||
|
// Filter tasks based on active status
|
||||||
const activeStatuses = ['pending', 'blocked', 'in-progress'];
|
const activeStatuses = ['pending', 'blocked', 'in-progress'];
|
||||||
const filteredTasks = tasksData.tasks.filter((task) =>
|
let filteredTasks = originalData.tasks.filter((task) =>
|
||||||
activeStatuses.includes(task.status?.toLowerCase() || 'pending')
|
activeStatuses.includes(task.status?.toLowerCase() || 'pending')
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Apply ID filtering if specified
|
||||||
|
if (specificIds && specificIds.length > 0) {
|
||||||
|
reportLog(
|
||||||
|
`Filtering tasks by specific IDs: ${specificIds.join(', ')}`,
|
||||||
|
'info'
|
||||||
|
);
|
||||||
|
filteredTasks = filteredTasks.filter((task) =>
|
||||||
|
specificIds.includes(task.id)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (outputFormat === 'text') {
|
||||||
|
if (filteredTasks.length === 0 && specificIds.length > 0) {
|
||||||
|
console.log(
|
||||||
|
chalk.yellow(
|
||||||
|
`Warning: No active tasks found with IDs: ${specificIds.join(', ')}`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} else if (filteredTasks.length < specificIds.length) {
|
||||||
|
const foundIds = filteredTasks.map((t) => t.id);
|
||||||
|
const missingIds = specificIds.filter(
|
||||||
|
(id) => !foundIds.includes(id)
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
chalk.yellow(
|
||||||
|
`Warning: Some requested task IDs were not found or are not active: ${missingIds.join(', ')}`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Apply range filtering if specified
|
||||||
|
else if (fromId !== null || toId !== null) {
|
||||||
|
const effectiveFromId = fromId !== null ? fromId : 1;
|
||||||
|
const effectiveToId =
|
||||||
|
toId !== null
|
||||||
|
? toId
|
||||||
|
: Math.max(...originalData.tasks.map((t) => t.id));
|
||||||
|
|
||||||
|
reportLog(
|
||||||
|
`Filtering tasks by ID range: ${effectiveFromId} to ${effectiveToId}`,
|
||||||
|
'info'
|
||||||
|
);
|
||||||
|
filteredTasks = filteredTasks.filter(
|
||||||
|
(task) => task.id >= effectiveFromId && task.id <= effectiveToId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (outputFormat === 'text' && filteredTasks.length === 0) {
|
||||||
|
console.log(
|
||||||
|
chalk.yellow(
|
||||||
|
`Warning: No active tasks found in range: ${effectiveFromId}-${effectiveToId}`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
tasksData = {
|
tasksData = {
|
||||||
...tasksData,
|
...originalData,
|
||||||
tasks: filteredTasks,
|
tasks: filteredTasks,
|
||||||
_originalTaskCount: originalTaskCount
|
_originalTaskCount: originalTaskCount
|
||||||
};
|
};
|
||||||
@@ -125,7 +201,18 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
`Found ${originalTaskCount} total tasks in the task file.`,
|
`Found ${originalTaskCount} total tasks in the task file.`,
|
||||||
'info'
|
'info'
|
||||||
);
|
);
|
||||||
if (skippedCount > 0) {
|
|
||||||
|
// Updated messaging to reflect filtering logic
|
||||||
|
if (specificIds || fromId !== null || toId !== null) {
|
||||||
|
const filterMsg = specificIds
|
||||||
|
? `Analyzing ${tasksData.tasks.length} tasks with specific IDs: ${specificIds.join(', ')}`
|
||||||
|
: `Analyzing ${tasksData.tasks.length} tasks in range: ${fromId || 1} to ${toId || 'end'}`;
|
||||||
|
|
||||||
|
reportLog(filterMsg, 'info');
|
||||||
|
if (outputFormat === 'text') {
|
||||||
|
console.log(chalk.blue(filterMsg));
|
||||||
|
}
|
||||||
|
} else if (skippedCount > 0) {
|
||||||
const skipMessage = `Skipping ${skippedCount} tasks marked as done/cancelled/deferred. Analyzing ${tasksData.tasks.length} active tasks.`;
|
const skipMessage = `Skipping ${skippedCount} tasks marked as done/cancelled/deferred. Analyzing ${tasksData.tasks.length} active tasks.`;
|
||||||
reportLog(skipMessage, 'info');
|
reportLog(skipMessage, 'info');
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
@@ -133,7 +220,59 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check for existing report before doing analysis
|
||||||
|
let existingReport = null;
|
||||||
|
let existingAnalysisMap = new Map(); // For quick lookups by task ID
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(outputPath)) {
|
||||||
|
existingReport = readJSON(outputPath);
|
||||||
|
reportLog(`Found existing complexity report at ${outputPath}`, 'info');
|
||||||
|
|
||||||
|
if (
|
||||||
|
existingReport &&
|
||||||
|
existingReport.complexityAnalysis &&
|
||||||
|
Array.isArray(existingReport.complexityAnalysis)
|
||||||
|
) {
|
||||||
|
// Create lookup map of existing analysis entries
|
||||||
|
existingReport.complexityAnalysis.forEach((item) => {
|
||||||
|
existingAnalysisMap.set(item.taskId, item);
|
||||||
|
});
|
||||||
|
reportLog(
|
||||||
|
`Existing report contains ${existingReport.complexityAnalysis.length} task analyses`,
|
||||||
|
'info'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (readError) {
|
||||||
|
reportLog(
|
||||||
|
`Warning: Could not read existing report: ${readError.message}`,
|
||||||
|
'warn'
|
||||||
|
);
|
||||||
|
existingReport = null;
|
||||||
|
existingAnalysisMap.clear();
|
||||||
|
}
|
||||||
|
|
||||||
if (tasksData.tasks.length === 0) {
|
if (tasksData.tasks.length === 0) {
|
||||||
|
// If using ID filtering but no matching tasks, return existing report or empty
|
||||||
|
if (existingReport && (specificIds || fromId !== null || toId !== null)) {
|
||||||
|
reportLog(
|
||||||
|
`No matching tasks found for analysis. Keeping existing report.`,
|
||||||
|
'info'
|
||||||
|
);
|
||||||
|
if (outputFormat === 'text') {
|
||||||
|
console.log(
|
||||||
|
chalk.yellow(
|
||||||
|
`No matching tasks found for analysis. Keeping existing report.`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
report: existingReport,
|
||||||
|
telemetryData: null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise create empty report
|
||||||
const emptyReport = {
|
const emptyReport = {
|
||||||
meta: {
|
meta: {
|
||||||
generatedAt: new Date().toISOString(),
|
generatedAt: new Date().toISOString(),
|
||||||
@@ -142,9 +281,9 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
projectName: getProjectName(session),
|
projectName: getProjectName(session),
|
||||||
usedResearch: useResearch
|
usedResearch: useResearch
|
||||||
},
|
},
|
||||||
complexityAnalysis: []
|
complexityAnalysis: existingReport?.complexityAnalysis || []
|
||||||
};
|
};
|
||||||
reportLog(`Writing empty complexity report to ${outputPath}...`, 'info');
|
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
|
||||||
writeJSON(outputPath, emptyReport);
|
writeJSON(outputPath, emptyReport);
|
||||||
reportLog(
|
reportLog(
|
||||||
`Task complexity analysis complete. Report written to ${outputPath}`,
|
`Task complexity analysis complete. Report written to ${outputPath}`,
|
||||||
@@ -192,39 +331,40 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return emptyReport;
|
return {
|
||||||
|
report: emptyReport,
|
||||||
|
telemetryData: null
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Continue with regular analysis path
|
||||||
const prompt = generateInternalComplexityAnalysisPrompt(tasksData);
|
const prompt = generateInternalComplexityAnalysisPrompt(tasksData);
|
||||||
// System prompt remains simple for text generation
|
|
||||||
const systemPrompt =
|
const systemPrompt =
|
||||||
'You are an expert software architect and project manager analyzing task complexity. Respond only with the requested valid JSON array.';
|
'You are an expert software architect and project manager analyzing task complexity. Respond only with the requested valid JSON array.';
|
||||||
|
|
||||||
let loadingIndicator = null;
|
let loadingIndicator = null;
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
loadingIndicator = startLoadingIndicator('Calling AI service...');
|
loadingIndicator = startLoadingIndicator(
|
||||||
|
`${useResearch ? 'Researching' : 'Analyzing'} the complexity of your tasks with AI...\n`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let fullResponse = ''; // To store the raw text response
|
let aiServiceResponse = null;
|
||||||
|
let complexityAnalysis = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const role = useResearch ? 'research' : 'main';
|
const role = useResearch ? 'research' : 'main';
|
||||||
reportLog(`Using AI service with role: ${role}`, 'info');
|
|
||||||
|
|
||||||
fullResponse = await generateTextService({
|
aiServiceResponse = await generateTextService({
|
||||||
prompt,
|
prompt,
|
||||||
systemPrompt,
|
systemPrompt,
|
||||||
role,
|
role,
|
||||||
session,
|
session,
|
||||||
projectRoot
|
projectRoot,
|
||||||
|
commandName: 'analyze-complexity',
|
||||||
|
outputType: mcpLog ? 'mcp' : 'cli'
|
||||||
});
|
});
|
||||||
|
|
||||||
reportLog(
|
|
||||||
'Successfully received text response via AI service',
|
|
||||||
'success'
|
|
||||||
);
|
|
||||||
|
|
||||||
// --- Stop Loading Indicator (Unchanged) ---
|
|
||||||
if (loadingIndicator) {
|
if (loadingIndicator) {
|
||||||
stopLoadingIndicator(loadingIndicator);
|
stopLoadingIndicator(loadingIndicator);
|
||||||
loadingIndicator = null;
|
loadingIndicator = null;
|
||||||
@@ -236,26 +376,18 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
chalk.green('AI service call complete. Parsing response...')
|
chalk.green('AI service call complete. Parsing response...')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// --- End Stop Loading Indicator ---
|
|
||||||
|
|
||||||
// --- Re-introduce Manual JSON Parsing & Cleanup ---
|
|
||||||
reportLog(`Parsing complexity analysis from text response...`, 'info');
|
reportLog(`Parsing complexity analysis from text response...`, 'info');
|
||||||
let complexityAnalysis;
|
|
||||||
try {
|
try {
|
||||||
let cleanedResponse = fullResponse;
|
let cleanedResponse = aiServiceResponse.mainResult;
|
||||||
// Basic trim first
|
|
||||||
cleanedResponse = cleanedResponse.trim();
|
cleanedResponse = cleanedResponse.trim();
|
||||||
|
|
||||||
// Remove potential markdown code block fences
|
|
||||||
const codeBlockMatch = cleanedResponse.match(
|
const codeBlockMatch = cleanedResponse.match(
|
||||||
/```(?:json)?\s*([\s\S]*?)\s*```/
|
/```(?:json)?\s*([\s\S]*?)\s*```/
|
||||||
);
|
);
|
||||||
if (codeBlockMatch) {
|
if (codeBlockMatch) {
|
||||||
cleanedResponse = codeBlockMatch[1].trim(); // Trim content inside block
|
cleanedResponse = codeBlockMatch[1].trim();
|
||||||
reportLog('Extracted JSON from code block', 'info');
|
|
||||||
} else {
|
} else {
|
||||||
// If no code block, ensure it starts with '[' and ends with ']'
|
|
||||||
// This is less robust but a common fallback
|
|
||||||
const firstBracket = cleanedResponse.indexOf('[');
|
const firstBracket = cleanedResponse.indexOf('[');
|
||||||
const lastBracket = cleanedResponse.lastIndexOf(']');
|
const lastBracket = cleanedResponse.lastIndexOf(']');
|
||||||
if (firstBracket !== -1 && lastBracket > firstBracket) {
|
if (firstBracket !== -1 && lastBracket > firstBracket) {
|
||||||
@@ -263,13 +395,11 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
firstBracket,
|
firstBracket,
|
||||||
lastBracket + 1
|
lastBracket + 1
|
||||||
);
|
);
|
||||||
reportLog('Extracted content between first [ and last ]', 'info');
|
|
||||||
} else {
|
} else {
|
||||||
reportLog(
|
reportLog(
|
||||||
'Warning: Response does not appear to be a JSON array.',
|
'Warning: Response does not appear to be a JSON array.',
|
||||||
'warn'
|
'warn'
|
||||||
);
|
);
|
||||||
// Keep going, maybe JSON.parse can handle it or will fail informatively
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,48 +413,23 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
complexityAnalysis = JSON.parse(cleanedResponse);
|
||||||
complexityAnalysis = JSON.parse(cleanedResponse);
|
} catch (parseError) {
|
||||||
} catch (jsonError) {
|
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
||||||
reportLog(
|
|
||||||
'Initial JSON parsing failed. Raw response might be malformed.',
|
|
||||||
'error'
|
|
||||||
);
|
|
||||||
reportLog(`Original JSON Error: ${jsonError.message}`, 'error');
|
|
||||||
if (outputFormat === 'text' && getDebugFlag(session)) {
|
|
||||||
console.log(chalk.red('--- Start Raw Malformed Response ---'));
|
|
||||||
console.log(chalk.gray(fullResponse));
|
|
||||||
console.log(chalk.red('--- End Raw Malformed Response ---'));
|
|
||||||
}
|
|
||||||
// Re-throw the specific JSON parsing error
|
|
||||||
throw new Error(
|
|
||||||
`Failed to parse JSON response: ${jsonError.message}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure it's an array after parsing
|
|
||||||
if (!Array.isArray(complexityAnalysis)) {
|
|
||||||
throw new Error('Parsed response is not a valid JSON array.');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// Catch errors specifically from the parsing/cleanup block
|
|
||||||
if (loadingIndicator) stopLoadingIndicator(loadingIndicator); // Ensure indicator stops
|
|
||||||
reportLog(
|
reportLog(
|
||||||
`Error parsing complexity analysis JSON: ${error.message}`,
|
`Error parsing complexity analysis JSON: ${parseError.message}`,
|
||||||
'error'
|
'error'
|
||||||
);
|
);
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
console.error(
|
console.error(
|
||||||
chalk.red(
|
chalk.red(
|
||||||
`Error parsing complexity analysis JSON: ${error.message}`
|
`Error parsing complexity analysis JSON: ${parseError.message}`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
throw error; // Re-throw parsing error
|
throw parseError;
|
||||||
}
|
}
|
||||||
// --- End Manual JSON Parsing & Cleanup ---
|
|
||||||
|
|
||||||
// --- Post-processing (Missing Task Check) - (Unchanged) ---
|
|
||||||
const taskIds = tasksData.tasks.map((t) => t.id);
|
const taskIds = tasksData.tasks.map((t) => t.id);
|
||||||
const analysisTaskIds = complexityAnalysis.map((a) => a.taskId);
|
const analysisTaskIds = complexityAnalysis.map((a) => a.taskId);
|
||||||
const missingTaskIds = taskIds.filter(
|
const missingTaskIds = taskIds.filter(
|
||||||
@@ -359,35 +464,64 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// --- End Post-processing ---
|
|
||||||
|
|
||||||
// --- Report Creation & Writing (Unchanged) ---
|
// Merge with existing report
|
||||||
const finalReport = {
|
let finalComplexityAnalysis = [];
|
||||||
|
|
||||||
|
if (existingReport && Array.isArray(existingReport.complexityAnalysis)) {
|
||||||
|
// Create a map of task IDs that we just analyzed
|
||||||
|
const analyzedTaskIds = new Set(
|
||||||
|
complexityAnalysis.map((item) => item.taskId)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Keep existing entries that weren't in this analysis run
|
||||||
|
const existingEntriesNotAnalyzed =
|
||||||
|
existingReport.complexityAnalysis.filter(
|
||||||
|
(item) => !analyzedTaskIds.has(item.taskId)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Combine with new analysis
|
||||||
|
finalComplexityAnalysis = [
|
||||||
|
...existingEntriesNotAnalyzed,
|
||||||
|
...complexityAnalysis
|
||||||
|
];
|
||||||
|
|
||||||
|
reportLog(
|
||||||
|
`Merged ${complexityAnalysis.length} new analyses with ${existingEntriesNotAnalyzed.length} existing entries`,
|
||||||
|
'info'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// No existing report or invalid format, just use the new analysis
|
||||||
|
finalComplexityAnalysis = complexityAnalysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = {
|
||||||
meta: {
|
meta: {
|
||||||
generatedAt: new Date().toISOString(),
|
generatedAt: new Date().toISOString(),
|
||||||
tasksAnalyzed: tasksData.tasks.length,
|
tasksAnalyzed: tasksData.tasks.length,
|
||||||
|
totalTasks: originalTaskCount,
|
||||||
|
analysisCount: finalComplexityAnalysis.length,
|
||||||
thresholdScore: thresholdScore,
|
thresholdScore: thresholdScore,
|
||||||
projectName: getProjectName(session),
|
projectName: getProjectName(session),
|
||||||
usedResearch: useResearch
|
usedResearch: useResearch
|
||||||
},
|
},
|
||||||
complexityAnalysis: complexityAnalysis
|
complexityAnalysis: finalComplexityAnalysis
|
||||||
};
|
};
|
||||||
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
|
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
|
||||||
writeJSON(outputPath, finalReport);
|
writeJSON(outputPath, report);
|
||||||
|
|
||||||
reportLog(
|
reportLog(
|
||||||
`Task complexity analysis complete. Report written to ${outputPath}`,
|
`Task complexity analysis complete. Report written to ${outputPath}`,
|
||||||
'success'
|
'success'
|
||||||
);
|
);
|
||||||
// --- End Report Creation & Writing ---
|
|
||||||
|
|
||||||
// --- Display CLI Summary (Unchanged) ---
|
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
console.log(
|
console.log(
|
||||||
chalk.green(
|
chalk.green(
|
||||||
`Task complexity analysis complete. Report written to ${outputPath}`
|
`Task complexity analysis complete. Report written to ${outputPath}`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
// Calculate statistics specifically for this analysis run
|
||||||
const highComplexity = complexityAnalysis.filter(
|
const highComplexity = complexityAnalysis.filter(
|
||||||
(t) => t.complexityScore >= 8
|
(t) => t.complexityScore >= 8
|
||||||
).length;
|
).length;
|
||||||
@@ -399,18 +533,25 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
).length;
|
).length;
|
||||||
const totalAnalyzed = complexityAnalysis.length;
|
const totalAnalyzed = complexityAnalysis.length;
|
||||||
|
|
||||||
console.log('\nComplexity Analysis Summary:');
|
console.log('\nCurrent Analysis Summary:');
|
||||||
console.log('----------------------------');
|
console.log('----------------------------');
|
||||||
console.log(
|
console.log(`Tasks analyzed in this run: ${totalAnalyzed}`);
|
||||||
`Active tasks sent for analysis: ${tasksData.tasks.length}`
|
|
||||||
);
|
|
||||||
console.log(`Tasks successfully analyzed: ${totalAnalyzed}`);
|
|
||||||
console.log(`High complexity tasks: ${highComplexity}`);
|
console.log(`High complexity tasks: ${highComplexity}`);
|
||||||
console.log(`Medium complexity tasks: ${mediumComplexity}`);
|
console.log(`Medium complexity tasks: ${mediumComplexity}`);
|
||||||
console.log(`Low complexity tasks: ${lowComplexity}`);
|
console.log(`Low complexity tasks: ${lowComplexity}`);
|
||||||
console.log(
|
|
||||||
`Sum verification: ${highComplexity + mediumComplexity + lowComplexity} (should equal ${totalAnalyzed})`
|
if (existingReport) {
|
||||||
);
|
console.log('\nUpdated Report Summary:');
|
||||||
|
console.log('----------------------------');
|
||||||
|
console.log(
|
||||||
|
`Total analyses in report: ${finalComplexityAnalysis.length}`
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`Analyses from previous runs: ${finalComplexityAnalysis.length - totalAnalyzed}`
|
||||||
|
);
|
||||||
|
console.log(`New/updated analyses: ${totalAnalyzed}`);
|
||||||
|
}
|
||||||
|
|
||||||
console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`);
|
console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`);
|
||||||
console.log(
|
console.log(
|
||||||
`\nSee ${outputPath} for the full report and expansion commands.`
|
`\nSee ${outputPath} for the full report and expansion commands.`
|
||||||
@@ -435,23 +576,28 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
if (getDebugFlag(session)) {
|
if (getDebugFlag(session)) {
|
||||||
console.debug(
|
console.debug(
|
||||||
chalk.gray(
|
chalk.gray(
|
||||||
`Final analysis object: ${JSON.stringify(finalReport, null, 2)}`
|
`Final analysis object: ${JSON.stringify(report, null, 2)}`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
// --- End Display CLI Summary ---
|
|
||||||
|
|
||||||
return finalReport;
|
if (aiServiceResponse.telemetryData) {
|
||||||
} catch (error) {
|
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
|
||||||
// Catches errors from generateTextService call
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
report: report,
|
||||||
|
telemetryData: aiServiceResponse?.telemetryData
|
||||||
|
};
|
||||||
|
} catch (aiError) {
|
||||||
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
||||||
reportLog(`Error during AI service call: ${error.message}`, 'error');
|
reportLog(`Error during AI service call: ${aiError.message}`, 'error');
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
console.error(
|
console.error(
|
||||||
chalk.red(`Error during AI service call: ${error.message}`)
|
chalk.red(`Error during AI service call: ${aiError.message}`)
|
||||||
);
|
);
|
||||||
if (error.message.includes('API key')) {
|
if (aiError.message.includes('API key')) {
|
||||||
console.log(
|
console.log(
|
||||||
chalk.yellow(
|
chalk.yellow(
|
||||||
'\nPlease ensure your API keys are correctly configured in .env or ~/.taskmaster/.env'
|
'\nPlease ensure your API keys are correctly configured in .env or ~/.taskmaster/.env'
|
||||||
@@ -462,10 +608,9 @@ async function analyzeTaskComplexity(options, context = {}) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw error; // Re-throw AI service error
|
throw aiError;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catches general errors (file read, etc.)
|
|
||||||
reportLog(`Error analyzing task complexity: ${error.message}`, 'error');
|
reportLog(`Error analyzing task complexity: ${error.message}`, 'error');
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
console.error(
|
console.error(
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
import { log, readJSON, isSilentMode } from '../utils.js';
|
import { log, readJSON, isSilentMode } from '../utils.js';
|
||||||
import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
|
import {
|
||||||
|
startLoadingIndicator,
|
||||||
|
stopLoadingIndicator,
|
||||||
|
displayAiUsageSummary
|
||||||
|
} from '../ui.js';
|
||||||
import expandTask from './expand-task.js';
|
import expandTask from './expand-task.js';
|
||||||
import { getDebugFlag } from '../config-manager.js';
|
import { getDebugFlag } from '../config-manager.js';
|
||||||
|
import { aggregateTelemetry } from '../utils.js';
|
||||||
|
import chalk from 'chalk';
|
||||||
|
import boxen from 'boxen';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Expand all eligible pending or in-progress tasks using the expandTask function.
|
* Expand all eligible pending or in-progress tasks using the expandTask function.
|
||||||
@@ -14,7 +21,7 @@ import { getDebugFlag } from '../config-manager.js';
|
|||||||
* @param {Object} [context.session] - Session object from MCP.
|
* @param {Object} [context.session] - Session object from MCP.
|
||||||
* @param {Object} [context.mcpLog] - MCP logger object.
|
* @param {Object} [context.mcpLog] - MCP logger object.
|
||||||
* @param {string} [outputFormat='text'] - Output format ('text' or 'json'). MCP calls should use 'json'.
|
* @param {string} [outputFormat='text'] - Output format ('text' or 'json'). MCP calls should use 'json'.
|
||||||
* @returns {Promise<{success: boolean, expandedCount: number, failedCount: number, skippedCount: number, tasksToExpand: number, message?: string}>} - Result summary.
|
* @returns {Promise<{success: boolean, expandedCount: number, failedCount: number, skippedCount: number, tasksToExpand: number, telemetryData: Array<Object>}>} - Result summary.
|
||||||
*/
|
*/
|
||||||
async function expandAllTasks(
|
async function expandAllTasks(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
@@ -51,8 +58,8 @@ async function expandAllTasks(
|
|||||||
let loadingIndicator = null;
|
let loadingIndicator = null;
|
||||||
let expandedCount = 0;
|
let expandedCount = 0;
|
||||||
let failedCount = 0;
|
let failedCount = 0;
|
||||||
// No skipped count needed now as the filter handles it upfront
|
let tasksToExpandCount = 0;
|
||||||
let tasksToExpandCount = 0; // Renamed for clarity
|
const allTelemetryData = []; // Still collect individual data first
|
||||||
|
|
||||||
if (!isMCPCall && outputFormat === 'text') {
|
if (!isMCPCall && outputFormat === 'text') {
|
||||||
loadingIndicator = startLoadingIndicator(
|
loadingIndicator = startLoadingIndicator(
|
||||||
@@ -90,6 +97,7 @@ async function expandAllTasks(
|
|||||||
failedCount: 0,
|
failedCount: 0,
|
||||||
skippedCount: 0,
|
skippedCount: 0,
|
||||||
tasksToExpand: 0,
|
tasksToExpand: 0,
|
||||||
|
telemetryData: allTelemetryData,
|
||||||
message: 'No tasks eligible for expansion.'
|
message: 'No tasks eligible for expansion.'
|
||||||
};
|
};
|
||||||
// --- End Fix ---
|
// --- End Fix ---
|
||||||
@@ -97,19 +105,6 @@ async function expandAllTasks(
|
|||||||
|
|
||||||
// Iterate over the already filtered tasks
|
// Iterate over the already filtered tasks
|
||||||
for (const task of tasksToExpand) {
|
for (const task of tasksToExpand) {
|
||||||
// --- Remove Redundant Check ---
|
|
||||||
// The check below is no longer needed as the initial filter handles it
|
|
||||||
/*
|
|
||||||
if (task.subtasks && task.subtasks.length > 0 && !force) {
|
|
||||||
logger.info(
|
|
||||||
`Skipping task ${task.id}: Already has subtasks. Use --force to overwrite.`
|
|
||||||
);
|
|
||||||
skippedCount++;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
// --- End Removed Redundant Check ---
|
|
||||||
|
|
||||||
// Start indicator for individual task expansion in CLI mode
|
// Start indicator for individual task expansion in CLI mode
|
||||||
let taskIndicator = null;
|
let taskIndicator = null;
|
||||||
if (!isMCPCall && outputFormat === 'text') {
|
if (!isMCPCall && outputFormat === 'text') {
|
||||||
@@ -117,17 +112,23 @@ async function expandAllTasks(
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Call the refactored expandTask function
|
// Call the refactored expandTask function AND capture result
|
||||||
await expandTask(
|
const result = await expandTask(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
task.id,
|
task.id,
|
||||||
numSubtasks, // Pass numSubtasks, expandTask handles defaults/complexity
|
numSubtasks,
|
||||||
useResearch,
|
useResearch,
|
||||||
additionalContext,
|
additionalContext,
|
||||||
context, // Pass the whole context object { session, mcpLog }
|
context, // Pass the whole context object { session, mcpLog }
|
||||||
force // Pass the force flag down
|
force
|
||||||
);
|
);
|
||||||
expandedCount++;
|
expandedCount++;
|
||||||
|
|
||||||
|
// Collect individual telemetry data
|
||||||
|
if (result && result.telemetryData) {
|
||||||
|
allTelemetryData.push(result.telemetryData);
|
||||||
|
}
|
||||||
|
|
||||||
if (taskIndicator) {
|
if (taskIndicator) {
|
||||||
stopLoadingIndicator(taskIndicator, `Task ${task.id} expanded.`);
|
stopLoadingIndicator(taskIndicator, `Task ${task.id} expanded.`);
|
||||||
}
|
}
|
||||||
@@ -146,18 +147,48 @@ async function expandAllTasks(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log final summary (removed skipped count from message)
|
// --- AGGREGATION AND DISPLAY ---
|
||||||
logger.info(
|
logger.info(
|
||||||
`Expansion complete: ${expandedCount} expanded, ${failedCount} failed.`
|
`Expansion complete: ${expandedCount} expanded, ${failedCount} failed.`
|
||||||
);
|
);
|
||||||
|
|
||||||
// Return summary (skippedCount is now 0) - Add success: true here as well for consistency
|
// Aggregate the collected telemetry data
|
||||||
|
const aggregatedTelemetryData = aggregateTelemetry(
|
||||||
|
allTelemetryData,
|
||||||
|
'expand-all-tasks'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (outputFormat === 'text') {
|
||||||
|
const summaryContent =
|
||||||
|
`${chalk.white.bold('Expansion Summary:')}\n\n` +
|
||||||
|
`${chalk.cyan('-')} Attempted: ${chalk.bold(tasksToExpandCount)}\n` +
|
||||||
|
`${chalk.green('-')} Expanded: ${chalk.bold(expandedCount)}\n` +
|
||||||
|
// Skipped count is always 0 now due to pre-filtering
|
||||||
|
`${chalk.gray('-')} Skipped: ${chalk.bold(0)}\n` +
|
||||||
|
`${chalk.red('-')} Failed: ${chalk.bold(failedCount)}`;
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
boxen(summaryContent, {
|
||||||
|
padding: 1,
|
||||||
|
margin: { top: 1 },
|
||||||
|
borderColor: failedCount > 0 ? 'red' : 'green', // Red if failures, green otherwise
|
||||||
|
borderStyle: 'round'
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (outputFormat === 'text' && aggregatedTelemetryData) {
|
||||||
|
displayAiUsageSummary(aggregatedTelemetryData, 'cli');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return summary including the AGGREGATED telemetry data
|
||||||
return {
|
return {
|
||||||
success: true, // Indicate overall success
|
success: true,
|
||||||
expandedCount,
|
expandedCount,
|
||||||
failedCount,
|
failedCount,
|
||||||
skippedCount: 0,
|
skippedCount: 0,
|
||||||
tasksToExpand: tasksToExpandCount
|
tasksToExpand: tasksToExpandCount,
|
||||||
|
telemetryData: aggregatedTelemetryData
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (loadingIndicator)
|
if (loadingIndicator)
|
||||||
|
|||||||
@@ -4,7 +4,11 @@ import { z } from 'zod';
|
|||||||
|
|
||||||
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
|
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
|
||||||
|
|
||||||
import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
|
import {
|
||||||
|
startLoadingIndicator,
|
||||||
|
stopLoadingIndicator,
|
||||||
|
displayAiUsageSummary
|
||||||
|
} from '../ui.js';
|
||||||
|
|
||||||
import { generateTextService } from '../ai-services-unified.js';
|
import { generateTextService } from '../ai-services-unified.js';
|
||||||
|
|
||||||
@@ -142,7 +146,7 @@ function generateResearchUserPrompt(
|
|||||||
"id": <number>, // Sequential ID starting from ${nextSubtaskId}
|
"id": <number>, // Sequential ID starting from ${nextSubtaskId}
|
||||||
"title": "<string>",
|
"title": "<string>",
|
||||||
"description": "<string>",
|
"description": "<string>",
|
||||||
"dependencies": [<number>], // e.g., [${nextSubtaskId + 1}]
|
"dependencies": [<number>], // e.g., [${nextSubtaskId + 1}]. If no dependencies, use an empty array [].
|
||||||
"details": "<string>",
|
"details": "<string>",
|
||||||
"testStrategy": "<string>" // Optional
|
"testStrategy": "<string>" // Optional
|
||||||
},
|
},
|
||||||
@@ -162,6 +166,8 @@ ${contextPrompt}
|
|||||||
CRITICAL: Respond ONLY with a valid JSON object containing a single key "subtasks". The value must be an array of the generated subtasks, strictly matching this structure:
|
CRITICAL: Respond ONLY with a valid JSON object containing a single key "subtasks". The value must be an array of the generated subtasks, strictly matching this structure:
|
||||||
${schemaDescription}
|
${schemaDescription}
|
||||||
|
|
||||||
|
Important: For the 'dependencies' field, if a subtask has no dependencies, you MUST use an empty array, for example: "dependencies": []. Do not use null or omit the field.
|
||||||
|
|
||||||
Do not include ANY explanatory text, markdown, or code block markers. Just the JSON object.`;
|
Do not include ANY explanatory text, markdown, or code block markers. Just the JSON object.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,77 +188,153 @@ function parseSubtasksFromText(
|
|||||||
parentTaskId,
|
parentTaskId,
|
||||||
logger
|
logger
|
||||||
) {
|
) {
|
||||||
logger.info('Attempting to parse subtasks object from text response...');
|
if (typeof text !== 'string') {
|
||||||
if (!text || text.trim() === '') {
|
logger.error(
|
||||||
throw new Error('AI response text is empty.');
|
`AI response text is not a string. Received type: ${typeof text}, Value: ${text}`
|
||||||
|
);
|
||||||
|
throw new Error('AI response text is not a string.');
|
||||||
}
|
}
|
||||||
|
|
||||||
let cleanedResponse = text.trim();
|
if (!text || text.trim() === '') {
|
||||||
const originalResponseForDebug = cleanedResponse;
|
throw new Error('AI response text is empty after trimming.');
|
||||||
|
}
|
||||||
|
|
||||||
// 1. Extract from Markdown code block first
|
const originalTrimmedResponse = text.trim(); // Store the original trimmed response
|
||||||
const codeBlockMatch = cleanedResponse.match(
|
let jsonToParse = originalTrimmedResponse; // Initialize jsonToParse with it
|
||||||
/```(?:json)?\s*([\s\S]*?)\s*```/
|
|
||||||
|
logger.debug(
|
||||||
|
`Original AI Response for parsing (full length: ${jsonToParse.length}): ${jsonToParse.substring(0, 1000)}...`
|
||||||
);
|
);
|
||||||
if (codeBlockMatch) {
|
|
||||||
cleanedResponse = codeBlockMatch[1].trim();
|
// --- Pre-emptive cleanup for known AI JSON issues ---
|
||||||
logger.info('Extracted JSON content from Markdown code block.');
|
// Fix for "dependencies": , or "dependencies":,
|
||||||
} else {
|
if (jsonToParse.includes('"dependencies":')) {
|
||||||
// 2. If no code block, find first '{' and last '}' for the object
|
const malformedPattern = /"dependencies":\s*,/g;
|
||||||
const firstBrace = cleanedResponse.indexOf('{');
|
if (malformedPattern.test(jsonToParse)) {
|
||||||
const lastBrace = cleanedResponse.lastIndexOf('}');
|
logger.warn('Attempting to fix malformed "dependencies": , issue.');
|
||||||
if (firstBrace !== -1 && lastBrace > firstBrace) {
|
jsonToParse = jsonToParse.replace(
|
||||||
cleanedResponse = cleanedResponse.substring(firstBrace, lastBrace + 1);
|
malformedPattern,
|
||||||
logger.info('Extracted content between first { and last }.');
|
'"dependencies": [],'
|
||||||
|
);
|
||||||
|
logger.debug(
|
||||||
|
`JSON after fixing "dependencies": ${jsonToParse.substring(0, 500)}...`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// --- End pre-emptive cleanup ---
|
||||||
|
|
||||||
|
let parsedObject;
|
||||||
|
let primaryParseAttemptFailed = false;
|
||||||
|
|
||||||
|
// --- Attempt 1: Simple Parse (with optional Markdown cleanup) ---
|
||||||
|
logger.debug('Attempting simple parse...');
|
||||||
|
try {
|
||||||
|
// Check for markdown code block
|
||||||
|
const codeBlockMatch = jsonToParse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
|
||||||
|
let contentToParseDirectly = jsonToParse;
|
||||||
|
if (codeBlockMatch && codeBlockMatch[1]) {
|
||||||
|
contentToParseDirectly = codeBlockMatch[1].trim();
|
||||||
|
logger.debug('Simple parse: Extracted content from markdown code block.');
|
||||||
} else {
|
} else {
|
||||||
|
logger.debug(
|
||||||
|
'Simple parse: No markdown code block found, using trimmed original.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedObject = JSON.parse(contentToParseDirectly);
|
||||||
|
logger.debug('Simple parse successful!');
|
||||||
|
|
||||||
|
// Quick check if it looks like our target object
|
||||||
|
if (
|
||||||
|
!parsedObject ||
|
||||||
|
typeof parsedObject !== 'object' ||
|
||||||
|
!Array.isArray(parsedObject.subtasks)
|
||||||
|
) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
'Response does not appear to contain a JSON object structure. Parsing raw response.'
|
'Simple parse succeeded, but result is not the expected {"subtasks": []} structure. Will proceed to advanced extraction.'
|
||||||
|
);
|
||||||
|
primaryParseAttemptFailed = true;
|
||||||
|
parsedObject = null; // Reset parsedObject so we enter the advanced logic
|
||||||
|
}
|
||||||
|
// If it IS the correct structure, we'll skip advanced extraction.
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn(
|
||||||
|
`Simple parse failed: ${e.message}. Proceeding to advanced extraction logic.`
|
||||||
|
);
|
||||||
|
primaryParseAttemptFailed = true;
|
||||||
|
// jsonToParse is already originalTrimmedResponse if simple parse failed before modifying it for markdown
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Attempt 2: Advanced Extraction (if simple parse failed or produced wrong structure) ---
|
||||||
|
if (primaryParseAttemptFailed || !parsedObject) {
|
||||||
|
// Ensure we try advanced if simple parse gave wrong structure
|
||||||
|
logger.debug('Attempting advanced extraction logic...');
|
||||||
|
// Reset jsonToParse to the original full trimmed response for advanced logic
|
||||||
|
jsonToParse = originalTrimmedResponse;
|
||||||
|
|
||||||
|
// (Insert the more complex extraction logic here - the one we worked on with:
|
||||||
|
// - targetPattern = '{"subtasks":';
|
||||||
|
// - careful brace counting for that targetPattern
|
||||||
|
// - fallbacks to last '{' and '}' if targetPattern logic fails)
|
||||||
|
// This was the logic from my previous message. Let's assume it's here.
|
||||||
|
// This block should ultimately set `jsonToParse` to the best candidate string.
|
||||||
|
|
||||||
|
// Example snippet of that advanced logic's start:
|
||||||
|
const targetPattern = '{"subtasks":';
|
||||||
|
const patternStartIndex = jsonToParse.indexOf(targetPattern);
|
||||||
|
|
||||||
|
if (patternStartIndex !== -1) {
|
||||||
|
let openBraces = 0;
|
||||||
|
let firstBraceFound = false;
|
||||||
|
let extractedJsonBlock = '';
|
||||||
|
// ... (loop for brace counting as before) ...
|
||||||
|
// ... (if successful, jsonToParse = extractedJsonBlock) ...
|
||||||
|
// ... (if that fails, fallbacks as before) ...
|
||||||
|
} else {
|
||||||
|
// ... (fallback to last '{' and '}' if targetPattern not found) ...
|
||||||
|
}
|
||||||
|
// End of advanced logic excerpt
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
`Advanced extraction: JSON string that will be parsed: ${jsonToParse.substring(0, 500)}...`
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
parsedObject = JSON.parse(jsonToParse);
|
||||||
|
logger.debug('Advanced extraction parse successful!');
|
||||||
|
} catch (parseError) {
|
||||||
|
logger.error(
|
||||||
|
`Advanced extraction: Failed to parse JSON object: ${parseError.message}`
|
||||||
|
);
|
||||||
|
logger.error(
|
||||||
|
`Advanced extraction: Problematic JSON string for parse (first 500 chars): ${jsonToParse.substring(0, 500)}`
|
||||||
|
);
|
||||||
|
throw new Error( // Re-throw a more specific error if advanced also fails
|
||||||
|
`Failed to parse JSON response object after both simple and advanced attempts: ${parseError.message}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Attempt to parse the object
|
// --- Validation (applies to successfully parsedObject from either attempt) ---
|
||||||
let parsedObject;
|
|
||||||
try {
|
|
||||||
parsedObject = JSON.parse(cleanedResponse);
|
|
||||||
} catch (parseError) {
|
|
||||||
logger.error(`Failed to parse JSON object: ${parseError.message}`);
|
|
||||||
logger.error(
|
|
||||||
`Problematic JSON string (first 500 chars): ${cleanedResponse.substring(0, 500)}`
|
|
||||||
);
|
|
||||||
logger.error(
|
|
||||||
`Original Raw Response (first 500 chars): ${originalResponseForDebug.substring(0, 500)}`
|
|
||||||
);
|
|
||||||
throw new Error(
|
|
||||||
`Failed to parse JSON response object: ${parseError.message}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Validate the object structure and extract the subtasks array
|
|
||||||
if (
|
if (
|
||||||
!parsedObject ||
|
!parsedObject ||
|
||||||
typeof parsedObject !== 'object' ||
|
typeof parsedObject !== 'object' ||
|
||||||
!Array.isArray(parsedObject.subtasks)
|
!Array.isArray(parsedObject.subtasks)
|
||||||
) {
|
) {
|
||||||
logger.error(
|
logger.error(
|
||||||
`Parsed content is not an object or missing 'subtasks' array. Content: ${JSON.stringify(parsedObject).substring(0, 200)}`
|
`Final parsed content is not an object or missing 'subtasks' array. Content: ${JSON.stringify(parsedObject).substring(0, 200)}`
|
||||||
);
|
);
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'Parsed AI response is not a valid object containing a "subtasks" array.'
|
'Parsed AI response is not a valid object containing a "subtasks" array after all attempts.'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const parsedSubtasks = parsedObject.subtasks; // Extract the array
|
const parsedSubtasks = parsedObject.subtasks;
|
||||||
|
|
||||||
logger.info(
|
|
||||||
`Successfully parsed ${parsedSubtasks.length} potential subtasks from the object.`
|
|
||||||
);
|
|
||||||
if (expectedCount && parsedSubtasks.length !== expectedCount) {
|
if (expectedCount && parsedSubtasks.length !== expectedCount) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
`Expected ${expectedCount} subtasks, but parsed ${parsedSubtasks.length}.`
|
`Expected ${expectedCount} subtasks, but parsed ${parsedSubtasks.length}.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Validate and Normalize each subtask using Zod schema
|
|
||||||
let currentId = startId;
|
let currentId = startId;
|
||||||
const validatedSubtasks = [];
|
const validatedSubtasks = [];
|
||||||
const validationErrors = [];
|
const validationErrors = [];
|
||||||
@@ -260,22 +342,21 @@ function parseSubtasksFromText(
|
|||||||
for (const rawSubtask of parsedSubtasks) {
|
for (const rawSubtask of parsedSubtasks) {
|
||||||
const correctedSubtask = {
|
const correctedSubtask = {
|
||||||
...rawSubtask,
|
...rawSubtask,
|
||||||
id: currentId, // Enforce sequential ID
|
id: currentId,
|
||||||
dependencies: Array.isArray(rawSubtask.dependencies)
|
dependencies: Array.isArray(rawSubtask.dependencies)
|
||||||
? rawSubtask.dependencies
|
? rawSubtask.dependencies
|
||||||
.map((dep) => (typeof dep === 'string' ? parseInt(dep, 10) : dep))
|
.map((dep) => (typeof dep === 'string' ? parseInt(dep, 10) : dep))
|
||||||
.filter(
|
.filter(
|
||||||
(depId) => !isNaN(depId) && depId >= startId && depId < currentId
|
(depId) => !isNaN(depId) && depId >= startId && depId < currentId
|
||||||
) // Ensure deps are numbers, valid range
|
)
|
||||||
: [],
|
: [],
|
||||||
status: 'pending' // Enforce pending status
|
status: 'pending'
|
||||||
// parentTaskId can be added if needed: parentTaskId: parentTaskId
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = subtaskSchema.safeParse(correctedSubtask);
|
const result = subtaskSchema.safeParse(correctedSubtask);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
validatedSubtasks.push(result.data); // Add the validated data
|
validatedSubtasks.push(result.data);
|
||||||
} else {
|
} else {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
`Subtask validation failed for raw data: ${JSON.stringify(rawSubtask).substring(0, 100)}...`
|
`Subtask validation failed for raw data: ${JSON.stringify(rawSubtask).substring(0, 100)}...`
|
||||||
@@ -285,18 +366,14 @@ function parseSubtasksFromText(
|
|||||||
logger.warn(errorMessage);
|
logger.warn(errorMessage);
|
||||||
validationErrors.push(`Subtask ${currentId}: ${errorMessage}`);
|
validationErrors.push(`Subtask ${currentId}: ${errorMessage}`);
|
||||||
});
|
});
|
||||||
// Optionally, decide whether to include partially valid tasks or skip them
|
|
||||||
// For now, we'll skip invalid ones
|
|
||||||
}
|
}
|
||||||
currentId++; // Increment ID for the next *potential* subtask
|
currentId++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (validationErrors.length > 0) {
|
if (validationErrors.length > 0) {
|
||||||
logger.error(
|
logger.error(
|
||||||
`Found ${validationErrors.length} validation errors in the generated subtasks.`
|
`Found ${validationErrors.length} validation errors in the generated subtasks.`
|
||||||
);
|
);
|
||||||
// Optionally throw an error here if strict validation is required
|
|
||||||
// throw new Error(`Subtask validation failed:\n${validationErrors.join('\n')}`);
|
|
||||||
logger.warn('Proceeding with only the successfully validated subtasks.');
|
logger.warn('Proceeding with only the successfully validated subtasks.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,8 +382,6 @@ function parseSubtasksFromText(
|
|||||||
'AI response contained potential subtasks, but none passed validation.'
|
'AI response contained potential subtasks, but none passed validation.'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure we don't return more than expected, preferring validated ones
|
|
||||||
return validatedSubtasks.slice(0, expectedCount || validatedSubtasks.length);
|
return validatedSubtasks.slice(0, expectedCount || validatedSubtasks.length);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -336,9 +411,13 @@ async function expandTask(
|
|||||||
context = {},
|
context = {},
|
||||||
force = false
|
force = false
|
||||||
) {
|
) {
|
||||||
const { session, mcpLog } = context;
|
const { session, mcpLog, projectRoot: contextProjectRoot } = context;
|
||||||
const outputFormat = mcpLog ? 'json' : 'text';
|
const outputFormat = mcpLog ? 'json' : 'text';
|
||||||
|
|
||||||
|
// Determine projectRoot: Use from context if available, otherwise derive from tasksPath
|
||||||
|
const projectRoot =
|
||||||
|
contextProjectRoot || path.dirname(path.dirname(tasksPath));
|
||||||
|
|
||||||
// Use mcpLog if available, otherwise use the default console log wrapper
|
// Use mcpLog if available, otherwise use the default console log wrapper
|
||||||
const logger = mcpLog || {
|
const logger = mcpLog || {
|
||||||
info: (msg) => !isSilentMode() && log('info', msg),
|
info: (msg) => !isSilentMode() && log('info', msg),
|
||||||
@@ -363,7 +442,9 @@ async function expandTask(
|
|||||||
);
|
);
|
||||||
if (taskIndex === -1) throw new Error(`Task ${taskId} not found`);
|
if (taskIndex === -1) throw new Error(`Task ${taskId} not found`);
|
||||||
const task = data.tasks[taskIndex];
|
const task = data.tasks[taskIndex];
|
||||||
logger.info(`Expanding task ${taskId}: ${task.title}`);
|
logger.info(
|
||||||
|
`Expanding task ${taskId}: ${task.title}${useResearch ? ' with research' : ''}`
|
||||||
|
);
|
||||||
// --- End Task Loading/Filtering ---
|
// --- End Task Loading/Filtering ---
|
||||||
|
|
||||||
// --- Handle Force Flag: Clear existing subtasks if force=true ---
|
// --- Handle Force Flag: Clear existing subtasks if force=true ---
|
||||||
@@ -381,7 +462,6 @@ async function expandTask(
|
|||||||
let complexityReasoningContext = '';
|
let complexityReasoningContext = '';
|
||||||
let systemPrompt; // Declare systemPrompt here
|
let systemPrompt; // Declare systemPrompt here
|
||||||
|
|
||||||
const projectRoot = path.dirname(path.dirname(tasksPath));
|
|
||||||
const complexityReportPath = path.join(
|
const complexityReportPath = path.join(
|
||||||
projectRoot,
|
projectRoot,
|
||||||
'scripts/task-complexity-report.json'
|
'scripts/task-complexity-report.json'
|
||||||
@@ -488,28 +568,27 @@ async function expandTask(
|
|||||||
let loadingIndicator = null;
|
let loadingIndicator = null;
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
loadingIndicator = startLoadingIndicator(
|
loadingIndicator = startLoadingIndicator(
|
||||||
`Generating ${finalSubtaskCount} subtasks...`
|
`Generating ${finalSubtaskCount} subtasks...\n`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let responseText = '';
|
let responseText = '';
|
||||||
|
let aiServiceResponse = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const role = useResearch ? 'research' : 'main';
|
const role = useResearch ? 'research' : 'main';
|
||||||
logger.info(`Using AI service with role: ${role}`);
|
|
||||||
|
|
||||||
// Call generateTextService with the determined prompts
|
// Call generateTextService with the determined prompts and telemetry params
|
||||||
responseText = await generateTextService({
|
aiServiceResponse = await generateTextService({
|
||||||
prompt: promptContent,
|
prompt: promptContent,
|
||||||
systemPrompt: systemPrompt, // Use the determined system prompt
|
systemPrompt: systemPrompt,
|
||||||
role,
|
role,
|
||||||
session,
|
session,
|
||||||
projectRoot
|
projectRoot,
|
||||||
|
commandName: 'expand-task',
|
||||||
|
outputType: outputFormat
|
||||||
});
|
});
|
||||||
logger.info(
|
responseText = aiServiceResponse.mainResult;
|
||||||
'Successfully received text response from AI service',
|
|
||||||
'success'
|
|
||||||
);
|
|
||||||
|
|
||||||
// Parse Subtasks
|
// Parse Subtasks
|
||||||
generatedSubtasks = parseSubtasksFromText(
|
generatedSubtasks = parseSubtasksFromText(
|
||||||
@@ -550,14 +629,23 @@ async function expandTask(
|
|||||||
// --- End Change: Append instead of replace ---
|
// --- End Change: Append instead of replace ---
|
||||||
|
|
||||||
data.tasks[taskIndex] = task; // Assign the modified task back
|
data.tasks[taskIndex] = task; // Assign the modified task back
|
||||||
logger.info(`Writing updated tasks to ${tasksPath}`);
|
|
||||||
writeJSON(tasksPath, data);
|
writeJSON(tasksPath, data);
|
||||||
logger.info(`Generating individual task files...`);
|
|
||||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||||
logger.info(`Task files generated.`);
|
|
||||||
// --- End Task Update & File Writing ---
|
|
||||||
|
|
||||||
return task; // Return the updated task object
|
// Display AI Usage Summary for CLI
|
||||||
|
if (
|
||||||
|
outputFormat === 'text' &&
|
||||||
|
aiServiceResponse &&
|
||||||
|
aiServiceResponse.telemetryData
|
||||||
|
) {
|
||||||
|
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the updated task object AND telemetry data
|
||||||
|
return {
|
||||||
|
task,
|
||||||
|
telemetryData: aiServiceResponse?.telemetryData
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catches errors from file reading, parsing, AI call etc.
|
// Catches errors from file reading, parsing, AI call etc.
|
||||||
logger.error(`Error expanding task ${taskId}: ${error.message}`, 'error');
|
logger.error(`Error expanding task ${taskId}: ${error.message}`, 'error');
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
import { log } from '../utils.js';
|
||||||
|
import { addComplexityToTask } from '../utils.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return the next work item:
|
* Return the next work item:
|
||||||
* • Prefer an eligible SUBTASK that belongs to any parent task
|
* • Prefer an eligible SUBTASK that belongs to any parent task
|
||||||
@@ -15,9 +18,10 @@
|
|||||||
* ─ parentId → number (present only when it's a subtask)
|
* ─ parentId → number (present only when it's a subtask)
|
||||||
*
|
*
|
||||||
* @param {Object[]} tasks – full array of top-level tasks, each may contain .subtasks[]
|
* @param {Object[]} tasks – full array of top-level tasks, each may contain .subtasks[]
|
||||||
|
* @param {Object} [complexityReport=null] - Optional complexity report object
|
||||||
* @returns {Object|null} – next work item or null if nothing is eligible
|
* @returns {Object|null} – next work item or null if nothing is eligible
|
||||||
*/
|
*/
|
||||||
function findNextTask(tasks) {
|
function findNextTask(tasks, complexityReport = null) {
|
||||||
// ---------- helpers ----------------------------------------------------
|
// ---------- helpers ----------------------------------------------------
|
||||||
const priorityValues = { high: 3, medium: 2, low: 1 };
|
const priorityValues = { high: 3, medium: 2, low: 1 };
|
||||||
|
|
||||||
@@ -91,7 +95,14 @@ function findNextTask(tasks) {
|
|||||||
if (aPar !== bPar) return aPar - bPar;
|
if (aPar !== bPar) return aPar - bPar;
|
||||||
return aSub - bSub;
|
return aSub - bSub;
|
||||||
});
|
});
|
||||||
return candidateSubtasks[0];
|
const nextTask = candidateSubtasks[0];
|
||||||
|
|
||||||
|
// Add complexity to the task before returning
|
||||||
|
if (nextTask && complexityReport) {
|
||||||
|
addComplexityToTask(nextTask, complexityReport);
|
||||||
|
}
|
||||||
|
|
||||||
|
return nextTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 2) fall back to top-level tasks (original logic) ------------
|
// ---------- 2) fall back to top-level tasks (original logic) ------------
|
||||||
@@ -116,6 +127,11 @@ function findNextTask(tasks) {
|
|||||||
return a.id - b.id;
|
return a.id - b.id;
|
||||||
})[0];
|
})[0];
|
||||||
|
|
||||||
|
// Add complexity to the task before returning
|
||||||
|
if (nextTask && complexityReport) {
|
||||||
|
addComplexityToTask(nextTask, complexityReport);
|
||||||
|
}
|
||||||
|
|
||||||
return nextTask;
|
return nextTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,8 +19,6 @@ function generateTaskFiles(tasksPath, outputDir, options = {}) {
|
|||||||
// Determine if we're in MCP mode by checking for mcpLog
|
// Determine if we're in MCP mode by checking for mcpLog
|
||||||
const isMcpMode = !!options?.mcpLog;
|
const isMcpMode = !!options?.mcpLog;
|
||||||
|
|
||||||
log('info', `Preparing to regenerate task files in ${tasksPath}`);
|
|
||||||
|
|
||||||
const data = readJSON(tasksPath);
|
const data = readJSON(tasksPath);
|
||||||
if (!data || !data.tasks) {
|
if (!data || !data.tasks) {
|
||||||
throw new Error(`No valid tasks found in ${tasksPath}`);
|
throw new Error(`No valid tasks found in ${tasksPath}`);
|
||||||
@@ -31,12 +29,59 @@ function generateTaskFiles(tasksPath, outputDir, options = {}) {
|
|||||||
fs.mkdirSync(outputDir, { recursive: true });
|
fs.mkdirSync(outputDir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
log('info', `Found ${data.tasks.length} tasks to regenerate`);
|
log('info', `Preparing to regenerate ${data.tasks.length} task files`);
|
||||||
|
|
||||||
// Validate and fix dependencies before generating files
|
// Validate and fix dependencies before generating files
|
||||||
log('info', `Validating and fixing dependencies`);
|
log('info', `Validating and fixing dependencies`);
|
||||||
validateAndFixDependencies(data, tasksPath);
|
validateAndFixDependencies(data, tasksPath);
|
||||||
|
|
||||||
|
// Get valid task IDs from tasks.json
|
||||||
|
const validTaskIds = data.tasks.map((task) => task.id);
|
||||||
|
|
||||||
|
// Cleanup orphaned task files
|
||||||
|
log('info', 'Checking for orphaned task files to clean up...');
|
||||||
|
try {
|
||||||
|
// Get all task files in the output directory
|
||||||
|
const files = fs.readdirSync(outputDir);
|
||||||
|
const taskFilePattern = /^task_(\d+)\.txt$/;
|
||||||
|
|
||||||
|
// Filter for task files and check if they match a valid task ID
|
||||||
|
const orphanedFiles = files.filter((file) => {
|
||||||
|
const match = file.match(taskFilePattern);
|
||||||
|
if (match) {
|
||||||
|
const fileTaskId = parseInt(match[1], 10);
|
||||||
|
return !validTaskIds.includes(fileTaskId);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete orphaned files
|
||||||
|
if (orphanedFiles.length > 0) {
|
||||||
|
log(
|
||||||
|
'info',
|
||||||
|
`Found ${orphanedFiles.length} orphaned task files to remove`
|
||||||
|
);
|
||||||
|
|
||||||
|
orphanedFiles.forEach((file) => {
|
||||||
|
const filePath = path.join(outputDir, file);
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(filePath);
|
||||||
|
log('info', `Removed orphaned task file: ${file}`);
|
||||||
|
} catch (err) {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
`Failed to remove orphaned task file ${file}: ${err.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
log('info', 'No orphaned task files found');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
log('warn', `Error cleaning up orphaned task files: ${err.message}`);
|
||||||
|
// Continue with file generation even if cleanup fails
|
||||||
|
}
|
||||||
|
|
||||||
// Generate task files
|
// Generate task files
|
||||||
log('info', 'Generating individual task files...');
|
log('info', 'Generating individual task files...');
|
||||||
data.tasks.forEach((task) => {
|
data.tasks.forEach((task) => {
|
||||||
|
|||||||
@@ -2,13 +2,20 @@ import chalk from 'chalk';
|
|||||||
import boxen from 'boxen';
|
import boxen from 'boxen';
|
||||||
import Table from 'cli-table3';
|
import Table from 'cli-table3';
|
||||||
|
|
||||||
import { log, readJSON, truncate } from '../utils.js';
|
import {
|
||||||
|
log,
|
||||||
|
readJSON,
|
||||||
|
truncate,
|
||||||
|
readComplexityReport,
|
||||||
|
addComplexityToTask
|
||||||
|
} from '../utils.js';
|
||||||
import findNextTask from './find-next-task.js';
|
import findNextTask from './find-next-task.js';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
displayBanner,
|
displayBanner,
|
||||||
getStatusWithColor,
|
getStatusWithColor,
|
||||||
formatDependenciesWithStatus,
|
formatDependenciesWithStatus,
|
||||||
|
getComplexityWithColor,
|
||||||
createProgressBar
|
createProgressBar
|
||||||
} from '../ui.js';
|
} from '../ui.js';
|
||||||
|
|
||||||
@@ -16,6 +23,7 @@ import {
|
|||||||
* List all tasks
|
* List all tasks
|
||||||
* @param {string} tasksPath - Path to the tasks.json file
|
* @param {string} tasksPath - Path to the tasks.json file
|
||||||
* @param {string} statusFilter - Filter by status
|
* @param {string} statusFilter - Filter by status
|
||||||
|
* @param {string} reportPath - Path to the complexity report
|
||||||
* @param {boolean} withSubtasks - Whether to show subtasks
|
* @param {boolean} withSubtasks - Whether to show subtasks
|
||||||
* @param {string} outputFormat - Output format (text or json)
|
* @param {string} outputFormat - Output format (text or json)
|
||||||
* @returns {Object} - Task list result for json format
|
* @returns {Object} - Task list result for json format
|
||||||
@@ -23,6 +31,7 @@ import {
|
|||||||
function listTasks(
|
function listTasks(
|
||||||
tasksPath,
|
tasksPath,
|
||||||
statusFilter,
|
statusFilter,
|
||||||
|
reportPath = null,
|
||||||
withSubtasks = false,
|
withSubtasks = false,
|
||||||
outputFormat = 'text'
|
outputFormat = 'text'
|
||||||
) {
|
) {
|
||||||
@@ -37,6 +46,13 @@ function listTasks(
|
|||||||
throw new Error(`No valid tasks found in ${tasksPath}`);
|
throw new Error(`No valid tasks found in ${tasksPath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add complexity scores to tasks if report exists
|
||||||
|
const complexityReport = readComplexityReport(reportPath);
|
||||||
|
// Apply complexity scores to tasks
|
||||||
|
if (complexityReport && complexityReport.complexityAnalysis) {
|
||||||
|
data.tasks.forEach((task) => addComplexityToTask(task, complexityReport));
|
||||||
|
}
|
||||||
|
|
||||||
// Filter tasks by status if specified
|
// Filter tasks by status if specified
|
||||||
const filteredTasks =
|
const filteredTasks =
|
||||||
statusFilter && statusFilter.toLowerCase() !== 'all' // <-- Added check for 'all'
|
statusFilter && statusFilter.toLowerCase() !== 'all' // <-- Added check for 'all'
|
||||||
@@ -257,8 +273,8 @@ function listTasks(
|
|||||||
);
|
);
|
||||||
const avgDependenciesPerTask = totalDependencies / data.tasks.length;
|
const avgDependenciesPerTask = totalDependencies / data.tasks.length;
|
||||||
|
|
||||||
// Find next task to work on
|
// Find next task to work on, passing the complexity report
|
||||||
const nextItem = findNextTask(data.tasks);
|
const nextItem = findNextTask(data.tasks, complexityReport);
|
||||||
|
|
||||||
// Get terminal width - more reliable method
|
// Get terminal width - more reliable method
|
||||||
let terminalWidth;
|
let terminalWidth;
|
||||||
@@ -301,8 +317,11 @@ function listTasks(
|
|||||||
`${chalk.blue('•')} ${chalk.white('Avg dependencies per task:')} ${avgDependenciesPerTask.toFixed(1)}\n\n` +
|
`${chalk.blue('•')} ${chalk.white('Avg dependencies per task:')} ${avgDependenciesPerTask.toFixed(1)}\n\n` +
|
||||||
chalk.cyan.bold('Next Task to Work On:') +
|
chalk.cyan.bold('Next Task to Work On:') +
|
||||||
'\n' +
|
'\n' +
|
||||||
`ID: ${chalk.cyan(nextItem ? nextItem.id : 'N/A')} - ${nextItem ? chalk.white.bold(truncate(nextItem.title, 40)) : chalk.yellow('No task available')}\n` +
|
`ID: ${chalk.cyan(nextItem ? nextItem.id : 'N/A')} - ${nextItem ? chalk.white.bold(truncate(nextItem.title, 40)) : chalk.yellow('No task available')}
|
||||||
`Priority: ${nextItem ? chalk.white(nextItem.priority || 'medium') : ''} Dependencies: ${nextItem ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true) : ''}`;
|
` +
|
||||||
|
`Priority: ${nextItem ? chalk.white(nextItem.priority || 'medium') : ''} Dependencies: ${nextItem ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true, complexityReport) : ''}
|
||||||
|
` +
|
||||||
|
`Complexity: ${nextItem && nextItem.complexityScore ? getComplexityWithColor(nextItem.complexityScore) : chalk.gray('N/A')}`;
|
||||||
|
|
||||||
// Calculate width for side-by-side display
|
// Calculate width for side-by-side display
|
||||||
// Box borders, padding take approximately 4 chars on each side
|
// Box borders, padding take approximately 4 chars on each side
|
||||||
@@ -412,9 +431,16 @@ function listTasks(
|
|||||||
// Make dependencies column smaller as requested (-20%)
|
// Make dependencies column smaller as requested (-20%)
|
||||||
const depsWidthPct = 20;
|
const depsWidthPct = 20;
|
||||||
|
|
||||||
|
const complexityWidthPct = 10;
|
||||||
|
|
||||||
// Calculate title/description width as remaining space (+20% from dependencies reduction)
|
// Calculate title/description width as remaining space (+20% from dependencies reduction)
|
||||||
const titleWidthPct =
|
const titleWidthPct =
|
||||||
100 - idWidthPct - statusWidthPct - priorityWidthPct - depsWidthPct;
|
100 -
|
||||||
|
idWidthPct -
|
||||||
|
statusWidthPct -
|
||||||
|
priorityWidthPct -
|
||||||
|
depsWidthPct -
|
||||||
|
complexityWidthPct;
|
||||||
|
|
||||||
// Allow 10 characters for borders and padding
|
// Allow 10 characters for borders and padding
|
||||||
const availableWidth = terminalWidth - 10;
|
const availableWidth = terminalWidth - 10;
|
||||||
@@ -424,6 +450,9 @@ function listTasks(
|
|||||||
const statusWidth = Math.floor(availableWidth * (statusWidthPct / 100));
|
const statusWidth = Math.floor(availableWidth * (statusWidthPct / 100));
|
||||||
const priorityWidth = Math.floor(availableWidth * (priorityWidthPct / 100));
|
const priorityWidth = Math.floor(availableWidth * (priorityWidthPct / 100));
|
||||||
const depsWidth = Math.floor(availableWidth * (depsWidthPct / 100));
|
const depsWidth = Math.floor(availableWidth * (depsWidthPct / 100));
|
||||||
|
const complexityWidth = Math.floor(
|
||||||
|
availableWidth * (complexityWidthPct / 100)
|
||||||
|
);
|
||||||
const titleWidth = Math.floor(availableWidth * (titleWidthPct / 100));
|
const titleWidth = Math.floor(availableWidth * (titleWidthPct / 100));
|
||||||
|
|
||||||
// Create a table with correct borders and spacing
|
// Create a table with correct borders and spacing
|
||||||
@@ -433,9 +462,17 @@ function listTasks(
|
|||||||
chalk.cyan.bold('Title'),
|
chalk.cyan.bold('Title'),
|
||||||
chalk.cyan.bold('Status'),
|
chalk.cyan.bold('Status'),
|
||||||
chalk.cyan.bold('Priority'),
|
chalk.cyan.bold('Priority'),
|
||||||
chalk.cyan.bold('Dependencies')
|
chalk.cyan.bold('Dependencies'),
|
||||||
|
chalk.cyan.bold('Complexity')
|
||||||
|
],
|
||||||
|
colWidths: [
|
||||||
|
idWidth,
|
||||||
|
titleWidth,
|
||||||
|
statusWidth,
|
||||||
|
priorityWidth,
|
||||||
|
depsWidth,
|
||||||
|
complexityWidth // Added complexity column width
|
||||||
],
|
],
|
||||||
colWidths: [idWidth, titleWidth, statusWidth, priorityWidth, depsWidth],
|
|
||||||
style: {
|
style: {
|
||||||
head: [], // No special styling for header
|
head: [], // No special styling for header
|
||||||
border: [], // No special styling for border
|
border: [], // No special styling for border
|
||||||
@@ -454,7 +491,8 @@ function listTasks(
|
|||||||
depText = formatDependenciesWithStatus(
|
depText = formatDependenciesWithStatus(
|
||||||
task.dependencies,
|
task.dependencies,
|
||||||
data.tasks,
|
data.tasks,
|
||||||
true
|
true,
|
||||||
|
complexityReport
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
depText = chalk.gray('None');
|
depText = chalk.gray('None');
|
||||||
@@ -480,7 +518,10 @@ function listTasks(
|
|||||||
truncate(cleanTitle, titleWidth - 3),
|
truncate(cleanTitle, titleWidth - 3),
|
||||||
status,
|
status,
|
||||||
priorityColor(truncate(task.priority || 'medium', priorityWidth - 2)),
|
priorityColor(truncate(task.priority || 'medium', priorityWidth - 2)),
|
||||||
depText // No truncation for dependencies
|
depText,
|
||||||
|
task.complexityScore
|
||||||
|
? getComplexityWithColor(task.complexityScore)
|
||||||
|
: chalk.gray('N/A')
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Add subtasks if requested
|
// Add subtasks if requested
|
||||||
@@ -516,6 +557,8 @@ function listTasks(
|
|||||||
// Default to regular task dependency
|
// Default to regular task dependency
|
||||||
const depTask = data.tasks.find((t) => t.id === depId);
|
const depTask = data.tasks.find((t) => t.id === depId);
|
||||||
if (depTask) {
|
if (depTask) {
|
||||||
|
// Add complexity to depTask before checking status
|
||||||
|
addComplexityToTask(depTask, complexityReport);
|
||||||
const isDone =
|
const isDone =
|
||||||
depTask.status === 'done' || depTask.status === 'completed';
|
depTask.status === 'done' || depTask.status === 'completed';
|
||||||
const isInProgress = depTask.status === 'in-progress';
|
const isInProgress = depTask.status === 'in-progress';
|
||||||
@@ -541,7 +584,10 @@ function listTasks(
|
|||||||
chalk.dim(`└─ ${truncate(subtask.title, titleWidth - 5)}`),
|
chalk.dim(`└─ ${truncate(subtask.title, titleWidth - 5)}`),
|
||||||
getStatusWithColor(subtask.status, true),
|
getStatusWithColor(subtask.status, true),
|
||||||
chalk.dim('-'),
|
chalk.dim('-'),
|
||||||
subtaskDepText // No truncation for dependencies
|
subtaskDepText,
|
||||||
|
subtask.complexityScore
|
||||||
|
? chalk.gray(`${subtask.complexityScore}`)
|
||||||
|
: chalk.gray('N/A')
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -597,6 +643,8 @@ function listTasks(
|
|||||||
subtasksSection = `\n\n${chalk.white.bold('Subtasks:')}\n`;
|
subtasksSection = `\n\n${chalk.white.bold('Subtasks:')}\n`;
|
||||||
subtasksSection += parentTaskForSubtasks.subtasks
|
subtasksSection += parentTaskForSubtasks.subtasks
|
||||||
.map((subtask) => {
|
.map((subtask) => {
|
||||||
|
// Add complexity to subtask before display
|
||||||
|
addComplexityToTask(subtask, complexityReport);
|
||||||
// Using a more simplified format for subtask status display
|
// Using a more simplified format for subtask status display
|
||||||
const status = subtask.status || 'pending';
|
const status = subtask.status || 'pending';
|
||||||
const statusColors = {
|
const statusColors = {
|
||||||
@@ -625,8 +673,8 @@ function listTasks(
|
|||||||
'\n\n' +
|
'\n\n' +
|
||||||
// Use nextItem.priority, nextItem.status, nextItem.dependencies
|
// Use nextItem.priority, nextItem.status, nextItem.dependencies
|
||||||
`${chalk.white('Priority:')} ${priorityColors[nextItem.priority || 'medium'](nextItem.priority || 'medium')} ${chalk.white('Status:')} ${getStatusWithColor(nextItem.status, true)}\n` +
|
`${chalk.white('Priority:')} ${priorityColors[nextItem.priority || 'medium'](nextItem.priority || 'medium')} ${chalk.white('Status:')} ${getStatusWithColor(nextItem.status, true)}\n` +
|
||||||
`${chalk.white('Dependencies:')} ${nextItem.dependencies && nextItem.dependencies.length > 0 ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true) : chalk.gray('None')}\n\n` +
|
`${chalk.white('Dependencies:')} ${nextItem.dependencies && nextItem.dependencies.length > 0 ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true, complexityReport) : chalk.gray('None')}\n\n` +
|
||||||
// Use nextItem.description (Note: findNextTask doesn't return description, need to fetch original task/subtask for this)
|
// Use nextTask.description (Note: findNextTask doesn't return description, need to fetch original task/subtask for this)
|
||||||
// *** Fetching original item for description and details ***
|
// *** Fetching original item for description and details ***
|
||||||
`${chalk.white('Description:')} ${getWorkItemDescription(nextItem, data.tasks)}` +
|
`${chalk.white('Description:')} ${getWorkItemDescription(nextItem, data.tasks)}` +
|
||||||
subtasksSection + // <-- Subtasks are handled above now
|
subtasksSection + // <-- Subtasks are handled above now
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import https from 'https';
|
import https from 'https';
|
||||||
|
import http from 'http';
|
||||||
import {
|
import {
|
||||||
getMainModelId,
|
getMainModelId,
|
||||||
getResearchModelId,
|
getResearchModelId,
|
||||||
@@ -19,7 +20,8 @@ import {
|
|||||||
getConfig,
|
getConfig,
|
||||||
writeConfig,
|
writeConfig,
|
||||||
isConfigFilePresent,
|
isConfigFilePresent,
|
||||||
getAllProviders
|
getAllProviders,
|
||||||
|
getBaseUrlForRole
|
||||||
} from '../config-manager.js';
|
} from '../config-manager.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -68,6 +70,68 @@ function fetchOpenRouterModels() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches the list of models from Ollama instance.
|
||||||
|
* @param {string} baseUrl - The base URL for the Ollama API (e.g., "http://localhost:11434/api")
|
||||||
|
* @returns {Promise<Array|null>} A promise that resolves with the list of model objects or null if fetch fails.
|
||||||
|
*/
|
||||||
|
function fetchOllamaModels(baseUrl = 'http://localhost:11434/api') {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
// Parse the base URL to extract hostname, port, and base path
|
||||||
|
const url = new URL(baseUrl);
|
||||||
|
const isHttps = url.protocol === 'https:';
|
||||||
|
const port = url.port || (isHttps ? 443 : 80);
|
||||||
|
const basePath = url.pathname.endsWith('/')
|
||||||
|
? url.pathname.slice(0, -1)
|
||||||
|
: url.pathname;
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
hostname: url.hostname,
|
||||||
|
port: parseInt(port, 10),
|
||||||
|
path: `${basePath}/tags`,
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const requestLib = isHttps ? https : http;
|
||||||
|
const req = requestLib.request(options, (res) => {
|
||||||
|
let data = '';
|
||||||
|
res.on('data', (chunk) => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
res.on('end', () => {
|
||||||
|
if (res.statusCode === 200) {
|
||||||
|
try {
|
||||||
|
const parsedData = JSON.parse(data);
|
||||||
|
resolve(parsedData.models || []); // Return the array of models
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error parsing Ollama response:', e);
|
||||||
|
resolve(null); // Indicate failure
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error(
|
||||||
|
`Ollama API request failed with status code: ${res.statusCode}`
|
||||||
|
);
|
||||||
|
resolve(null); // Indicate failure
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('error', (e) => {
|
||||||
|
console.error('Error fetching Ollama models:', e);
|
||||||
|
resolve(null); // Indicate failure
|
||||||
|
});
|
||||||
|
req.end();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error parsing Ollama base URL:', e);
|
||||||
|
resolve(null); // Indicate failure
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the current model configuration
|
* Get the current model configuration
|
||||||
* @param {Object} [options] - Options for the operation
|
* @param {Object} [options] - Options for the operation
|
||||||
@@ -416,10 +480,29 @@ async function setModel(role, modelId, options = {}) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else if (providerHint === 'ollama') {
|
} else if (providerHint === 'ollama') {
|
||||||
// Hinted as Ollama - set provider directly WITHOUT checking OpenRouter
|
// Check Ollama ONLY because hint was ollama
|
||||||
determinedProvider = 'ollama';
|
report('info', `Checking Ollama for ${modelId} (as hinted)...`);
|
||||||
warningMessage = `Warning: Custom Ollama model '${modelId}' set. Ensure your Ollama server is running and has pulled this model. Taskmaster cannot guarantee compatibility.`;
|
|
||||||
report('warn', warningMessage);
|
// Get the Ollama base URL from config
|
||||||
|
const ollamaBaseUrl = getBaseUrlForRole(role, projectRoot);
|
||||||
|
const ollamaModels = await fetchOllamaModels(ollamaBaseUrl);
|
||||||
|
|
||||||
|
if (ollamaModels === null) {
|
||||||
|
// Connection failed - server probably not running
|
||||||
|
throw new Error(
|
||||||
|
`Unable to connect to Ollama server at ${ollamaBaseUrl}. Please ensure Ollama is running and try again.`
|
||||||
|
);
|
||||||
|
} else if (ollamaModels.some((m) => m.model === modelId)) {
|
||||||
|
determinedProvider = 'ollama';
|
||||||
|
warningMessage = `Warning: Custom Ollama model '${modelId}' set. Ensure your Ollama server is running and has pulled this model. Taskmaster cannot guarantee compatibility.`;
|
||||||
|
report('warn', warningMessage);
|
||||||
|
} else {
|
||||||
|
// Server is running but model not found
|
||||||
|
const tagsUrl = `${ollamaBaseUrl}/tags`;
|
||||||
|
throw new Error(
|
||||||
|
`Model ID "${modelId}" not found in the Ollama instance. Please verify the model is pulled and available. You can check available models with: curl ${tagsUrl}`
|
||||||
|
);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// Invalid provider hint - should not happen
|
// Invalid provider hint - should not happen
|
||||||
throw new Error(`Invalid provider hint received: ${providerHint}`);
|
throw new Error(`Invalid provider hint received: ${providerHint}`);
|
||||||
|
|||||||
571
scripts/modules/task-manager/move-task.js
Normal file
571
scripts/modules/task-manager/move-task.js
Normal file
@@ -0,0 +1,571 @@
|
|||||||
|
import path from 'path';
|
||||||
|
import { log, readJSON, writeJSON } from '../utils.js';
|
||||||
|
import { isTaskDependentOn } from '../task-manager.js';
|
||||||
|
import generateTaskFiles from './generate-task-files.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move a task or subtask to a new position
|
||||||
|
* @param {string} tasksPath - Path to tasks.json file
|
||||||
|
* @param {string} sourceId - ID of the task/subtask to move (e.g., '5' or '5.2')
|
||||||
|
* @param {string} destinationId - ID of the destination (e.g., '7' or '7.3')
|
||||||
|
* @param {boolean} generateFiles - Whether to regenerate task files after moving
|
||||||
|
* @returns {Object} Result object with moved task details
|
||||||
|
*/
|
||||||
|
async function moveTask(
|
||||||
|
tasksPath,
|
||||||
|
sourceId,
|
||||||
|
destinationId,
|
||||||
|
generateFiles = true
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
log('info', `Moving task/subtask ${sourceId} to ${destinationId}...`);
|
||||||
|
|
||||||
|
// Read the existing tasks
|
||||||
|
const data = readJSON(tasksPath);
|
||||||
|
if (!data || !data.tasks) {
|
||||||
|
throw new Error(`Invalid or missing tasks file at ${tasksPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse source ID to determine if it's a task or subtask
|
||||||
|
const isSourceSubtask = sourceId.includes('.');
|
||||||
|
let sourceTask,
|
||||||
|
sourceParentTask,
|
||||||
|
sourceSubtask,
|
||||||
|
sourceTaskIndex,
|
||||||
|
sourceSubtaskIndex;
|
||||||
|
|
||||||
|
// Parse destination ID to determine the target
|
||||||
|
const isDestinationSubtask = destinationId.includes('.');
|
||||||
|
let destTask, destParentTask, destSubtask, destTaskIndex, destSubtaskIndex;
|
||||||
|
|
||||||
|
// Validate source exists
|
||||||
|
if (isSourceSubtask) {
|
||||||
|
// Source is a subtask
|
||||||
|
const [parentIdStr, subtaskIdStr] = sourceId.split('.');
|
||||||
|
const parentIdNum = parseInt(parentIdStr, 10);
|
||||||
|
const subtaskIdNum = parseInt(subtaskIdStr, 10);
|
||||||
|
|
||||||
|
sourceParentTask = data.tasks.find((t) => t.id === parentIdNum);
|
||||||
|
if (!sourceParentTask) {
|
||||||
|
throw new Error(`Source parent task with ID ${parentIdNum} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
!sourceParentTask.subtasks ||
|
||||||
|
sourceParentTask.subtasks.length === 0
|
||||||
|
) {
|
||||||
|
throw new Error(`Source parent task ${parentIdNum} has no subtasks`);
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceSubtaskIndex = sourceParentTask.subtasks.findIndex(
|
||||||
|
(st) => st.id === subtaskIdNum
|
||||||
|
);
|
||||||
|
if (sourceSubtaskIndex === -1) {
|
||||||
|
throw new Error(`Source subtask ${sourceId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceSubtask = { ...sourceParentTask.subtasks[sourceSubtaskIndex] };
|
||||||
|
} else {
|
||||||
|
// Source is a task
|
||||||
|
const sourceIdNum = parseInt(sourceId, 10);
|
||||||
|
sourceTaskIndex = data.tasks.findIndex((t) => t.id === sourceIdNum);
|
||||||
|
if (sourceTaskIndex === -1) {
|
||||||
|
throw new Error(`Source task with ID ${sourceIdNum} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceTask = { ...data.tasks[sourceTaskIndex] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate destination exists
|
||||||
|
if (isDestinationSubtask) {
|
||||||
|
// Destination is a subtask (target will be the parent of this subtask)
|
||||||
|
const [parentIdStr, subtaskIdStr] = destinationId.split('.');
|
||||||
|
const parentIdNum = parseInt(parentIdStr, 10);
|
||||||
|
const subtaskIdNum = parseInt(subtaskIdStr, 10);
|
||||||
|
|
||||||
|
destParentTask = data.tasks.find((t) => t.id === parentIdNum);
|
||||||
|
if (!destParentTask) {
|
||||||
|
throw new Error(
|
||||||
|
`Destination parent task with ID ${parentIdNum} not found`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!destParentTask.subtasks || destParentTask.subtasks.length === 0) {
|
||||||
|
throw new Error(
|
||||||
|
`Destination parent task ${parentIdNum} has no subtasks`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
destSubtaskIndex = destParentTask.subtasks.findIndex(
|
||||||
|
(st) => st.id === subtaskIdNum
|
||||||
|
);
|
||||||
|
if (destSubtaskIndex === -1) {
|
||||||
|
throw new Error(`Destination subtask ${destinationId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
destSubtask = destParentTask.subtasks[destSubtaskIndex];
|
||||||
|
} else {
|
||||||
|
// Destination is a task
|
||||||
|
const destIdNum = parseInt(destinationId, 10);
|
||||||
|
destTaskIndex = data.tasks.findIndex((t) => t.id === destIdNum);
|
||||||
|
|
||||||
|
if (destTaskIndex === -1) {
|
||||||
|
// Create placeholder for destination if it doesn't exist
|
||||||
|
log('info', `Creating placeholder for destination task ${destIdNum}`);
|
||||||
|
const newTask = {
|
||||||
|
id: destIdNum,
|
||||||
|
title: `Task ${destIdNum}`,
|
||||||
|
description: '',
|
||||||
|
status: 'pending',
|
||||||
|
priority: 'medium',
|
||||||
|
details: '',
|
||||||
|
testStrategy: ''
|
||||||
|
};
|
||||||
|
|
||||||
|
// Find correct position to insert the new task
|
||||||
|
let insertIndex = 0;
|
||||||
|
while (
|
||||||
|
insertIndex < data.tasks.length &&
|
||||||
|
data.tasks[insertIndex].id < destIdNum
|
||||||
|
) {
|
||||||
|
insertIndex++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert the new task at the appropriate position
|
||||||
|
data.tasks.splice(insertIndex, 0, newTask);
|
||||||
|
destTaskIndex = insertIndex;
|
||||||
|
destTask = data.tasks[destTaskIndex];
|
||||||
|
} else {
|
||||||
|
destTask = data.tasks[destTaskIndex];
|
||||||
|
|
||||||
|
// Check if destination task is already a "real" task with content
|
||||||
|
// Only allow moving to destination IDs that don't have meaningful content
|
||||||
|
if (
|
||||||
|
destTask.title !== `Task ${destTask.id}` ||
|
||||||
|
destTask.description !== '' ||
|
||||||
|
destTask.details !== ''
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
`Cannot move to task ID ${destIdNum} as it already contains content. Choose a different destination ID.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate that we aren't trying to move a task to itself
|
||||||
|
if (sourceId === destinationId) {
|
||||||
|
throw new Error('Cannot move a task/subtask to itself');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prevent moving a parent to its own subtask
|
||||||
|
if (!isSourceSubtask && isDestinationSubtask) {
|
||||||
|
const destParentId = parseInt(destinationId.split('.')[0], 10);
|
||||||
|
if (parseInt(sourceId, 10) === destParentId) {
|
||||||
|
throw new Error('Cannot move a parent task to one of its own subtasks');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for circular dependency when moving tasks
|
||||||
|
if (!isSourceSubtask && !isDestinationSubtask) {
|
||||||
|
const sourceIdNum = parseInt(sourceId, 10);
|
||||||
|
const destIdNum = parseInt(destinationId, 10);
|
||||||
|
|
||||||
|
// Check if destination is dependent on source
|
||||||
|
if (isTaskDependentOn(data.tasks, destTask, sourceIdNum)) {
|
||||||
|
throw new Error(
|
||||||
|
`Cannot move task ${sourceId} to task ${destinationId} as it would create a circular dependency`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let movedTask;
|
||||||
|
|
||||||
|
// Handle different move scenarios
|
||||||
|
if (!isSourceSubtask && !isDestinationSubtask) {
|
||||||
|
// Check if destination is a placeholder we just created
|
||||||
|
if (
|
||||||
|
destTask.title === `Task ${destTask.id}` &&
|
||||||
|
destTask.description === '' &&
|
||||||
|
destTask.details === ''
|
||||||
|
) {
|
||||||
|
// Case 0: Move task to a new position/ID (destination is a placeholder)
|
||||||
|
movedTask = moveTaskToNewId(
|
||||||
|
data,
|
||||||
|
sourceTask,
|
||||||
|
sourceTaskIndex,
|
||||||
|
destTask,
|
||||||
|
destTaskIndex
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Case 1: Move standalone task to become a subtask of another task
|
||||||
|
movedTask = moveTaskToTask(data, sourceTask, sourceTaskIndex, destTask);
|
||||||
|
}
|
||||||
|
} else if (!isSourceSubtask && isDestinationSubtask) {
|
||||||
|
// Case 2: Move standalone task to become a subtask at a specific position
|
||||||
|
movedTask = moveTaskToSubtaskPosition(
|
||||||
|
data,
|
||||||
|
sourceTask,
|
||||||
|
sourceTaskIndex,
|
||||||
|
destParentTask,
|
||||||
|
destSubtaskIndex
|
||||||
|
);
|
||||||
|
} else if (isSourceSubtask && !isDestinationSubtask) {
|
||||||
|
// Case 3: Move subtask to become a standalone task
|
||||||
|
movedTask = moveSubtaskToTask(
|
||||||
|
data,
|
||||||
|
sourceSubtask,
|
||||||
|
sourceParentTask,
|
||||||
|
sourceSubtaskIndex,
|
||||||
|
destTask
|
||||||
|
);
|
||||||
|
} else if (isSourceSubtask && isDestinationSubtask) {
|
||||||
|
// Case 4: Move subtask to another parent or position
|
||||||
|
// First check if it's the same parent
|
||||||
|
const sourceParentId = parseInt(sourceId.split('.')[0], 10);
|
||||||
|
const destParentId = parseInt(destinationId.split('.')[0], 10);
|
||||||
|
|
||||||
|
if (sourceParentId === destParentId) {
|
||||||
|
// Case 4a: Move subtask within the same parent (reordering)
|
||||||
|
movedTask = reorderSubtask(
|
||||||
|
sourceParentTask,
|
||||||
|
sourceSubtaskIndex,
|
||||||
|
destSubtaskIndex
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Case 4b: Move subtask to a different parent
|
||||||
|
movedTask = moveSubtaskToAnotherParent(
|
||||||
|
sourceSubtask,
|
||||||
|
sourceParentTask,
|
||||||
|
sourceSubtaskIndex,
|
||||||
|
destParentTask,
|
||||||
|
destSubtaskIndex
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the updated tasks back to the file
|
||||||
|
writeJSON(tasksPath, data);
|
||||||
|
|
||||||
|
// Generate task files if requested
|
||||||
|
if (generateFiles) {
|
||||||
|
log('info', 'Regenerating task files...');
|
||||||
|
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
return movedTask;
|
||||||
|
} catch (error) {
|
||||||
|
log('error', `Error moving task/subtask: ${error.message}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move a standalone task to become a subtask of another task
|
||||||
|
* @param {Object} data - Tasks data object
|
||||||
|
* @param {Object} sourceTask - Source task to move
|
||||||
|
* @param {number} sourceTaskIndex - Index of source task in data.tasks
|
||||||
|
* @param {Object} destTask - Destination task
|
||||||
|
* @returns {Object} Moved task object
|
||||||
|
*/
|
||||||
|
function moveTaskToTask(data, sourceTask, sourceTaskIndex, destTask) {
|
||||||
|
// Initialize subtasks array if it doesn't exist
|
||||||
|
if (!destTask.subtasks) {
|
||||||
|
destTask.subtasks = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the highest subtask ID to determine the next ID
|
||||||
|
const highestSubtaskId =
|
||||||
|
destTask.subtasks.length > 0
|
||||||
|
? Math.max(...destTask.subtasks.map((st) => st.id))
|
||||||
|
: 0;
|
||||||
|
const newSubtaskId = highestSubtaskId + 1;
|
||||||
|
|
||||||
|
// Create the new subtask from the source task
|
||||||
|
const newSubtask = {
|
||||||
|
...sourceTask,
|
||||||
|
id: newSubtaskId,
|
||||||
|
parentTaskId: destTask.id
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add to destination's subtasks
|
||||||
|
destTask.subtasks.push(newSubtask);
|
||||||
|
|
||||||
|
// Remove the original task from the tasks array
|
||||||
|
data.tasks.splice(sourceTaskIndex, 1);
|
||||||
|
|
||||||
|
log(
|
||||||
|
'info',
|
||||||
|
`Moved task ${sourceTask.id} to become subtask ${destTask.id}.${newSubtaskId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
return newSubtask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move a standalone task to become a subtask at a specific position
|
||||||
|
* @param {Object} data - Tasks data object
|
||||||
|
* @param {Object} sourceTask - Source task to move
|
||||||
|
* @param {number} sourceTaskIndex - Index of source task in data.tasks
|
||||||
|
* @param {Object} destParentTask - Destination parent task
|
||||||
|
* @param {number} destSubtaskIndex - Index of the subtask before which to insert
|
||||||
|
* @returns {Object} Moved task object
|
||||||
|
*/
|
||||||
|
function moveTaskToSubtaskPosition(
|
||||||
|
data,
|
||||||
|
sourceTask,
|
||||||
|
sourceTaskIndex,
|
||||||
|
destParentTask,
|
||||||
|
destSubtaskIndex
|
||||||
|
) {
|
||||||
|
// Initialize subtasks array if it doesn't exist
|
||||||
|
if (!destParentTask.subtasks) {
|
||||||
|
destParentTask.subtasks = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the highest subtask ID to determine the next ID
|
||||||
|
const highestSubtaskId =
|
||||||
|
destParentTask.subtasks.length > 0
|
||||||
|
? Math.max(...destParentTask.subtasks.map((st) => st.id))
|
||||||
|
: 0;
|
||||||
|
const newSubtaskId = highestSubtaskId + 1;
|
||||||
|
|
||||||
|
// Create the new subtask from the source task
|
||||||
|
const newSubtask = {
|
||||||
|
...sourceTask,
|
||||||
|
id: newSubtaskId,
|
||||||
|
parentTaskId: destParentTask.id
|
||||||
|
};
|
||||||
|
|
||||||
|
// Insert at specific position
|
||||||
|
destParentTask.subtasks.splice(destSubtaskIndex + 1, 0, newSubtask);
|
||||||
|
|
||||||
|
// Remove the original task from the tasks array
|
||||||
|
data.tasks.splice(sourceTaskIndex, 1);
|
||||||
|
|
||||||
|
log(
|
||||||
|
'info',
|
||||||
|
`Moved task ${sourceTask.id} to become subtask ${destParentTask.id}.${newSubtaskId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
return newSubtask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move a subtask to become a standalone task
|
||||||
|
* @param {Object} data - Tasks data object
|
||||||
|
* @param {Object} sourceSubtask - Source subtask to move
|
||||||
|
* @param {Object} sourceParentTask - Parent task of the source subtask
|
||||||
|
* @param {number} sourceSubtaskIndex - Index of source subtask in parent's subtasks
|
||||||
|
* @param {Object} destTask - Destination task (for position reference)
|
||||||
|
* @returns {Object} Moved task object
|
||||||
|
*/
|
||||||
|
function moveSubtaskToTask(
|
||||||
|
data,
|
||||||
|
sourceSubtask,
|
||||||
|
sourceParentTask,
|
||||||
|
sourceSubtaskIndex,
|
||||||
|
destTask
|
||||||
|
) {
|
||||||
|
// Find the highest task ID to determine the next ID
|
||||||
|
const highestId = Math.max(...data.tasks.map((t) => t.id));
|
||||||
|
const newTaskId = highestId + 1;
|
||||||
|
|
||||||
|
// Create the new task from the subtask
|
||||||
|
const newTask = {
|
||||||
|
...sourceSubtask,
|
||||||
|
id: newTaskId,
|
||||||
|
priority: sourceParentTask.priority || 'medium' // Inherit priority from parent
|
||||||
|
};
|
||||||
|
delete newTask.parentTaskId;
|
||||||
|
|
||||||
|
// Add the parent task as a dependency if not already present
|
||||||
|
if (!newTask.dependencies) {
|
||||||
|
newTask.dependencies = [];
|
||||||
|
}
|
||||||
|
if (!newTask.dependencies.includes(sourceParentTask.id)) {
|
||||||
|
newTask.dependencies.push(sourceParentTask.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the destination index to insert the new task
|
||||||
|
const destTaskIndex = data.tasks.findIndex((t) => t.id === destTask.id);
|
||||||
|
|
||||||
|
// Insert the new task after the destination task
|
||||||
|
data.tasks.splice(destTaskIndex + 1, 0, newTask);
|
||||||
|
|
||||||
|
// Remove the subtask from the parent
|
||||||
|
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
|
||||||
|
|
||||||
|
// If parent has no more subtasks, remove the subtasks array
|
||||||
|
if (sourceParentTask.subtasks.length === 0) {
|
||||||
|
delete sourceParentTask.subtasks;
|
||||||
|
}
|
||||||
|
|
||||||
|
log(
|
||||||
|
'info',
|
||||||
|
`Moved subtask ${sourceParentTask.id}.${sourceSubtask.id} to become task ${newTaskId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
return newTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reorder a subtask within the same parent
|
||||||
|
* @param {Object} parentTask - Parent task containing the subtask
|
||||||
|
* @param {number} sourceIndex - Current index of the subtask
|
||||||
|
* @param {number} destIndex - Destination index for the subtask
|
||||||
|
* @returns {Object} Moved subtask object
|
||||||
|
*/
|
||||||
|
function reorderSubtask(parentTask, sourceIndex, destIndex) {
|
||||||
|
// Get the subtask to move
|
||||||
|
const subtask = parentTask.subtasks[sourceIndex];
|
||||||
|
|
||||||
|
// Remove the subtask from its current position
|
||||||
|
parentTask.subtasks.splice(sourceIndex, 1);
|
||||||
|
|
||||||
|
// Insert the subtask at the new position
|
||||||
|
// If destIndex was after sourceIndex, it's now one less because we removed an item
|
||||||
|
const adjustedDestIndex = sourceIndex < destIndex ? destIndex - 1 : destIndex;
|
||||||
|
parentTask.subtasks.splice(adjustedDestIndex, 0, subtask);
|
||||||
|
|
||||||
|
log(
|
||||||
|
'info',
|
||||||
|
`Reordered subtask ${parentTask.id}.${subtask.id} within parent task ${parentTask.id}`
|
||||||
|
);
|
||||||
|
|
||||||
|
return subtask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move a subtask to a different parent
|
||||||
|
* @param {Object} sourceSubtask - Source subtask to move
|
||||||
|
* @param {Object} sourceParentTask - Parent task of the source subtask
|
||||||
|
* @param {number} sourceSubtaskIndex - Index of source subtask in parent's subtasks
|
||||||
|
* @param {Object} destParentTask - Destination parent task
|
||||||
|
* @param {number} destSubtaskIndex - Index of the subtask before which to insert
|
||||||
|
* @returns {Object} Moved subtask object
|
||||||
|
*/
|
||||||
|
function moveSubtaskToAnotherParent(
|
||||||
|
sourceSubtask,
|
||||||
|
sourceParentTask,
|
||||||
|
sourceSubtaskIndex,
|
||||||
|
destParentTask,
|
||||||
|
destSubtaskIndex
|
||||||
|
) {
|
||||||
|
// Find the highest subtask ID in the destination parent
|
||||||
|
const highestSubtaskId =
|
||||||
|
destParentTask.subtasks.length > 0
|
||||||
|
? Math.max(...destParentTask.subtasks.map((st) => st.id))
|
||||||
|
: 0;
|
||||||
|
const newSubtaskId = highestSubtaskId + 1;
|
||||||
|
|
||||||
|
// Create the new subtask with updated parent reference
|
||||||
|
const newSubtask = {
|
||||||
|
...sourceSubtask,
|
||||||
|
id: newSubtaskId,
|
||||||
|
parentTaskId: destParentTask.id
|
||||||
|
};
|
||||||
|
|
||||||
|
// If the subtask depends on its original parent, keep that dependency
|
||||||
|
if (!newSubtask.dependencies) {
|
||||||
|
newSubtask.dependencies = [];
|
||||||
|
}
|
||||||
|
if (!newSubtask.dependencies.includes(sourceParentTask.id)) {
|
||||||
|
newSubtask.dependencies.push(sourceParentTask.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert at the destination position
|
||||||
|
destParentTask.subtasks.splice(destSubtaskIndex + 1, 0, newSubtask);
|
||||||
|
|
||||||
|
// Remove the subtask from the original parent
|
||||||
|
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
|
||||||
|
|
||||||
|
// If original parent has no more subtasks, remove the subtasks array
|
||||||
|
if (sourceParentTask.subtasks.length === 0) {
|
||||||
|
delete sourceParentTask.subtasks;
|
||||||
|
}
|
||||||
|
|
||||||
|
log(
|
||||||
|
'info',
|
||||||
|
`Moved subtask ${sourceParentTask.id}.${sourceSubtask.id} to become subtask ${destParentTask.id}.${newSubtaskId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
return newSubtask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move a standalone task to a new ID position
|
||||||
|
* @param {Object} data - Tasks data object
|
||||||
|
* @param {Object} sourceTask - Source task to move
|
||||||
|
* @param {number} sourceTaskIndex - Index of source task in data.tasks
|
||||||
|
* @param {Object} destTask - Destination placeholder task
|
||||||
|
* @param {number} destTaskIndex - Index of destination task in data.tasks
|
||||||
|
* @returns {Object} Moved task object
|
||||||
|
*/
|
||||||
|
function moveTaskToNewId(
|
||||||
|
data,
|
||||||
|
sourceTask,
|
||||||
|
sourceTaskIndex,
|
||||||
|
destTask,
|
||||||
|
destTaskIndex
|
||||||
|
) {
|
||||||
|
// Create a copy of the source task with the new ID
|
||||||
|
const movedTask = {
|
||||||
|
...sourceTask,
|
||||||
|
id: destTask.id
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get numeric IDs for comparison
|
||||||
|
const sourceIdNum = parseInt(sourceTask.id, 10);
|
||||||
|
const destIdNum = parseInt(destTask.id, 10);
|
||||||
|
|
||||||
|
// Handle subtasks if present
|
||||||
|
if (sourceTask.subtasks && sourceTask.subtasks.length > 0) {
|
||||||
|
// Update subtasks to reference the new parent ID if needed
|
||||||
|
movedTask.subtasks = sourceTask.subtasks.map((subtask) => ({
|
||||||
|
...subtask,
|
||||||
|
parentTaskId: destIdNum
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update any dependencies in other tasks that referenced the old ID
|
||||||
|
data.tasks.forEach((task) => {
|
||||||
|
if (task.dependencies && task.dependencies.includes(sourceIdNum)) {
|
||||||
|
// Replace the old ID with the new ID
|
||||||
|
const depIndex = task.dependencies.indexOf(sourceIdNum);
|
||||||
|
task.dependencies[depIndex] = destIdNum;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also check for subtask dependencies that might reference this task
|
||||||
|
if (task.subtasks && task.subtasks.length > 0) {
|
||||||
|
task.subtasks.forEach((subtask) => {
|
||||||
|
if (
|
||||||
|
subtask.dependencies &&
|
||||||
|
subtask.dependencies.includes(sourceIdNum)
|
||||||
|
) {
|
||||||
|
const depIndex = subtask.dependencies.indexOf(sourceIdNum);
|
||||||
|
subtask.dependencies[depIndex] = destIdNum;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove the original task from its position
|
||||||
|
data.tasks.splice(sourceTaskIndex, 1);
|
||||||
|
|
||||||
|
// If we're moving to a position after the original, adjust the destination index
|
||||||
|
// since removing the original shifts everything down by 1
|
||||||
|
const adjustedDestIndex =
|
||||||
|
sourceTaskIndex < destTaskIndex ? destTaskIndex - 1 : destTaskIndex;
|
||||||
|
|
||||||
|
// Remove the placeholder destination task
|
||||||
|
data.tasks.splice(adjustedDestIndex, 1);
|
||||||
|
|
||||||
|
// Insert the moved task at the destination position
|
||||||
|
data.tasks.splice(adjustedDestIndex, 0, movedTask);
|
||||||
|
|
||||||
|
log('info', `Moved task ${sourceIdNum} to new ID ${destIdNum}`);
|
||||||
|
|
||||||
|
return movedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default moveTask;
|
||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
import { generateObjectService } from '../ai-services-unified.js';
|
import { generateObjectService } from '../ai-services-unified.js';
|
||||||
import { getDebugFlag } from '../config-manager.js';
|
import { getDebugFlag } from '../config-manager.js';
|
||||||
import generateTaskFiles from './generate-task-files.js';
|
import generateTaskFiles from './generate-task-files.js';
|
||||||
|
import { displayAiUsageSummary } from '../ui.js';
|
||||||
|
|
||||||
// Define the Zod schema for a SINGLE task object
|
// Define the Zod schema for a SINGLE task object
|
||||||
const prdSingleTaskSchema = z.object({
|
const prdSingleTaskSchema = z.object({
|
||||||
@@ -47,8 +48,9 @@ const prdResponseSchema = z.object({
|
|||||||
* @param {string} tasksPath - Path to the tasks.json file
|
* @param {string} tasksPath - Path to the tasks.json file
|
||||||
* @param {number} numTasks - Number of tasks to generate
|
* @param {number} numTasks - Number of tasks to generate
|
||||||
* @param {Object} options - Additional options
|
* @param {Object} options - Additional options
|
||||||
* @param {boolean} [options.useForce=false] - Whether to overwrite existing tasks.json.
|
* @param {boolean} [options.force=false] - Whether to overwrite existing tasks.json.
|
||||||
* @param {boolean} [options.useAppend=false] - Append to existing tasks file.
|
* @param {boolean} [options.append=false] - Append to existing tasks file.
|
||||||
|
* @param {boolean} [options.research=false] - Use research model for enhanced PRD analysis.
|
||||||
* @param {Object} [options.reportProgress] - Function to report progress (optional, likely unused).
|
* @param {Object} [options.reportProgress] - Function to report progress (optional, likely unused).
|
||||||
* @param {Object} [options.mcpLog] - MCP logger object (optional).
|
* @param {Object} [options.mcpLog] - MCP logger object (optional).
|
||||||
* @param {Object} [options.session] - Session object from MCP server (optional).
|
* @param {Object} [options.session] - Session object from MCP server (optional).
|
||||||
@@ -61,8 +63,9 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
|
|||||||
mcpLog,
|
mcpLog,
|
||||||
session,
|
session,
|
||||||
projectRoot,
|
projectRoot,
|
||||||
useForce = false,
|
force = false,
|
||||||
useAppend = false
|
append = false,
|
||||||
|
research = false
|
||||||
} = options;
|
} = options;
|
||||||
const isMCP = !!mcpLog;
|
const isMCP = !!mcpLog;
|
||||||
const outputFormat = isMCP ? 'json' : 'text';
|
const outputFormat = isMCP ? 'json' : 'text';
|
||||||
@@ -90,16 +93,17 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
report(
|
report(
|
||||||
`Parsing PRD file: ${prdPath}, Force: ${useForce}, Append: ${useAppend}`
|
`Parsing PRD file: ${prdPath}, Force: ${force}, Append: ${append}, Research: ${research}`
|
||||||
);
|
);
|
||||||
|
|
||||||
let existingTasks = [];
|
let existingTasks = [];
|
||||||
let nextId = 1;
|
let nextId = 1;
|
||||||
|
let aiServiceResponse = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Handle file existence and overwrite/append logic
|
// Handle file existence and overwrite/append logic
|
||||||
if (fs.existsSync(tasksPath)) {
|
if (fs.existsSync(tasksPath)) {
|
||||||
if (useAppend) {
|
if (append) {
|
||||||
report(
|
report(
|
||||||
`Append mode enabled. Reading existing tasks from ${tasksPath}`,
|
`Append mode enabled. Reading existing tasks from ${tasksPath}`,
|
||||||
'info'
|
'info'
|
||||||
@@ -121,7 +125,7 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
|
|||||||
);
|
);
|
||||||
existingTasks = []; // Reset if read fails
|
existingTasks = []; // Reset if read fails
|
||||||
}
|
}
|
||||||
} else if (!useForce) {
|
} else if (!force) {
|
||||||
// Not appending and not forcing overwrite
|
// Not appending and not forcing overwrite
|
||||||
const overwriteError = new Error(
|
const overwriteError = new Error(
|
||||||
`Output file ${tasksPath} already exists. Use --force to overwrite or --append.`
|
`Output file ${tasksPath} already exists. Use --force to overwrite or --append.`
|
||||||
@@ -148,8 +152,22 @@ async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
|
|||||||
throw new Error(`Input file ${prdPath} is empty or could not be read.`);
|
throw new Error(`Input file ${prdPath} is empty or could not be read.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build system prompt for PRD parsing
|
// Research-specific enhancements to the system prompt
|
||||||
const systemPrompt = `You are an AI assistant specialized in analyzing Product Requirements Documents (PRDs) and generating a structured, logically ordered, dependency-aware and sequenced list of development tasks in JSON format.
|
const researchPromptAddition = research
|
||||||
|
? `\nBefore breaking down the PRD into tasks, you will:
|
||||||
|
1. Research and analyze the latest technologies, libraries, frameworks, and best practices that would be appropriate for this project
|
||||||
|
2. Identify any potential technical challenges, security concerns, or scalability issues not explicitly mentioned in the PRD without discarding any explicit requirements or going overboard with complexity -- always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches
|
||||||
|
3. Consider current industry standards and evolving trends relevant to this project (this step aims to solve LLM hallucinations and out of date information due to training data cutoff dates)
|
||||||
|
4. Evaluate alternative implementation approaches and recommend the most efficient path
|
||||||
|
5. Include specific library versions, helpful APIs, and concrete implementation guidance based on your research
|
||||||
|
6. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches
|
||||||
|
|
||||||
|
Your task breakdown should incorporate this research, resulting in more detailed implementation guidance, more accurate dependency mapping, and more precise technology recommendations than would be possible from the PRD text alone, while maintaining all explicit requirements and best practices and all details and nuances of the PRD.`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
// Base system prompt for PRD parsing
|
||||||
|
const systemPrompt = `You are an AI assistant specialized in analyzing Product Requirements Documents (PRDs) and generating a structured, logically ordered, dependency-aware and sequenced list of development tasks in JSON format.${researchPromptAddition}
|
||||||
|
|
||||||
Analyze the provided PRD content and generate approximately ${numTasks} top-level development tasks. If the complexity or the level of detail of the PRD is high, generate more tasks relative to the complexity of the PRD
|
Analyze the provided PRD content and generate approximately ${numTasks} top-level development tasks. If the complexity or the level of detail of the PRD is high, generate more tasks relative to the complexity of the PRD
|
||||||
Each task should represent a logical unit of work needed to implement the requirements and focus on the most direct and effective way to implement the requirements without unnecessary complexity or overengineering. Include pseudo-code, implementation details, and test strategy for each task. Find the most up to date information to implement each task.
|
Each task should represent a logical unit of work needed to implement the requirements and focus on the most direct and effective way to implement the requirements without unnecessary complexity or overengineering. Include pseudo-code, implementation details, and test strategy for each task. Find the most up to date information to implement each task.
|
||||||
Assign sequential IDs starting from ${nextId}. Infer title, description, details, and test strategy for each task based *only* on the PRD content.
|
Assign sequential IDs starting from ${nextId}. Infer title, description, details, and test strategy for each task based *only* on the PRD content.
|
||||||
@@ -176,13 +194,13 @@ Guidelines:
|
|||||||
5. Include clear validation/testing approach for each task
|
5. Include clear validation/testing approach for each task
|
||||||
6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs, potentially including existing tasks with IDs less than ${nextId} if applicable)
|
6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs, potentially including existing tasks with IDs less than ${nextId} if applicable)
|
||||||
7. Assign priority (high/medium/low) based on criticality and dependency order
|
7. Assign priority (high/medium/low) based on criticality and dependency order
|
||||||
8. Include detailed implementation guidance in the "details" field
|
8. Include detailed implementation guidance in the "details" field${research ? ', with specific libraries and version recommendations based on your research' : ''}
|
||||||
9. If the PRD contains specific requirements for libraries, database schemas, frameworks, tech stacks, or any other implementation details, STRICTLY ADHERE to these requirements in your task breakdown and do not discard them under any circumstance
|
9. If the PRD contains specific requirements for libraries, database schemas, frameworks, tech stacks, or any other implementation details, STRICTLY ADHERE to these requirements in your task breakdown and do not discard them under any circumstance
|
||||||
10. Focus on filling in any gaps left by the PRD or areas that aren't fully specified, while preserving all explicit requirements
|
10. Focus on filling in any gaps left by the PRD or areas that aren't fully specified, while preserving all explicit requirements
|
||||||
11. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches`;
|
11. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches${research ? '\n12. For each task, include specific, actionable guidance based on current industry standards and best practices discovered through research' : ''}`;
|
||||||
|
|
||||||
// Build user prompt with PRD content
|
// Build user prompt with PRD content
|
||||||
const userPrompt = `Here's the Product Requirements Document (PRD) to break down into approximately ${numTasks} tasks, starting IDs from ${nextId}:\n\n${prdContent}\n\n
|
const userPrompt = `Here's the Product Requirements Document (PRD) to break down into approximately ${numTasks} tasks, starting IDs from ${nextId}:${research ? '\n\nRemember to thoroughly research current best practices and technologies before task breakdown to provide specific, actionable implementation details.' : ''}\n\n${prdContent}\n\n
|
||||||
|
|
||||||
Return your response in this format:
|
Return your response in this format:
|
||||||
{
|
{
|
||||||
@@ -204,18 +222,22 @@ Guidelines:
|
|||||||
}`;
|
}`;
|
||||||
|
|
||||||
// Call the unified AI service
|
// Call the unified AI service
|
||||||
report('Calling AI service to generate tasks from PRD...', 'info');
|
report(
|
||||||
|
`Calling AI service to generate tasks from PRD${research ? ' with research-backed analysis' : ''}...`,
|
||||||
|
'info'
|
||||||
|
);
|
||||||
|
|
||||||
// Call generateObjectService with the CORRECT schema
|
// Call generateObjectService with the CORRECT schema and additional telemetry params
|
||||||
const generatedData = await generateObjectService({
|
aiServiceResponse = await generateObjectService({
|
||||||
role: 'main',
|
role: research ? 'research' : 'main', // Use research role if flag is set
|
||||||
session: session,
|
session: session,
|
||||||
projectRoot: projectRoot,
|
projectRoot: projectRoot,
|
||||||
schema: prdResponseSchema,
|
schema: prdResponseSchema,
|
||||||
objectName: 'tasks_data',
|
objectName: 'tasks_data',
|
||||||
systemPrompt: systemPrompt,
|
systemPrompt: systemPrompt,
|
||||||
prompt: userPrompt,
|
prompt: userPrompt,
|
||||||
reportProgress
|
commandName: 'parse-prd',
|
||||||
|
outputType: isMCP ? 'mcp' : 'cli'
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create the directory if it doesn't exist
|
// Create the directory if it doesn't exist
|
||||||
@@ -223,12 +245,34 @@ Guidelines:
|
|||||||
if (!fs.existsSync(tasksDir)) {
|
if (!fs.existsSync(tasksDir)) {
|
||||||
fs.mkdirSync(tasksDir, { recursive: true });
|
fs.mkdirSync(tasksDir, { recursive: true });
|
||||||
}
|
}
|
||||||
logFn.success('Successfully parsed PRD via AI service.'); // Assumes generateObjectService validated
|
logFn.success(
|
||||||
|
`Successfully parsed PRD via AI service${research ? ' with research-backed analysis' : ''}.`
|
||||||
|
);
|
||||||
|
|
||||||
// Validate and Process Tasks
|
// Validate and Process Tasks
|
||||||
|
// const generatedData = aiServiceResponse?.mainResult?.object;
|
||||||
|
|
||||||
|
// Robustly get the actual AI-generated object
|
||||||
|
let generatedData = null;
|
||||||
|
if (aiServiceResponse?.mainResult) {
|
||||||
|
if (
|
||||||
|
typeof aiServiceResponse.mainResult === 'object' &&
|
||||||
|
aiServiceResponse.mainResult !== null &&
|
||||||
|
'tasks' in aiServiceResponse.mainResult
|
||||||
|
) {
|
||||||
|
// If mainResult itself is the object with a 'tasks' property
|
||||||
|
generatedData = aiServiceResponse.mainResult;
|
||||||
|
} else if (
|
||||||
|
typeof aiServiceResponse.mainResult.object === 'object' &&
|
||||||
|
aiServiceResponse.mainResult.object !== null &&
|
||||||
|
'tasks' in aiServiceResponse.mainResult.object
|
||||||
|
) {
|
||||||
|
// If mainResult.object is the object with a 'tasks' property
|
||||||
|
generatedData = aiServiceResponse.mainResult.object;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!generatedData || !Array.isArray(generatedData.tasks)) {
|
if (!generatedData || !Array.isArray(generatedData.tasks)) {
|
||||||
// This error *shouldn't* happen if generateObjectService enforced prdResponseSchema
|
|
||||||
// But keep it as a safeguard
|
|
||||||
logFn.error(
|
logFn.error(
|
||||||
`Internal Error: generateObjectService returned unexpected data structure: ${JSON.stringify(generatedData)}`
|
`Internal Error: generateObjectService returned unexpected data structure: ${JSON.stringify(generatedData)}`
|
||||||
);
|
);
|
||||||
@@ -265,36 +309,27 @@ Guidelines:
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const allTasks = useAppend
|
const finalTasks = append
|
||||||
? [...existingTasks, ...processedNewTasks]
|
? [...existingTasks, ...processedNewTasks]
|
||||||
: processedNewTasks;
|
: processedNewTasks;
|
||||||
|
const outputData = { tasks: finalTasks };
|
||||||
|
|
||||||
const finalTaskData = { tasks: allTasks }; // Use the combined list
|
// Write the final tasks to the file
|
||||||
|
writeJSON(tasksPath, outputData);
|
||||||
// Write the tasks to the file
|
|
||||||
writeJSON(tasksPath, finalTaskData);
|
|
||||||
report(
|
report(
|
||||||
`Successfully wrote ${allTasks.length} total tasks to ${tasksPath} (${processedNewTasks.length} new).`,
|
`Successfully ${append ? 'appended' : 'generated'} ${processedNewTasks.length} tasks in ${tasksPath}${research ? ' with research-backed analysis' : ''}`,
|
||||||
'success'
|
'success'
|
||||||
);
|
);
|
||||||
report(`Tasks saved to: ${tasksPath}`, 'info');
|
|
||||||
|
|
||||||
// Generate individual task files
|
// Generate markdown task files after writing tasks.json
|
||||||
if (reportProgress && mcpLog) {
|
await generateTaskFiles(tasksPath, path.dirname(tasksPath), { mcpLog });
|
||||||
// Enable silent mode when being called from MCP server
|
|
||||||
enableSilentMode();
|
|
||||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
|
||||||
disableSilentMode();
|
|
||||||
} else {
|
|
||||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only show success boxes for text output (CLI)
|
// Handle CLI output (e.g., success message)
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
console.log(
|
console.log(
|
||||||
boxen(
|
boxen(
|
||||||
chalk.green(
|
chalk.green(
|
||||||
`Successfully generated ${processedNewTasks.length} new tasks. Total tasks in ${tasksPath}: ${allTasks.length}`
|
`Successfully generated ${processedNewTasks.length} new tasks${research ? ' with research-backed analysis' : ''}. Total tasks in ${tasksPath}: ${finalTasks.length}`
|
||||||
),
|
),
|
||||||
{ padding: 1, borderColor: 'green', borderStyle: 'round' }
|
{ padding: 1, borderColor: 'green', borderStyle: 'round' }
|
||||||
)
|
)
|
||||||
@@ -314,9 +349,18 @@ Guidelines:
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (aiServiceResponse && aiServiceResponse.telemetryData) {
|
||||||
|
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success: true, tasks: processedNewTasks };
|
// Return telemetry data
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
tasksPath,
|
||||||
|
telemetryData: aiServiceResponse?.telemetryData
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
report(`Error parsing PRD: ${error.message}`, 'error');
|
report(`Error parsing PRD: ${error.message}`, 'error');
|
||||||
|
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ import path from 'path';
|
|||||||
import chalk from 'chalk';
|
import chalk from 'chalk';
|
||||||
import boxen from 'boxen';
|
import boxen from 'boxen';
|
||||||
import Table from 'cli-table3';
|
import Table from 'cli-table3';
|
||||||
import { z } from 'zod';
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getStatusWithColor,
|
getStatusWithColor,
|
||||||
startLoadingIndicator,
|
startLoadingIndicator,
|
||||||
stopLoadingIndicator
|
stopLoadingIndicator,
|
||||||
|
displayAiUsageSummary
|
||||||
} from '../ui.js';
|
} from '../ui.js';
|
||||||
import {
|
import {
|
||||||
log as consoleLog,
|
log as consoleLog,
|
||||||
@@ -17,10 +17,7 @@ import {
|
|||||||
truncate,
|
truncate,
|
||||||
isSilentMode
|
isSilentMode
|
||||||
} from '../utils.js';
|
} from '../utils.js';
|
||||||
import {
|
import { generateTextService } from '../ai-services-unified.js';
|
||||||
generateObjectService,
|
|
||||||
generateTextService
|
|
||||||
} from '../ai-services-unified.js';
|
|
||||||
import { getDebugFlag } from '../config-manager.js';
|
import { getDebugFlag } from '../config-manager.js';
|
||||||
import generateTaskFiles from './generate-task-files.js';
|
import generateTaskFiles from './generate-task-files.js';
|
||||||
|
|
||||||
@@ -64,7 +61,6 @@ async function updateSubtaskById(
|
|||||||
try {
|
try {
|
||||||
report('info', `Updating subtask ${subtaskId} with prompt: "${prompt}"`);
|
report('info', `Updating subtask ${subtaskId} with prompt: "${prompt}"`);
|
||||||
|
|
||||||
// Validate subtask ID format
|
|
||||||
if (
|
if (
|
||||||
!subtaskId ||
|
!subtaskId ||
|
||||||
typeof subtaskId !== 'string' ||
|
typeof subtaskId !== 'string' ||
|
||||||
@@ -75,19 +71,16 @@ async function updateSubtaskById(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate prompt
|
|
||||||
if (!prompt || typeof prompt !== 'string' || prompt.trim() === '') {
|
if (!prompt || typeof prompt !== 'string' || prompt.trim() === '') {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'Prompt cannot be empty. Please provide context for the subtask update.'
|
'Prompt cannot be empty. Please provide context for the subtask update.'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate tasks file exists
|
|
||||||
if (!fs.existsSync(tasksPath)) {
|
if (!fs.existsSync(tasksPath)) {
|
||||||
throw new Error(`Tasks file not found at path: ${tasksPath}`);
|
throw new Error(`Tasks file not found at path: ${tasksPath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the tasks file
|
|
||||||
const data = readJSON(tasksPath);
|
const data = readJSON(tasksPath);
|
||||||
if (!data || !data.tasks) {
|
if (!data || !data.tasks) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -95,7 +88,6 @@ async function updateSubtaskById(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse parent and subtask IDs
|
|
||||||
const [parentIdStr, subtaskIdStr] = subtaskId.split('.');
|
const [parentIdStr, subtaskIdStr] = subtaskId.split('.');
|
||||||
const parentId = parseInt(parentIdStr, 10);
|
const parentId = parseInt(parentIdStr, 10);
|
||||||
const subtaskIdNum = parseInt(subtaskIdStr, 10);
|
const subtaskIdNum = parseInt(subtaskIdStr, 10);
|
||||||
@@ -111,7 +103,6 @@ async function updateSubtaskById(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the parent task
|
|
||||||
const parentTask = data.tasks.find((task) => task.id === parentId);
|
const parentTask = data.tasks.find((task) => task.id === parentId);
|
||||||
if (!parentTask) {
|
if (!parentTask) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -119,7 +110,6 @@ async function updateSubtaskById(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the subtask
|
|
||||||
if (!parentTask.subtasks || !Array.isArray(parentTask.subtasks)) {
|
if (!parentTask.subtasks || !Array.isArray(parentTask.subtasks)) {
|
||||||
throw new Error(`Parent task ${parentId} has no subtasks.`);
|
throw new Error(`Parent task ${parentId} has no subtasks.`);
|
||||||
}
|
}
|
||||||
@@ -135,20 +125,7 @@ async function updateSubtaskById(
|
|||||||
|
|
||||||
const subtask = parentTask.subtasks[subtaskIndex];
|
const subtask = parentTask.subtasks[subtaskIndex];
|
||||||
|
|
||||||
const subtaskSchema = z.object({
|
|
||||||
id: z.number().int().positive(),
|
|
||||||
title: z.string(),
|
|
||||||
description: z.string().optional(),
|
|
||||||
status: z.string(),
|
|
||||||
dependencies: z.array(z.union([z.string(), z.number()])).optional(),
|
|
||||||
priority: z.string().optional(),
|
|
||||||
details: z.string().optional(),
|
|
||||||
testStrategy: z.string().optional()
|
|
||||||
});
|
|
||||||
|
|
||||||
// Only show UI elements for text output (CLI)
|
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
// Show the subtask that will be updated
|
|
||||||
const table = new Table({
|
const table = new Table({
|
||||||
head: [
|
head: [
|
||||||
chalk.cyan.bold('ID'),
|
chalk.cyan.bold('ID'),
|
||||||
@@ -157,13 +134,11 @@ async function updateSubtaskById(
|
|||||||
],
|
],
|
||||||
colWidths: [10, 55, 10]
|
colWidths: [10, 55, 10]
|
||||||
});
|
});
|
||||||
|
|
||||||
table.push([
|
table.push([
|
||||||
subtaskId,
|
subtaskId,
|
||||||
truncate(subtask.title, 52),
|
truncate(subtask.title, 52),
|
||||||
getStatusWithColor(subtask.status)
|
getStatusWithColor(subtask.status)
|
||||||
]);
|
]);
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
boxen(chalk.white.bold(`Updating Subtask #${subtaskId}`), {
|
boxen(chalk.white.bold(`Updating Subtask #${subtaskId}`), {
|
||||||
padding: 1,
|
padding: 1,
|
||||||
@@ -172,10 +147,7 @@ async function updateSubtaskById(
|
|||||||
margin: { top: 1, bottom: 0 }
|
margin: { top: 1, bottom: 0 }
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log(table.toString());
|
console.log(table.toString());
|
||||||
|
|
||||||
// Start the loading indicator - only for text output
|
|
||||||
loadingIndicator = startLoadingIndicator(
|
loadingIndicator = startLoadingIndicator(
|
||||||
useResearch
|
useResearch
|
||||||
? 'Updating subtask with research...'
|
? 'Updating subtask with research...'
|
||||||
@@ -183,15 +155,15 @@ async function updateSubtaskById(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let parsedAIResponse;
|
let generatedContentString = '';
|
||||||
|
let newlyAddedSnippet = '';
|
||||||
|
let aiServiceResponse = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// --- GET PARENT & SIBLING CONTEXT ---
|
|
||||||
const parentContext = {
|
const parentContext = {
|
||||||
id: parentTask.id,
|
id: parentTask.id,
|
||||||
title: parentTask.title
|
title: parentTask.title
|
||||||
// Avoid sending full parent description/details unless necessary
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const prevSubtask =
|
const prevSubtask =
|
||||||
subtaskIndex > 0
|
subtaskIndex > 0
|
||||||
? {
|
? {
|
||||||
@@ -200,7 +172,6 @@ async function updateSubtaskById(
|
|||||||
status: parentTask.subtasks[subtaskIndex - 1].status
|
status: parentTask.subtasks[subtaskIndex - 1].status
|
||||||
}
|
}
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const nextSubtask =
|
const nextSubtask =
|
||||||
subtaskIndex < parentTask.subtasks.length - 1
|
subtaskIndex < parentTask.subtasks.length - 1
|
||||||
? {
|
? {
|
||||||
@@ -214,154 +185,123 @@ async function updateSubtaskById(
|
|||||||
Parent Task: ${JSON.stringify(parentContext)}
|
Parent Task: ${JSON.stringify(parentContext)}
|
||||||
${prevSubtask ? `Previous Subtask: ${JSON.stringify(prevSubtask)}` : ''}
|
${prevSubtask ? `Previous Subtask: ${JSON.stringify(prevSubtask)}` : ''}
|
||||||
${nextSubtask ? `Next Subtask: ${JSON.stringify(nextSubtask)}` : ''}
|
${nextSubtask ? `Next Subtask: ${JSON.stringify(nextSubtask)}` : ''}
|
||||||
|
Current Subtask Details (for context only):\n${subtask.details || '(No existing details)'}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const systemPrompt = `You are an AI assistant updating a parent task's subtask. This subtask will be part of a larger parent task and will be used to direct AI agents to complete the subtask. Your goal is to GENERATE new, relevant information based on the user's request (which may be high-level, mid-level or low-level) and APPEND it to the existing subtask 'details' field, wrapped in specific XML-like tags with an ISO 8601 timestamp. Intelligently determine the level of detail to include based on the user's request. Some requests are meant simply to update the subtask with some mid-implementation details, while others are meant to update the subtask with a detailed plan or strategy.
|
const systemPrompt = `You are an AI assistant helping to update a subtask. You will be provided with the subtask's existing details, context about its parent and sibling tasks, and a user request string.
|
||||||
|
|
||||||
Context Provided:
|
Your Goal: Based *only* on the user's request and all the provided context (including existing details if relevant to the request), GENERATE the new text content that should be added to the subtask's details.
|
||||||
- The current subtask object.
|
Focus *only* on generating the substance of the update.
|
||||||
- Basic info about the parent task (ID, title).
|
|
||||||
- Basic info about the immediately preceding subtask (ID, title, status), if it exists.
|
|
||||||
- Basic info about the immediately succeeding subtask (ID, title, status), if it exists.
|
|
||||||
- A user request string.
|
|
||||||
|
|
||||||
Guidelines:
|
Output Requirements:
|
||||||
1. Analyze the user request considering the provided subtask details AND the context of the parent and sibling tasks.
|
1. Return *only* the newly generated text content as a plain string. Do NOT return a JSON object or any other structured data.
|
||||||
2. GENERATE new, relevant text content that should be added to the 'details' field. Focus *only* on the substance of the update based on the user request and context. Do NOT add timestamps or any special formatting yourself. Avoid over-engineering the details, provide .
|
2. Your string response should NOT include any of the subtask's original details, unless the user's request explicitly asks to rephrase, summarize, or directly modify existing text.
|
||||||
3. Update the 'details' field in the subtask object with the GENERATED text content. It's okay if this overwrites previous details in the object you return, as the calling code will handle the final appending.
|
3. Do NOT include any timestamps, XML-like tags, markdown, or any other special formatting in your string response.
|
||||||
4. Return the *entire* updated subtask object (with your generated content in the 'details' field) as a valid JSON object conforming to the provided schema. Do NOT return explanations or markdown formatting.`;
|
4. Ensure the generated text is concise yet complete for the update based on the user request. Avoid conversational fillers or explanations about what you are doing (e.g., do not start with "Okay, here's the update...").`;
|
||||||
|
|
||||||
const subtaskDataString = JSON.stringify(subtask, null, 2);
|
// Pass the existing subtask.details in the user prompt for the AI's context.
|
||||||
// Updated user prompt including context
|
const userPrompt = `Task Context:\n${contextString}\n\nUser Request: "${prompt}"\n\nBased on the User Request and all the Task Context (including current subtask details provided above), what is the new information or text that should be appended to this subtask's details? Return ONLY this new text as a plain string.`;
|
||||||
const userPrompt = `Task Context:\n${contextString}\nCurrent Subtask:\n${subtaskDataString}\n\nUser Request: "${prompt}"\n\nPlease GENERATE new, relevant text content for the 'details' field based on the user request and the provided context. Return the entire updated subtask object as a valid JSON object matching the schema, with the newly generated text placed in the 'details' field.`;
|
|
||||||
// --- END UPDATED PROMPTS ---
|
|
||||||
|
|
||||||
// Call Unified AI Service using generateObjectService
|
|
||||||
const role = useResearch ? 'research' : 'main';
|
const role = useResearch ? 'research' : 'main';
|
||||||
report('info', `Using AI object service with role: ${role}`);
|
report('info', `Using AI text service with role: ${role}`);
|
||||||
|
|
||||||
parsedAIResponse = await generateObjectService({
|
aiServiceResponse = await generateTextService({
|
||||||
prompt: userPrompt,
|
prompt: userPrompt,
|
||||||
systemPrompt: systemPrompt,
|
systemPrompt: systemPrompt,
|
||||||
schema: subtaskSchema,
|
|
||||||
objectName: 'updatedSubtask',
|
|
||||||
role,
|
role,
|
||||||
session,
|
session,
|
||||||
projectRoot,
|
projectRoot,
|
||||||
maxRetries: 2
|
maxRetries: 2,
|
||||||
|
commandName: 'update-subtask',
|
||||||
|
outputType: isMCP ? 'mcp' : 'cli'
|
||||||
});
|
});
|
||||||
report(
|
|
||||||
'success',
|
if (
|
||||||
'Successfully received object response from AI service'
|
aiServiceResponse &&
|
||||||
);
|
aiServiceResponse.mainResult &&
|
||||||
|
typeof aiServiceResponse.mainResult === 'string'
|
||||||
|
) {
|
||||||
|
generatedContentString = aiServiceResponse.mainResult;
|
||||||
|
} else {
|
||||||
|
generatedContentString = '';
|
||||||
|
report(
|
||||||
|
'warn',
|
||||||
|
'AI service response did not contain expected text string.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (outputFormat === 'text' && loadingIndicator) {
|
if (outputFormat === 'text' && loadingIndicator) {
|
||||||
stopLoadingIndicator(loadingIndicator);
|
stopLoadingIndicator(loadingIndicator);
|
||||||
loadingIndicator = null;
|
loadingIndicator = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!parsedAIResponse || typeof parsedAIResponse !== 'object') {
|
|
||||||
throw new Error('AI did not return a valid object.');
|
|
||||||
}
|
|
||||||
|
|
||||||
report(
|
|
||||||
'success',
|
|
||||||
`Successfully generated object using AI role: ${role}.`
|
|
||||||
);
|
|
||||||
} catch (aiError) {
|
} catch (aiError) {
|
||||||
report('error', `AI service call failed: ${aiError.message}`);
|
report('error', `AI service call failed: ${aiError.message}`);
|
||||||
if (outputFormat === 'text' && loadingIndicator) {
|
if (outputFormat === 'text' && loadingIndicator) {
|
||||||
stopLoadingIndicator(loadingIndicator); // Ensure stop on error
|
stopLoadingIndicator(loadingIndicator);
|
||||||
loadingIndicator = null;
|
loadingIndicator = null;
|
||||||
}
|
}
|
||||||
throw aiError;
|
throw aiError;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- TIMESTAMP & FORMATTING LOGIC (Handled Locally) ---
|
if (generatedContentString && generatedContentString.trim()) {
|
||||||
// Extract only the generated content from the AI's response details field.
|
// Check if the string is not empty
|
||||||
const generatedContent = parsedAIResponse.details || ''; // Default to empty string
|
const timestamp = new Date().toISOString();
|
||||||
|
const formattedBlock = `<info added on ${timestamp}>\n${generatedContentString.trim()}\n</info added on ${timestamp}>`;
|
||||||
|
newlyAddedSnippet = formattedBlock; // <--- ADD THIS LINE: Store for display
|
||||||
|
|
||||||
if (generatedContent.trim()) {
|
|
||||||
// Generate timestamp locally
|
|
||||||
const timestamp = new Date().toISOString(); // <<< Local Timestamp
|
|
||||||
|
|
||||||
// Format the content with XML-like tags and timestamp LOCALLY
|
|
||||||
const formattedBlock = `<info added on ${timestamp}>\n${generatedContent.trim()}\n</info added on ${timestamp}>`; // <<< Local Formatting
|
|
||||||
|
|
||||||
// Append the formatted block to the *original* subtask details
|
|
||||||
subtask.details =
|
subtask.details =
|
||||||
(subtask.details ? subtask.details + '\n' : '') + formattedBlock; // <<< Local Appending
|
(subtask.details ? subtask.details + '\n' : '') + formattedBlock;
|
||||||
report(
|
|
||||||
'info',
|
|
||||||
'Appended timestamped, formatted block with AI-generated content to subtask.details.'
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
report(
|
report(
|
||||||
'warn',
|
'warn',
|
||||||
'AI response object did not contain generated content in the "details" field. Original details remain unchanged.'
|
'AI response was empty or whitespace after trimming. Original details remain unchanged.'
|
||||||
);
|
);
|
||||||
|
newlyAddedSnippet = 'No new details were added by the AI.';
|
||||||
}
|
}
|
||||||
// --- END TIMESTAMP & FORMATTING LOGIC ---
|
|
||||||
|
|
||||||
// Get a reference to the subtask *after* its details have been updated
|
const updatedSubtask = parentTask.subtasks[subtaskIndex];
|
||||||
const updatedSubtask = parentTask.subtasks[subtaskIndex]; // subtask === updatedSubtask now
|
|
||||||
|
|
||||||
report('info', 'Updated subtask details locally after AI generation.');
|
|
||||||
// --- END UPDATE SUBTASK ---
|
|
||||||
|
|
||||||
// Only show debug info for text output (CLI)
|
|
||||||
if (outputFormat === 'text' && getDebugFlag(session)) {
|
if (outputFormat === 'text' && getDebugFlag(session)) {
|
||||||
console.log(
|
console.log(
|
||||||
'>>> DEBUG: Subtask details AFTER AI update:',
|
'>>> DEBUG: Subtask details AFTER AI update:',
|
||||||
updatedSubtask.details // Use updatedSubtask
|
updatedSubtask.details
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Description update logic (keeping as is for now)
|
|
||||||
if (updatedSubtask.description) {
|
if (updatedSubtask.description) {
|
||||||
// Use updatedSubtask
|
|
||||||
if (prompt.length < 100) {
|
if (prompt.length < 100) {
|
||||||
if (outputFormat === 'text' && getDebugFlag(session)) {
|
if (outputFormat === 'text' && getDebugFlag(session)) {
|
||||||
console.log(
|
console.log(
|
||||||
'>>> DEBUG: Subtask description BEFORE append:',
|
'>>> DEBUG: Subtask description BEFORE append:',
|
||||||
updatedSubtask.description // Use updatedSubtask
|
updatedSubtask.description
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
updatedSubtask.description += ` [Updated: ${new Date().toLocaleDateString()}]`; // Use updatedSubtask
|
updatedSubtask.description += ` [Updated: ${new Date().toLocaleDateString()}]`;
|
||||||
if (outputFormat === 'text' && getDebugFlag(session)) {
|
if (outputFormat === 'text' && getDebugFlag(session)) {
|
||||||
console.log(
|
console.log(
|
||||||
'>>> DEBUG: Subtask description AFTER append:',
|
'>>> DEBUG: Subtask description AFTER append:',
|
||||||
updatedSubtask.description // Use updatedSubtask
|
updatedSubtask.description
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only show debug info for text output (CLI)
|
|
||||||
if (outputFormat === 'text' && getDebugFlag(session)) {
|
if (outputFormat === 'text' && getDebugFlag(session)) {
|
||||||
console.log('>>> DEBUG: About to call writeJSON with updated data...');
|
console.log('>>> DEBUG: About to call writeJSON with updated data...');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write the updated tasks to the file (parentTask already contains the updated subtask)
|
|
||||||
writeJSON(tasksPath, data);
|
writeJSON(tasksPath, data);
|
||||||
|
|
||||||
// Only show debug info for text output (CLI)
|
|
||||||
if (outputFormat === 'text' && getDebugFlag(session)) {
|
if (outputFormat === 'text' && getDebugFlag(session)) {
|
||||||
console.log('>>> DEBUG: writeJSON call completed.');
|
console.log('>>> DEBUG: writeJSON call completed.');
|
||||||
}
|
}
|
||||||
|
|
||||||
report('success', `Successfully updated subtask ${subtaskId}`);
|
report('success', `Successfully updated subtask ${subtaskId}`);
|
||||||
|
|
||||||
// Generate individual task files
|
|
||||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||||
|
|
||||||
// Stop indicator before final console output - only for text output (CLI)
|
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
if (loadingIndicator) {
|
if (loadingIndicator) {
|
||||||
stopLoadingIndicator(loadingIndicator);
|
stopLoadingIndicator(loadingIndicator);
|
||||||
loadingIndicator = null;
|
loadingIndicator = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
boxen(
|
boxen(
|
||||||
chalk.green(`Successfully updated subtask #${subtaskId}`) +
|
chalk.green(`Successfully updated subtask #${subtaskId}`) +
|
||||||
@@ -370,31 +310,30 @@ Guidelines:
|
|||||||
' ' +
|
' ' +
|
||||||
updatedSubtask.title +
|
updatedSubtask.title +
|
||||||
'\n\n' +
|
'\n\n' +
|
||||||
// Update the display to show the new details field
|
chalk.white.bold('Newly Added Snippet:') +
|
||||||
chalk.white.bold('Updated Details:') +
|
|
||||||
'\n' +
|
'\n' +
|
||||||
chalk.white(truncate(updatedSubtask.details || '', 500, true)), // Use updatedSubtask
|
chalk.white(newlyAddedSnippet),
|
||||||
{ padding: 1, borderColor: 'green', borderStyle: 'round' }
|
{ padding: 1, borderColor: 'green', borderStyle: 'round' }
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return updatedSubtask; // Return the modified subtask object
|
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
|
||||||
|
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
updatedSubtask: updatedSubtask,
|
||||||
|
telemetryData: aiServiceResponse.telemetryData
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Outer catch block handles final errors after loop/attempts
|
|
||||||
// Stop indicator on error - only for text output (CLI)
|
|
||||||
if (outputFormat === 'text' && loadingIndicator) {
|
if (outputFormat === 'text' && loadingIndicator) {
|
||||||
stopLoadingIndicator(loadingIndicator);
|
stopLoadingIndicator(loadingIndicator);
|
||||||
loadingIndicator = null;
|
loadingIndicator = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
report('error', `Error updating subtask: ${error.message}`);
|
report('error', `Error updating subtask: ${error.message}`);
|
||||||
|
|
||||||
// Only show error UI for text output (CLI)
|
|
||||||
if (outputFormat === 'text') {
|
if (outputFormat === 'text') {
|
||||||
console.error(chalk.red(`Error: ${error.message}`));
|
console.error(chalk.red(`Error: ${error.message}`));
|
||||||
|
|
||||||
// Provide helpful error messages based on error type
|
|
||||||
if (error.message?.includes('ANTHROPIC_API_KEY')) {
|
if (error.message?.includes('ANTHROPIC_API_KEY')) {
|
||||||
console.log(
|
console.log(
|
||||||
chalk.yellow('\nTo fix this issue, set your Anthropic API key:')
|
chalk.yellow('\nTo fix this issue, set your Anthropic API key:')
|
||||||
@@ -409,7 +348,6 @@ Guidelines:
|
|||||||
' 2. Or run without the research flag: task-master update-subtask --id=<id> --prompt="..."'
|
' 2. Or run without the research flag: task-master update-subtask --id=<id> --prompt="..."'
|
||||||
);
|
);
|
||||||
} else if (error.message?.includes('overloaded')) {
|
} else if (error.message?.includes('overloaded')) {
|
||||||
// Catch final overload error
|
|
||||||
console.log(
|
console.log(
|
||||||
chalk.yellow(
|
chalk.yellow(
|
||||||
'\nAI model overloaded, and fallback failed or was unavailable:'
|
'\nAI model overloaded, and fallback failed or was unavailable:'
|
||||||
@@ -417,7 +355,6 @@ Guidelines:
|
|||||||
);
|
);
|
||||||
console.log(' 1. Try again in a few minutes.');
|
console.log(' 1. Try again in a few minutes.');
|
||||||
console.log(' 2. Ensure PERPLEXITY_API_KEY is set for fallback.');
|
console.log(' 2. Ensure PERPLEXITY_API_KEY is set for fallback.');
|
||||||
console.log(' 3. Consider breaking your prompt into smaller updates.');
|
|
||||||
} else if (error.message?.includes('not found')) {
|
} else if (error.message?.includes('not found')) {
|
||||||
console.log(chalk.yellow('\nTo fix this issue:'));
|
console.log(chalk.yellow('\nTo fix this issue:'));
|
||||||
console.log(
|
console.log(
|
||||||
@@ -426,22 +363,22 @@ Guidelines:
|
|||||||
console.log(
|
console.log(
|
||||||
' 2. Use a valid subtask ID with the --id parameter in format "parentId.subtaskId"'
|
' 2. Use a valid subtask ID with the --id parameter in format "parentId.subtaskId"'
|
||||||
);
|
);
|
||||||
} else if (error.message?.includes('empty stream response')) {
|
} else if (
|
||||||
|
error.message?.includes('empty stream response') ||
|
||||||
|
error.message?.includes('AI did not return a valid text string')
|
||||||
|
) {
|
||||||
console.log(
|
console.log(
|
||||||
chalk.yellow(
|
chalk.yellow(
|
||||||
'\nThe AI model returned an empty response. This might be due to the prompt or API issues. Try rephrasing or trying again later.'
|
'\nThe AI model returned an empty or invalid response. This might be due to the prompt or API issues. Try rephrasing or trying again later.'
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (getDebugFlag(session)) {
|
if (getDebugFlag(session)) {
|
||||||
// Use getter
|
|
||||||
console.error(error);
|
console.error(error);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw error; // Re-throw for JSON output
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ import {
|
|||||||
import {
|
import {
|
||||||
getStatusWithColor,
|
getStatusWithColor,
|
||||||
startLoadingIndicator,
|
startLoadingIndicator,
|
||||||
stopLoadingIndicator
|
stopLoadingIndicator,
|
||||||
|
displayAiUsageSummary
|
||||||
} from '../ui.js';
|
} from '../ui.js';
|
||||||
|
|
||||||
import { generateTextService } from '../ai-services-unified.js';
|
import { generateTextService } from '../ai-services-unified.js';
|
||||||
@@ -94,10 +95,6 @@ function parseUpdatedTaskFromText(text, expectedTaskId, logFn, isMCP) {
|
|||||||
// It worked! Use this as the primary cleaned response.
|
// It worked! Use this as the primary cleaned response.
|
||||||
cleanedResponse = potentialJsonFromBraces;
|
cleanedResponse = potentialJsonFromBraces;
|
||||||
parseMethodUsed = 'braces';
|
parseMethodUsed = 'braces';
|
||||||
report(
|
|
||||||
'info',
|
|
||||||
'Successfully parsed JSON content extracted between first { and last }.'
|
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
report(
|
report(
|
||||||
'info',
|
'info',
|
||||||
@@ -376,29 +373,125 @@ The changes described in the prompt should be thoughtfully applied to make the t
|
|||||||
const userPrompt = `Here is the task to update:\n${taskDataString}\n\nPlease update this task based on the following new context:\n${prompt}\n\nIMPORTANT: In the task JSON above, any subtasks with "status": "done" or "status": "completed" should be preserved exactly as is. Build your changes around these completed items.\n\nReturn only the updated task as a valid JSON object.`;
|
const userPrompt = `Here is the task to update:\n${taskDataString}\n\nPlease update this task based on the following new context:\n${prompt}\n\nIMPORTANT: In the task JSON above, any subtasks with "status": "done" or "status": "completed" should be preserved exactly as is. Build your changes around these completed items.\n\nReturn only the updated task as a valid JSON object.`;
|
||||||
// --- End Build Prompts ---
|
// --- End Build Prompts ---
|
||||||
|
|
||||||
let updatedTask;
|
|
||||||
let loadingIndicator = null;
|
let loadingIndicator = null;
|
||||||
if (outputFormat === 'text') {
|
let aiServiceResponse = null;
|
||||||
|
|
||||||
|
if (!isMCP && outputFormat === 'text') {
|
||||||
loadingIndicator = startLoadingIndicator(
|
loadingIndicator = startLoadingIndicator(
|
||||||
useResearch ? 'Updating task with research...\n' : 'Updating task...\n'
|
useResearch ? 'Updating task with research...\n' : 'Updating task...\n'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let responseText = '';
|
|
||||||
try {
|
try {
|
||||||
// --- Call Unified AI Service (generateTextService) ---
|
const serviceRole = useResearch ? 'research' : 'main';
|
||||||
const role = useResearch ? 'research' : 'main';
|
aiServiceResponse = await generateTextService({
|
||||||
report('info', `Using AI service with role: ${role}`);
|
role: serviceRole,
|
||||||
|
session: session,
|
||||||
responseText = await generateTextService({
|
projectRoot: projectRoot,
|
||||||
prompt: userPrompt,
|
|
||||||
systemPrompt: systemPrompt,
|
systemPrompt: systemPrompt,
|
||||||
role,
|
prompt: userPrompt,
|
||||||
session,
|
commandName: 'update-task',
|
||||||
projectRoot
|
outputType: isMCP ? 'mcp' : 'cli'
|
||||||
});
|
});
|
||||||
report('success', 'Successfully received text response from AI service');
|
|
||||||
// --- End AI Service Call ---
|
if (loadingIndicator)
|
||||||
|
stopLoadingIndicator(loadingIndicator, 'AI update complete.');
|
||||||
|
|
||||||
|
// Use mainResult (text) for parsing
|
||||||
|
const updatedTask = parseUpdatedTaskFromText(
|
||||||
|
aiServiceResponse.mainResult,
|
||||||
|
taskId,
|
||||||
|
logFn,
|
||||||
|
isMCP
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- Task Validation/Correction (Keep existing logic) ---
|
||||||
|
if (!updatedTask || typeof updatedTask !== 'object')
|
||||||
|
throw new Error('Received invalid task object from AI.');
|
||||||
|
if (!updatedTask.title || !updatedTask.description)
|
||||||
|
throw new Error('Updated task missing required fields.');
|
||||||
|
// Preserve ID if AI changed it
|
||||||
|
if (updatedTask.id !== taskId) {
|
||||||
|
report('warn', `AI changed task ID. Restoring original ID ${taskId}.`);
|
||||||
|
updatedTask.id = taskId;
|
||||||
|
}
|
||||||
|
// Preserve status if AI changed it
|
||||||
|
if (
|
||||||
|
updatedTask.status !== taskToUpdate.status &&
|
||||||
|
!prompt.toLowerCase().includes('status')
|
||||||
|
) {
|
||||||
|
report(
|
||||||
|
'warn',
|
||||||
|
`AI changed task status. Restoring original status '${taskToUpdate.status}'.`
|
||||||
|
);
|
||||||
|
updatedTask.status = taskToUpdate.status;
|
||||||
|
}
|
||||||
|
// Preserve completed subtasks (Keep existing logic)
|
||||||
|
if (taskToUpdate.subtasks?.length > 0) {
|
||||||
|
if (!updatedTask.subtasks) {
|
||||||
|
report(
|
||||||
|
'warn',
|
||||||
|
'Subtasks removed by AI. Restoring original subtasks.'
|
||||||
|
);
|
||||||
|
updatedTask.subtasks = taskToUpdate.subtasks;
|
||||||
|
} else {
|
||||||
|
const completedOriginal = taskToUpdate.subtasks.filter(
|
||||||
|
(st) => st.status === 'done' || st.status === 'completed'
|
||||||
|
);
|
||||||
|
completedOriginal.forEach((compSub) => {
|
||||||
|
const updatedSub = updatedTask.subtasks.find(
|
||||||
|
(st) => st.id === compSub.id
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!updatedSub ||
|
||||||
|
JSON.stringify(updatedSub) !== JSON.stringify(compSub)
|
||||||
|
) {
|
||||||
|
report(
|
||||||
|
'warn',
|
||||||
|
`Completed subtask ${compSub.id} was modified or removed. Restoring.`
|
||||||
|
);
|
||||||
|
// Remove potentially modified version
|
||||||
|
updatedTask.subtasks = updatedTask.subtasks.filter(
|
||||||
|
(st) => st.id !== compSub.id
|
||||||
|
);
|
||||||
|
// Add back original
|
||||||
|
updatedTask.subtasks.push(compSub);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Deduplicate just in case
|
||||||
|
const subtaskIds = new Set();
|
||||||
|
updatedTask.subtasks = updatedTask.subtasks.filter((st) => {
|
||||||
|
if (!subtaskIds.has(st.id)) {
|
||||||
|
subtaskIds.add(st.id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
report('warn', `Duplicate subtask ID ${st.id} removed.`);
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// --- End Task Validation/Correction ---
|
||||||
|
|
||||||
|
// --- Update Task Data (Keep existing) ---
|
||||||
|
data.tasks[taskIndex] = updatedTask;
|
||||||
|
// --- End Update Task Data ---
|
||||||
|
|
||||||
|
// --- Write File and Generate (Unchanged) ---
|
||||||
|
writeJSON(tasksPath, data);
|
||||||
|
report('success', `Successfully updated task ${taskId}`);
|
||||||
|
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||||
|
// --- End Write File ---
|
||||||
|
|
||||||
|
// --- Display CLI Telemetry ---
|
||||||
|
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
|
||||||
|
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli'); // <<< ADD display
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Return Success with Telemetry ---
|
||||||
|
return {
|
||||||
|
updatedTask: updatedTask, // Return the updated task object
|
||||||
|
telemetryData: aiServiceResponse.telemetryData // <<< ADD telemetryData
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Catch errors from generateTextService
|
// Catch errors from generateTextService
|
||||||
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
||||||
@@ -407,114 +500,7 @@ The changes described in the prompt should be thoughtfully applied to make the t
|
|||||||
report('error', 'Please ensure API keys are configured correctly.');
|
report('error', 'Please ensure API keys are configured correctly.');
|
||||||
}
|
}
|
||||||
throw error; // Re-throw error
|
throw error; // Re-throw error
|
||||||
} finally {
|
|
||||||
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Parse and Validate Response ---
|
|
||||||
try {
|
|
||||||
// Pass logFn and isMCP flag to the parser
|
|
||||||
updatedTask = parseUpdatedTaskFromText(
|
|
||||||
responseText,
|
|
||||||
taskId,
|
|
||||||
logFn,
|
|
||||||
isMCP
|
|
||||||
);
|
|
||||||
} catch (parseError) {
|
|
||||||
report(
|
|
||||||
'error',
|
|
||||||
`Failed to parse updated task from AI response: ${parseError.message}`
|
|
||||||
);
|
|
||||||
if (getDebugFlag(session)) {
|
|
||||||
report('error', `Raw AI Response:\n${responseText}`);
|
|
||||||
}
|
|
||||||
throw new Error(
|
|
||||||
`Failed to parse valid updated task from AI response: ${parseError.message}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// --- End Parse/Validate ---
|
|
||||||
|
|
||||||
// --- Task Validation/Correction (Keep existing logic) ---
|
|
||||||
if (!updatedTask || typeof updatedTask !== 'object')
|
|
||||||
throw new Error('Received invalid task object from AI.');
|
|
||||||
if (!updatedTask.title || !updatedTask.description)
|
|
||||||
throw new Error('Updated task missing required fields.');
|
|
||||||
// Preserve ID if AI changed it
|
|
||||||
if (updatedTask.id !== taskId) {
|
|
||||||
report('warn', `AI changed task ID. Restoring original ID ${taskId}.`);
|
|
||||||
updatedTask.id = taskId;
|
|
||||||
}
|
|
||||||
// Preserve status if AI changed it
|
|
||||||
if (
|
|
||||||
updatedTask.status !== taskToUpdate.status &&
|
|
||||||
!prompt.toLowerCase().includes('status')
|
|
||||||
) {
|
|
||||||
report(
|
|
||||||
'warn',
|
|
||||||
`AI changed task status. Restoring original status '${taskToUpdate.status}'.`
|
|
||||||
);
|
|
||||||
updatedTask.status = taskToUpdate.status;
|
|
||||||
}
|
|
||||||
// Preserve completed subtasks (Keep existing logic)
|
|
||||||
if (taskToUpdate.subtasks?.length > 0) {
|
|
||||||
if (!updatedTask.subtasks) {
|
|
||||||
report('warn', 'Subtasks removed by AI. Restoring original subtasks.');
|
|
||||||
updatedTask.subtasks = taskToUpdate.subtasks;
|
|
||||||
} else {
|
|
||||||
const completedOriginal = taskToUpdate.subtasks.filter(
|
|
||||||
(st) => st.status === 'done' || st.status === 'completed'
|
|
||||||
);
|
|
||||||
completedOriginal.forEach((compSub) => {
|
|
||||||
const updatedSub = updatedTask.subtasks.find(
|
|
||||||
(st) => st.id === compSub.id
|
|
||||||
);
|
|
||||||
if (
|
|
||||||
!updatedSub ||
|
|
||||||
JSON.stringify(updatedSub) !== JSON.stringify(compSub)
|
|
||||||
) {
|
|
||||||
report(
|
|
||||||
'warn',
|
|
||||||
`Completed subtask ${compSub.id} was modified or removed. Restoring.`
|
|
||||||
);
|
|
||||||
// Remove potentially modified version
|
|
||||||
updatedTask.subtasks = updatedTask.subtasks.filter(
|
|
||||||
(st) => st.id !== compSub.id
|
|
||||||
);
|
|
||||||
// Add back original
|
|
||||||
updatedTask.subtasks.push(compSub);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// Deduplicate just in case
|
|
||||||
const subtaskIds = new Set();
|
|
||||||
updatedTask.subtasks = updatedTask.subtasks.filter((st) => {
|
|
||||||
if (!subtaskIds.has(st.id)) {
|
|
||||||
subtaskIds.add(st.id);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
report('warn', `Duplicate subtask ID ${st.id} removed.`);
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// --- End Task Validation/Correction ---
|
|
||||||
|
|
||||||
// --- Update Task Data (Keep existing) ---
|
|
||||||
data.tasks[taskIndex] = updatedTask;
|
|
||||||
// --- End Update Task Data ---
|
|
||||||
|
|
||||||
// --- Write File and Generate (Keep existing) ---
|
|
||||||
writeJSON(tasksPath, data);
|
|
||||||
report('success', `Successfully updated task ${taskId}`);
|
|
||||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
|
||||||
// --- End Write File ---
|
|
||||||
|
|
||||||
// --- Final CLI Output (Keep existing) ---
|
|
||||||
if (outputFormat === 'text') {
|
|
||||||
/* ... success boxen ... */
|
|
||||||
}
|
|
||||||
// --- End Final CLI Output ---
|
|
||||||
|
|
||||||
return updatedTask; // Return the updated task
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// General error catch
|
// General error catch
|
||||||
// --- General Error Handling (Keep existing) ---
|
// --- General Error Handling (Keep existing) ---
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ import {
|
|||||||
import {
|
import {
|
||||||
getStatusWithColor,
|
getStatusWithColor,
|
||||||
startLoadingIndicator,
|
startLoadingIndicator,
|
||||||
stopLoadingIndicator
|
stopLoadingIndicator,
|
||||||
|
displayAiUsageSummary
|
||||||
} from '../ui.js';
|
} from '../ui.js';
|
||||||
|
|
||||||
import { getDebugFlag } from '../config-manager.js';
|
import { getDebugFlag } from '../config-manager.js';
|
||||||
@@ -93,10 +94,6 @@ function parseUpdatedTasksFromText(text, expectedCount, logFn, isMCP) {
|
|||||||
// It worked! Use this as the primary cleaned response.
|
// It worked! Use this as the primary cleaned response.
|
||||||
cleanedResponse = potentialJsonFromArray;
|
cleanedResponse = potentialJsonFromArray;
|
||||||
parseMethodUsed = 'brackets';
|
parseMethodUsed = 'brackets';
|
||||||
report(
|
|
||||||
'info',
|
|
||||||
'Successfully parsed JSON content extracted between first [ and last ].'
|
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
report(
|
report(
|
||||||
'info',
|
'info',
|
||||||
@@ -350,31 +347,100 @@ The changes described in the prompt should be applied to ALL tasks in the list.`
|
|||||||
const userPrompt = `Here are the tasks to update:\n${taskDataString}\n\nPlease update these tasks based on the following new context:\n${prompt}\n\nIMPORTANT: In the tasks JSON above, any subtasks with "status": "done" or "status": "completed" should be preserved exactly as is. Build your changes around these completed items.\n\nReturn only the updated tasks as a valid JSON array.`;
|
const userPrompt = `Here are the tasks to update:\n${taskDataString}\n\nPlease update these tasks based on the following new context:\n${prompt}\n\nIMPORTANT: In the tasks JSON above, any subtasks with "status": "done" or "status": "completed" should be preserved exactly as is. Build your changes around these completed items.\n\nReturn only the updated tasks as a valid JSON array.`;
|
||||||
// --- End Build Prompts ---
|
// --- End Build Prompts ---
|
||||||
|
|
||||||
|
// --- AI Call ---
|
||||||
let loadingIndicator = null;
|
let loadingIndicator = null;
|
||||||
if (outputFormat === 'text') {
|
let aiServiceResponse = null;
|
||||||
loadingIndicator = startLoadingIndicator('Updating tasks...\n');
|
|
||||||
|
if (!isMCP && outputFormat === 'text') {
|
||||||
|
loadingIndicator = startLoadingIndicator('Updating tasks with AI...\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
let responseText = '';
|
|
||||||
let updatedTasks;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// --- Call Unified AI Service ---
|
// Determine role based on research flag
|
||||||
const role = useResearch ? 'research' : 'main';
|
const serviceRole = useResearch ? 'research' : 'main';
|
||||||
if (isMCP) logFn.info(`Using AI service with role: ${role}`);
|
|
||||||
else logFn('info', `Using AI service with role: ${role}`);
|
|
||||||
|
|
||||||
responseText = await generateTextService({
|
// Call the unified AI service
|
||||||
prompt: userPrompt,
|
aiServiceResponse = await generateTextService({
|
||||||
|
role: serviceRole,
|
||||||
|
session: session,
|
||||||
|
projectRoot: projectRoot,
|
||||||
systemPrompt: systemPrompt,
|
systemPrompt: systemPrompt,
|
||||||
role,
|
prompt: userPrompt,
|
||||||
session,
|
commandName: 'update-tasks',
|
||||||
projectRoot
|
outputType: isMCP ? 'mcp' : 'cli'
|
||||||
});
|
});
|
||||||
if (isMCP) logFn.info('Successfully received text response');
|
|
||||||
|
if (loadingIndicator)
|
||||||
|
stopLoadingIndicator(loadingIndicator, 'AI update complete.');
|
||||||
|
|
||||||
|
// Use the mainResult (text) for parsing
|
||||||
|
const parsedUpdatedTasks = parseUpdatedTasksFromText(
|
||||||
|
aiServiceResponse.mainResult,
|
||||||
|
tasksToUpdate.length,
|
||||||
|
logFn,
|
||||||
|
isMCP
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- Update Tasks Data (Unchanged) ---
|
||||||
|
if (!Array.isArray(parsedUpdatedTasks)) {
|
||||||
|
// Should be caught by parser, but extra check
|
||||||
|
throw new Error(
|
||||||
|
'Parsed AI response for updated tasks was not an array.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (isMCP)
|
||||||
|
logFn.info(
|
||||||
|
`Received ${parsedUpdatedTasks.length} updated tasks from AI.`
|
||||||
|
);
|
||||||
else
|
else
|
||||||
logFn('success', 'Successfully received text response via AI service');
|
logFn(
|
||||||
// --- End AI Service Call ---
|
'info',
|
||||||
|
`Received ${parsedUpdatedTasks.length} updated tasks from AI.`
|
||||||
|
);
|
||||||
|
// Create a map for efficient lookup
|
||||||
|
const updatedTasksMap = new Map(
|
||||||
|
parsedUpdatedTasks.map((task) => [task.id, task])
|
||||||
|
);
|
||||||
|
|
||||||
|
let actualUpdateCount = 0;
|
||||||
|
data.tasks.forEach((task, index) => {
|
||||||
|
if (updatedTasksMap.has(task.id)) {
|
||||||
|
// Only update if the task was part of the set sent to AI
|
||||||
|
data.tasks[index] = updatedTasksMap.get(task.id);
|
||||||
|
actualUpdateCount++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (isMCP)
|
||||||
|
logFn.info(
|
||||||
|
`Applied updates to ${actualUpdateCount} tasks in the dataset.`
|
||||||
|
);
|
||||||
|
else
|
||||||
|
logFn(
|
||||||
|
'info',
|
||||||
|
`Applied updates to ${actualUpdateCount} tasks in the dataset.`
|
||||||
|
);
|
||||||
|
|
||||||
|
writeJSON(tasksPath, data);
|
||||||
|
if (isMCP)
|
||||||
|
logFn.info(
|
||||||
|
`Successfully updated ${actualUpdateCount} tasks in ${tasksPath}`
|
||||||
|
);
|
||||||
|
else
|
||||||
|
logFn(
|
||||||
|
'success',
|
||||||
|
`Successfully updated ${actualUpdateCount} tasks in ${tasksPath}`
|
||||||
|
);
|
||||||
|
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||||
|
|
||||||
|
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
|
||||||
|
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
updatedTasks: parsedUpdatedTasks,
|
||||||
|
telemetryData: aiServiceResponse.telemetryData
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
||||||
if (isMCP) logFn.error(`Error during AI service call: ${error.message}`);
|
if (isMCP) logFn.error(`Error during AI service call: ${error.message}`);
|
||||||
@@ -390,98 +456,10 @@ The changes described in the prompt should be applied to ALL tasks in the list.`
|
|||||||
'Please ensure API keys are configured correctly in .env or mcp.json.'
|
'Please ensure API keys are configured correctly in .env or mcp.json.'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
throw error; // Re-throw error
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Parse and Validate Response ---
|
|
||||||
try {
|
|
||||||
updatedTasks = parseUpdatedTasksFromText(
|
|
||||||
responseText,
|
|
||||||
tasksToUpdate.length,
|
|
||||||
logFn,
|
|
||||||
isMCP
|
|
||||||
);
|
|
||||||
} catch (parseError) {
|
|
||||||
if (isMCP)
|
|
||||||
logFn.error(
|
|
||||||
`Failed to parse updated tasks from AI response: ${parseError.message}`
|
|
||||||
);
|
|
||||||
else
|
|
||||||
logFn(
|
|
||||||
'error',
|
|
||||||
`Failed to parse updated tasks from AI response: ${parseError.message}`
|
|
||||||
);
|
|
||||||
if (getDebugFlag(session)) {
|
|
||||||
if (isMCP) logFn.error(`Raw AI Response:\n${responseText}`);
|
|
||||||
else logFn('error', `Raw AI Response:\n${responseText}`);
|
|
||||||
}
|
|
||||||
throw new Error(
|
|
||||||
`Failed to parse valid updated tasks from AI response: ${parseError.message}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// --- End Parse/Validate ---
|
|
||||||
|
|
||||||
// --- Update Tasks Data (Unchanged) ---
|
|
||||||
if (!Array.isArray(updatedTasks)) {
|
|
||||||
// Should be caught by parser, but extra check
|
|
||||||
throw new Error('Parsed AI response for updated tasks was not an array.');
|
|
||||||
}
|
|
||||||
if (isMCP)
|
|
||||||
logFn.info(`Received ${updatedTasks.length} updated tasks from AI.`);
|
|
||||||
else
|
|
||||||
logFn('info', `Received ${updatedTasks.length} updated tasks from AI.`);
|
|
||||||
// Create a map for efficient lookup
|
|
||||||
const updatedTasksMap = new Map(
|
|
||||||
updatedTasks.map((task) => [task.id, task])
|
|
||||||
);
|
|
||||||
|
|
||||||
// Iterate through the original data and update based on the map
|
|
||||||
let actualUpdateCount = 0;
|
|
||||||
data.tasks.forEach((task, index) => {
|
|
||||||
if (updatedTasksMap.has(task.id)) {
|
|
||||||
// Only update if the task was part of the set sent to AI
|
|
||||||
data.tasks[index] = updatedTasksMap.get(task.id);
|
|
||||||
actualUpdateCount++;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if (isMCP)
|
|
||||||
logFn.info(
|
|
||||||
`Applied updates to ${actualUpdateCount} tasks in the dataset.`
|
|
||||||
);
|
|
||||||
else
|
|
||||||
logFn(
|
|
||||||
'info',
|
|
||||||
`Applied updates to ${actualUpdateCount} tasks in the dataset.`
|
|
||||||
);
|
|
||||||
// --- End Update Tasks Data ---
|
|
||||||
|
|
||||||
// --- Write File and Generate (Unchanged) ---
|
|
||||||
writeJSON(tasksPath, data);
|
|
||||||
if (isMCP)
|
|
||||||
logFn.info(
|
|
||||||
`Successfully updated ${actualUpdateCount} tasks in ${tasksPath}`
|
|
||||||
);
|
|
||||||
else
|
|
||||||
logFn(
|
|
||||||
'success',
|
|
||||||
`Successfully updated ${actualUpdateCount} tasks in ${tasksPath}`
|
|
||||||
);
|
|
||||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
|
||||||
// --- End Write File ---
|
|
||||||
|
|
||||||
// --- Final CLI Output (Unchanged) ---
|
|
||||||
if (outputFormat === 'text') {
|
|
||||||
console.log(
|
|
||||||
boxen(chalk.green(`Successfully updated ${actualUpdateCount} tasks`), {
|
|
||||||
padding: 1,
|
|
||||||
borderColor: 'green',
|
|
||||||
borderStyle: 'round'
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// --- End Final CLI Output ---
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// --- General Error Handling (Unchanged) ---
|
// --- General Error Handling (Unchanged) ---
|
||||||
if (isMCP) logFn.error(`Error updating tasks: ${error.message}`);
|
if (isMCP) logFn.error(`Error updating tasks: ${error.message}`);
|
||||||
|
|||||||
@@ -17,7 +17,11 @@ import {
|
|||||||
isSilentMode
|
isSilentMode
|
||||||
} from './utils.js';
|
} from './utils.js';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { findNextTask, analyzeTaskComplexity } from './task-manager.js';
|
import {
|
||||||
|
findNextTask,
|
||||||
|
analyzeTaskComplexity,
|
||||||
|
readComplexityReport
|
||||||
|
} from './task-manager.js';
|
||||||
import { getProjectName, getDefaultSubtasks } from './config-manager.js';
|
import { getProjectName, getDefaultSubtasks } from './config-manager.js';
|
||||||
import { TASK_STATUS_OPTIONS } from '../../src/constants/task-status.js';
|
import { TASK_STATUS_OPTIONS } from '../../src/constants/task-status.js';
|
||||||
import { getTaskMasterVersion } from '../../src/utils/getVersion.js';
|
import { getTaskMasterVersion } from '../../src/utils/getVersion.js';
|
||||||
@@ -264,12 +268,14 @@ function getStatusWithColor(status, forTable = false) {
|
|||||||
* @param {Array} dependencies - Array of dependency IDs
|
* @param {Array} dependencies - Array of dependency IDs
|
||||||
* @param {Array} allTasks - Array of all tasks
|
* @param {Array} allTasks - Array of all tasks
|
||||||
* @param {boolean} forConsole - Whether the output is for console display
|
* @param {boolean} forConsole - Whether the output is for console display
|
||||||
|
* @param {Object|null} complexityReport - Optional pre-loaded complexity report
|
||||||
* @returns {string} Formatted dependencies string
|
* @returns {string} Formatted dependencies string
|
||||||
*/
|
*/
|
||||||
function formatDependenciesWithStatus(
|
function formatDependenciesWithStatus(
|
||||||
dependencies,
|
dependencies,
|
||||||
allTasks,
|
allTasks,
|
||||||
forConsole = false
|
forConsole = false,
|
||||||
|
complexityReport = null // Add complexityReport parameter
|
||||||
) {
|
) {
|
||||||
if (
|
if (
|
||||||
!dependencies ||
|
!dependencies ||
|
||||||
@@ -333,7 +339,11 @@ function formatDependenciesWithStatus(
|
|||||||
typeof depId === 'string' ? parseInt(depId, 10) : depId;
|
typeof depId === 'string' ? parseInt(depId, 10) : depId;
|
||||||
|
|
||||||
// Look up the task using the numeric ID
|
// Look up the task using the numeric ID
|
||||||
const depTaskResult = findTaskById(allTasks, numericDepId);
|
const depTaskResult = findTaskById(
|
||||||
|
allTasks,
|
||||||
|
numericDepId,
|
||||||
|
complexityReport
|
||||||
|
);
|
||||||
const depTask = depTaskResult.task; // Access the task object from the result
|
const depTask = depTaskResult.task; // Access the task object from the result
|
||||||
|
|
||||||
if (!depTask) {
|
if (!depTask) {
|
||||||
@@ -752,7 +762,7 @@ function truncateString(str, maxLength) {
|
|||||||
* Display the next task to work on
|
* Display the next task to work on
|
||||||
* @param {string} tasksPath - Path to the tasks.json file
|
* @param {string} tasksPath - Path to the tasks.json file
|
||||||
*/
|
*/
|
||||||
async function displayNextTask(tasksPath) {
|
async function displayNextTask(tasksPath, complexityReportPath = null) {
|
||||||
displayBanner();
|
displayBanner();
|
||||||
|
|
||||||
// Read the tasks file
|
// Read the tasks file
|
||||||
@@ -762,8 +772,11 @@ async function displayNextTask(tasksPath) {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read complexity report once
|
||||||
|
const complexityReport = readComplexityReport(complexityReportPath);
|
||||||
|
|
||||||
// Find the next task
|
// Find the next task
|
||||||
const nextTask = findNextTask(data.tasks);
|
const nextTask = findNextTask(data.tasks, complexityReport);
|
||||||
|
|
||||||
if (!nextTask) {
|
if (!nextTask) {
|
||||||
console.log(
|
console.log(
|
||||||
@@ -824,7 +837,18 @@ async function displayNextTask(tasksPath) {
|
|||||||
],
|
],
|
||||||
[
|
[
|
||||||
chalk.cyan.bold('Dependencies:'),
|
chalk.cyan.bold('Dependencies:'),
|
||||||
formatDependenciesWithStatus(nextTask.dependencies, data.tasks, true)
|
formatDependenciesWithStatus(
|
||||||
|
nextTask.dependencies,
|
||||||
|
data.tasks,
|
||||||
|
true,
|
||||||
|
complexityReport
|
||||||
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
chalk.cyan.bold('Complexity:'),
|
||||||
|
nextTask.complexityScore
|
||||||
|
? getComplexityWithColor(nextTask.complexityScore)
|
||||||
|
: chalk.gray('N/A')
|
||||||
],
|
],
|
||||||
[chalk.cyan.bold('Description:'), nextTask.description]
|
[chalk.cyan.bold('Description:'), nextTask.description]
|
||||||
);
|
);
|
||||||
@@ -846,8 +870,11 @@ async function displayNextTask(tasksPath) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show subtasks if they exist
|
// Determine if the nextTask is a subtask
|
||||||
if (nextTask.subtasks && nextTask.subtasks.length > 0) {
|
const isSubtask = !!nextTask.parentId;
|
||||||
|
|
||||||
|
// Show subtasks if they exist (only for parent tasks)
|
||||||
|
if (!isSubtask && nextTask.subtasks && nextTask.subtasks.length > 0) {
|
||||||
console.log(
|
console.log(
|
||||||
boxen(chalk.white.bold('Subtasks'), {
|
boxen(chalk.white.bold('Subtasks'), {
|
||||||
padding: { top: 0, bottom: 0, left: 1, right: 1 },
|
padding: { top: 0, bottom: 0, left: 1, right: 1 },
|
||||||
@@ -947,8 +974,10 @@ async function displayNextTask(tasksPath) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
console.log(subtaskTable.toString());
|
console.log(subtaskTable.toString());
|
||||||
} else {
|
}
|
||||||
// Suggest expanding if no subtasks
|
|
||||||
|
// Suggest expanding if no subtasks (only for parent tasks without subtasks)
|
||||||
|
if (!isSubtask && (!nextTask.subtasks || nextTask.subtasks.length === 0)) {
|
||||||
console.log(
|
console.log(
|
||||||
boxen(
|
boxen(
|
||||||
chalk.yellow('No subtasks found. Consider breaking down this task:') +
|
chalk.yellow('No subtasks found. Consider breaking down this task:') +
|
||||||
@@ -967,22 +996,30 @@ async function displayNextTask(tasksPath) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Show action suggestions
|
// Show action suggestions
|
||||||
|
let suggestedActionsContent = chalk.white.bold('Suggested Actions:') + '\n';
|
||||||
|
if (isSubtask) {
|
||||||
|
// Suggested actions for a subtask
|
||||||
|
suggestedActionsContent +=
|
||||||
|
`${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`task-master set-status --id=${nextTask.id} --status=in-progress`)}\n` +
|
||||||
|
`${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`task-master set-status --id=${nextTask.id} --status=done`)}\n` +
|
||||||
|
`${chalk.cyan('3.')} View parent task: ${chalk.yellow(`task-master show --id=${nextTask.parentId}`)}`;
|
||||||
|
} else {
|
||||||
|
// Suggested actions for a parent task
|
||||||
|
suggestedActionsContent +=
|
||||||
|
`${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`task-master set-status --id=${nextTask.id} --status=in-progress`)}\n` +
|
||||||
|
`${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`task-master set-status --id=${nextTask.id} --status=done`)}\n` +
|
||||||
|
(nextTask.subtasks && nextTask.subtasks.length > 0
|
||||||
|
? `${chalk.cyan('3.')} Update subtask status: ${chalk.yellow(`task-master set-status --id=${nextTask.id}.1 --status=done`)}` // Example: first subtask
|
||||||
|
: `${chalk.cyan('3.')} Break down into subtasks: ${chalk.yellow(`task-master expand --id=${nextTask.id}`)}`);
|
||||||
|
}
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
boxen(
|
boxen(suggestedActionsContent, {
|
||||||
chalk.white.bold('Suggested Actions:') +
|
padding: { top: 0, bottom: 0, left: 1, right: 1 },
|
||||||
'\n' +
|
borderColor: 'green',
|
||||||
`${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`task-master set-status --id=${nextTask.id} --status=in-progress`)}\n` +
|
borderStyle: 'round',
|
||||||
`${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`task-master set-status --id=${nextTask.id} --status=done`)}\n` +
|
margin: { top: 1 }
|
||||||
(nextTask.subtasks && nextTask.subtasks.length > 0
|
})
|
||||||
? `${chalk.cyan('3.')} Update subtask status: ${chalk.yellow(`task-master set-status --id=${nextTask.id}.1 --status=done`)}`
|
|
||||||
: `${chalk.cyan('3.')} Break down into subtasks: ${chalk.yellow(`task-master expand --id=${nextTask.id}`)}`),
|
|
||||||
{
|
|
||||||
padding: { top: 0, bottom: 0, left: 1, right: 1 },
|
|
||||||
borderColor: 'green',
|
|
||||||
borderStyle: 'round',
|
|
||||||
margin: { top: 1 }
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -992,7 +1029,12 @@ async function displayNextTask(tasksPath) {
|
|||||||
* @param {string|number} taskId - The ID of the task to display
|
* @param {string|number} taskId - The ID of the task to display
|
||||||
* @param {string} [statusFilter] - Optional status to filter subtasks by
|
* @param {string} [statusFilter] - Optional status to filter subtasks by
|
||||||
*/
|
*/
|
||||||
async function displayTaskById(tasksPath, taskId, statusFilter = null) {
|
async function displayTaskById(
|
||||||
|
tasksPath,
|
||||||
|
taskId,
|
||||||
|
complexityReportPath = null,
|
||||||
|
statusFilter = null
|
||||||
|
) {
|
||||||
displayBanner();
|
displayBanner();
|
||||||
|
|
||||||
// Read the tasks file
|
// Read the tasks file
|
||||||
@@ -1002,11 +1044,15 @@ async function displayTaskById(tasksPath, taskId, statusFilter = null) {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read complexity report once
|
||||||
|
const complexityReport = readComplexityReport(complexityReportPath);
|
||||||
|
|
||||||
// Find the task by ID, applying the status filter if provided
|
// Find the task by ID, applying the status filter if provided
|
||||||
// Returns { task, originalSubtaskCount, originalSubtasks }
|
// Returns { task, originalSubtaskCount, originalSubtasks }
|
||||||
const { task, originalSubtaskCount, originalSubtasks } = findTaskById(
|
const { task, originalSubtaskCount, originalSubtasks } = findTaskById(
|
||||||
data.tasks,
|
data.tasks,
|
||||||
taskId,
|
taskId,
|
||||||
|
complexityReport,
|
||||||
statusFilter
|
statusFilter
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1061,6 +1107,12 @@ async function displayTaskById(tasksPath, taskId, statusFilter = null) {
|
|||||||
chalk.cyan.bold('Status:'),
|
chalk.cyan.bold('Status:'),
|
||||||
getStatusWithColor(task.status || 'pending', true)
|
getStatusWithColor(task.status || 'pending', true)
|
||||||
],
|
],
|
||||||
|
[
|
||||||
|
chalk.cyan.bold('Complexity:'),
|
||||||
|
task.complexityScore
|
||||||
|
? getComplexityWithColor(task.complexityScore)
|
||||||
|
: chalk.gray('N/A')
|
||||||
|
],
|
||||||
[
|
[
|
||||||
chalk.cyan.bold('Description:'),
|
chalk.cyan.bold('Description:'),
|
||||||
task.description || 'No description provided.'
|
task.description || 'No description provided.'
|
||||||
@@ -1139,7 +1191,18 @@ async function displayTaskById(tasksPath, taskId, statusFilter = null) {
|
|||||||
[chalk.cyan.bold('Priority:'), priorityColor(task.priority || 'medium')],
|
[chalk.cyan.bold('Priority:'), priorityColor(task.priority || 'medium')],
|
||||||
[
|
[
|
||||||
chalk.cyan.bold('Dependencies:'),
|
chalk.cyan.bold('Dependencies:'),
|
||||||
formatDependenciesWithStatus(task.dependencies, data.tasks, true)
|
formatDependenciesWithStatus(
|
||||||
|
task.dependencies,
|
||||||
|
data.tasks,
|
||||||
|
true,
|
||||||
|
complexityReport
|
||||||
|
)
|
||||||
|
],
|
||||||
|
[
|
||||||
|
chalk.cyan.bold('Complexity:'),
|
||||||
|
task.complexityScore
|
||||||
|
? getComplexityWithColor(task.complexityScore)
|
||||||
|
: chalk.gray('N/A')
|
||||||
],
|
],
|
||||||
[chalk.cyan.bold('Description:'), task.description]
|
[chalk.cyan.bold('Description:'), task.description]
|
||||||
);
|
);
|
||||||
@@ -1955,6 +2018,51 @@ function displayAvailableModels(availableModels) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays AI usage telemetry summary in the CLI.
|
||||||
|
* @param {object} telemetryData - The telemetry data object.
|
||||||
|
* @param {string} outputType - 'cli' or 'mcp' (though typically only called for 'cli').
|
||||||
|
*/
|
||||||
|
function displayAiUsageSummary(telemetryData, outputType = 'cli') {
|
||||||
|
if (
|
||||||
|
(outputType !== 'cli' && outputType !== 'text') ||
|
||||||
|
!telemetryData ||
|
||||||
|
isSilentMode()
|
||||||
|
) {
|
||||||
|
return; // Only display for CLI and if data exists and not in silent mode
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
modelUsed,
|
||||||
|
providerName,
|
||||||
|
inputTokens,
|
||||||
|
outputTokens,
|
||||||
|
totalTokens,
|
||||||
|
totalCost,
|
||||||
|
commandName
|
||||||
|
} = telemetryData;
|
||||||
|
|
||||||
|
let summary = chalk.bold.blue('AI Usage Summary:') + '\n';
|
||||||
|
summary += chalk.gray(` Command: ${commandName}\n`);
|
||||||
|
summary += chalk.gray(` Provider: ${providerName}\n`);
|
||||||
|
summary += chalk.gray(` Model: ${modelUsed}\n`);
|
||||||
|
summary += chalk.gray(
|
||||||
|
` Tokens: ${totalTokens} (Input: ${inputTokens}, Output: ${outputTokens})\n`
|
||||||
|
);
|
||||||
|
summary += chalk.gray(` Est. Cost: $${totalCost.toFixed(6)}`);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
boxen(summary, {
|
||||||
|
padding: 1,
|
||||||
|
margin: { top: 1 },
|
||||||
|
borderColor: 'blue',
|
||||||
|
borderStyle: 'round',
|
||||||
|
title: '💡 Telemetry',
|
||||||
|
titleAlignment: 'center'
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Export UI functions
|
// Export UI functions
|
||||||
export {
|
export {
|
||||||
displayBanner,
|
displayBanner,
|
||||||
@@ -1972,5 +2080,6 @@ export {
|
|||||||
confirmTaskOverwrite,
|
confirmTaskOverwrite,
|
||||||
displayApiKeyStatus,
|
displayApiKeyStatus,
|
||||||
displayModelConfiguration,
|
displayModelConfiguration,
|
||||||
displayAvailableModels
|
displayAvailableModels,
|
||||||
|
displayAiUsageSummary
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -275,6 +275,22 @@ function findTaskInComplexityReport(report, taskId) {
|
|||||||
return report.complexityAnalysis.find((task) => task.taskId === taskId);
|
return report.complexityAnalysis.find((task) => task.taskId === taskId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function addComplexityToTask(task, complexityReport) {
|
||||||
|
let taskId;
|
||||||
|
if (task.isSubtask) {
|
||||||
|
taskId = task.parentTask.id;
|
||||||
|
} else if (task.parentId) {
|
||||||
|
taskId = task.parentId;
|
||||||
|
} else {
|
||||||
|
taskId = task.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const taskAnalysis = findTaskInComplexityReport(complexityReport, taskId);
|
||||||
|
if (taskAnalysis) {
|
||||||
|
task.complexityScore = taskAnalysis.complexityScore;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks if a task exists in the tasks array
|
* Checks if a task exists in the tasks array
|
||||||
* @param {Array} tasks - The tasks array
|
* @param {Array} tasks - The tasks array
|
||||||
@@ -325,10 +341,17 @@ function formatTaskId(id) {
|
|||||||
* Finds a task by ID in the tasks array. Optionally filters subtasks by status.
|
* Finds a task by ID in the tasks array. Optionally filters subtasks by status.
|
||||||
* @param {Array} tasks - The tasks array
|
* @param {Array} tasks - The tasks array
|
||||||
* @param {string|number} taskId - The task ID to find
|
* @param {string|number} taskId - The task ID to find
|
||||||
|
* @param {Object|null} complexityReport - Optional pre-loaded complexity report
|
||||||
|
* @returns {Object|null} The task object or null if not found
|
||||||
* @param {string} [statusFilter] - Optional status to filter subtasks by
|
* @param {string} [statusFilter] - Optional status to filter subtasks by
|
||||||
* @returns {{task: Object|null, originalSubtaskCount: number|null}} The task object (potentially with filtered subtasks) and the original subtask count if filtered, or nulls if not found.
|
* @returns {{task: Object|null, originalSubtaskCount: number|null}} The task object (potentially with filtered subtasks) and the original subtask count if filtered, or nulls if not found.
|
||||||
*/
|
*/
|
||||||
function findTaskById(tasks, taskId, statusFilter = null) {
|
function findTaskById(
|
||||||
|
tasks,
|
||||||
|
taskId,
|
||||||
|
complexityReport = null,
|
||||||
|
statusFilter = null
|
||||||
|
) {
|
||||||
if (!taskId || !tasks || !Array.isArray(tasks)) {
|
if (!taskId || !tasks || !Array.isArray(tasks)) {
|
||||||
return { task: null, originalSubtaskCount: null };
|
return { task: null, originalSubtaskCount: null };
|
||||||
}
|
}
|
||||||
@@ -356,10 +379,17 @@ function findTaskById(tasks, taskId, statusFilter = null) {
|
|||||||
subtask.isSubtask = true;
|
subtask.isSubtask = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return the found subtask (or null) and null for originalSubtaskCount
|
// If we found a task, check for complexity data
|
||||||
|
if (subtask && complexityReport) {
|
||||||
|
addComplexityToTask(subtask, complexityReport);
|
||||||
|
}
|
||||||
|
|
||||||
return { task: subtask || null, originalSubtaskCount: null };
|
return { task: subtask || null, originalSubtaskCount: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let taskResult = null;
|
||||||
|
let originalSubtaskCount = null;
|
||||||
|
|
||||||
// Find the main task
|
// Find the main task
|
||||||
const id = parseInt(taskId, 10);
|
const id = parseInt(taskId, 10);
|
||||||
const task = tasks.find((t) => t.id === id) || null;
|
const task = tasks.find((t) => t.id === id) || null;
|
||||||
@@ -369,6 +399,8 @@ function findTaskById(tasks, taskId, statusFilter = null) {
|
|||||||
return { task: null, originalSubtaskCount: null };
|
return { task: null, originalSubtaskCount: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
taskResult = task;
|
||||||
|
|
||||||
// If task found and statusFilter provided, filter its subtasks
|
// If task found and statusFilter provided, filter its subtasks
|
||||||
if (statusFilter && task.subtasks && Array.isArray(task.subtasks)) {
|
if (statusFilter && task.subtasks && Array.isArray(task.subtasks)) {
|
||||||
const originalSubtaskCount = task.subtasks.length;
|
const originalSubtaskCount = task.subtasks.length;
|
||||||
@@ -379,12 +411,18 @@ function findTaskById(tasks, taskId, statusFilter = null) {
|
|||||||
subtask.status &&
|
subtask.status &&
|
||||||
subtask.status.toLowerCase() === statusFilter.toLowerCase()
|
subtask.status.toLowerCase() === statusFilter.toLowerCase()
|
||||||
);
|
);
|
||||||
// Return the filtered task and the original count
|
|
||||||
return { task: filteredTask, originalSubtaskCount: originalSubtaskCount };
|
taskResult = filteredTask;
|
||||||
|
originalSubtaskCount = originalSubtaskCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return original task and null count if no filter or no subtasks
|
// If task found and complexityReport provided, add complexity data
|
||||||
return { task: task, originalSubtaskCount: null };
|
if (taskResult && complexityReport) {
|
||||||
|
addComplexityToTask(taskResult, complexityReport);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the found task and original subtask count
|
||||||
|
return { task: taskResult, originalSubtaskCount };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -508,6 +546,61 @@ function detectCamelCaseFlags(args) {
|
|||||||
return camelCaseFlags;
|
return camelCaseFlags;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aggregates an array of telemetry objects into a single summary object.
|
||||||
|
* @param {Array<Object>} telemetryArray - Array of telemetryData objects.
|
||||||
|
* @param {string} overallCommandName - The name for the aggregated command.
|
||||||
|
* @returns {Object|null} Aggregated telemetry object or null if input is empty.
|
||||||
|
*/
|
||||||
|
function aggregateTelemetry(telemetryArray, overallCommandName) {
|
||||||
|
if (!telemetryArray || telemetryArray.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const aggregated = {
|
||||||
|
timestamp: new Date().toISOString(), // Use current time for aggregation time
|
||||||
|
userId: telemetryArray[0].userId, // Assume userId is consistent
|
||||||
|
commandName: overallCommandName,
|
||||||
|
modelUsed: 'Multiple', // Default if models vary
|
||||||
|
providerName: 'Multiple', // Default if providers vary
|
||||||
|
inputTokens: 0,
|
||||||
|
outputTokens: 0,
|
||||||
|
totalTokens: 0,
|
||||||
|
totalCost: 0,
|
||||||
|
currency: telemetryArray[0].currency || 'USD' // Assume consistent currency or default
|
||||||
|
};
|
||||||
|
|
||||||
|
const uniqueModels = new Set();
|
||||||
|
const uniqueProviders = new Set();
|
||||||
|
const uniqueCurrencies = new Set();
|
||||||
|
|
||||||
|
telemetryArray.forEach((item) => {
|
||||||
|
aggregated.inputTokens += item.inputTokens || 0;
|
||||||
|
aggregated.outputTokens += item.outputTokens || 0;
|
||||||
|
aggregated.totalCost += item.totalCost || 0;
|
||||||
|
uniqueModels.add(item.modelUsed);
|
||||||
|
uniqueProviders.add(item.providerName);
|
||||||
|
uniqueCurrencies.add(item.currency || 'USD');
|
||||||
|
});
|
||||||
|
|
||||||
|
aggregated.totalTokens = aggregated.inputTokens + aggregated.outputTokens;
|
||||||
|
aggregated.totalCost = parseFloat(aggregated.totalCost.toFixed(6)); // Fix precision
|
||||||
|
|
||||||
|
if (uniqueModels.size === 1) {
|
||||||
|
aggregated.modelUsed = [...uniqueModels][0];
|
||||||
|
}
|
||||||
|
if (uniqueProviders.size === 1) {
|
||||||
|
aggregated.providerName = [...uniqueProviders][0];
|
||||||
|
}
|
||||||
|
if (uniqueCurrencies.size > 1) {
|
||||||
|
aggregated.currency = 'Multiple'; // Mark if currencies actually differ
|
||||||
|
} else if (uniqueCurrencies.size === 1) {
|
||||||
|
aggregated.currency = [...uniqueCurrencies][0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return aggregated;
|
||||||
|
}
|
||||||
|
|
||||||
// Export all utility functions and configuration
|
// Export all utility functions and configuration
|
||||||
export {
|
export {
|
||||||
LOG_LEVELS,
|
LOG_LEVELS,
|
||||||
@@ -524,10 +617,12 @@ export {
|
|||||||
findCycles,
|
findCycles,
|
||||||
toKebabCase,
|
toKebabCase,
|
||||||
detectCamelCaseFlags,
|
detectCamelCaseFlags,
|
||||||
enableSilentMode,
|
|
||||||
disableSilentMode,
|
disableSilentMode,
|
||||||
isSilentMode,
|
enableSilentMode,
|
||||||
resolveEnvVariable,
|
|
||||||
getTaskManager,
|
getTaskManager,
|
||||||
findProjectRoot
|
isSilentMode,
|
||||||
|
addComplexityToTask,
|
||||||
|
resolveEnvVariable,
|
||||||
|
findProjectRoot,
|
||||||
|
aggregateTelemetry
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,299 +1,357 @@
|
|||||||
{
|
{
|
||||||
"meta": {
|
"meta": {
|
||||||
"generatedAt": "2025-05-03T04:45:36.864Z",
|
"generatedAt": "2025-05-22T05:48:33.026Z",
|
||||||
"tasksAnalyzed": 36,
|
"tasksAnalyzed": 6,
|
||||||
|
"totalTasks": 88,
|
||||||
|
"analysisCount": 43,
|
||||||
"thresholdScore": 5,
|
"thresholdScore": 5,
|
||||||
"projectName": "Taskmaster",
|
"projectName": "Taskmaster",
|
||||||
"usedResearch": false
|
"usedResearch": true
|
||||||
},
|
},
|
||||||
"complexityAnalysis": [
|
"complexityAnalysis": [
|
||||||
{
|
{
|
||||||
"taskId": 24,
|
"taskId": 24,
|
||||||
"taskTitle": "Implement AI-Powered Test Generation Command",
|
"taskTitle": "Implement AI-Powered Test Generation Command",
|
||||||
"complexityScore": 8,
|
"complexityScore": 7,
|
||||||
"recommendedSubtasks": 5,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement AI-Powered Test Generation Command' task by detailing the specific steps required for AI prompt engineering, including data extraction, prompt formatting, and error handling.",
|
"expansionPrompt": "Break down the implementation of the AI-powered test generation command into detailed subtasks covering: command structure setup, AI prompt engineering, test file generation logic, integration with Claude API, and comprehensive error handling.",
|
||||||
"reasoning": "Requires AI integration, complex logic, and thorough testing. Prompt engineering and API interaction add significant complexity."
|
"reasoning": "This task involves complex integration with an AI service (Claude), requires sophisticated prompt engineering, and needs to generate structured code files. The existing 3 subtasks are a good start but could be expanded to include more detailed steps for AI integration, error handling, and test file formatting."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 26,
|
"taskId": 26,
|
||||||
"taskTitle": "Implement Context Foundation for AI Operations",
|
"taskTitle": "Implement Context Foundation for AI Operations",
|
||||||
"complexityScore": 7,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 4,
|
||||||
"expansionPrompt": "Expand the 'Implement Context Foundation for AI Operations' task by detailing the specific steps for integrating file reading, cursor rules, and basic context extraction into the Claude API prompts.",
|
"expansionPrompt": "The current 4 subtasks for implementing the context foundation appear comprehensive. Consider if any additional subtasks are needed for testing, documentation, or integration with existing systems.",
|
||||||
"reasoning": "Involves modifying multiple commands and integrating different context sources. Error handling and backwards compatibility are crucial."
|
"reasoning": "This task involves creating a foundation for context integration with several well-defined components. The existing 4 subtasks cover the main implementation areas (context-file flag, cursor rules integration, context extraction utility, and command handler updates). The complexity is moderate as it requires careful integration with existing systems but has clear requirements."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 27,
|
"taskId": 27,
|
||||||
"taskTitle": "Implement Context Enhancements for AI Operations",
|
"taskTitle": "Implement Context Enhancements for AI Operations",
|
||||||
"complexityScore": 8,
|
"complexityScore": 7,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 4,
|
||||||
"expansionPrompt": "Expand the 'Implement Context Enhancements for AI Operations' task by detailing the specific steps for code context extraction, task history integration, and PRD context integration, including parsing, summarization, and formatting.",
|
"expansionPrompt": "The current 4 subtasks for implementing context enhancements appear well-structured. Consider if any additional subtasks are needed for testing, documentation, or performance optimization.",
|
||||||
"reasoning": "Builds upon the previous task with more sophisticated context extraction and integration. Requires intelligent parsing and summarization."
|
"reasoning": "This task builds upon the foundation from Task #26 and adds more sophisticated context handling features. The 4 existing subtasks cover the main implementation areas (code context extraction, task history context, PRD context integration, and context formatting). The complexity is higher than the foundation task due to the need for intelligent context selection and optimization."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 28,
|
"taskId": 28,
|
||||||
"taskTitle": "Implement Advanced ContextManager System",
|
"taskTitle": "Implement Advanced ContextManager System",
|
||||||
"complexityScore": 9,
|
"complexityScore": 8,
|
||||||
"recommendedSubtasks": 7,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement Advanced ContextManager System' task by detailing the specific steps for creating the ContextManager class, implementing the optimization pipeline, and adding command interface enhancements, including caching and performance monitoring.",
|
"expansionPrompt": "The current 5 subtasks for implementing the advanced ContextManager system appear comprehensive. Consider if any additional subtasks are needed for testing, documentation, or backward compatibility with previous context implementations.",
|
||||||
"reasoning": "A comprehensive system requiring careful design, optimization, and testing. Involves complex algorithms and performance considerations."
|
"reasoning": "This task represents the most complex phase of the context implementation, requiring a sophisticated class design, optimization algorithms, and integration with multiple systems. The 5 existing subtasks cover the core implementation areas, but the complexity is high due to the need for intelligent context prioritization, token management, and performance monitoring."
|
||||||
},
|
|
||||||
{
|
|
||||||
"taskId": 32,
|
|
||||||
"taskTitle": "Implement \"learn\" Command for Automatic Cursor Rule Generation",
|
|
||||||
"complexityScore": 9,
|
|
||||||
"recommendedSubtasks": 10,
|
|
||||||
"expansionPrompt": "Expand the 'Implement \"learn\" Command for Automatic Cursor Rule Generation' task by detailing the specific steps for Cursor data analysis, rule management, and AI integration, including error handling and performance optimization.",
|
|
||||||
"reasoning": "Requires deep integration with Cursor's data, complex pattern analysis, and AI interaction. Significant error handling and performance optimization are needed."
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 40,
|
"taskId": 40,
|
||||||
"taskTitle": "Implement 'plan' Command for Task Implementation Planning",
|
"taskTitle": "Implement 'plan' Command for Task Implementation Planning",
|
||||||
"complexityScore": 6,
|
"complexityScore": 5,
|
||||||
"recommendedSubtasks": 4,
|
"recommendedSubtasks": 4,
|
||||||
"expansionPrompt": "Expand the 'Implement 'plan' Command for Task Implementation Planning' task by detailing the steps for retrieving task content, generating implementation plans with AI, and formatting the plan within XML tags.",
|
"expansionPrompt": "The current 4 subtasks for implementing the 'plan' command appear well-structured. Consider if any additional subtasks are needed for testing, documentation, or integration with existing task management workflows.",
|
||||||
"reasoning": "Involves AI integration and requires careful formatting and error handling. Switching between Claude and Perplexity adds complexity."
|
"reasoning": "This task involves creating a new command that leverages AI to generate implementation plans. The existing 4 subtasks cover the main implementation areas (retrieving task content, generating plans with AI, formatting in XML, and error handling). The complexity is moderate as it builds on existing patterns for task updates but requires careful AI integration."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 41,
|
"taskId": 41,
|
||||||
"taskTitle": "Implement Visual Task Dependency Graph in Terminal",
|
"taskTitle": "Implement Visual Task Dependency Graph in Terminal",
|
||||||
"complexityScore": 8,
|
"complexityScore": 8,
|
||||||
"recommendedSubtasks": 8,
|
"recommendedSubtasks": 10,
|
||||||
"expansionPrompt": "Expand the 'Implement Visual Task Dependency Graph in Terminal' task by detailing the steps for designing the graph rendering system, implementing layout algorithms, and handling circular dependencies and filtering options.",
|
"expansionPrompt": "The current 10 subtasks for implementing the visual task dependency graph appear comprehensive. Consider if any additional subtasks are needed for performance optimization with large graphs or additional visualization options.",
|
||||||
"reasoning": "Requires complex graph algorithms and terminal rendering. Accessibility and performance are important considerations."
|
"reasoning": "This task involves creating a sophisticated visualization system for terminal display, which is inherently complex due to layout algorithms, ASCII/Unicode rendering, and handling complex dependency relationships. The 10 existing subtasks cover all major aspects of implementation, from CLI interface to accessibility features."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 42,
|
"taskId": 42,
|
||||||
"taskTitle": "Implement MCP-to-MCP Communication Protocol",
|
"taskTitle": "Implement MCP-to-MCP Communication Protocol",
|
||||||
"complexityScore": 8,
|
"complexityScore": 9,
|
||||||
"recommendedSubtasks": 7,
|
"recommendedSubtasks": 8,
|
||||||
"expansionPrompt": "Expand the 'Implement MCP-to-MCP Communication Protocol' task by detailing the steps for defining the protocol, implementing the adapter pattern, and building the client module, including error handling and security considerations.",
|
"expansionPrompt": "The current 8 subtasks for implementing the MCP-to-MCP communication protocol appear well-structured. Consider if any additional subtasks are needed for security hardening, performance optimization, or comprehensive documentation.",
|
||||||
"reasoning": "Requires designing a new protocol and implementing communication with external systems. Security and error handling are critical."
|
"reasoning": "This task involves designing and implementing a complex communication protocol between different MCP tools and servers. It requires sophisticated adapter patterns, client-server architecture, and handling of multiple operational modes. The complexity is very high due to the need for standardization, security, and backward compatibility."
|
||||||
},
|
|
||||||
{
|
|
||||||
"taskId": 43,
|
|
||||||
"taskTitle": "Add Research Flag to Add-Task Command",
|
|
||||||
"complexityScore": 5,
|
|
||||||
"recommendedSubtasks": 3,
|
|
||||||
"expansionPrompt": "Expand the 'Add Research Flag to Add-Task Command' task by detailing the steps for updating the command parser, generating research subtasks, and linking them to the parent task.",
|
|
||||||
"reasoning": "Relatively straightforward, but requires careful handling of subtask generation and linking."
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 44,
|
"taskId": 44,
|
||||||
"taskTitle": "Implement Task Automation with Webhooks and Event Triggers",
|
"taskTitle": "Implement Task Automation with Webhooks and Event Triggers",
|
||||||
"complexityScore": 8,
|
"complexityScore": 8,
|
||||||
"recommendedSubtasks": 7,
|
"recommendedSubtasks": 7,
|
||||||
"expansionPrompt": "Expand the 'Implement Task Automation with Webhooks and Event Triggers' task by detailing the steps for implementing the webhook registration system, event system, and trigger definition interface, including security and error handling.",
|
"expansionPrompt": "The current 7 subtasks for implementing task automation with webhooks appear comprehensive. Consider if any additional subtasks are needed for security testing, rate limiting implementation, or webhook monitoring tools.",
|
||||||
"reasoning": "Requires designing a robust event system and integrating with external services. Security and error handling are critical."
|
"reasoning": "This task involves creating a sophisticated event system with webhooks for integration with external services. The complexity is high due to the need for secure authentication, reliable delivery mechanisms, and handling of various webhook formats and protocols. The existing subtasks cover the main implementation areas but security and monitoring could be emphasized more."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 45,
|
"taskId": 45,
|
||||||
"taskTitle": "Implement GitHub Issue Import Feature",
|
"taskTitle": "Implement GitHub Issue Import Feature",
|
||||||
"complexityScore": 7,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 5,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement GitHub Issue Import Feature' task by detailing the steps for parsing the URL, fetching issue details from the GitHub API, and generating a well-formatted task.",
|
"expansionPrompt": "The current 5 subtasks for implementing the GitHub issue import feature appear well-structured. Consider if any additional subtasks are needed for handling GitHub API rate limiting, caching, or supporting additional issue metadata.",
|
||||||
"reasoning": "Requires interacting with the GitHub API and handling various error conditions. Authentication adds complexity."
|
"reasoning": "This task involves integrating with the GitHub API to import issues as tasks. The complexity is moderate as it requires API authentication, data mapping, and error handling. The existing 5 subtasks cover the main implementation areas from design to end-to-end implementation."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 46,
|
"taskId": 46,
|
||||||
"taskTitle": "Implement ICE Analysis Command for Task Prioritization",
|
"taskTitle": "Implement ICE Analysis Command for Task Prioritization",
|
||||||
"complexityScore": 7,
|
"complexityScore": 7,
|
||||||
"recommendedSubtasks": 5,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement ICE Analysis Command for Task Prioritization' task by detailing the steps for calculating ICE scores, generating the report file, and implementing the CLI rendering.",
|
"expansionPrompt": "The current 5 subtasks for implementing the ICE analysis command appear comprehensive. Consider if any additional subtasks are needed for visualization of ICE scores or integration with other prioritization methods.",
|
||||||
"reasoning": "Requires AI integration for scoring and careful formatting of the report. Integration with existing complexity reports adds complexity."
|
"reasoning": "This task involves creating an AI-powered analysis system for task prioritization using the ICE methodology. The complexity is high due to the need for sophisticated scoring algorithms, AI integration, and report generation. The existing subtasks cover the main implementation areas from algorithm design to integration with existing systems."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 47,
|
"taskId": 47,
|
||||||
"taskTitle": "Enhance Task Suggestion Actions Card Workflow",
|
"taskTitle": "Enhance Task Suggestion Actions Card Workflow",
|
||||||
"complexityScore": 7,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 6,
|
||||||
"expansionPrompt": "Expand the 'Enhance Task Suggestion Actions Card Workflow' task by detailing the steps for implementing the task expansion, context addition, and task management phases, including UI/UX considerations.",
|
"expansionPrompt": "The current 6 subtasks for enhancing the task suggestion actions card workflow appear well-structured. Consider if any additional subtasks are needed for user testing, accessibility improvements, or performance optimization.",
|
||||||
"reasoning": "Requires significant UI/UX work and careful state management. Integration with existing functionality is crucial."
|
"reasoning": "This task involves redesigning the UI workflow for task expansion and management. The complexity is moderate as it requires careful UX design and state management but builds on existing components. The 6 existing subtasks cover the main implementation areas from design to testing."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 48,
|
"taskId": 48,
|
||||||
"taskTitle": "Refactor Prompts into Centralized Structure",
|
"taskTitle": "Refactor Prompts into Centralized Structure",
|
||||||
"complexityScore": 5,
|
"complexityScore": 4,
|
||||||
"recommendedSubtasks": 3,
|
"recommendedSubtasks": 3,
|
||||||
"expansionPrompt": "Expand the 'Refactor Prompts into Centralized Structure' task by detailing the steps for creating the 'prompts' directory, extracting prompts into individual files, and updating functions to import them.",
|
"expansionPrompt": "The current 3 subtasks for refactoring prompts into a centralized structure appear appropriate. Consider if any additional subtasks are needed for prompt versioning, documentation, or testing.",
|
||||||
"reasoning": "Primarily a refactoring task, but requires careful attention to detail to avoid breaking existing functionality."
|
"reasoning": "This task involves a straightforward refactoring to improve code organization. The complexity is relatively low as it primarily involves moving code rather than creating new functionality. The 3 existing subtasks cover the main implementation areas from directory structure to integration."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 49,
|
"taskId": 49,
|
||||||
"taskTitle": "Implement Code Quality Analysis Command",
|
"taskTitle": "Implement Code Quality Analysis Command",
|
||||||
"complexityScore": 8,
|
"complexityScore": 8,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 6,
|
||||||
"expansionPrompt": "Expand the 'Implement Code Quality Analysis Command' task by detailing the steps for pattern recognition, best practice verification, and improvement recommendations, including AI integration and task creation.",
|
"expansionPrompt": "The current 6 subtasks for implementing the code quality analysis command appear comprehensive. Consider if any additional subtasks are needed for performance optimization with large codebases or integration with existing code quality tools.",
|
||||||
"reasoning": "Requires complex code analysis and AI integration. Generating actionable recommendations adds complexity."
|
"reasoning": "This task involves creating a sophisticated code analysis system with pattern recognition, best practice verification, and AI-powered recommendations. The complexity is high due to the need for code parsing, complex analysis algorithms, and integration with AI services. The existing subtasks cover the main implementation areas from algorithm design to user interface."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 50,
|
"taskId": 50,
|
||||||
"taskTitle": "Implement Test Coverage Tracking System by Task",
|
"taskTitle": "Implement Test Coverage Tracking System by Task",
|
||||||
"complexityScore": 9,
|
"complexityScore": 9,
|
||||||
"recommendedSubtasks": 7,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement Test Coverage Tracking System by Task' task by detailing the steps for creating the tests.json file structure, developing the coverage report parser, and implementing the CLI commands and AI-powered test generation system.",
|
"expansionPrompt": "The current 5 subtasks for implementing the test coverage tracking system appear well-structured. Consider if any additional subtasks are needed for integration with CI/CD systems, performance optimization, or visualization tools.",
|
||||||
"reasoning": "A comprehensive system requiring deep integration with testing tools and AI. Maintaining bidirectional relationships adds complexity."
|
"reasoning": "This task involves creating a complex system that maps test coverage to specific tasks and subtasks. The complexity is very high due to the need for sophisticated data structures, integration with coverage tools, and AI-powered test generation. The existing subtasks are comprehensive and cover the main implementation areas from data structure design to AI integration."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 51,
|
"taskId": 51,
|
||||||
"taskTitle": "Implement Perplexity Research Command",
|
"taskTitle": "Implement Perplexity Research Command",
|
||||||
"complexityScore": 7,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 5,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement Perplexity Research Command' task by detailing the steps for creating the Perplexity API client, implementing task context extraction, and building the CLI interface.",
|
"expansionPrompt": "The current 5 subtasks for implementing the Perplexity research command appear comprehensive. Consider if any additional subtasks are needed for caching optimization, result formatting, or integration with other research tools.",
|
||||||
"reasoning": "Requires API integration and careful formatting of the research results. Caching adds complexity."
|
"reasoning": "This task involves creating a new command that integrates with the Perplexity AI API for research. The complexity is moderate as it requires API integration, context extraction, and result formatting. The 5 existing subtasks cover the main implementation areas from API client to caching system."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 52,
|
"taskId": 52,
|
||||||
"taskTitle": "Implement Task Suggestion Command for CLI",
|
"taskTitle": "Implement Task Suggestion Command for CLI",
|
||||||
"complexityScore": 7,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 5,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement Task Suggestion Command for CLI' task by detailing the steps for collecting existing task data, generating task suggestions with AI, and implementing the interactive CLI interface.",
|
"expansionPrompt": "The current 5 subtasks for implementing the task suggestion command appear well-structured. Consider if any additional subtasks are needed for suggestion quality evaluation, user feedback collection, or integration with existing task workflows.",
|
||||||
"reasoning": "Requires AI integration and careful design of the interactive interface. Handling various flag combinations adds complexity."
|
"reasoning": "This task involves creating a new CLI command that generates contextually relevant task suggestions using AI. The complexity is moderate as it requires AI integration, context collection, and interactive CLI interfaces. The existing subtasks cover the main implementation areas from data collection to user interface."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 53,
|
"taskId": 53,
|
||||||
"taskTitle": "Implement Subtask Suggestion Feature for Parent Tasks",
|
"taskTitle": "Implement Subtask Suggestion Feature for Parent Tasks",
|
||||||
"complexityScore": 7,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 6,
|
||||||
"expansionPrompt": "Expand the 'Implement Subtask Suggestion Feature for Parent Tasks' task by detailing the steps for validating parent tasks, gathering context, generating subtask suggestions with AI, and implementing the interactive CLI interface.",
|
"expansionPrompt": "The current 6 subtasks for implementing the subtask suggestion feature appear comprehensive. Consider if any additional subtasks are needed for suggestion quality metrics, user feedback collection, or performance optimization.",
|
||||||
"reasoning": "Requires AI integration and careful design of the interactive interface. Linking subtasks to parent tasks adds complexity."
|
"reasoning": "This task involves creating a feature that suggests contextually relevant subtasks for parent tasks. The complexity is moderate as it builds on existing task management systems but requires sophisticated AI integration and context analysis. The 6 existing subtasks cover the main implementation areas from validation to testing."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 55,
|
"taskId": 55,
|
||||||
"taskTitle": "Implement Positional Arguments Support for CLI Commands",
|
"taskTitle": "Implement Positional Arguments Support for CLI Commands",
|
||||||
"complexityScore": 7,
|
"complexityScore": 5,
|
||||||
"recommendedSubtasks": 5,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement Positional Arguments Support for CLI Commands' task by detailing the steps for updating the argument parsing logic, defining the positional argument order, and handling edge cases.",
|
"expansionPrompt": "The current 5 subtasks for implementing positional arguments support appear well-structured. Consider if any additional subtasks are needed for backward compatibility testing, documentation updates, or user experience improvements.",
|
||||||
"reasoning": "Requires careful modification of the command parsing logic and ensuring backward compatibility. Handling edge cases adds complexity."
|
"reasoning": "This task involves modifying the command parsing logic to support positional arguments alongside the existing flag-based syntax. The complexity is moderate as it requires careful handling of different argument styles and edge cases. The 5 existing subtasks cover the main implementation areas from analysis to documentation."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 57,
|
"taskId": 57,
|
||||||
"taskTitle": "Enhance Task-Master CLI User Experience and Interface",
|
"taskTitle": "Enhance Task-Master CLI User Experience and Interface",
|
||||||
"complexityScore": 7,
|
"complexityScore": 7,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 6,
|
||||||
"expansionPrompt": "Expand the 'Enhance Task-Master CLI User Experience and Interface' task by detailing the steps for log management, visual enhancements, interactive elements, and output formatting.",
|
"expansionPrompt": "The current 6 subtasks for enhancing the CLI user experience appear comprehensive. Consider if any additional subtasks are needed for accessibility testing, internationalization, or performance optimization.",
|
||||||
"reasoning": "Requires significant UI/UX work and careful consideration of different terminal environments. Reducing verbose logging adds complexity."
|
"reasoning": "This task involves a significant overhaul of the CLI interface to improve user experience. The complexity is high due to the breadth of changes (logging, visual elements, interactive components, etc.) and the need for consistent design across all commands. The 6 existing subtasks cover the main implementation areas from log management to help systems."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 60,
|
"taskId": 60,
|
||||||
"taskTitle": "Implement Mentor System with Round-Table Discussion Feature",
|
"taskTitle": "Implement Mentor System with Round-Table Discussion Feature",
|
||||||
"complexityScore": 8,
|
"complexityScore": 8,
|
||||||
"recommendedSubtasks": 7,
|
"recommendedSubtasks": 7,
|
||||||
"expansionPrompt": "Expand the 'Implement Mentor System with Round-Table Discussion Feature' task by detailing the steps for mentor management, round-table discussion implementation, and integration with the task system, including LLM integration.",
|
"expansionPrompt": "The current 7 subtasks for implementing the mentor system appear well-structured. Consider if any additional subtasks are needed for mentor personality consistency, discussion quality evaluation, or performance optimization with multiple mentors.",
|
||||||
"reasoning": "Requires complex AI simulation and careful formatting of the discussion output. Integrating with the task system adds complexity."
|
"reasoning": "This task involves creating a sophisticated mentor simulation system with round-table discussions. The complexity is high due to the need for personality simulation, complex LLM integration, and structured discussion management. The 7 existing subtasks cover the main implementation areas from architecture to testing."
|
||||||
},
|
|
||||||
{
|
|
||||||
"taskId": 61,
|
|
||||||
"taskTitle": "Implement Flexible AI Model Management",
|
|
||||||
"complexityScore": 9,
|
|
||||||
"recommendedSubtasks": 8,
|
|
||||||
"expansionPrompt": "Expand the 'Implement Flexible AI Model Management' task by detailing the steps for creating the configuration management module, implementing the CLI command parser, and integrating the Vercel AI SDK.",
|
|
||||||
"reasoning": "Requires deep integration with multiple AI models and careful management of API keys and configuration options. Vercel AI SDK integration adds complexity."
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 62,
|
"taskId": 62,
|
||||||
"taskTitle": "Add --simple Flag to Update Commands for Direct Text Input",
|
"taskTitle": "Add --simple Flag to Update Commands for Direct Text Input",
|
||||||
"complexityScore": 5,
|
"complexityScore": 4,
|
||||||
"recommendedSubtasks": 4,
|
"recommendedSubtasks": 8,
|
||||||
"expansionPrompt": "Expand the 'Add --simple Flag to Update Commands for Direct Text Input' task by detailing the steps for updating the command parsers, implementing the conditional logic, and formatting the user input with a timestamp.",
|
"expansionPrompt": "The current 8 subtasks for implementing the --simple flag appear comprehensive. Consider if any additional subtasks are needed for user experience testing or documentation updates.",
|
||||||
"reasoning": "Relatively straightforward, but requires careful attention to formatting and ensuring consistency with AI-processed updates."
|
"reasoning": "This task involves adding a simple flag option to bypass AI processing for updates. The complexity is relatively low as it primarily involves modifying existing command handlers and adding a flag. The 8 existing subtasks are very detailed and cover all aspects of implementation from command parsing to testing."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 63,
|
"taskId": 63,
|
||||||
"taskTitle": "Add pnpm Support for the Taskmaster Package",
|
"taskTitle": "Add pnpm Support for the Taskmaster Package",
|
||||||
"complexityScore": 7,
|
"complexityScore": 5,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 8,
|
||||||
"expansionPrompt": "Expand the 'Add pnpm Support for the Taskmaster Package' task by detailing the steps for updating the documentation, ensuring package scripts compatibility, and testing the installation and operation with pnpm.",
|
"expansionPrompt": "The current 8 subtasks for adding pnpm support appear comprehensive. Consider if any additional subtasks are needed for CI/CD integration, performance comparison, or documentation updates.",
|
||||||
"reasoning": "Requires careful attention to detail to ensure compatibility with pnpm's execution model. Testing and documentation are crucial."
|
"reasoning": "This task involves ensuring the package works correctly with pnpm as an alternative package manager. The complexity is moderate as it requires careful testing of installation processes and scripts across different environments. The 8 existing subtasks cover all major aspects from documentation to binary verification."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 64,
|
"taskId": 64,
|
||||||
"taskTitle": "Add Yarn Support for Taskmaster Installation",
|
"taskTitle": "Add Yarn Support for Taskmaster Installation",
|
||||||
"complexityScore": 7,
|
"complexityScore": 5,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 9,
|
||||||
"expansionPrompt": "Expand the 'Add Yarn Support for Taskmaster Installation' task by detailing the steps for updating package.json, adding Yarn-specific configuration files, and testing the installation and operation with Yarn.",
|
"expansionPrompt": "The current 9 subtasks for adding Yarn support appear comprehensive. Consider if any additional subtasks are needed for performance testing, CI/CD integration, or compatibility with different Yarn versions.",
|
||||||
"reasoning": "Requires careful attention to detail to ensure compatibility with Yarn's execution model. Testing and documentation are crucial."
|
"reasoning": "This task involves ensuring the package works correctly with Yarn as an alternative package manager. The complexity is moderate as it requires careful testing of installation processes and scripts across different environments. The 9 existing subtasks are very detailed and cover all aspects from configuration to testing."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 65,
|
"taskId": 65,
|
||||||
"taskTitle": "Add Bun Support for Taskmaster Installation",
|
"taskTitle": "Add Bun Support for Taskmaster Installation",
|
||||||
"complexityScore": 7,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 6,
|
||||||
"expansionPrompt": "Expand the 'Add Bun Support for Taskmaster Installation' task by detailing the steps for updating the installation scripts, testing the installation and operation with Bun, and updating the documentation.",
|
"expansionPrompt": "The current 6 subtasks for adding Bun support appear well-structured. Consider if any additional subtasks are needed for handling Bun-specific issues, performance testing, or documentation updates.",
|
||||||
"reasoning": "Requires careful attention to detail to ensure compatibility with Bun's execution model. Testing and documentation are crucial."
|
"reasoning": "This task involves adding support for the newer Bun package manager. The complexity is slightly higher than the other package manager tasks due to Bun's differences from Node.js and potential compatibility issues. The 6 existing subtasks cover the main implementation areas from research to documentation."
|
||||||
},
|
|
||||||
{
|
|
||||||
"taskId": 66,
|
|
||||||
"taskTitle": "Support Status Filtering in Show Command for Subtasks",
|
|
||||||
"complexityScore": 5,
|
|
||||||
"recommendedSubtasks": 4,
|
|
||||||
"expansionPrompt": "Expand the 'Support Status Filtering in Show Command for Subtasks' task by detailing the steps for updating the command parser, modifying the show command handler, and updating the help documentation.",
|
|
||||||
"reasoning": "Relatively straightforward, but requires careful handling of status validation and filtering."
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 67,
|
"taskId": 67,
|
||||||
"taskTitle": "Add CLI JSON output and Cursor keybindings integration",
|
"taskTitle": "Add CLI JSON output and Cursor keybindings integration",
|
||||||
"complexityScore": 7,
|
"complexityScore": 5,
|
||||||
"recommendedSubtasks": 6,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Add CLI JSON output and Cursor keybindings integration' task by detailing the steps for implementing the JSON output logic, creating the install-keybindings command structure, and handling keybinding file manipulation.",
|
"expansionPrompt": "The current 5 subtasks for implementing JSON output and Cursor keybindings appear well-structured. Consider if any additional subtasks are needed for testing across different operating systems, documentation updates, or user experience improvements.",
|
||||||
"reasoning": "Requires careful formatting of the JSON output and handling of file system operations. OS detection adds complexity."
|
"reasoning": "This task involves two distinct features: adding JSON output to CLI commands and creating a keybindings installation command. The complexity is moderate as it requires careful handling of different output formats and OS-specific file paths. The 5 existing subtasks cover the main implementation areas for both features."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 68,
|
"taskId": 68,
|
||||||
"taskTitle": "Ability to create tasks without parsing PRD",
|
"taskTitle": "Ability to create tasks without parsing PRD",
|
||||||
"complexityScore": 3,
|
"complexityScore": 3,
|
||||||
"recommendedSubtasks": 2,
|
"recommendedSubtasks": 2,
|
||||||
"expansionPrompt": "Expand the 'Ability to create tasks without parsing PRD' task by detailing the steps for creating tasks without a PRD.",
|
"expansionPrompt": "The current 2 subtasks for implementing task creation without PRD appear appropriate. Consider if any additional subtasks are needed for validation, error handling, or integration with existing task management workflows.",
|
||||||
"reasoning": "Simple task to allow task creation without a PRD."
|
"reasoning": "This task involves a relatively simple modification to allow task creation without requiring a PRD document. The complexity is low as it primarily involves creating a form interface and saving functionality. The 2 existing subtasks cover the main implementation areas of UI design and data saving."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 72,
|
||||||
|
"taskTitle": "Implement PDF Generation for Project Progress and Dependency Overview",
|
||||||
|
"complexityScore": 7,
|
||||||
|
"recommendedSubtasks": 6,
|
||||||
|
"expansionPrompt": "The current 6 subtasks for implementing PDF generation appear comprehensive. Consider if any additional subtasks are needed for handling large projects, additional visualization options, or integration with existing reporting tools.",
|
||||||
|
"reasoning": "This task involves creating a feature to generate PDF reports of project progress and dependency visualization. The complexity is high due to the need for PDF generation, data collection, and visualization integration. The 6 existing subtasks cover the main implementation areas from library selection to export options."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 75,
|
||||||
|
"taskTitle": "Integrate Google Search Grounding for Research Role",
|
||||||
|
"complexityScore": 5,
|
||||||
|
"recommendedSubtasks": 4,
|
||||||
|
"expansionPrompt": "The current 4 subtasks for integrating Google Search Grounding appear well-structured. Consider if any additional subtasks are needed for testing with different query types, error handling, or performance optimization.",
|
||||||
|
"reasoning": "This task involves updating the AI service layer to enable Google Search Grounding for research roles. The complexity is moderate as it requires careful integration with the existing AI service architecture and conditional logic. The 4 existing subtasks cover the main implementation areas from service layer modification to testing."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 76,
|
||||||
|
"taskTitle": "Develop E2E Test Framework for Taskmaster MCP Server (FastMCP over stdio)",
|
||||||
|
"complexityScore": 8,
|
||||||
|
"recommendedSubtasks": 7,
|
||||||
|
"expansionPrompt": "The current 7 subtasks for developing the E2E test framework appear comprehensive. Consider if any additional subtasks are needed for test result reporting, CI/CD integration, or performance benchmarking.",
|
||||||
|
"reasoning": "This task involves creating a sophisticated end-to-end testing framework for the MCP server. The complexity is high due to the need for subprocess management, protocol handling, and robust test case definition. The 7 existing subtasks cover the main implementation areas from architecture to documentation."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 77,
|
||||||
|
"taskTitle": "Implement AI Usage Telemetry for Taskmaster (with external analytics endpoint)",
|
||||||
|
"complexityScore": 7,
|
||||||
|
"recommendedSubtasks": 18,
|
||||||
|
"expansionPrompt": "The current 18 subtasks for implementing AI usage telemetry appear very comprehensive. Consider if any additional subtasks are needed for security hardening, privacy compliance, or user feedback collection.",
|
||||||
|
"reasoning": "This task involves creating a telemetry system to track AI usage metrics. The complexity is high due to the need for secure data transmission, comprehensive data collection, and integration across multiple commands. The 18 existing subtasks are extremely detailed and cover all aspects of implementation from core utility to provider-specific updates."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 80,
|
||||||
|
"taskTitle": "Implement Unique User ID Generation and Storage During Installation",
|
||||||
|
"complexityScore": 4,
|
||||||
|
"recommendedSubtasks": 5,
|
||||||
|
"expansionPrompt": "The current 5 subtasks for implementing unique user ID generation appear well-structured. Consider if any additional subtasks are needed for privacy compliance, security auditing, or integration with the telemetry system.",
|
||||||
|
"reasoning": "This task involves generating and storing a unique user identifier during installation. The complexity is relatively low as it primarily involves UUID generation and configuration file management. The 5 existing subtasks cover the main implementation areas from script structure to documentation."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 81,
|
||||||
|
"taskTitle": "Task #81: Implement Comprehensive Local Telemetry System with Future Server Integration Capability",
|
||||||
|
"complexityScore": 8,
|
||||||
|
"recommendedSubtasks": 6,
|
||||||
|
"expansionPrompt": "The current 6 subtasks for implementing the comprehensive local telemetry system appear well-structured. Consider if any additional subtasks are needed for data migration, storage optimization, or visualization tools.",
|
||||||
|
"reasoning": "This task involves expanding the telemetry system to capture additional metrics and implement local storage with future server integration capability. The complexity is high due to the breadth of data collection, storage requirements, and privacy considerations. The 6 existing subtasks cover the main implementation areas from data collection to user-facing benefits."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 82,
|
||||||
|
"taskTitle": "Update supported-models.json with token limit fields",
|
||||||
|
"complexityScore": 3,
|
||||||
|
"recommendedSubtasks": 1,
|
||||||
|
"expansionPrompt": "This task appears straightforward enough to be implemented without further subtasks. Focus on researching accurate token limit values for each model and ensuring backward compatibility.",
|
||||||
|
"reasoning": "This task involves a simple update to the supported-models.json file to include new token limit fields. The complexity is low as it primarily involves research and data entry. No subtasks are necessary as the task is well-defined and focused."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 83,
|
||||||
|
"taskTitle": "Update config-manager.js defaults and getters",
|
||||||
|
"complexityScore": 4,
|
||||||
|
"recommendedSubtasks": 1,
|
||||||
|
"expansionPrompt": "This task appears straightforward enough to be implemented without further subtasks. Focus on updating the DEFAULTS object and related getter functions while maintaining backward compatibility.",
|
||||||
|
"reasoning": "This task involves updating the config-manager.js module to replace maxTokens with more specific token limit fields. The complexity is relatively low as it primarily involves modifying existing code rather than creating new functionality. No subtasks are necessary as the task is well-defined and focused."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 84,
|
||||||
|
"taskTitle": "Implement token counting utility",
|
||||||
|
"complexityScore": 5,
|
||||||
|
"recommendedSubtasks": 1,
|
||||||
|
"expansionPrompt": "This task appears well-defined enough to be implemented without further subtasks. Focus on implementing accurate token counting for different models and proper fallback mechanisms.",
|
||||||
|
"reasoning": "This task involves creating a utility function to count tokens for different AI models. The complexity is moderate as it requires integration with the tiktoken library and handling different tokenization schemes. No subtasks are necessary as the task is well-defined and focused."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 69,
|
"taskId": 69,
|
||||||
"taskTitle": "Enhance Analyze Complexity for Specific Task IDs",
|
"taskTitle": "Enhance Analyze Complexity for Specific Task IDs",
|
||||||
"complexityScore": 6,
|
"complexityScore": 7,
|
||||||
"recommendedSubtasks": 4,
|
"recommendedSubtasks": 6,
|
||||||
"expansionPrompt": "Expand the 'Enhance Analyze Complexity for Specific Task IDs' task by detailing the steps for modifying the core logic, updating the CLI, and updating the MCP tool.",
|
"expansionPrompt": "Break down the task 'Enhance Analyze Complexity for Specific Task IDs' into 6 subtasks focusing on: 1) Core logic modification to accept ID parameters, 2) Report merging functionality, 3) CLI interface updates, 4) MCP tool integration, 5) Documentation updates, and 6) Comprehensive testing across all components.",
|
||||||
"reasoning": "Requires modifying existing functionality and ensuring compatibility with both CLI and MCP."
|
"reasoning": "This task involves modifying existing functionality across multiple components (core logic, CLI, MCP) with complex logic for filtering tasks and merging reports. The implementation requires careful handling of different parameter combinations and edge cases. The task has interdependent components that need to work together seamlessly, and the report merging functionality adds significant complexity."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 70,
|
"taskId": 70,
|
||||||
"taskTitle": "Implement 'diagram' command for Mermaid diagram generation",
|
"taskTitle": "Implement 'diagram' command for Mermaid diagram generation",
|
||||||
"complexityScore": 6,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 4,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement 'diagram' command for Mermaid diagram generation' task by detailing the steps for creating the command, generating the Mermaid diagram, and handling different output options.",
|
"expansionPrompt": "Break down the 'diagram' command implementation into 5 subtasks: 1) Command interface and parameter handling, 2) Task data extraction and transformation to Mermaid syntax, 3) Diagram rendering with status color coding, 4) Output formatting and file export functionality, and 5) Error handling and edge case management.",
|
||||||
"reasoning": "Requires generating Mermaid diagrams and handling different output options."
|
"reasoning": "This task requires implementing a new feature rather than modifying existing code, which reduces complexity from integration challenges. However, it involves working with visualization logic, dependency mapping, and multiple output formats. The color coding based on status and handling of dependency relationships adds moderate complexity. The task is well-defined but requires careful attention to diagram formatting and error handling."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 72,
|
"taskId": 85,
|
||||||
"taskTitle": "Implement PDF Generation for Project Progress and Dependency Overview",
|
"taskTitle": "Update ai-services-unified.js for dynamic token limits",
|
||||||
"complexityScore": 8,
|
|
||||||
"recommendedSubtasks": 6,
|
|
||||||
"expansionPrompt": "Expand the 'Implement PDF Generation for Project Progress and Dependency Overview' task by detailing the steps for summarizing project progress, visualizing the dependency chain, and generating the PDF document.",
|
|
||||||
"reasoning": "Requires integrating with the diagram command and using a PDF generation library. Handling large dependency chains adds complexity."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"taskId": 73,
|
|
||||||
"taskTitle": "Implement Custom Model ID Support for Ollama/OpenRouter",
|
|
||||||
"complexityScore": 7,
|
"complexityScore": 7,
|
||||||
"recommendedSubtasks": 5,
|
"recommendedSubtasks": 5,
|
||||||
"expansionPrompt": "Expand the 'Implement Custom Model ID Support for Ollama/OpenRouter' task by detailing the steps for modifying the CLI, implementing the interactive setup, and handling validation and warnings.",
|
"expansionPrompt": "Break down the update of ai-services-unified.js for dynamic token limits into subtasks such as: (1) Import and integrate the token counting utility, (2) Refactor _unifiedServiceRunner to calculate and enforce dynamic token limits, (3) Update error handling for token limit violations, (4) Add and verify logging for token usage, (5) Write and execute tests for various prompt and model scenarios.",
|
||||||
"reasoning": "Requires integrating with external APIs and handling different model types. Validation and warnings are crucial."
|
"reasoning": "This task involves significant code changes to a core function, integration of a new utility, dynamic logic for multiple models, and robust error handling. It also requires comprehensive testing for edge cases and integration, making it moderately complex and best managed by splitting into focused subtasks."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 75,
|
"taskId": 86,
|
||||||
"taskTitle": "Integrate Google Search Grounding for Research Role",
|
"taskTitle": "Update .taskmasterconfig schema and user guide",
|
||||||
"complexityScore": 6,
|
"complexityScore": 6,
|
||||||
"recommendedSubtasks": 4,
|
"recommendedSubtasks": 4,
|
||||||
"expansionPrompt": "Expand the 'Integrate Google Search Grounding for Research Role' task by detailing the steps for modifying the AI service layer, implementing the conditional logic, and updating the supported models.",
|
"expansionPrompt": "Expand this task into subtasks: (1) Draft a migration guide for users, (2) Update user documentation to explain new config fields, (3) Modify schema validation logic in config-manager.js, (4) Test and validate backward compatibility and error messaging.",
|
||||||
"reasoning": "Requires conditional logic and integration with the Google Search Grounding API."
|
"reasoning": "The task spans documentation, schema changes, migration guidance, and validation logic. While not algorithmically complex, it requires careful coordination and thorough testing to ensure a smooth user transition and robust validation."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"taskId": 76,
|
"taskId": 87,
|
||||||
"taskTitle": "Develop E2E Test Framework for Taskmaster MCP Server (FastMCP over stdio)",
|
"taskTitle": "Implement validation and error handling",
|
||||||
"complexityScore": 9,
|
"complexityScore": 5,
|
||||||
"recommendedSubtasks": 7,
|
"recommendedSubtasks": 4,
|
||||||
"expansionPrompt": "Expand the 'Develop E2E Test Framework for Taskmaster MCP Server (FastMCP over stdio)' task by detailing the steps for launching the FastMCP server, implementing the message protocol handler, and developing the request/response correlation mechanism.",
|
"expansionPrompt": "Decompose this task into: (1) Add validation logic for model and config loading, (2) Implement error handling and fallback mechanisms, (3) Enhance logging and reporting for token usage, (4) Develop helper functions for configuration suggestions and improvements.",
|
||||||
"reasoning": "Requires complex system integration and robust error handling. Designing a comprehensive test framework adds complexity."
|
"reasoning": "This task is primarily about adding validation, error handling, and logging. While important for robustness, the logic is straightforward and can be modularized into a few clear subtasks."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 89,
|
||||||
|
"taskTitle": "Introduce Prioritize Command with Enhanced Priority Levels",
|
||||||
|
"complexityScore": 6,
|
||||||
|
"recommendedSubtasks": 5,
|
||||||
|
"expansionPrompt": "Expand this task into: (1) Implement the prioritize command with all required flags and shorthands, (2) Update CLI output and help documentation for new priority levels, (3) Ensure backward compatibility with existing commands, (4) Add error handling for invalid inputs, (5) Write and run tests for all command scenarios.",
|
||||||
|
"reasoning": "This CLI feature requires command parsing, updating internal logic for new priority levels, documentation, and robust error handling. The complexity is moderate due to the need for backward compatibility and comprehensive testing."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 90,
|
||||||
|
"taskTitle": "Implement Subtask Progress Analyzer and Reporting System",
|
||||||
|
"complexityScore": 8,
|
||||||
|
"recommendedSubtasks": 6,
|
||||||
|
"expansionPrompt": "Break down the analyzer implementation into: (1) Design and implement progress tracking logic, (2) Develop status validation and issue detection, (3) Build the reporting system with multiple output formats, (4) Integrate analyzer with the existing task management system, (5) Optimize for performance and scalability, (6) Write unit, integration, and performance tests.",
|
||||||
|
"reasoning": "This is a complex, multi-faceted feature involving data analysis, reporting, integration, and performance optimization. It touches many parts of the system and requires careful design, making it one of the most complex tasks in the list."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"taskId": 91,
|
||||||
|
"taskTitle": "Implement Move Command for Tasks and Subtasks",
|
||||||
|
"complexityScore": 7,
|
||||||
|
"recommendedSubtasks": 5,
|
||||||
|
"expansionPrompt": "Expand this task into: (1) Implement move logic for tasks and subtasks, (2) Handle edge cases (invalid ids, non-existent parents, circular dependencies), (3) Update CLI to support move command with flags, (4) Ensure data integrity and update relationships, (5) Write and execute tests for various move scenarios.",
|
||||||
|
"reasoning": "Moving tasks and subtasks requires careful handling of hierarchical data, edge cases, and data integrity. The command must be robust and user-friendly, necessitating multiple focused subtasks for safe implementation."
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ function getClient(apiKey, baseUrl) {
|
|||||||
* @param {number} [params.maxTokens] - Maximum tokens for the response.
|
* @param {number} [params.maxTokens] - Maximum tokens for the response.
|
||||||
* @param {number} [params.temperature] - Temperature for generation.
|
* @param {number} [params.temperature] - Temperature for generation.
|
||||||
* @param {string} [params.baseUrl] - The base URL for the Anthropic API.
|
* @param {string} [params.baseUrl] - The base URL for the Anthropic API.
|
||||||
* @returns {Promise<string>} The generated text content.
|
* @returns {Promise<object>} The generated text content and usage.
|
||||||
* @throws {Error} If the API call fails.
|
* @throws {Error} If the API call fails.
|
||||||
*/
|
*/
|
||||||
export async function generateAnthropicText({
|
export async function generateAnthropicText({
|
||||||
@@ -76,7 +76,14 @@ export async function generateAnthropicText({
|
|||||||
'debug',
|
'debug',
|
||||||
`Anthropic generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
`Anthropic generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
||||||
);
|
);
|
||||||
return result.text;
|
// Return both text and usage
|
||||||
|
return {
|
||||||
|
text: result.text,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log('error', `Anthropic generateText failed: ${error.message}`);
|
log('error', `Anthropic generateText failed: ${error.message}`);
|
||||||
// Consider more specific error handling or re-throwing a standardized error
|
// Consider more specific error handling or re-throwing a standardized error
|
||||||
@@ -156,7 +163,7 @@ export async function streamAnthropicText({
|
|||||||
* @param {number} [params.temperature] - Temperature for generation.
|
* @param {number} [params.temperature] - Temperature for generation.
|
||||||
* @param {number} [params.maxRetries] - Max retries for validation/generation.
|
* @param {number} [params.maxRetries] - Max retries for validation/generation.
|
||||||
* @param {string} [params.baseUrl] - The base URL for the Anthropic API.
|
* @param {string} [params.baseUrl] - The base URL for the Anthropic API.
|
||||||
* @returns {Promise<object>} The generated object matching the schema.
|
* @returns {Promise<object>} The generated object matching the schema and usage.
|
||||||
* @throws {Error} If generation or validation fails.
|
* @throws {Error} If generation or validation fails.
|
||||||
*/
|
*/
|
||||||
export async function generateAnthropicObject({
|
export async function generateAnthropicObject({
|
||||||
@@ -197,7 +204,14 @@ export async function generateAnthropicObject({
|
|||||||
'debug',
|
'debug',
|
||||||
`Anthropic generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
`Anthropic generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
||||||
);
|
);
|
||||||
return result.object;
|
// Return both object and usage
|
||||||
|
return {
|
||||||
|
object: result.object,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
log(
|
||||||
'error',
|
'error',
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { generateText, streamText, generateObject } from 'ai'; // Import from ma
|
|||||||
import { log } from '../../scripts/modules/utils.js'; // Import logging utility
|
import { log } from '../../scripts/modules/utils.js'; // Import logging utility
|
||||||
|
|
||||||
// Consider making model configurable via config-manager.js later
|
// Consider making model configurable via config-manager.js later
|
||||||
const DEFAULT_MODEL = 'gemini-2.0-pro'; // Or a suitable default
|
const DEFAULT_MODEL = 'gemini-2.5-pro-exp-03-25'; // Or a suitable default
|
||||||
const DEFAULT_TEMPERATURE = 0.2; // Or a suitable default
|
const DEFAULT_TEMPERATURE = 0.2; // Or a suitable default
|
||||||
|
|
||||||
function getClient(apiKey, baseUrl) {
|
function getClient(apiKey, baseUrl) {
|
||||||
@@ -56,7 +56,17 @@ async function generateGoogleText({
|
|||||||
temperature,
|
temperature,
|
||||||
maxOutputTokens: maxTokens
|
maxOutputTokens: maxTokens
|
||||||
});
|
});
|
||||||
return result.text;
|
|
||||||
|
// Assuming result structure provides text directly or within a property
|
||||||
|
// return result.text; // Adjust based on actual SDK response
|
||||||
|
// Return both text and usage
|
||||||
|
return {
|
||||||
|
text: result.text,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
log(
|
||||||
'error',
|
'error',
|
||||||
@@ -142,14 +152,23 @@ async function generateGoogleObject({
|
|||||||
try {
|
try {
|
||||||
const googleProvider = getClient(apiKey, baseUrl);
|
const googleProvider = getClient(apiKey, baseUrl);
|
||||||
const model = googleProvider(modelId);
|
const model = googleProvider(modelId);
|
||||||
const { object } = await generateObject({
|
const result = await generateObject({
|
||||||
model,
|
model,
|
||||||
schema,
|
schema,
|
||||||
messages,
|
messages,
|
||||||
temperature,
|
temperature,
|
||||||
maxOutputTokens: maxTokens
|
maxOutputTokens: maxTokens
|
||||||
});
|
});
|
||||||
return object;
|
|
||||||
|
// return object; // Return the parsed object
|
||||||
|
// Return both object and usage
|
||||||
|
return {
|
||||||
|
object: result.object,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
log(
|
||||||
'error',
|
'error',
|
||||||
|
|||||||
163
src/ai-providers/ollama.js
Normal file
163
src/ai-providers/ollama.js
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
/**
|
||||||
|
* ollama.js
|
||||||
|
* AI provider implementation for Ollama models using the ollama-ai-provider package.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createOllama } from 'ollama-ai-provider';
|
||||||
|
import { log } from '../../scripts/modules/utils.js'; // Import logging utility
|
||||||
|
import { generateObject, generateText, streamText } from 'ai';
|
||||||
|
|
||||||
|
// Consider making model configurable via config-manager.js later
|
||||||
|
const DEFAULT_MODEL = 'llama3'; // Or a suitable default for Ollama
|
||||||
|
const DEFAULT_TEMPERATURE = 0.2;
|
||||||
|
|
||||||
|
function getClient(baseUrl) {
|
||||||
|
// baseUrl is optional, defaults to http://localhost:11434
|
||||||
|
return createOllama({
|
||||||
|
baseUrl: baseUrl || undefined
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates text using an Ollama model.
|
||||||
|
*
|
||||||
|
* @param {object} params - Parameters for the generation.
|
||||||
|
* @param {string} params.modelId - Specific model ID to use (overrides default).
|
||||||
|
* @param {number} params.temperature - Generation temperature.
|
||||||
|
* @param {Array<object>} params.messages - The conversation history (system/user prompts).
|
||||||
|
* @param {number} [params.maxTokens] - Optional max tokens.
|
||||||
|
* @param {string} [params.baseUrl] - Optional Ollama base URL.
|
||||||
|
* @returns {Promise<string>} The generated text content.
|
||||||
|
* @throws {Error} If API call fails.
|
||||||
|
*/
|
||||||
|
async function generateOllamaText({
|
||||||
|
modelId = DEFAULT_MODEL,
|
||||||
|
messages,
|
||||||
|
maxTokens,
|
||||||
|
temperature = DEFAULT_TEMPERATURE,
|
||||||
|
baseUrl
|
||||||
|
}) {
|
||||||
|
log('info', `Generating text with Ollama model: ${modelId}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = getClient(baseUrl);
|
||||||
|
const result = await generateText({
|
||||||
|
model: client(modelId),
|
||||||
|
messages,
|
||||||
|
maxTokens,
|
||||||
|
temperature
|
||||||
|
});
|
||||||
|
log('debug', `Ollama generated text: ${result.text}`);
|
||||||
|
return {
|
||||||
|
text: result.text,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
log(
|
||||||
|
'error',
|
||||||
|
`Error generating text with Ollama (${modelId}): ${error.message}`
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Streams text using an Ollama model.
|
||||||
|
*
|
||||||
|
* @param {object} params - Parameters for the streaming.
|
||||||
|
* @param {string} params.modelId - Specific model ID to use (overrides default).
|
||||||
|
* @param {number} params.temperature - Generation temperature.
|
||||||
|
* @param {Array<object>} params.messages - The conversation history.
|
||||||
|
* @param {number} [params.maxTokens] - Optional max tokens.
|
||||||
|
* @param {string} [params.baseUrl] - Optional Ollama base URL.
|
||||||
|
* @returns {Promise<ReadableStream>} A readable stream of text deltas.
|
||||||
|
* @throws {Error} If API call fails.
|
||||||
|
*/
|
||||||
|
async function streamOllamaText({
|
||||||
|
modelId = DEFAULT_MODEL,
|
||||||
|
temperature = DEFAULT_TEMPERATURE,
|
||||||
|
messages,
|
||||||
|
maxTokens,
|
||||||
|
baseUrl
|
||||||
|
}) {
|
||||||
|
log('info', `Streaming text with Ollama model: ${modelId}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const ollama = getClient(baseUrl);
|
||||||
|
const stream = await streamText({
|
||||||
|
model: modelId,
|
||||||
|
messages,
|
||||||
|
temperature,
|
||||||
|
maxTokens
|
||||||
|
});
|
||||||
|
return stream;
|
||||||
|
} catch (error) {
|
||||||
|
log(
|
||||||
|
'error',
|
||||||
|
`Error streaming text with Ollama (${modelId}): ${error.message}`
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a structured object using an Ollama model using the Vercel AI SDK's generateObject.
|
||||||
|
*
|
||||||
|
* @param {object} params - Parameters for the object generation.
|
||||||
|
* @param {string} params.modelId - Specific model ID to use (overrides default).
|
||||||
|
* @param {number} params.temperature - Generation temperature.
|
||||||
|
* @param {Array<object>} params.messages - The conversation history.
|
||||||
|
* @param {import('zod').ZodSchema} params.schema - Zod schema for the expected object.
|
||||||
|
* @param {string} params.objectName - Name for the object generation context.
|
||||||
|
* @param {number} [params.maxTokens] - Optional max tokens.
|
||||||
|
* @param {number} [params.maxRetries] - Max retries for validation/generation.
|
||||||
|
* @param {string} [params.baseUrl] - Optional Ollama base URL.
|
||||||
|
* @returns {Promise<object>} The generated object matching the schema.
|
||||||
|
* @throws {Error} If generation or validation fails.
|
||||||
|
*/
|
||||||
|
async function generateOllamaObject({
|
||||||
|
modelId = DEFAULT_MODEL,
|
||||||
|
temperature = DEFAULT_TEMPERATURE,
|
||||||
|
messages,
|
||||||
|
schema,
|
||||||
|
objectName = 'generated_object',
|
||||||
|
maxTokens,
|
||||||
|
maxRetries = 3,
|
||||||
|
baseUrl
|
||||||
|
}) {
|
||||||
|
log('info', `Generating object with Ollama model: ${modelId}`);
|
||||||
|
try {
|
||||||
|
const ollama = getClient(baseUrl);
|
||||||
|
const result = await generateObject({
|
||||||
|
model: ollama(modelId),
|
||||||
|
mode: 'tool',
|
||||||
|
schema: schema,
|
||||||
|
messages: messages,
|
||||||
|
tool: {
|
||||||
|
name: objectName,
|
||||||
|
description: `Generate a ${objectName} based on the prompt.`
|
||||||
|
},
|
||||||
|
maxOutputTokens: maxTokens,
|
||||||
|
temperature: temperature,
|
||||||
|
maxRetries: maxRetries
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
object: result.object,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
log(
|
||||||
|
'error',
|
||||||
|
`Ollama generateObject ('${objectName}') failed: ${error.message}`
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { generateOllamaText, streamOllamaText, generateOllamaObject };
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createOpenAI } from '@ai-sdk/openai'; // Using openai provider from Vercel AI SDK
|
import { createOpenAI } from '@ai-sdk/openai'; // Using openai provider from Vercel AI SDK
|
||||||
import { generateObject } from 'ai'; // Import necessary functions from 'ai'
|
import { generateObject, generateText } from 'ai'; // Import necessary functions from 'ai'
|
||||||
import { log } from '../../scripts/modules/utils.js';
|
import { log } from '../../scripts/modules/utils.js';
|
||||||
|
|
||||||
function getClient(apiKey, baseUrl) {
|
function getClient(apiKey, baseUrl) {
|
||||||
@@ -16,7 +16,7 @@ function getClient(apiKey, baseUrl) {
|
|||||||
* Generates text using OpenAI models via Vercel AI SDK.
|
* Generates text using OpenAI models via Vercel AI SDK.
|
||||||
*
|
*
|
||||||
* @param {object} params - Parameters including apiKey, modelId, messages, maxTokens, temperature, baseUrl.
|
* @param {object} params - Parameters including apiKey, modelId, messages, maxTokens, temperature, baseUrl.
|
||||||
* @returns {Promise<string>} The generated text content.
|
* @returns {Promise<object>} The generated text content and usage.
|
||||||
* @throws {Error} If API call fails.
|
* @throws {Error} If API call fails.
|
||||||
*/
|
*/
|
||||||
export async function generateOpenAIText(params) {
|
export async function generateOpenAIText(params) {
|
||||||
@@ -36,15 +36,14 @@ export async function generateOpenAIText(params) {
|
|||||||
const openaiClient = getClient(apiKey, baseUrl);
|
const openaiClient = getClient(apiKey, baseUrl);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await openaiClient.chat(messages, {
|
const result = await generateText({
|
||||||
model: modelId,
|
model: openaiClient(modelId),
|
||||||
max_tokens: maxTokens,
|
messages,
|
||||||
|
maxTokens,
|
||||||
temperature
|
temperature
|
||||||
});
|
});
|
||||||
|
|
||||||
const textContent = result?.choices?.[0]?.message?.content?.trim();
|
if (!result || !result.text) {
|
||||||
|
|
||||||
if (!textContent) {
|
|
||||||
log(
|
log(
|
||||||
'warn',
|
'warn',
|
||||||
'OpenAI generateText response did not contain expected content.',
|
'OpenAI generateText response did not contain expected content.',
|
||||||
@@ -56,7 +55,13 @@ export async function generateOpenAIText(params) {
|
|||||||
'debug',
|
'debug',
|
||||||
`OpenAI generateText completed successfully for model: ${modelId}`
|
`OpenAI generateText completed successfully for model: ${modelId}`
|
||||||
);
|
);
|
||||||
return textContent;
|
return {
|
||||||
|
text: result.text.trim(),
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
log(
|
||||||
'error',
|
'error',
|
||||||
@@ -122,7 +127,7 @@ export async function streamOpenAIText(params) {
|
|||||||
* Generates structured objects using OpenAI models via Vercel AI SDK.
|
* Generates structured objects using OpenAI models via Vercel AI SDK.
|
||||||
*
|
*
|
||||||
* @param {object} params - Parameters including apiKey, modelId, messages, schema, objectName, maxTokens, temperature, baseUrl.
|
* @param {object} params - Parameters including apiKey, modelId, messages, schema, objectName, maxTokens, temperature, baseUrl.
|
||||||
* @returns {Promise<object>} The generated object matching the schema.
|
* @returns {Promise<object>} The generated object matching the schema and usage.
|
||||||
* @throws {Error} If API call fails or object generation fails.
|
* @throws {Error} If API call fails or object generation fails.
|
||||||
*/
|
*/
|
||||||
export async function generateOpenAIObject(params) {
|
export async function generateOpenAIObject(params) {
|
||||||
@@ -166,7 +171,21 @@ export async function generateOpenAIObject(params) {
|
|||||||
'debug',
|
'debug',
|
||||||
`OpenAI generateObject completed successfully for model: ${modelId}`
|
`OpenAI generateObject completed successfully for model: ${modelId}`
|
||||||
);
|
);
|
||||||
return result.object;
|
if (!result || typeof result.object === 'undefined') {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
'OpenAI generateObject response did not contain expected object.',
|
||||||
|
{ result }
|
||||||
|
);
|
||||||
|
throw new Error('Failed to extract object from OpenAI response.');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
object: result.object,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
log(
|
||||||
'error',
|
'error',
|
||||||
|
|||||||
@@ -41,20 +41,53 @@ async function generateOpenRouterText({
|
|||||||
const openrouter = getClient(apiKey, baseUrl);
|
const openrouter = getClient(apiKey, baseUrl);
|
||||||
const model = openrouter.chat(modelId); // Assuming chat model
|
const model = openrouter.chat(modelId); // Assuming chat model
|
||||||
|
|
||||||
const { text } = await generateText({
|
// Capture the full result from generateText
|
||||||
|
const result = await generateText({
|
||||||
model,
|
model,
|
||||||
messages,
|
messages,
|
||||||
maxTokens,
|
maxTokens,
|
||||||
temperature,
|
temperature,
|
||||||
...rest // Pass any additional parameters
|
...rest // Pass any additional parameters
|
||||||
});
|
});
|
||||||
return text;
|
|
||||||
|
// Check if text and usage are present
|
||||||
|
if (!result || typeof result.text !== 'string') {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
`OpenRouter generateText for model ${modelId} did not return expected text.`,
|
||||||
|
{ result }
|
||||||
|
);
|
||||||
|
throw new Error('Failed to extract text from OpenRouter response.');
|
||||||
|
}
|
||||||
|
if (!result.usage) {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
`OpenRouter generateText for model ${modelId} did not return usage data.`,
|
||||||
|
{ result }
|
||||||
|
);
|
||||||
|
// Decide if this is critical. For now, let it pass but telemetry will be incomplete.
|
||||||
|
}
|
||||||
|
|
||||||
|
log('debug', `OpenRouter generateText completed for model ${modelId}`);
|
||||||
|
// Return text and usage
|
||||||
|
return {
|
||||||
|
text: result.text,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
let detailedMessage = `OpenRouter generateText failed for model ${modelId}: ${error.message}`;
|
||||||
'error',
|
if (error.cause) {
|
||||||
`OpenRouter generateText failed for model ${modelId}: ${error.message}`
|
detailedMessage += `\n\nCause:\n\n ${typeof error.cause === 'string' ? error.cause : JSON.stringify(error.cause)}`;
|
||||||
);
|
}
|
||||||
// Re-throw the error for the unified layer to handle retries/fallbacks
|
// Vercel AI SDK sometimes wraps the actual API error response in error.data
|
||||||
|
if (error.data) {
|
||||||
|
detailedMessage += `\n\nData:\n\n ${JSON.stringify(error.data)}`;
|
||||||
|
}
|
||||||
|
// Log the original error object for full context if needed for deeper debugging
|
||||||
|
log('error', detailedMessage, { originalErrorObject: error });
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,10 +133,14 @@ async function streamOpenRouterText({
|
|||||||
});
|
});
|
||||||
return stream;
|
return stream;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
let detailedMessage = `OpenRouter streamText failed for model ${modelId}: ${error.message}`;
|
||||||
'error',
|
if (error.cause) {
|
||||||
`OpenRouter streamText failed for model ${modelId}: ${error.message}`
|
detailedMessage += `\n\nCause:\n\n ${typeof error.cause === 'string' ? error.cause : JSON.stringify(error.cause)}`;
|
||||||
);
|
}
|
||||||
|
if (error.data) {
|
||||||
|
detailedMessage += `\n\nData:\n\n ${JSON.stringify(error.data)}`;
|
||||||
|
}
|
||||||
|
log('error', detailedMessage, { originalErrorObject: error });
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -146,12 +183,12 @@ async function generateOpenRouterObject({
|
|||||||
const openrouter = getClient(apiKey, baseUrl);
|
const openrouter = getClient(apiKey, baseUrl);
|
||||||
const model = openrouter.chat(modelId);
|
const model = openrouter.chat(modelId);
|
||||||
|
|
||||||
const { object } = await generateObject({
|
// Capture the full result from generateObject
|
||||||
|
const result = await generateObject({
|
||||||
model,
|
model,
|
||||||
schema,
|
schema,
|
||||||
mode: 'tool', // Standard mode for most object generation
|
mode: 'tool',
|
||||||
tool: {
|
tool: {
|
||||||
// Define the tool based on the schema
|
|
||||||
name: objectName,
|
name: objectName,
|
||||||
description: `Generate an object conforming to the ${objectName} schema.`,
|
description: `Generate an object conforming to the ${objectName} schema.`,
|
||||||
parameters: schema
|
parameters: schema
|
||||||
@@ -159,15 +196,45 @@ async function generateOpenRouterObject({
|
|||||||
messages,
|
messages,
|
||||||
maxTokens,
|
maxTokens,
|
||||||
temperature,
|
temperature,
|
||||||
maxRetries, // Pass maxRetries if supported by generateObject
|
maxRetries,
|
||||||
...rest
|
...rest
|
||||||
});
|
});
|
||||||
return object;
|
|
||||||
|
// Check if object and usage are present
|
||||||
|
if (!result || typeof result.object === 'undefined') {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
`OpenRouter generateObject for model ${modelId} did not return expected object.`,
|
||||||
|
{ result }
|
||||||
|
);
|
||||||
|
throw new Error('Failed to extract object from OpenRouter response.');
|
||||||
|
}
|
||||||
|
if (!result.usage) {
|
||||||
|
log(
|
||||||
|
'warn',
|
||||||
|
`OpenRouter generateObject for model ${modelId} did not return usage data.`,
|
||||||
|
{ result }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
log('debug', `OpenRouter generateObject completed for model ${modelId}`);
|
||||||
|
// Return object and usage
|
||||||
|
return {
|
||||||
|
object: result.object,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
let detailedMessage = `OpenRouter generateObject failed for model ${modelId}: ${error.message}`;
|
||||||
'error',
|
if (error.cause) {
|
||||||
`OpenRouter generateObject failed for model ${modelId}: ${error.message}`
|
detailedMessage += `\n\nCause:\n\n ${typeof error.cause === 'string' ? error.cause : JSON.stringify(error.cause)}`;
|
||||||
);
|
}
|
||||||
|
if (error.data) {
|
||||||
|
detailedMessage += `\n\nData:\n\n ${JSON.stringify(error.data)}`;
|
||||||
|
}
|
||||||
|
log('error', detailedMessage, { originalErrorObject: error });
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,7 +56,14 @@ export async function generatePerplexityText({
|
|||||||
'debug',
|
'debug',
|
||||||
`Perplexity generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
`Perplexity generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
||||||
);
|
);
|
||||||
return result.text;
|
|
||||||
|
return {
|
||||||
|
text: result.text,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log('error', `Perplexity generateText failed: ${error.message}`);
|
log('error', `Perplexity generateText failed: ${error.message}`);
|
||||||
throw error;
|
throw error;
|
||||||
@@ -153,7 +160,13 @@ export async function generatePerplexityObject({
|
|||||||
'debug',
|
'debug',
|
||||||
`Perplexity generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
`Perplexity generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
||||||
);
|
);
|
||||||
return result.object;
|
return {
|
||||||
|
object: result.object,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
log(
|
||||||
'error',
|
'error',
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ function getClient(apiKey, baseUrl) {
|
|||||||
* @param {number} [params.maxTokens] - Maximum tokens for the response.
|
* @param {number} [params.maxTokens] - Maximum tokens for the response.
|
||||||
* @param {number} [params.temperature] - Temperature for generation.
|
* @param {number} [params.temperature] - Temperature for generation.
|
||||||
* @param {string} [params.baseUrl] - The base URL for the xAI API.
|
* @param {string} [params.baseUrl] - The base URL for the xAI API.
|
||||||
* @returns {Promise<string>} The generated text content.
|
* @returns {Promise<object>} The generated text content and usage.
|
||||||
* @throws {Error} If the API call fails.
|
* @throws {Error} If the API call fails.
|
||||||
*/
|
*/
|
||||||
export async function generateXaiText({
|
export async function generateXaiText({
|
||||||
@@ -55,7 +55,14 @@ export async function generateXaiText({
|
|||||||
'debug',
|
'debug',
|
||||||
`xAI generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
`xAI generateText result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
||||||
);
|
);
|
||||||
return result.text;
|
// Return text and usage
|
||||||
|
return {
|
||||||
|
text: result.text,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log('error', `xAI generateText failed: ${error.message}`);
|
log('error', `xAI generateText failed: ${error.message}`);
|
||||||
throw error;
|
throw error;
|
||||||
@@ -114,7 +121,7 @@ export async function streamXaiText({
|
|||||||
* @param {number} [params.temperature] - Temperature for generation.
|
* @param {number} [params.temperature] - Temperature for generation.
|
||||||
* @param {number} [params.maxRetries] - Max retries for validation/generation.
|
* @param {number} [params.maxRetries] - Max retries for validation/generation.
|
||||||
* @param {string} [params.baseUrl] - The base URL for the xAI API.
|
* @param {string} [params.baseUrl] - The base URL for the xAI API.
|
||||||
* @returns {Promise<object>} The generated object matching the schema.
|
* @returns {Promise<object>} The generated object matching the schema and its usage.
|
||||||
* @throws {Error} If generation or validation fails.
|
* @throws {Error} If generation or validation fails.
|
||||||
*/
|
*/
|
||||||
export async function generateXaiObject({
|
export async function generateXaiObject({
|
||||||
@@ -142,7 +149,8 @@ export async function generateXaiObject({
|
|||||||
messages: messages,
|
messages: messages,
|
||||||
tool: {
|
tool: {
|
||||||
name: objectName,
|
name: objectName,
|
||||||
description: `Generate a ${objectName} based on the prompt.`
|
description: `Generate a ${objectName} based on the prompt.`,
|
||||||
|
parameters: schema
|
||||||
},
|
},
|
||||||
maxTokens: maxTokens,
|
maxTokens: maxTokens,
|
||||||
temperature: temperature,
|
temperature: temperature,
|
||||||
@@ -152,7 +160,14 @@ export async function generateXaiObject({
|
|||||||
'debug',
|
'debug',
|
||||||
`xAI generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
`xAI generateObject result received. Tokens: ${result.usage.completionTokens}/${result.usage.promptTokens}`
|
||||||
);
|
);
|
||||||
return result.object;
|
// Return object and usage
|
||||||
|
return {
|
||||||
|
object: result.object,
|
||||||
|
usage: {
|
||||||
|
inputTokens: result.usage.promptTokens,
|
||||||
|
outputTokens: result.usage.completionTokens
|
||||||
|
}
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(
|
log(
|
||||||
'error',
|
'error',
|
||||||
|
|||||||
@@ -58,6 +58,50 @@ Testing approach:
|
|||||||
- Test parameter validation (missing ID, invalid ID format)
|
- Test parameter validation (missing ID, invalid ID format)
|
||||||
- Test error handling for non-existent task IDs
|
- Test error handling for non-existent task IDs
|
||||||
- Test basic command flow with a mock task store
|
- Test basic command flow with a mock task store
|
||||||
|
<info added on 2025-05-23T21:02:03.909Z>
|
||||||
|
## Updated Implementation Approach
|
||||||
|
|
||||||
|
Based on code review findings, the implementation approach needs to be revised:
|
||||||
|
|
||||||
|
1. Implement the command in `scripts/modules/commands.js` instead of creating a new file
|
||||||
|
2. Add command registration in the `registerCommands()` function (around line 482)
|
||||||
|
3. Follow existing command structure pattern:
|
||||||
|
```javascript
|
||||||
|
programInstance
|
||||||
|
.command('generate-test')
|
||||||
|
.description('Generate test cases for a task using AI')
|
||||||
|
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
|
||||||
|
.option('-i, --id <id>', 'Task ID parameter')
|
||||||
|
.option('-p, --prompt <text>', 'Additional prompt context')
|
||||||
|
.option('-r, --research', 'Use research model')
|
||||||
|
.action(async (options) => {
|
||||||
|
// Implementation
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Use the following utilities:
|
||||||
|
- `findProjectRoot()` for resolving project paths
|
||||||
|
- `findTaskById()` for retrieving task data
|
||||||
|
- `chalk` for formatted console output
|
||||||
|
|
||||||
|
5. Implement error handling following the pattern:
|
||||||
|
```javascript
|
||||||
|
try {
|
||||||
|
// Implementation
|
||||||
|
} catch (error) {
|
||||||
|
console.error(chalk.red(`Error generating test: ${error.message}`));
|
||||||
|
if (error.details) {
|
||||||
|
console.error(chalk.red(error.details));
|
||||||
|
}
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
6. Required imports:
|
||||||
|
- chalk for colored output
|
||||||
|
- path for file path operations
|
||||||
|
- findProjectRoot and findTaskById from './utils.js'
|
||||||
|
</info added on 2025-05-23T21:02:03.909Z>
|
||||||
|
|
||||||
## 2. Implement AI prompt construction and FastMCP integration [pending]
|
## 2. Implement AI prompt construction and FastMCP integration [pending]
|
||||||
### Dependencies: 24.1
|
### Dependencies: 24.1
|
||||||
@@ -76,6 +120,50 @@ Testing approach:
|
|||||||
- Test FastMCP integration with mocked responses
|
- Test FastMCP integration with mocked responses
|
||||||
- Test error handling for FastMCP failures
|
- Test error handling for FastMCP failures
|
||||||
- Test response processing with sample FastMCP outputs
|
- Test response processing with sample FastMCP outputs
|
||||||
|
<info added on 2025-05-23T21:04:33.890Z>
|
||||||
|
## AI Integration Implementation
|
||||||
|
|
||||||
|
### AI Service Integration
|
||||||
|
- Use the unified AI service layer, not FastMCP directly
|
||||||
|
- Implement with `generateObjectService` from '../ai-services-unified.js'
|
||||||
|
- Define Zod schema for structured test generation output:
|
||||||
|
- testContent: Complete Jest test file content
|
||||||
|
- fileName: Suggested filename for the test file
|
||||||
|
- mockRequirements: External dependencies that need mocking
|
||||||
|
|
||||||
|
### Prompt Construction
|
||||||
|
- Create system prompt defining AI's role as test generator
|
||||||
|
- Build user prompt with task context (ID, title, description, details)
|
||||||
|
- Include test strategy and subtasks context in the prompt
|
||||||
|
- Follow patterns from add-task.js for prompt structure
|
||||||
|
|
||||||
|
### Task Analysis
|
||||||
|
- Retrieve task data using `findTaskById()` from utils.js
|
||||||
|
- Build context by analyzing task description, details, and testStrategy
|
||||||
|
- Examine project structure for import patterns
|
||||||
|
- Parse specific testing requirements from task.testStrategy field
|
||||||
|
|
||||||
|
### File System Operations
|
||||||
|
- Determine output path in same directory as tasks.json
|
||||||
|
- Generate standardized filename based on task ID
|
||||||
|
- Use fs.writeFileSync for writing test content to file
|
||||||
|
|
||||||
|
### Error Handling & UI
|
||||||
|
- Implement try/catch blocks for AI service calls
|
||||||
|
- Display user-friendly error messages with chalk
|
||||||
|
- Use loading indicators during AI processing
|
||||||
|
- Support both research and main AI models
|
||||||
|
|
||||||
|
### Telemetry
|
||||||
|
- Pass through telemetryData from AI service response
|
||||||
|
- Display AI usage summary for CLI output
|
||||||
|
|
||||||
|
### Required Dependencies
|
||||||
|
- generateObjectService from ai-services-unified.js
|
||||||
|
- UI components (loading indicators, display functions)
|
||||||
|
- Zod for schema validation
|
||||||
|
- Chalk for formatted console output
|
||||||
|
</info added on 2025-05-23T21:04:33.890Z>
|
||||||
|
|
||||||
## 3. Implement test file generation and output [pending]
|
## 3. Implement test file generation and output [pending]
|
||||||
### Dependencies: 24.2
|
### Dependencies: 24.2
|
||||||
@@ -97,4 +185,419 @@ Testing approach:
|
|||||||
- Test file system operations with mocked fs module
|
- Test file system operations with mocked fs module
|
||||||
- Test the complete flow from command input to file output
|
- Test the complete flow from command input to file output
|
||||||
- Verify generated tests can be executed by Jest
|
- Verify generated tests can be executed by Jest
|
||||||
|
<info added on 2025-05-23T21:06:32.457Z>
|
||||||
|
## Detailed Implementation Guidelines
|
||||||
|
|
||||||
|
### File Naming Convention Implementation
|
||||||
|
```javascript
|
||||||
|
function generateTestFileName(taskId, isSubtask = false) {
|
||||||
|
if (isSubtask) {
|
||||||
|
// For subtasks like "24.1", generate "task_024_001.test.js"
|
||||||
|
const [parentId, subtaskId] = taskId.split('.');
|
||||||
|
return `task_${parentId.padStart(3, '0')}_${subtaskId.padStart(3, '0')}.test.js`;
|
||||||
|
} else {
|
||||||
|
// For parent tasks like "24", generate "task_024.test.js"
|
||||||
|
return `task_${taskId.toString().padStart(3, '0')}.test.js`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### File Location Strategy
|
||||||
|
- Place generated test files in the `tasks/` directory alongside task files
|
||||||
|
- This ensures co-location with task documentation and simplifies implementation
|
||||||
|
|
||||||
|
### File Content Structure Template
|
||||||
|
```javascript
|
||||||
|
/**
|
||||||
|
* Test file for Task ${taskId}: ${taskTitle}
|
||||||
|
* Generated automatically by Task Master
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { jest } from '@jest/globals';
|
||||||
|
// Additional imports based on task requirements
|
||||||
|
|
||||||
|
describe('Task ${taskId}: ${taskTitle}', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
// Setup code
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
// Cleanup code
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should ${testDescription}', () => {
|
||||||
|
// Test implementation
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Code Formatting Standards
|
||||||
|
- Follow project's .prettierrc configuration:
|
||||||
|
- Tab width: 2 spaces (useTabs: true)
|
||||||
|
- Print width: 80 characters
|
||||||
|
- Semicolons: Required (semi: true)
|
||||||
|
- Quotes: Single quotes (singleQuote: true)
|
||||||
|
- Trailing commas: None (trailingComma: "none")
|
||||||
|
- Bracket spacing: True
|
||||||
|
- Arrow parens: Always
|
||||||
|
|
||||||
|
### File System Operations Implementation
|
||||||
|
```javascript
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
// Determine output path
|
||||||
|
const tasksDir = path.dirname(tasksPath); // Same directory as tasks.json
|
||||||
|
const fileName = generateTestFileName(task.id, isSubtask);
|
||||||
|
const filePath = path.join(tasksDir, fileName);
|
||||||
|
|
||||||
|
// Ensure directory exists
|
||||||
|
if (!fs.existsSync(tasksDir)) {
|
||||||
|
fs.mkdirSync(tasksDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write test file with proper error handling
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(filePath, formattedTestContent, 'utf8');
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Failed to write test file: ${error.message}`);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Error Handling for File Operations
|
||||||
|
```javascript
|
||||||
|
try {
|
||||||
|
// File writing operation
|
||||||
|
fs.writeFileSync(filePath, testContent, 'utf8');
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code === 'ENOENT') {
|
||||||
|
throw new Error(`Directory does not exist: ${path.dirname(filePath)}`);
|
||||||
|
} else if (error.code === 'EACCES') {
|
||||||
|
throw new Error(`Permission denied writing to: ${filePath}`);
|
||||||
|
} else if (error.code === 'ENOSPC') {
|
||||||
|
throw new Error('Insufficient disk space to write test file');
|
||||||
|
} else {
|
||||||
|
throw new Error(`Failed to write test file: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### User Feedback Implementation
|
||||||
|
```javascript
|
||||||
|
// Success feedback
|
||||||
|
console.log(chalk.green('✅ Test file generated successfully:'));
|
||||||
|
console.log(chalk.cyan(` File: ${fileName}`));
|
||||||
|
console.log(chalk.cyan(` Location: ${filePath}`));
|
||||||
|
console.log(chalk.gray(` Size: ${testContent.length} characters`));
|
||||||
|
|
||||||
|
// Additional info
|
||||||
|
if (mockRequirements && mockRequirements.length > 0) {
|
||||||
|
console.log(chalk.yellow(` Mocks needed: ${mockRequirements.join(', ')}`));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Content Validation Requirements
|
||||||
|
1. Jest Syntax Validation:
|
||||||
|
- Ensure proper describe/test structure
|
||||||
|
- Validate import statements
|
||||||
|
- Check for balanced brackets and parentheses
|
||||||
|
|
||||||
|
2. Code Quality Checks:
|
||||||
|
- Verify no syntax errors
|
||||||
|
- Ensure proper indentation
|
||||||
|
- Check for required imports
|
||||||
|
|
||||||
|
3. Test Completeness:
|
||||||
|
- At least one test case
|
||||||
|
- Proper test descriptions
|
||||||
|
- Appropriate assertions
|
||||||
|
|
||||||
|
### Required Dependencies
|
||||||
|
```javascript
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import chalk from 'chalk';
|
||||||
|
import { log } from '../utils.js';
|
||||||
|
```
|
||||||
|
|
||||||
|
### Integration with Existing Patterns
|
||||||
|
Follow the pattern from `generate-task-files.js`:
|
||||||
|
1. Read task data using existing utilities
|
||||||
|
2. Process content with proper formatting
|
||||||
|
3. Write files with error handling
|
||||||
|
4. Provide feedback to user
|
||||||
|
5. Return success data for MCP integration
|
||||||
|
</info added on 2025-05-23T21:06:32.457Z>
|
||||||
|
<info added on 2025-05-23T21:18:25.369Z>
|
||||||
|
## Corrected Implementation Approach
|
||||||
|
|
||||||
|
### Updated File Location Strategy
|
||||||
|
|
||||||
|
**CORRECTION**: Tests should go in `/tests/` directory, not `/tasks/` directory.
|
||||||
|
|
||||||
|
Based on Jest configuration analysis:
|
||||||
|
- Jest is configured with `roots: ['<rootDir>/tests']`
|
||||||
|
- Test pattern: `**/?(*.)+(spec|test).js`
|
||||||
|
- Current test structure has `/tests/unit/`, `/tests/integration/`, etc.
|
||||||
|
|
||||||
|
### Recommended Directory Structure:
|
||||||
|
```
|
||||||
|
tests/
|
||||||
|
├── unit/ # Manual unit tests
|
||||||
|
├── integration/ # Manual integration tests
|
||||||
|
├── generated/ # AI-generated tests
|
||||||
|
│ ├── tasks/ # Generated task tests
|
||||||
|
│ │ ├── task_024.test.js
|
||||||
|
│ │ └── task_024_001.test.js
|
||||||
|
│ └── README.md # Explains generated tests
|
||||||
|
└── fixtures/ # Test fixtures
|
||||||
|
```
|
||||||
|
|
||||||
|
### Updated File Path Logic:
|
||||||
|
```javascript
|
||||||
|
// Determine output path - place in tests/generated/tasks/
|
||||||
|
const projectRoot = findProjectRoot() || '.';
|
||||||
|
const testsDir = path.join(projectRoot, 'tests', 'generated', 'tasks');
|
||||||
|
const fileName = generateTestFileName(task.id, isSubtask);
|
||||||
|
const filePath = path.join(testsDir, fileName);
|
||||||
|
|
||||||
|
// Ensure directory structure exists
|
||||||
|
if (!fs.existsSync(testsDir)) {
|
||||||
|
fs.mkdirSync(testsDir, { recursive: true });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Testing Framework Configuration
|
||||||
|
|
||||||
|
The generate-test command should read the configured testing framework from `.taskmasterconfig`:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Read testing framework from config
|
||||||
|
const config = getConfig(projectRoot);
|
||||||
|
const testingFramework = config.testingFramework || 'jest'; // Default to Jest
|
||||||
|
|
||||||
|
// Generate different templates based on framework
|
||||||
|
switch (testingFramework) {
|
||||||
|
case 'jest':
|
||||||
|
return generateJestTest(task, context);
|
||||||
|
case 'mocha':
|
||||||
|
return generateMochaTest(task, context);
|
||||||
|
case 'vitest':
|
||||||
|
return generateVitestTest(task, context);
|
||||||
|
default:
|
||||||
|
throw new Error(`Unsupported testing framework: ${testingFramework}`);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Framework-Specific Templates
|
||||||
|
|
||||||
|
**Jest Template** (current):
|
||||||
|
```javascript
|
||||||
|
/**
|
||||||
|
* Test file for Task ${taskId}: ${taskTitle}
|
||||||
|
* Generated automatically by Task Master
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { jest } from '@jest/globals';
|
||||||
|
// Task-specific imports
|
||||||
|
|
||||||
|
describe('Task ${taskId}: ${taskTitle}', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should ${testDescription}', () => {
|
||||||
|
// Test implementation
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Mocha Template**:
|
||||||
|
```javascript
|
||||||
|
/**
|
||||||
|
* Test file for Task ${taskId}: ${taskTitle}
|
||||||
|
* Generated automatically by Task Master
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { expect } from 'chai';
|
||||||
|
import sinon from 'sinon';
|
||||||
|
// Task-specific imports
|
||||||
|
|
||||||
|
describe('Task ${taskId}: ${taskTitle}', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
sinon.restore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should ${testDescription}', () => {
|
||||||
|
// Test implementation
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vitest Template**:
|
||||||
|
```javascript
|
||||||
|
/**
|
||||||
|
* Test file for Task ${taskId}: ${taskTitle}
|
||||||
|
* Generated automatically by Task Master
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||||
|
// Task-specific imports
|
||||||
|
|
||||||
|
describe('Task ${taskId}: ${taskTitle}', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should ${testDescription}', () => {
|
||||||
|
// Test implementation
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### AI Prompt Enhancement for Mocking
|
||||||
|
|
||||||
|
To address the mocking challenge, enhance the AI prompt with project context:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const systemPrompt = `You are an expert at generating comprehensive test files. When generating tests, pay special attention to mocking external dependencies correctly.
|
||||||
|
|
||||||
|
CRITICAL MOCKING GUIDELINES:
|
||||||
|
1. Analyze the task requirements to identify external dependencies (APIs, databases, file system, etc.)
|
||||||
|
2. Mock external dependencies at the module level, not inline
|
||||||
|
3. Use the testing framework's mocking utilities (jest.mock(), sinon.stub(), vi.mock())
|
||||||
|
4. Create realistic mock data that matches the expected API responses
|
||||||
|
5. Test both success and error scenarios for mocked dependencies
|
||||||
|
6. Ensure mocks are cleared between tests to prevent test pollution
|
||||||
|
|
||||||
|
Testing Framework: ${testingFramework}
|
||||||
|
Project Structure: ${projectStructureContext}
|
||||||
|
`;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Integration with Future Features
|
||||||
|
|
||||||
|
This primitive command design enables:
|
||||||
|
1. **Automatic test generation**: `task-master add-task --with-test`
|
||||||
|
2. **Batch test generation**: `task-master generate-tests --all`
|
||||||
|
3. **Framework-agnostic**: Support multiple testing frameworks
|
||||||
|
4. **Smart mocking**: LLM analyzes dependencies and generates appropriate mocks
|
||||||
|
|
||||||
|
### Updated Implementation Requirements:
|
||||||
|
|
||||||
|
1. **Read testing framework** from `.taskmasterconfig`
|
||||||
|
2. **Create tests directory structure** if it doesn't exist
|
||||||
|
3. **Generate framework-specific templates** based on configuration
|
||||||
|
4. **Enhanced AI prompts** with mocking best practices
|
||||||
|
5. **Project structure analysis** for better import resolution
|
||||||
|
6. **Mock dependency detection** from task requirements
|
||||||
|
</info added on 2025-05-23T21:18:25.369Z>
|
||||||
|
|
||||||
|
## 4. Implement MCP tool integration for generate-test command [pending]
|
||||||
|
### Dependencies: 24.3
|
||||||
|
### Description: Create MCP server tool support for the generate-test command to enable integration with Claude Code and other MCP clients.
|
||||||
|
### Details:
|
||||||
|
Implementation steps:
|
||||||
|
1. Create direct function wrapper in mcp-server/src/core/direct-functions/
|
||||||
|
2. Create MCP tool registration in mcp-server/src/tools/
|
||||||
|
3. Add tool to the main tools index
|
||||||
|
4. Implement proper parameter validation and error handling
|
||||||
|
5. Ensure telemetry data is properly passed through
|
||||||
|
6. Add tool to MCP server registration
|
||||||
|
|
||||||
|
The MCP tool should support the same parameters as the CLI command:
|
||||||
|
- id: Task ID to generate tests for
|
||||||
|
- file: Path to tasks.json file
|
||||||
|
- research: Whether to use research model
|
||||||
|
- prompt: Additional context for test generation
|
||||||
|
|
||||||
|
Follow the existing pattern from other MCP tools like add-task.js and expand-task.js.
|
||||||
|
|
||||||
|
## 5. Add testing framework configuration to project initialization [pending]
|
||||||
|
### Dependencies: 24.3
|
||||||
|
### Description: Enhance the init.js process to let users choose their preferred testing framework (Jest, Mocha, Vitest, etc.) and store this choice in .taskmasterconfig for use by the generate-test command.
|
||||||
|
### Details:
|
||||||
|
Implementation requirements:
|
||||||
|
|
||||||
|
1. **Add Testing Framework Prompt to init.js**:
|
||||||
|
- Add interactive prompt asking users to choose testing framework
|
||||||
|
- Support Jest (default), Mocha + Chai, Vitest, Ava, Jasmine
|
||||||
|
- Include brief descriptions of each framework
|
||||||
|
- Allow --testing-framework flag for non-interactive mode
|
||||||
|
|
||||||
|
2. **Update .taskmasterconfig Template**:
|
||||||
|
- Add testingFramework field to configuration file
|
||||||
|
- Include default dependencies for each framework
|
||||||
|
- Store framework-specific configuration options
|
||||||
|
|
||||||
|
3. **Framework-Specific Setup**:
|
||||||
|
- Generate appropriate config files (jest.config.js, vitest.config.ts, etc.)
|
||||||
|
- Add framework dependencies to package.json suggestions
|
||||||
|
- Create sample test file for the chosen framework
|
||||||
|
|
||||||
|
4. **Integration Points**:
|
||||||
|
- Ensure generate-test command reads testingFramework from config
|
||||||
|
- Add validation to prevent conflicts between framework choices
|
||||||
|
- Support switching frameworks later via models command or separate config command
|
||||||
|
|
||||||
|
This makes the generate-test command truly framework-agnostic and sets up the foundation for --with-test flags in other commands.
|
||||||
|
<info added on 2025-05-23T21:22:02.048Z>
|
||||||
|
# Implementation Plan for Testing Framework Integration
|
||||||
|
|
||||||
|
## Code Structure
|
||||||
|
|
||||||
|
### 1. Update init.js
|
||||||
|
- Add testing framework prompt after addAliases prompt
|
||||||
|
- Implement framework selection with descriptions
|
||||||
|
- Support non-interactive mode with --testing-framework flag
|
||||||
|
- Create setupTestingFramework() function to handle framework-specific setup
|
||||||
|
|
||||||
|
### 2. Create New Module Files
|
||||||
|
- Create `scripts/modules/testing-frameworks.js` for framework templates and setup
|
||||||
|
- Add sample test generators for each supported framework
|
||||||
|
- Implement config file generation for each framework
|
||||||
|
|
||||||
|
### 3. Update Configuration Templates
|
||||||
|
- Modify `assets/.taskmasterconfig` to include testing fields:
|
||||||
|
```json
|
||||||
|
"testingFramework": "{{testingFramework}}",
|
||||||
|
"testingConfig": {
|
||||||
|
"framework": "{{testingFramework}}",
|
||||||
|
"setupFiles": [],
|
||||||
|
"testDirectory": "tests",
|
||||||
|
"testPattern": "**/*.test.js",
|
||||||
|
"coverage": {
|
||||||
|
"enabled": false,
|
||||||
|
"threshold": 80
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Create Framework-Specific Templates
|
||||||
|
- `assets/jest.config.template.js`
|
||||||
|
- `assets/vitest.config.template.ts`
|
||||||
|
- `assets/.mocharc.template.json`
|
||||||
|
- `assets/ava.config.template.js`
|
||||||
|
- `assets/jasmine.json.template`
|
||||||
|
|
||||||
|
### 5. Update commands.js
|
||||||
|
- Add `--testing-framework <framework>` option to init command
|
||||||
|
- Add validation for supported frameworks
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
- Validate selected framework against supported list
|
||||||
|
- Handle existing config files gracefully with warning/overwrite prompt
|
||||||
|
- Provide recovery options if framework setup fails
|
||||||
|
- Add conflict detection for multiple testing frameworks
|
||||||
|
|
||||||
|
## Integration Points
|
||||||
|
- Ensure generate-test command reads testingFramework from config
|
||||||
|
- Prepare for future --with-test flag in other commands
|
||||||
|
- Support framework switching via config command
|
||||||
|
|
||||||
|
## Testing Requirements
|
||||||
|
- Unit tests for framework selection logic
|
||||||
|
- Integration tests for config file generation
|
||||||
|
- Validation tests for each supported framework
|
||||||
|
</info added on 2025-05-23T21:22:02.048Z>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Task ID: 32
|
# Task ID: 32
|
||||||
# Title: Implement "learn" Command for Automatic Cursor Rule Generation
|
# Title: Implement "learn" Command for Automatic Cursor Rule Generation
|
||||||
# Status: pending
|
# Status: deferred
|
||||||
# Dependencies: None
|
# Dependencies: None
|
||||||
# Priority: high
|
# Priority: high
|
||||||
# Description: Create a new "learn" command that analyzes Cursor's chat history and code changes to automatically generate or update rule files in the .cursor/rules directory, following the cursor_rules.mdc template format. This command will help Cursor autonomously improve its ability to follow development standards by learning from successful implementations.
|
# Description: Create a new "learn" command that analyzes Cursor's chat history and code changes to automatically generate or update rule files in the .cursor/rules directory, following the cursor_rules.mdc template format. This command will help Cursor autonomously improve its ability to follow development standards by learning from successful implementations.
|
||||||
|
|||||||
@@ -77,48 +77,263 @@ This implementation should include:
|
|||||||
### Description: Design and implement the command-line interface for the dependency graph tool, including argument parsing and help documentation.
|
### Description: Design and implement the command-line interface for the dependency graph tool, including argument parsing and help documentation.
|
||||||
### Details:
|
### Details:
|
||||||
Define commands for input file specification, output options, filtering, and other user-configurable parameters.
|
Define commands for input file specification, output options, filtering, and other user-configurable parameters.
|
||||||
|
<info added on 2025-05-23T21:02:26.442Z>
|
||||||
|
Implement a new 'diagram' command (with 'graph' alias) in commands.js following the Commander.js pattern. The command should:
|
||||||
|
|
||||||
|
1. Import diagram-generator.js module functions for generating visual representations
|
||||||
|
2. Support multiple visualization types with --type option:
|
||||||
|
- dependencies: show task dependency relationships
|
||||||
|
- subtasks: show task/subtask hierarchy
|
||||||
|
- flow: show task workflow
|
||||||
|
- gantt: show timeline visualization
|
||||||
|
|
||||||
|
3. Include the following options:
|
||||||
|
- --task <id>: Filter diagram to show only specified task and its relationships
|
||||||
|
- --mermaid: Output raw Mermaid markdown for external rendering
|
||||||
|
- --visual: Render diagram directly in terminal
|
||||||
|
- --format <format>: Output format (text, svg, png)
|
||||||
|
|
||||||
|
4. Implement proper error handling and validation:
|
||||||
|
- Validate task IDs using existing taskExists() function
|
||||||
|
- Handle invalid option combinations
|
||||||
|
- Provide descriptive error messages
|
||||||
|
|
||||||
|
5. Integrate with UI components:
|
||||||
|
- Use ui.js display functions for consistent output formatting
|
||||||
|
- Apply chalk coloring for terminal output
|
||||||
|
- Use boxen formatting consistent with other commands
|
||||||
|
|
||||||
|
6. Handle file operations:
|
||||||
|
- Resolve file paths using findProjectRoot() pattern
|
||||||
|
- Support saving diagrams to files when appropriate
|
||||||
|
|
||||||
|
7. Include comprehensive help text following the established pattern in other commands
|
||||||
|
</info added on 2025-05-23T21:02:26.442Z>
|
||||||
|
|
||||||
## 2. Graph Layout Algorithms [pending]
|
## 2. Graph Layout Algorithms [pending]
|
||||||
### Dependencies: 41.1
|
### Dependencies: 41.1
|
||||||
### Description: Develop or integrate algorithms to compute optimal node and edge placement for clear and readable graph layouts in a terminal environment.
|
### Description: Develop or integrate algorithms to compute optimal node and edge placement for clear and readable graph layouts in a terminal environment.
|
||||||
### Details:
|
### Details:
|
||||||
Consider topological sorting, hierarchical, and force-directed layouts suitable for ASCII/Unicode rendering.
|
Consider topological sorting, hierarchical, and force-directed layouts suitable for ASCII/Unicode rendering.
|
||||||
|
<info added on 2025-05-23T21:02:49.434Z>
|
||||||
|
Create a new diagram-generator.js module in the scripts/modules/ directory following Task Master's module architecture pattern. The module should include:
|
||||||
|
|
||||||
|
1. Core functions for generating Mermaid diagrams:
|
||||||
|
- generateDependencyGraph(tasks, options) - creates flowchart showing task dependencies
|
||||||
|
- generateSubtaskDiagram(task, options) - creates hierarchy diagram for subtasks
|
||||||
|
- generateProjectFlow(tasks, options) - creates overall project workflow
|
||||||
|
- generateGanttChart(tasks, options) - creates timeline visualization
|
||||||
|
|
||||||
|
2. Integration with existing Task Master data structures:
|
||||||
|
- Use the same task object format from task-manager.js
|
||||||
|
- Leverage dependency analysis from dependency-manager.js
|
||||||
|
- Support complexity scores from analyze-complexity functionality
|
||||||
|
- Handle both main tasks and subtasks with proper ID notation (parentId.subtaskId)
|
||||||
|
|
||||||
|
3. Layout algorithm considerations for Mermaid:
|
||||||
|
- Topological sorting for dependency flows
|
||||||
|
- Hierarchical layouts for subtask trees
|
||||||
|
- Circular dependency detection and highlighting
|
||||||
|
- Terminal width-aware formatting for ASCII fallback
|
||||||
|
|
||||||
|
4. Export functions following the existing module pattern at the bottom of the file
|
||||||
|
</info added on 2025-05-23T21:02:49.434Z>
|
||||||
|
|
||||||
## 3. ASCII/Unicode Rendering Engine [pending]
|
## 3. ASCII/Unicode Rendering Engine [pending]
|
||||||
### Dependencies: 41.2
|
### Dependencies: 41.2
|
||||||
### Description: Implement rendering logic to display the dependency graph using ASCII and Unicode characters in the terminal.
|
### Description: Implement rendering logic to display the dependency graph using ASCII and Unicode characters in the terminal.
|
||||||
### Details:
|
### Details:
|
||||||
Support for various node and edge styles, and ensure compatibility with different terminal types.
|
Support for various node and edge styles, and ensure compatibility with different terminal types.
|
||||||
|
<info added on 2025-05-23T21:03:10.001Z>
|
||||||
|
Extend ui.js with diagram display functions that integrate with Task Master's existing UI patterns:
|
||||||
|
|
||||||
|
1. Implement core diagram display functions:
|
||||||
|
- displayTaskDiagram(tasksPath, diagramType, options) as the main entry point
|
||||||
|
- displayMermaidCode(mermaidCode, title) for formatted code output with boxen
|
||||||
|
- displayDiagramLegend() to explain symbols and colors
|
||||||
|
|
||||||
|
2. Ensure UI consistency by:
|
||||||
|
- Using established chalk color schemes (blue/green/yellow/red)
|
||||||
|
- Applying boxen for consistent component formatting
|
||||||
|
- Following existing display function patterns (displayTaskById, displayComplexityReport)
|
||||||
|
- Utilizing cli-table3 for any diagram metadata tables
|
||||||
|
|
||||||
|
3. Address terminal rendering challenges:
|
||||||
|
- Implement ASCII/Unicode fallback when Mermaid rendering isn't available
|
||||||
|
- Respect terminal width constraints using process.stdout.columns
|
||||||
|
- Integrate with loading indicators via startLoadingIndicator/stopLoadingIndicator
|
||||||
|
|
||||||
|
4. Update task file generation to include Mermaid diagram sections in individual task files
|
||||||
|
|
||||||
|
5. Support both CLI and MCP output formats through the outputFormat parameter
|
||||||
|
</info added on 2025-05-23T21:03:10.001Z>
|
||||||
|
|
||||||
## 4. Color Coding Support [pending]
|
## 4. Color Coding Support [pending]
|
||||||
### Dependencies: 41.3
|
### Dependencies: 41.3
|
||||||
### Description: Add color coding to nodes and edges to visually distinguish types, statuses, or other attributes in the graph.
|
### Description: Add color coding to nodes and edges to visually distinguish types, statuses, or other attributes in the graph.
|
||||||
### Details:
|
### Details:
|
||||||
Use ANSI escape codes for color; provide options for colorblind-friendly palettes.
|
Use ANSI escape codes for color; provide options for colorblind-friendly palettes.
|
||||||
|
<info added on 2025-05-23T21:03:35.762Z>
|
||||||
|
Integrate color coding with Task Master's existing status system:
|
||||||
|
|
||||||
|
1. Extend getStatusWithColor() in ui.js to support diagram contexts:
|
||||||
|
- Add 'diagram' parameter to determine rendering context
|
||||||
|
- Modify color intensity for better visibility in graph elements
|
||||||
|
|
||||||
|
2. Implement Task Master's established color scheme using ANSI codes:
|
||||||
|
- Green (\x1b[32m) for 'done'/'completed' tasks
|
||||||
|
- Yellow (\x1b[33m) for 'pending' tasks
|
||||||
|
- Orange (\x1b[38;5;208m) for 'in-progress' tasks
|
||||||
|
- Red (\x1b[31m) for 'blocked' tasks
|
||||||
|
- Gray (\x1b[90m) for 'deferred'/'cancelled' tasks
|
||||||
|
- Magenta (\x1b[35m) for 'review' tasks
|
||||||
|
|
||||||
|
3. Create diagram-specific color functions:
|
||||||
|
- getDependencyLineColor(fromTaskStatus, toTaskStatus) - color dependency arrows based on relationship status
|
||||||
|
- getNodeBorderColor(task) - style node borders using priority/complexity indicators
|
||||||
|
- getSubtaskGroupColor(parentTask) - visually group related subtasks
|
||||||
|
|
||||||
|
4. Integrate complexity visualization:
|
||||||
|
- Use getComplexityWithColor() for node background or border thickness
|
||||||
|
- Map complexity scores to visual weight in the graph
|
||||||
|
|
||||||
|
5. Ensure accessibility:
|
||||||
|
- Add text-based indicators (symbols like ✓, ⚠, ⏳) alongside colors
|
||||||
|
- Implement colorblind-friendly palettes as user-selectable option
|
||||||
|
- Include shape variations for different statuses
|
||||||
|
|
||||||
|
6. Follow existing ANSI patterns:
|
||||||
|
- Maintain consistency with terminal UI color usage
|
||||||
|
- Reuse color constants from the codebase
|
||||||
|
|
||||||
|
7. Support graceful degradation:
|
||||||
|
- Check terminal capabilities using existing detection
|
||||||
|
- Provide monochrome fallbacks with distinctive patterns
|
||||||
|
- Use bold/underline as alternatives when colors unavailable
|
||||||
|
</info added on 2025-05-23T21:03:35.762Z>
|
||||||
|
|
||||||
## 5. Circular Dependency Detection [pending]
|
## 5. Circular Dependency Detection [pending]
|
||||||
### Dependencies: 41.2
|
### Dependencies: 41.2
|
||||||
### Description: Implement algorithms to detect and highlight circular dependencies within the graph.
|
### Description: Implement algorithms to detect and highlight circular dependencies within the graph.
|
||||||
### Details:
|
### Details:
|
||||||
Clearly mark cycles in the rendered output and provide warnings or errors as appropriate.
|
Clearly mark cycles in the rendered output and provide warnings or errors as appropriate.
|
||||||
|
<info added on 2025-05-23T21:04:20.125Z>
|
||||||
|
Integrate with Task Master's existing circular dependency detection:
|
||||||
|
|
||||||
|
1. Import the dependency detection logic from dependency-manager.js module
|
||||||
|
2. Utilize the findCycles function from utils.js or dependency-manager.js
|
||||||
|
3. Extend validateDependenciesCommand functionality to highlight cycles in diagrams
|
||||||
|
|
||||||
|
Visual representation in Mermaid diagrams:
|
||||||
|
- Apply red/bold styling to nodes involved in dependency cycles
|
||||||
|
- Add warning annotations to cyclic edges
|
||||||
|
- Implement cycle path highlighting with distinctive line styles
|
||||||
|
|
||||||
|
Integration with validation workflow:
|
||||||
|
- Execute dependency validation before diagram generation
|
||||||
|
- Display cycle warnings consistent with existing CLI error messaging
|
||||||
|
- Utilize chalk.red and boxen for error highlighting following established patterns
|
||||||
|
|
||||||
|
Add diagram legend entries that explain cycle notation and warnings
|
||||||
|
|
||||||
|
Ensure detection of cycles in both:
|
||||||
|
- Main task dependencies
|
||||||
|
- Subtask dependencies within parent tasks
|
||||||
|
|
||||||
|
Follow Task Master's error handling patterns for graceful cycle reporting and user notification
|
||||||
|
</info added on 2025-05-23T21:04:20.125Z>
|
||||||
|
|
||||||
## 6. Filtering and Search Functionality [pending]
|
## 6. Filtering and Search Functionality [pending]
|
||||||
### Dependencies: 41.1, 41.2
|
### Dependencies: 41.1, 41.2
|
||||||
### Description: Enable users to filter nodes and edges by criteria such as name, type, or dependency depth.
|
### Description: Enable users to filter nodes and edges by criteria such as name, type, or dependency depth.
|
||||||
### Details:
|
### Details:
|
||||||
Support command-line flags for filtering and interactive search if feasible.
|
Support command-line flags for filtering and interactive search if feasible.
|
||||||
|
<info added on 2025-05-23T21:04:57.811Z>
|
||||||
|
Implement MCP tool integration for task dependency visualization:
|
||||||
|
|
||||||
|
1. Create task_diagram.js in mcp-server/src/tools/ following existing tool patterns
|
||||||
|
2. Implement taskDiagramDirect.js in mcp-server/src/core/direct-functions/
|
||||||
|
3. Use Zod schema for parameter validation:
|
||||||
|
- diagramType (dependencies, subtasks, flow, gantt)
|
||||||
|
- taskId (optional string)
|
||||||
|
- format (mermaid, text, json)
|
||||||
|
- includeComplexity (boolean)
|
||||||
|
|
||||||
|
4. Structure response data with:
|
||||||
|
- mermaidCode for client-side rendering
|
||||||
|
- metadata (nodeCount, edgeCount, cycleWarnings)
|
||||||
|
- support for both task-specific and project-wide diagrams
|
||||||
|
|
||||||
|
5. Integrate with session management and project root handling
|
||||||
|
6. Implement error handling using handleApiResult pattern
|
||||||
|
7. Register the tool in tools/index.js
|
||||||
|
|
||||||
|
Maintain compatibility with existing command-line flags for filtering and interactive search.
|
||||||
|
</info added on 2025-05-23T21:04:57.811Z>
|
||||||
|
|
||||||
## 7. Accessibility Features [pending]
|
## 7. Accessibility Features [pending]
|
||||||
### Dependencies: 41.3, 41.4
|
### Dependencies: 41.3, 41.4
|
||||||
### Description: Ensure the tool is accessible, including support for screen readers, high-contrast modes, and keyboard navigation.
|
### Description: Ensure the tool is accessible, including support for screen readers, high-contrast modes, and keyboard navigation.
|
||||||
### Details:
|
### Details:
|
||||||
Provide alternative text output and ensure color is not the sole means of conveying information.
|
Provide alternative text output and ensure color is not the sole means of conveying information.
|
||||||
|
<info added on 2025-05-23T21:05:54.584Z>
|
||||||
|
# Accessibility and Export Integration
|
||||||
|
|
||||||
|
## Accessibility Features
|
||||||
|
- Provide alternative text output for visual elements
|
||||||
|
- Ensure color is not the sole means of conveying information
|
||||||
|
- Support keyboard navigation through the dependency graph
|
||||||
|
- Add screen reader compatible node descriptions
|
||||||
|
|
||||||
|
## Export Integration
|
||||||
|
- Extend generateTaskFiles function in task-manager.js to include Mermaid diagram sections
|
||||||
|
- Add Mermaid code blocks to task markdown files under ## Diagrams header
|
||||||
|
- Follow existing task file generation patterns and markdown structure
|
||||||
|
- Support multiple diagram types per task file:
|
||||||
|
* Task dependencies (prerequisite relationships)
|
||||||
|
* Subtask hierarchy visualization
|
||||||
|
* Task flow context in project workflow
|
||||||
|
- Integrate with existing fs module file writing operations
|
||||||
|
- Add diagram export options to the generate command in commands.js
|
||||||
|
- Support SVG and PNG export using Mermaid CLI when available
|
||||||
|
- Implement error handling for diagram generation failures
|
||||||
|
- Reference exported diagrams in task markdown with proper paths
|
||||||
|
- Update CLI generate command with options like --include-diagrams
|
||||||
|
</info added on 2025-05-23T21:05:54.584Z>
|
||||||
|
|
||||||
## 8. Performance Optimization [pending]
|
## 8. Performance Optimization [pending]
|
||||||
### Dependencies: 41.2, 41.3, 41.4, 41.5, 41.6
|
### Dependencies: 41.2, 41.3, 41.4, 41.5, 41.6
|
||||||
### Description: Profile and optimize the tool for large graphs to ensure responsive rendering and low memory usage.
|
### Description: Profile and optimize the tool for large graphs to ensure responsive rendering and low memory usage.
|
||||||
### Details:
|
### Details:
|
||||||
Implement lazy loading, efficient data structures, and parallel processing where appropriate.
|
Implement lazy loading, efficient data structures, and parallel processing where appropriate.
|
||||||
|
<info added on 2025-05-23T21:06:14.533Z>
|
||||||
|
# Mermaid Library Integration and Terminal-Specific Handling
|
||||||
|
|
||||||
|
## Package Dependencies
|
||||||
|
- Add mermaid package as an optional dependency in package.json for generating raw Mermaid diagram code
|
||||||
|
- Consider mermaid-cli for SVG/PNG conversion capabilities
|
||||||
|
- Evaluate terminal-image or similar libraries for terminals with image support
|
||||||
|
- Explore ascii-art-ansi or box-drawing character libraries for text-only terminals
|
||||||
|
|
||||||
|
## Terminal Capability Detection
|
||||||
|
- Leverage existing terminal detection from ui.js to assess rendering capabilities
|
||||||
|
- Implement detection for:
|
||||||
|
- iTerm2 and other terminals with image protocol support
|
||||||
|
- Terminals with Unicode/extended character support
|
||||||
|
- Basic terminals requiring pure ASCII output
|
||||||
|
|
||||||
|
## Rendering Strategy with Fallbacks
|
||||||
|
1. Primary: Generate raw Mermaid code for user copy/paste
|
||||||
|
2. Secondary: Render simplified ASCII tree/flow representation using box characters
|
||||||
|
3. Tertiary: Present dependencies in tabular format for minimal terminals
|
||||||
|
|
||||||
|
## Implementation Approach
|
||||||
|
- Use dynamic imports for optional rendering libraries to maintain lightweight core
|
||||||
|
- Implement graceful degradation when optional packages aren't available
|
||||||
|
- Follow Task Master's philosophy of minimal dependencies
|
||||||
|
- Ensure performance optimization through lazy loading where appropriate
|
||||||
|
- Design modular rendering components that can be swapped based on terminal capabilities
|
||||||
|
</info added on 2025-05-23T21:06:14.533Z>
|
||||||
|
|
||||||
## 9. Documentation [pending]
|
## 9. Documentation [pending]
|
||||||
### Dependencies: 41.1, 41.2, 41.3, 41.4, 41.5, 41.6, 41.7, 41.8
|
### Dependencies: 41.1, 41.2, 41.3, 41.4, 41.5, 41.6, 41.7, 41.8
|
||||||
@@ -131,4 +346,28 @@ Include examples, troubleshooting, and contribution guidelines.
|
|||||||
### Description: Develop automated tests for all major features, including CLI parsing, layout correctness, rendering, color coding, filtering, and cycle detection.
|
### Description: Develop automated tests for all major features, including CLI parsing, layout correctness, rendering, color coding, filtering, and cycle detection.
|
||||||
### Details:
|
### Details:
|
||||||
Include unit, integration, and regression tests; validate accessibility and performance claims.
|
Include unit, integration, and regression tests; validate accessibility and performance claims.
|
||||||
|
<info added on 2025-05-23T21:08:36.329Z>
|
||||||
|
# Documentation Tasks for Visual Task Dependency Graph
|
||||||
|
|
||||||
|
## User Documentation
|
||||||
|
1. Update README.md with diagram command documentation following existing command reference format
|
||||||
|
2. Add examples to CLI command help text in commands.js matching patterns from other commands
|
||||||
|
3. Create docs/diagrams.md with detailed usage guide including:
|
||||||
|
- Command examples for each diagram type
|
||||||
|
- Mermaid code samples and output
|
||||||
|
- Terminal compatibility notes
|
||||||
|
- Integration with task workflow examples
|
||||||
|
- Troubleshooting section for common diagram rendering issues
|
||||||
|
- Accessibility features and terminal fallback options
|
||||||
|
|
||||||
|
## Developer Documentation
|
||||||
|
1. Update MCP tool documentation to include the new task_diagram tool
|
||||||
|
2. Add JSDoc comments to all new functions following existing code standards
|
||||||
|
3. Create contributor documentation for extending diagram types
|
||||||
|
4. Update API documentation for any new MCP interface endpoints
|
||||||
|
|
||||||
|
## Integration Documentation
|
||||||
|
1. Document integration with existing commands (analyze-complexity, generate, etc.)
|
||||||
|
2. Provide examples showing how diagrams complement other Task Master features
|
||||||
|
</info added on 2025-05-23T21:08:36.329Z>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Task ID: 43
|
# Task ID: 43
|
||||||
# Title: Add Research Flag to Add-Task Command
|
# Title: Add Research Flag to Add-Task Command
|
||||||
# Status: pending
|
# Status: done
|
||||||
# Dependencies: None
|
# Dependencies: None
|
||||||
# Priority: medium
|
# Priority: medium
|
||||||
# Description: Implement a '--research' flag for the add-task command that enables users to automatically generate research-related subtasks when creating a new task.
|
# Description: Implement a '--research' flag for the add-task command that enables users to automatically generate research-related subtasks when creating a new task.
|
||||||
|
|||||||
@@ -48,3 +48,47 @@ Testing should verify both the functionality and security of the webhook system:
|
|||||||
5. Manual verification:
|
5. Manual verification:
|
||||||
- Set up integrations with common services (GitHub, Slack, etc.) to verify real-world functionality
|
- Set up integrations with common services (GitHub, Slack, etc.) to verify real-world functionality
|
||||||
- Verify that the CLI interface for managing webhooks works as expected
|
- Verify that the CLI interface for managing webhooks works as expected
|
||||||
|
|
||||||
|
# Subtasks:
|
||||||
|
## 1. Design webhook registration API endpoints [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Create API endpoints for registering, updating, and deleting webhook subscriptions
|
||||||
|
### Details:
|
||||||
|
Implement RESTful API endpoints that allow clients to register webhook URLs, specify event types they want to subscribe to, and manage their subscriptions. Include validation for URL format, required parameters, and authentication requirements.
|
||||||
|
|
||||||
|
## 2. Implement webhook authentication and security measures [pending]
|
||||||
|
### Dependencies: 44.1
|
||||||
|
### Description: Develop security mechanisms for webhook verification and payload signing
|
||||||
|
### Details:
|
||||||
|
Implement signature verification using HMAC, rate limiting to prevent abuse, IP whitelisting options, and webhook secret management. Create a secure token system for webhook verification and implement TLS for all webhook communications.
|
||||||
|
|
||||||
|
## 3. Create event trigger definition interface [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Design and implement the interface for defining event triggers and conditions
|
||||||
|
### Details:
|
||||||
|
Develop a user interface or API that allows defining what events should trigger webhooks. Include support for conditional triggers based on event properties, filtering options, and the ability to specify payload formats.
|
||||||
|
|
||||||
|
## 4. Build event processing and queuing system [pending]
|
||||||
|
### Dependencies: 44.1, 44.3
|
||||||
|
### Description: Implement a robust system for processing and queuing events before webhook delivery
|
||||||
|
### Details:
|
||||||
|
Create an event queue using a message broker (like RabbitMQ or Kafka) to handle high volumes of events. Implement event deduplication, prioritization, and persistence to ensure reliable delivery even during system failures.
|
||||||
|
|
||||||
|
## 5. Develop webhook delivery and retry mechanism [pending]
|
||||||
|
### Dependencies: 44.2, 44.4
|
||||||
|
### Description: Create a reliable system for webhook delivery with retry logic and failure handling
|
||||||
|
### Details:
|
||||||
|
Implement exponential backoff retry logic, configurable retry attempts, and dead letter queues for failed deliveries. Add monitoring for webhook delivery success rates and performance metrics. Include timeout handling for unresponsive webhook endpoints.
|
||||||
|
|
||||||
|
## 6. Implement comprehensive error handling and logging [pending]
|
||||||
|
### Dependencies: 44.5
|
||||||
|
### Description: Create robust error handling, logging, and monitoring for the webhook system
|
||||||
|
### Details:
|
||||||
|
Develop detailed error logging for webhook failures, including response codes, error messages, and timing information. Implement alerting for critical failures and create a dashboard for monitoring system health. Add debugging tools for webhook delivery issues.
|
||||||
|
|
||||||
|
## 7. Create webhook testing and simulation tools [pending]
|
||||||
|
### Dependencies: 44.3, 44.5, 44.6
|
||||||
|
### Description: Develop tools for testing webhook integrations and simulating event triggers
|
||||||
|
### Details:
|
||||||
|
Build a webhook testing console that allows manual triggering of events, viewing delivery history, and replaying failed webhooks. Create a webhook simulator for developers to test their endpoint implementations without generating real system events.
|
||||||
|
|
||||||
|
|||||||
@@ -53,3 +53,35 @@ Testing should cover the following scenarios:
|
|||||||
- Test the interaction with other flags and commands
|
- Test the interaction with other flags and commands
|
||||||
|
|
||||||
Create mock GitHub API responses for testing to avoid hitting rate limits during development and testing. Use environment variables to configure test credentials if needed.
|
Create mock GitHub API responses for testing to avoid hitting rate limits during development and testing. Use environment variables to configure test credentials if needed.
|
||||||
|
|
||||||
|
# Subtasks:
|
||||||
|
## 1. Design GitHub API integration architecture [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Create a technical design document outlining the architecture for GitHub API integration, including authentication flow, rate limiting considerations, and error handling strategies.
|
||||||
|
### Details:
|
||||||
|
Document should include: API endpoints to be used, authentication method (OAuth vs Personal Access Token), data flow diagrams, and security considerations. Research GitHub API rate limits and implement appropriate throttling mechanisms.
|
||||||
|
|
||||||
|
## 2. Implement GitHub URL parsing and validation [pending]
|
||||||
|
### Dependencies: 45.1
|
||||||
|
### Description: Create a module to parse and validate GitHub issue URLs, extracting repository owner, repository name, and issue number.
|
||||||
|
### Details:
|
||||||
|
Handle various GitHub URL formats (e.g., github.com/owner/repo/issues/123, github.com/owner/repo/pull/123). Implement validation to ensure the URL points to a valid issue or pull request. Return structured data with owner, repo, and issue number for valid URLs.
|
||||||
|
|
||||||
|
## 3. Develop GitHub API client for issue fetching [pending]
|
||||||
|
### Dependencies: 45.1, 45.2
|
||||||
|
### Description: Create a service to authenticate with GitHub and fetch issue details using the GitHub REST API.
|
||||||
|
### Details:
|
||||||
|
Implement authentication using GitHub Personal Access Tokens or OAuth. Handle API responses, including error cases (rate limiting, authentication failures, not found). Extract relevant issue data: title, description, labels, assignees, and comments.
|
||||||
|
|
||||||
|
## 4. Create task formatter for GitHub issues [pending]
|
||||||
|
### Dependencies: 45.3
|
||||||
|
### Description: Develop a formatter to convert GitHub issue data into the application's task format.
|
||||||
|
### Details:
|
||||||
|
Map GitHub issue fields to task fields (title, description, etc.). Convert GitHub markdown to the application's supported format. Handle special GitHub features like issue references and user mentions. Generate appropriate tags based on GitHub labels.
|
||||||
|
|
||||||
|
## 5. Implement end-to-end import flow with UI [pending]
|
||||||
|
### Dependencies: 45.4
|
||||||
|
### Description: Create the user interface and workflow for importing GitHub issues, including progress indicators and error handling.
|
||||||
|
### Details:
|
||||||
|
Design and implement UI for URL input and import confirmation. Show loading states during API calls. Display meaningful error messages for various failure scenarios. Allow users to review and modify imported task details before saving. Add automated tests for the entire import flow.
|
||||||
|
|
||||||
|
|||||||
@@ -53,3 +53,35 @@ The command should follow the same design patterns as `analyze-complexity` for c
|
|||||||
- The ranking should prioritize high-impact, high-confidence, easy-to-implement tasks
|
- The ranking should prioritize high-impact, high-confidence, easy-to-implement tasks
|
||||||
- Performance should be acceptable even with a large number of tasks
|
- Performance should be acceptable even with a large number of tasks
|
||||||
- The command should handle edge cases gracefully (empty projects, missing data)
|
- The command should handle edge cases gracefully (empty projects, missing data)
|
||||||
|
|
||||||
|
# Subtasks:
|
||||||
|
## 1. Design ICE scoring algorithm [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Create the algorithm for calculating Impact, Confidence, and Ease scores for tasks
|
||||||
|
### Details:
|
||||||
|
Define the mathematical formula for ICE scoring (Impact × Confidence × Ease). Determine the scale for each component (e.g., 1-10). Create rules for how AI will evaluate each component based on task attributes like complexity, dependencies, and descriptions. Document the scoring methodology for future reference.
|
||||||
|
|
||||||
|
## 2. Implement AI integration for ICE scoring [pending]
|
||||||
|
### Dependencies: 46.1
|
||||||
|
### Description: Develop the AI component that will analyze tasks and generate ICE scores
|
||||||
|
### Details:
|
||||||
|
Create prompts for the AI to evaluate Impact, Confidence, and Ease. Implement error handling for AI responses. Add caching to prevent redundant AI calls. Ensure the AI provides justification for each score component. Test with various task types to ensure consistent scoring.
|
||||||
|
|
||||||
|
## 3. Create report file generator [pending]
|
||||||
|
### Dependencies: 46.2
|
||||||
|
### Description: Build functionality to generate a structured report file with ICE analysis results
|
||||||
|
### Details:
|
||||||
|
Design the report file format (JSON, CSV, or Markdown). Implement sorting of tasks by ICE score. Include task details, individual I/C/E scores, and final ICE score in the report. Add timestamp and project metadata. Create a function to save the report to the specified location.
|
||||||
|
|
||||||
|
## 4. Implement CLI rendering for ICE analysis [pending]
|
||||||
|
### Dependencies: 46.3
|
||||||
|
### Description: Develop the command-line interface for displaying ICE analysis results
|
||||||
|
### Details:
|
||||||
|
Design a tabular format for displaying ICE scores in the terminal. Use color coding to highlight high/medium/low priority tasks. Implement filtering options (by score range, task type, etc.). Add sorting capabilities. Create a summary view that shows top N tasks by ICE score.
|
||||||
|
|
||||||
|
## 5. Integrate with existing complexity reports [pending]
|
||||||
|
### Dependencies: 46.3, 46.4
|
||||||
|
### Description: Connect the ICE analysis functionality with the existing complexity reporting system
|
||||||
|
### Details:
|
||||||
|
Modify the existing complexity report to include ICE scores. Ensure consistent formatting between complexity and ICE reports. Add cross-referencing between reports. Update the command-line help documentation. Test the integrated system with various project sizes and configurations.
|
||||||
|
|
||||||
|
|||||||
@@ -64,3 +64,41 @@ Testing should verify the complete workflow functions correctly:
|
|||||||
5. Regression Testing:
|
5. Regression Testing:
|
||||||
- Verify that existing functionality continues to work
|
- Verify that existing functionality continues to work
|
||||||
- Ensure compatibility with keyboard shortcuts and accessibility features
|
- Ensure compatibility with keyboard shortcuts and accessibility features
|
||||||
|
|
||||||
|
# Subtasks:
|
||||||
|
## 1. Design Task Expansion UI Components [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Create UI components for the expanded task suggestion actions card that allow for task breakdown and additional context input.
|
||||||
|
### Details:
|
||||||
|
Design mockups for expanded card view, including subtask creation interface, context input fields, and task management controls. Ensure the design is consistent with existing UI patterns and responsive across different screen sizes. Include animations for card expansion/collapse.
|
||||||
|
|
||||||
|
## 2. Implement State Management for Task Expansion [pending]
|
||||||
|
### Dependencies: 47.1
|
||||||
|
### Description: Develop the state management logic to handle expanded task states, subtask creation, and context additions.
|
||||||
|
### Details:
|
||||||
|
Create state handlers for expanded/collapsed states, subtask array management, and context data. Implement proper validation for user inputs and error handling. Ensure state persistence across user sessions and synchronization with backend services.
|
||||||
|
|
||||||
|
## 3. Build Context Addition Functionality [pending]
|
||||||
|
### Dependencies: 47.2
|
||||||
|
### Description: Create the functionality that allows users to add additional context to tasks and subtasks.
|
||||||
|
### Details:
|
||||||
|
Implement context input fields with support for rich text, attachments, links, and references to other tasks. Add auto-save functionality for context changes and version history if applicable. Include context suggestion features based on task content.
|
||||||
|
|
||||||
|
## 4. Develop Task Management Controls [pending]
|
||||||
|
### Dependencies: 47.2
|
||||||
|
### Description: Implement controls for managing tasks within the expanded card view, including prioritization, scheduling, and assignment.
|
||||||
|
### Details:
|
||||||
|
Create UI controls for task prioritization (drag-and-drop ranking), deadline setting with calendar integration, assignee selection with user search, and status updates. Implement notification triggers for task changes and deadline reminders.
|
||||||
|
|
||||||
|
## 5. Integrate with Existing Task Systems [pending]
|
||||||
|
### Dependencies: 47.3, 47.4
|
||||||
|
### Description: Ensure the enhanced actions card workflow integrates seamlessly with existing task management functionality.
|
||||||
|
### Details:
|
||||||
|
Connect the new UI components to existing backend APIs. Update data models if necessary to support new features. Ensure compatibility with existing task filters, search, and reporting features. Implement data migration plan for existing tasks if needed.
|
||||||
|
|
||||||
|
## 6. Test and Optimize User Experience [pending]
|
||||||
|
### Dependencies: 47.5
|
||||||
|
### Description: Conduct thorough testing of the enhanced workflow and optimize based on user feedback and performance metrics.
|
||||||
|
### Details:
|
||||||
|
Perform usability testing with representative users. Collect metrics on task completion time, error rates, and user satisfaction. Optimize performance for large task lists and complex subtask hierarchies. Implement A/B testing for alternative UI approaches if needed.
|
||||||
|
|
||||||
|
|||||||
@@ -42,3 +42,23 @@ Testing should verify that the refactoring maintains identical functionality whi
|
|||||||
4. Documentation:
|
4. Documentation:
|
||||||
- Verify documentation is updated to reflect the new prompt organization
|
- Verify documentation is updated to reflect the new prompt organization
|
||||||
- Confirm the index.js export pattern works as expected for importing prompts
|
- Confirm the index.js export pattern works as expected for importing prompts
|
||||||
|
|
||||||
|
# Subtasks:
|
||||||
|
## 1. Create prompts directory structure [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Create a centralized 'prompts' directory with appropriate subdirectories for different prompt categories
|
||||||
|
### Details:
|
||||||
|
Create a 'prompts' directory at the project root. Within this directory, create subdirectories based on functional categories (e.g., 'core', 'agents', 'utils'). Add an index.js file in each subdirectory to facilitate imports. Create a root index.js file that re-exports all prompts for easy access.
|
||||||
|
|
||||||
|
## 2. Extract prompts into individual files [pending]
|
||||||
|
### Dependencies: 48.1
|
||||||
|
### Description: Identify all hardcoded prompts in the codebase and extract them into individual files in the prompts directory
|
||||||
|
### Details:
|
||||||
|
Search through the codebase for all hardcoded prompt strings. For each prompt, create a new file in the appropriate subdirectory with a descriptive name (e.g., 'taskBreakdownPrompt.js'). Format each file to export the prompt string as a constant. Add JSDoc comments to document the purpose and expected usage of each prompt.
|
||||||
|
|
||||||
|
## 3. Update functions to import prompts [pending]
|
||||||
|
### Dependencies: 48.1, 48.2
|
||||||
|
### Description: Modify all functions that use hardcoded prompts to import them from the centralized structure
|
||||||
|
### Details:
|
||||||
|
For each function that previously used a hardcoded prompt, add an import statement to pull in the prompt from the centralized structure. Test each function after modification to ensure it still works correctly. Update any tests that might be affected by the refactoring. Create a pull request with the changes and document the new prompt structure in the project documentation.
|
||||||
|
|
||||||
|
|||||||
@@ -64,3 +64,41 @@ Testing should verify all aspects of the code analysis command:
|
|||||||
- Generated recommendations are specific and actionable
|
- Generated recommendations are specific and actionable
|
||||||
- Created tasks follow the project's task format standards
|
- Created tasks follow the project's task format standards
|
||||||
- Analysis results are consistent across multiple runs on the same codebase
|
- Analysis results are consistent across multiple runs on the same codebase
|
||||||
|
|
||||||
|
# Subtasks:
|
||||||
|
## 1. Design pattern recognition algorithm [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Create an algorithm to identify common code patterns and anti-patterns in the codebase
|
||||||
|
### Details:
|
||||||
|
Develop a system that can scan code files and identify common design patterns (Factory, Singleton, etc.) and anti-patterns (God objects, excessive coupling, etc.). Include detection for language-specific patterns and create a classification system for identified patterns.
|
||||||
|
|
||||||
|
## 2. Implement best practice verification [pending]
|
||||||
|
### Dependencies: 49.1
|
||||||
|
### Description: Build verification checks against established coding standards and best practices
|
||||||
|
### Details:
|
||||||
|
Create a framework to compare code against established best practices for the specific language/framework. Include checks for naming conventions, function length, complexity metrics, comment coverage, and other industry-standard quality indicators.
|
||||||
|
|
||||||
|
## 3. Develop AI integration for code analysis [pending]
|
||||||
|
### Dependencies: 49.1, 49.2
|
||||||
|
### Description: Integrate AI capabilities to enhance code analysis and provide intelligent recommendations
|
||||||
|
### Details:
|
||||||
|
Connect to AI services (like OpenAI) to analyze code beyond rule-based checks. Configure the AI to understand context, project-specific patterns, and provide nuanced analysis that rule-based systems might miss.
|
||||||
|
|
||||||
|
## 4. Create recommendation generation system [pending]
|
||||||
|
### Dependencies: 49.2, 49.3
|
||||||
|
### Description: Build a system to generate actionable improvement recommendations based on analysis results
|
||||||
|
### Details:
|
||||||
|
Develop algorithms to transform analysis results into specific, actionable recommendations. Include priority levels, effort estimates, and potential impact assessments for each recommendation.
|
||||||
|
|
||||||
|
## 5. Implement task creation functionality [pending]
|
||||||
|
### Dependencies: 49.4
|
||||||
|
### Description: Add capability to automatically create tasks from code quality recommendations
|
||||||
|
### Details:
|
||||||
|
Build functionality to convert recommendations into tasks in the project management system. Include appropriate metadata, assignee suggestions based on code ownership, and integration with existing workflow systems.
|
||||||
|
|
||||||
|
## 6. Create comprehensive reporting interface [pending]
|
||||||
|
### Dependencies: 49.4, 49.5
|
||||||
|
### Description: Develop a user interface to display analysis results and recommendations
|
||||||
|
### Details:
|
||||||
|
Build a dashboard showing code quality metrics, identified patterns, recommendations, and created tasks. Include filtering options, trend analysis over time, and the ability to drill down into specific issues with code snippets and explanations.
|
||||||
|
|
||||||
|
|||||||
@@ -3,56 +3,89 @@
|
|||||||
# Status: pending
|
# Status: pending
|
||||||
# Dependencies: None
|
# Dependencies: None
|
||||||
# Priority: medium
|
# Priority: medium
|
||||||
# Description: Create a command that allows users to quickly research topics using Perplexity AI, with options to include task context or custom prompts.
|
# Description: Create an interactive REPL-style chat interface for AI-powered research that maintains conversation context, integrates project information, and provides session management capabilities.
|
||||||
# Details:
|
# Details:
|
||||||
Develop a new command called 'research' that integrates with Perplexity AI's API to fetch information on specified topics. The command should:
|
Develop an interactive REPL-style chat interface for AI-powered research that allows users to have ongoing research conversations with context awareness. The system should:
|
||||||
|
|
||||||
1. Accept the following parameters:
|
1. Create an interactive REPL using inquirer that:
|
||||||
- A search query string (required)
|
- Maintains conversation history and context
|
||||||
- A task or subtask ID for context (optional)
|
- Provides a natural chat-like experience
|
||||||
- A custom prompt to guide the research (optional)
|
- Supports special commands with the '/' prefix
|
||||||
|
|
||||||
2. When a task/subtask ID is provided, extract relevant information from it to enrich the research query with context.
|
2. Integrate with the existing ai-services-unified.js using research mode:
|
||||||
|
- Leverage our unified AI service architecture
|
||||||
|
- Configure appropriate system prompts for research context
|
||||||
|
- Handle streaming responses for real-time feedback
|
||||||
|
|
||||||
3. Implement proper API integration with Perplexity, including authentication and rate limiting handling.
|
3. Support multiple context sources:
|
||||||
|
- Task/subtask IDs for project context
|
||||||
|
- File paths for code or document context
|
||||||
|
- Custom prompts for specific research directions
|
||||||
|
- Project file tree for system context
|
||||||
|
|
||||||
4. Format and display the research results in a readable format in the terminal, with options to:
|
4. Implement chat commands including:
|
||||||
- Save the results to a file
|
- `/save` - Save conversation to file
|
||||||
- Copy results to clipboard
|
- `/task` - Associate with or load context from a task
|
||||||
- Generate a summary of key points
|
- `/help` - Show available commands and usage
|
||||||
|
- `/exit` - End the research session
|
||||||
|
- `/copy` - Copy last response to clipboard
|
||||||
|
- `/summary` - Generate summary of conversation
|
||||||
|
- `/detail` - Adjust research depth level
|
||||||
|
|
||||||
5. Cache research results to avoid redundant API calls for the same queries.
|
5. Create session management capabilities:
|
||||||
|
- Generate and track unique session IDs
|
||||||
|
- Save/load sessions automatically
|
||||||
|
- Browse and switch between previous sessions
|
||||||
|
- Export sessions to portable formats
|
||||||
|
|
||||||
6. Provide a configuration option to set the depth/detail level of research (quick overview vs. comprehensive).
|
6. Design a consistent UI using ui.js patterns:
|
||||||
|
- Color-coded messages for user/AI distinction
|
||||||
|
- Support for markdown rendering in terminal
|
||||||
|
- Progressive display of AI responses
|
||||||
|
- Clear visual hierarchy and readability
|
||||||
|
|
||||||
7. Handle errors gracefully, especially network issues or API limitations.
|
7. Follow the "taskmaster way":
|
||||||
|
- Create something new and exciting
|
||||||
|
- Focus on usefulness and practicality
|
||||||
|
- Avoid over-engineering
|
||||||
|
- Maintain consistency with existing patterns
|
||||||
|
|
||||||
The command should follow the existing CLI structure and maintain consistency with other commands in the system.
|
The REPL should feel like a natural conversation while providing powerful research capabilities that integrate seamlessly with the rest of the system.
|
||||||
|
|
||||||
# Test Strategy:
|
# Test Strategy:
|
||||||
1. Unit tests:
|
1. Unit tests:
|
||||||
- Test the command with various combinations of parameters (query only, query+task, query+custom prompt, all parameters)
|
- Test the REPL command parsing and execution
|
||||||
- Mock the Perplexity API responses to test different scenarios (successful response, error response, rate limiting)
|
- Mock AI service responses to test different scenarios
|
||||||
- Verify that task context is correctly extracted and incorporated into the research query
|
- Verify context extraction and integration from various sources
|
||||||
|
- Test session serialization and deserialization
|
||||||
|
|
||||||
2. Integration tests:
|
2. Integration tests:
|
||||||
- Test actual API calls to Perplexity with valid credentials (using a test account)
|
- Test actual AI service integration with the REPL
|
||||||
- Verify the caching mechanism works correctly for repeated queries
|
- Verify session persistence across application restarts
|
||||||
- Test error handling with intentionally invalid requests
|
- Test conversation state management with long interactions
|
||||||
|
- Verify context switching between different tasks and files
|
||||||
|
|
||||||
3. User acceptance testing:
|
3. User acceptance testing:
|
||||||
- Have team members use the command for real research needs and provide feedback
|
- Have team members use the REPL for real research needs
|
||||||
- Verify the command works in different network environments
|
- Test the conversation flow and command usability
|
||||||
- Test the command with very long queries and responses
|
- Verify the UI is intuitive and responsive
|
||||||
|
- Test with various terminal sizes and environments
|
||||||
|
|
||||||
4. Performance testing:
|
4. Performance testing:
|
||||||
- Measure and optimize response time for queries
|
- Measure and optimize response time for queries
|
||||||
- Test behavior under poor network conditions
|
- Test behavior with large conversation histories
|
||||||
|
- Verify performance with complex context sources
|
||||||
|
- Test under poor network conditions
|
||||||
|
|
||||||
Validate that the research results are properly formatted, readable, and that all output options (save, copy) function correctly.
|
5. Specific test scenarios:
|
||||||
|
- Verify markdown rendering for complex formatting
|
||||||
|
- Test streaming display with various response lengths
|
||||||
|
- Verify export features create properly formatted files
|
||||||
|
- Test session recovery from simulated crashes
|
||||||
|
- Validate handling of special characters and unicode
|
||||||
|
|
||||||
# Subtasks:
|
# Subtasks:
|
||||||
## 1. Create Perplexity API Client Service [pending]
|
## 1. Create Perplexity API Client Service [cancelled]
|
||||||
### Dependencies: None
|
### Dependencies: None
|
||||||
### Description: Develop a service module that handles all interactions with the Perplexity AI API, including authentication, request formatting, and response handling.
|
### Description: Develop a service module that handles all interactions with the Perplexity AI API, including authentication, request formatting, and response handling.
|
||||||
### Details:
|
### Details:
|
||||||
@@ -72,6 +105,9 @@ Testing approach:
|
|||||||
- Test error handling with simulated network failures
|
- Test error handling with simulated network failures
|
||||||
- Verify caching mechanism works correctly
|
- Verify caching mechanism works correctly
|
||||||
- Test with various query types and options
|
- Test with various query types and options
|
||||||
|
<info added on 2025-05-23T21:06:45.726Z>
|
||||||
|
DEPRECATION NOTICE: This subtask is no longer needed and has been marked for removal. Instead of creating a new Perplexity service, we will leverage the existing ai-services-unified.js with research mode. This approach allows us to maintain a unified architecture for AI services rather than implementing a separate service specifically for Perplexity.
|
||||||
|
</info added on 2025-05-23T21:06:45.726Z>
|
||||||
|
|
||||||
## 2. Implement Task Context Extraction Logic [pending]
|
## 2. Implement Task Context Extraction Logic [pending]
|
||||||
### Dependencies: None
|
### Dependencies: None
|
||||||
@@ -94,6 +130,37 @@ Testing approach:
|
|||||||
- Test with various task structures and content types
|
- Test with various task structures and content types
|
||||||
- Verify error handling for missing or invalid tasks
|
- Verify error handling for missing or invalid tasks
|
||||||
- Test the quality of extracted context with sample queries
|
- Test the quality of extracted context with sample queries
|
||||||
|
<info added on 2025-05-23T21:11:44.560Z>
|
||||||
|
Updated Implementation Approach:
|
||||||
|
|
||||||
|
REFACTORED IMPLEMENTATION:
|
||||||
|
1. Extract the fuzzy search logic from add-task.js (lines ~240-400) into `utils/contextExtractor.js`
|
||||||
|
2. Implement a reusable `TaskContextExtractor` class with the following methods:
|
||||||
|
- `extractTaskContext(taskId)` - Base context extraction
|
||||||
|
- `performFuzzySearch(query, options)` - Enhanced Fuse.js implementation
|
||||||
|
- `getRelevanceScore(task, query)` - Scoring mechanism from add-task.js
|
||||||
|
- `detectPurposeCategories(task)` - Category classification logic
|
||||||
|
- `findRelatedTasks(taskId)` - Identify dependencies and relationships
|
||||||
|
- `aggregateMultiQueryContext(queries)` - Support for multiple search terms
|
||||||
|
|
||||||
|
3. Add configurable context depth levels:
|
||||||
|
- Minimal: Just task title and description
|
||||||
|
- Standard: Include details and immediate relationships
|
||||||
|
- Comprehensive: Full context with all dependencies and related tasks
|
||||||
|
|
||||||
|
4. Implement context formatters:
|
||||||
|
- `formatForSystemPrompt(context)` - Structured for AI system instructions
|
||||||
|
- `formatForChatContext(context)` - Conversational format for chat
|
||||||
|
- `formatForResearchQuery(context, query)` - Optimized for research commands
|
||||||
|
|
||||||
|
5. Add caching layer for performance optimization:
|
||||||
|
- Implement LRU cache for expensive fuzzy search results
|
||||||
|
- Cache invalidation on task updates
|
||||||
|
|
||||||
|
6. Ensure backward compatibility with existing context extraction requirements
|
||||||
|
|
||||||
|
This approach leverages our existing sophisticated search logic rather than rebuilding from scratch, while making it more flexible and reusable across the application.
|
||||||
|
</info added on 2025-05-23T21:11:44.560Z>
|
||||||
|
|
||||||
## 3. Build Research Command CLI Interface [pending]
|
## 3. Build Research Command CLI Interface [pending]
|
||||||
### Dependencies: 51.1, 51.2
|
### Dependencies: 51.1, 51.2
|
||||||
@@ -120,6 +187,40 @@ Testing approach:
|
|||||||
- Verify command validation logic works correctly
|
- Verify command validation logic works correctly
|
||||||
- Test with various combinations of options
|
- Test with various combinations of options
|
||||||
- Ensure proper error messages for invalid inputs
|
- Ensure proper error messages for invalid inputs
|
||||||
|
<info added on 2025-05-23T21:09:08.478Z>
|
||||||
|
Implementation details:
|
||||||
|
1. Create a new module `repl/research-chat.js` for the interactive research experience
|
||||||
|
2. Implement REPL-style chat interface using inquirer with:
|
||||||
|
- Persistent conversation history management
|
||||||
|
- Context-aware prompting system
|
||||||
|
- Command parsing for special instructions
|
||||||
|
3. Implement REPL commands:
|
||||||
|
- `/save` - Save conversation to file
|
||||||
|
- `/task` - Associate with or load context from a task
|
||||||
|
- `/help` - Show available commands and usage
|
||||||
|
- `/exit` - End the research session
|
||||||
|
- `/copy` - Copy last response to clipboard
|
||||||
|
- `/summary` - Generate summary of conversation
|
||||||
|
- `/detail` - Adjust research depth level
|
||||||
|
4. Create context initialization system:
|
||||||
|
- Task/subtask context loading
|
||||||
|
- File content integration
|
||||||
|
- System prompt configuration
|
||||||
|
5. Integrate with ai-services-unified.js research mode
|
||||||
|
6. Implement conversation state management:
|
||||||
|
- Track message history
|
||||||
|
- Maintain context window
|
||||||
|
- Handle context pruning for long conversations
|
||||||
|
7. Design consistent UI patterns using ui.js library
|
||||||
|
8. Add entry point in main CLI application
|
||||||
|
|
||||||
|
Testing approach:
|
||||||
|
- Test REPL command parsing and execution
|
||||||
|
- Verify context initialization with various inputs
|
||||||
|
- Test conversation state management
|
||||||
|
- Ensure proper error handling and recovery
|
||||||
|
- Validate UI consistency across different terminal environments
|
||||||
|
</info added on 2025-05-23T21:09:08.478Z>
|
||||||
|
|
||||||
## 4. Implement Results Processing and Output Formatting [pending]
|
## 4. Implement Results Processing and Output Formatting [pending]
|
||||||
### Dependencies: 51.1, 51.3
|
### Dependencies: 51.1, 51.3
|
||||||
@@ -145,8 +246,45 @@ Testing approach:
|
|||||||
- Verify file saving functionality creates proper files with correct content
|
- Verify file saving functionality creates proper files with correct content
|
||||||
- Test clipboard functionality
|
- Test clipboard functionality
|
||||||
- Verify summarization produces useful results
|
- Verify summarization produces useful results
|
||||||
|
<info added on 2025-05-23T21:10:00.181Z>
|
||||||
|
Implementation details:
|
||||||
|
1. Create a new module `utils/chatFormatter.js` for REPL interface formatting
|
||||||
|
2. Implement terminal output formatting for conversational display:
|
||||||
|
- Color-coded messages distinguishing user inputs and AI responses
|
||||||
|
- Proper text wrapping and indentation for readability
|
||||||
|
- Support for markdown rendering in terminal
|
||||||
|
- Visual indicators for system messages and status updates
|
||||||
|
3. Implement streaming/progressive display of AI responses:
|
||||||
|
- Character-by-character or chunk-by-chunk display
|
||||||
|
- Cursor animations during response generation
|
||||||
|
- Ability to interrupt long responses
|
||||||
|
4. Design chat history visualization:
|
||||||
|
- Scrollable history with clear message boundaries
|
||||||
|
- Timestamp display options
|
||||||
|
- Session identification
|
||||||
|
5. Create specialized formatters for different content types:
|
||||||
|
- Code blocks with syntax highlighting
|
||||||
|
- Bulleted and numbered lists
|
||||||
|
- Tables and structured data
|
||||||
|
- Citations and references
|
||||||
|
6. Implement export functionality:
|
||||||
|
- Save conversations to markdown or text files
|
||||||
|
- Export individual responses
|
||||||
|
- Copy responses to clipboard
|
||||||
|
7. Adapt existing ui.js patterns for conversational context:
|
||||||
|
- Maintain consistent styling while supporting chat flow
|
||||||
|
- Handle multi-turn context appropriately
|
||||||
|
|
||||||
## 5. Implement Caching and Results Management System [pending]
|
Testing approach:
|
||||||
|
- Test streaming display with various response lengths and speeds
|
||||||
|
- Verify markdown rendering accuracy for complex formatting
|
||||||
|
- Test history navigation and scrolling functionality
|
||||||
|
- Verify export features create properly formatted files
|
||||||
|
- Test display on various terminal sizes and configurations
|
||||||
|
- Verify handling of special characters and unicode
|
||||||
|
</info added on 2025-05-23T21:10:00.181Z>
|
||||||
|
|
||||||
|
## 5. Implement Caching and Results Management System [cancelled]
|
||||||
### Dependencies: 51.1, 51.4
|
### Dependencies: 51.1, 51.4
|
||||||
### Description: Create a persistent caching system for research results and implement functionality to manage, retrieve, and reference previous research.
|
### Description: Create a persistent caching system for research results and implement functionality to manage, retrieve, and reference previous research.
|
||||||
### Details:
|
### Details:
|
||||||
@@ -173,4 +311,142 @@ Testing approach:
|
|||||||
- Test history management commands
|
- Test history management commands
|
||||||
- Verify task association functionality
|
- Verify task association functionality
|
||||||
- Test with large cache sizes to ensure performance
|
- Test with large cache sizes to ensure performance
|
||||||
|
<info added on 2025-05-23T21:10:28.544Z>
|
||||||
|
Implementation details:
|
||||||
|
1. Create a session management system for the REPL experience:
|
||||||
|
- Generate and track unique session IDs
|
||||||
|
- Store conversation history with timestamps
|
||||||
|
- Maintain context and state between interactions
|
||||||
|
2. Implement session persistence:
|
||||||
|
- Save sessions to disk automatically
|
||||||
|
- Load previous sessions on startup
|
||||||
|
- Handle graceful recovery from crashes
|
||||||
|
3. Build session browser and selector:
|
||||||
|
- List available sessions with preview
|
||||||
|
- Filter sessions by date, topic, or content
|
||||||
|
- Enable quick switching between sessions
|
||||||
|
4. Implement conversation state serialization:
|
||||||
|
- Capture full conversation context
|
||||||
|
- Preserve user preferences per session
|
||||||
|
- Handle state migration during updates
|
||||||
|
5. Add session sharing capabilities:
|
||||||
|
- Export sessions to portable formats
|
||||||
|
- Import sessions from files
|
||||||
|
- Generate shareable links (if applicable)
|
||||||
|
6. Create session management commands:
|
||||||
|
- Create new sessions
|
||||||
|
- Clone existing sessions
|
||||||
|
- Archive or delete old sessions
|
||||||
|
|
||||||
|
Testing approach:
|
||||||
|
- Verify session persistence across application restarts
|
||||||
|
- Test session recovery from simulated crashes
|
||||||
|
- Validate state serialization with complex conversations
|
||||||
|
- Ensure session switching maintains proper context
|
||||||
|
- Test session import/export functionality
|
||||||
|
- Verify performance with large conversation histories
|
||||||
|
</info added on 2025-05-23T21:10:28.544Z>
|
||||||
|
|
||||||
|
## 6. Implement Project Context Generation [pending]
|
||||||
|
### Dependencies: 51.2
|
||||||
|
### Description: Create functionality to generate and include project-level context such as file trees, repository structure, and codebase insights for more informed research.
|
||||||
|
### Details:
|
||||||
|
Implementation details:
|
||||||
|
1. Create a new module `utils/projectContextGenerator.js` for project-level context extraction
|
||||||
|
2. Implement file tree generation functionality:
|
||||||
|
- Scan project directory structure recursively
|
||||||
|
- Filter out irrelevant files (node_modules, .git, etc.)
|
||||||
|
- Format file tree for AI consumption
|
||||||
|
- Include file counts and structure statistics
|
||||||
|
3. Add code analysis capabilities:
|
||||||
|
- Extract key imports and dependencies
|
||||||
|
- Identify main modules and their relationships
|
||||||
|
- Generate high-level architecture overview
|
||||||
|
4. Implement context summarization:
|
||||||
|
- Create concise project overview
|
||||||
|
- Identify key technologies and patterns
|
||||||
|
- Summarize project purpose and structure
|
||||||
|
5. Add caching for expensive operations:
|
||||||
|
- Cache file tree with invalidation on changes
|
||||||
|
- Store analysis results with TTL
|
||||||
|
6. Create integration with research REPL:
|
||||||
|
- Add project context to system prompts
|
||||||
|
- Support `/project` command to refresh context
|
||||||
|
- Allow selective inclusion of project components
|
||||||
|
|
||||||
|
Testing approach:
|
||||||
|
- Test file tree generation with various project structures
|
||||||
|
- Verify filtering logic works correctly
|
||||||
|
- Test context summarization quality
|
||||||
|
- Measure performance impact of context generation
|
||||||
|
- Verify caching mechanism effectiveness
|
||||||
|
|
||||||
|
## 7. Create REPL Command System [pending]
|
||||||
|
### Dependencies: 51.3
|
||||||
|
### Description: Implement a flexible command system for the research REPL that allows users to control the conversation flow, manage sessions, and access additional functionality.
|
||||||
|
### Details:
|
||||||
|
Implementation details:
|
||||||
|
1. Create a new module `repl/commands.js` for REPL command handling
|
||||||
|
2. Implement a command parser that:
|
||||||
|
- Detects commands starting with `/`
|
||||||
|
- Parses arguments and options
|
||||||
|
- Handles quoted strings and special characters
|
||||||
|
3. Create a command registry system:
|
||||||
|
- Register command handlers with descriptions
|
||||||
|
- Support command aliases
|
||||||
|
- Enable command discovery and help
|
||||||
|
4. Implement core commands:
|
||||||
|
- `/save [filename]` - Save conversation
|
||||||
|
- `/task <taskId>` - Load task context
|
||||||
|
- `/file <path>` - Include file content
|
||||||
|
- `/help [command]` - Show help
|
||||||
|
- `/exit` - End session
|
||||||
|
- `/copy [n]` - Copy nth response
|
||||||
|
- `/summary` - Generate conversation summary
|
||||||
|
- `/detail <level>` - Set detail level
|
||||||
|
- `/clear` - Clear conversation
|
||||||
|
- `/project` - Refresh project context
|
||||||
|
- `/session <id|new>` - Switch/create session
|
||||||
|
5. Add command completion and suggestions
|
||||||
|
6. Implement error handling for invalid commands
|
||||||
|
7. Create a help system with examples
|
||||||
|
|
||||||
|
Testing approach:
|
||||||
|
- Test command parsing with various inputs
|
||||||
|
- Verify command execution and error handling
|
||||||
|
- Test command completion functionality
|
||||||
|
- Verify help system provides useful information
|
||||||
|
- Test with complex command sequences
|
||||||
|
|
||||||
|
## 8. Integrate with AI Services Unified [pending]
|
||||||
|
### Dependencies: 51.3, 51.4
|
||||||
|
### Description: Integrate the research REPL with the existing ai-services-unified.js to leverage the unified AI service architecture with research mode.
|
||||||
|
### Details:
|
||||||
|
Implementation details:
|
||||||
|
1. Update `repl/research-chat.js` to integrate with ai-services-unified.js
|
||||||
|
2. Configure research mode in AI service:
|
||||||
|
- Set appropriate system prompts
|
||||||
|
- Configure temperature and other parameters
|
||||||
|
- Enable streaming responses
|
||||||
|
3. Implement context management:
|
||||||
|
- Format conversation history for AI context
|
||||||
|
- Include task and project context
|
||||||
|
- Handle context window limitations
|
||||||
|
4. Add support for different research styles:
|
||||||
|
- Exploratory research with broader context
|
||||||
|
- Focused research with specific questions
|
||||||
|
- Comparative analysis between concepts
|
||||||
|
5. Implement response handling:
|
||||||
|
- Process streaming chunks
|
||||||
|
- Format and display responses
|
||||||
|
- Handle errors and retries
|
||||||
|
6. Add configuration options for AI service selection
|
||||||
|
7. Implement fallback mechanisms for service unavailability
|
||||||
|
|
||||||
|
Testing approach:
|
||||||
|
- Test integration with mocked AI services
|
||||||
|
- Verify context formatting and management
|
||||||
|
- Test streaming response handling
|
||||||
|
- Verify error handling and recovery
|
||||||
|
- Test with various research styles and queries
|
||||||
|
|
||||||
|
|||||||
@@ -49,3 +49,35 @@ Testing should verify both the functionality and user experience of the suggest-
|
|||||||
- Test with extremely large numbers of existing tasks
|
- Test with extremely large numbers of existing tasks
|
||||||
|
|
||||||
Manually verify the command produces contextually appropriate suggestions that align with the project's current state and needs.
|
Manually verify the command produces contextually appropriate suggestions that align with the project's current state and needs.
|
||||||
|
|
||||||
|
# Subtasks:
|
||||||
|
## 1. Design data collection mechanism for existing tasks [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Create a module to collect and format existing task data from the system for AI processing
|
||||||
|
### Details:
|
||||||
|
Implement a function that retrieves all existing tasks from storage, formats them appropriately for AI context, and handles edge cases like empty task lists or corrupted data. Include metadata like task status, dependencies, and creation dates to provide rich context for suggestions.
|
||||||
|
|
||||||
|
## 2. Implement AI integration for task suggestions [pending]
|
||||||
|
### Dependencies: 52.1
|
||||||
|
### Description: Develop the core functionality to generate task suggestions using AI based on existing tasks
|
||||||
|
### Details:
|
||||||
|
Create an AI prompt template that effectively communicates the existing task context and request for suggestions. Implement error handling for API failures, rate limiting, and malformed responses. Include parameters for controlling suggestion quantity and specificity.
|
||||||
|
|
||||||
|
## 3. Build interactive CLI interface for suggestions [pending]
|
||||||
|
### Dependencies: 52.2
|
||||||
|
### Description: Create the command-line interface for requesting and displaying task suggestions
|
||||||
|
### Details:
|
||||||
|
Design a user-friendly CLI command structure with appropriate flags for customization. Implement progress indicators during AI processing and format the output of suggestions in a clear, readable format. Include help text and examples in the command documentation.
|
||||||
|
|
||||||
|
## 4. Implement suggestion selection and task creation [pending]
|
||||||
|
### Dependencies: 52.3
|
||||||
|
### Description: Allow users to interactively select suggestions to convert into actual tasks
|
||||||
|
### Details:
|
||||||
|
Create an interactive selection interface where users can review suggestions, select which ones to create as tasks, and optionally modify them before creation. Implement batch creation capabilities and validation to ensure new tasks meet system requirements.
|
||||||
|
|
||||||
|
## 5. Add configuration options and flag handling [pending]
|
||||||
|
### Dependencies: 52.3, 52.4
|
||||||
|
### Description: Implement various configuration options and command flags for customizing suggestion behavior
|
||||||
|
### Details:
|
||||||
|
Create a comprehensive set of command flags for controlling suggestion quantity, specificity, format, and other parameters. Implement persistent configuration options that users can set as defaults. Document all available options and provide examples of common usage patterns.
|
||||||
|
|
||||||
|
|||||||
@@ -48,3 +48,35 @@ Testing should verify both the new positional argument functionality and continu
|
|||||||
- Verify examples in documentation show both styles where appropriate
|
- Verify examples in documentation show both styles where appropriate
|
||||||
|
|
||||||
All tests should pass with 100% of commands supporting both argument styles without any regression in existing functionality.
|
All tests should pass with 100% of commands supporting both argument styles without any regression in existing functionality.
|
||||||
|
|
||||||
|
# Subtasks:
|
||||||
|
## 1. Analyze current CLI argument parsing structure [pending]
|
||||||
|
### Dependencies: None
|
||||||
|
### Description: Review the existing CLI argument parsing code to understand how arguments are currently processed and identify integration points for positional arguments.
|
||||||
|
### Details:
|
||||||
|
Document the current argument parsing flow, identify key classes and methods responsible for argument handling, and determine how named arguments are currently processed. Create a technical design document outlining the current architecture and proposed changes.
|
||||||
|
|
||||||
|
## 2. Design positional argument specification format [pending]
|
||||||
|
### Dependencies: 55.1
|
||||||
|
### Description: Create a specification for how positional arguments will be defined in command definitions, including their order, required/optional status, and type validation.
|
||||||
|
### Details:
|
||||||
|
Define a clear syntax for specifying positional arguments in command definitions. Consider how to handle mixed positional and named arguments, default values, and type constraints. Document the specification with examples for different command types.
|
||||||
|
|
||||||
|
## 3. Implement core positional argument parsing logic [pending]
|
||||||
|
### Dependencies: 55.1, 55.2
|
||||||
|
### Description: Modify the argument parser to recognize and process positional arguments according to the specification, while maintaining compatibility with existing named arguments.
|
||||||
|
### Details:
|
||||||
|
Update the parser to identify arguments without flags as positional, map them to the correct parameter based on order, and apply appropriate validation. Ensure the implementation handles missing required positional arguments and provides helpful error messages.
|
||||||
|
|
||||||
|
## 4. Handle edge cases and error conditions [pending]
|
||||||
|
### Dependencies: 55.3
|
||||||
|
### Description: Implement robust handling for edge cases such as too many/few arguments, type mismatches, and ambiguous situations between positional and named arguments.
|
||||||
|
### Details:
|
||||||
|
Create comprehensive error handling for scenarios like: providing both positional and named version of the same argument, incorrect argument types, missing required positional arguments, and excess positional arguments. Ensure error messages are clear and actionable for users.
|
||||||
|
|
||||||
|
## 5. Update documentation and create usage examples [pending]
|
||||||
|
### Dependencies: 55.2, 55.3, 55.4
|
||||||
|
### Description: Update CLI documentation to explain positional argument support and provide clear examples showing how to use positional arguments with different commands.
|
||||||
|
### Details:
|
||||||
|
Revise user documentation to include positional argument syntax, update command reference with positional argument information, and create example command snippets showing both positional and named argument usage. Include a migration guide for users transitioning from named-only to positional arguments.
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user