Skip to content

An AI-powered task-management system you can drop into Cursor, Lovable, Windsurf, Roo, and others.

feat: Add task dependency management and enhance task information display

Eyal Toledano306d79fb7ce6
diff --git a/.cursor/rules/dev_workflow.mdc b/.cursor/rules/dev_workflow.mdc
index e5175c32..8a599186 100644
--- a/.cursor/rules/dev_workflow.mdc
+++ b/.cursor/rules/dev_workflow.mdc
@@ -10,6 +10,7 @@ alwaysApply: true
- Analyze task complexity with `node scripts/dev.js analyze-complexity --research` before breaking down tasks
- Select tasks based on dependencies (all marked 'done'), priority level, and ID order
- Clarify tasks by checking task files in tasks/ directory or asking for user input
+ - View specific task details using `node scripts/dev.js show --id=<id>` to understand implementation requirements
- Break down complex tasks using `node scripts/dev.js expand --id=<id>` with appropriate flags
- Clear existing subtasks if needed using `node scripts/dev.js clear-subtasks --id=<id>` before regenerating
- Implement code following task details, dependencies, and project standards
@@ -149,6 +150,8 @@ alwaysApply: true
- **description**: Concise summary of what the task involves (Example: `"Create a new repository, set up initial structure."`)
- **status**: Current state of the task (Example: `"pending"`, `"done"`, `"deferred"`)
- **dependencies**: IDs of prerequisite tasks (Example: `[1, 2]`)
+ - Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending)
+ - This helps quickly identify which prerequisite tasks are blocking work
- **priority**: Importance level (Example: `"high"`, `"medium"`, `"low"`)
- **details**: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
- **testStrategy**: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
@@ -167,3 +170,52 @@ alwaysApply: true
- **PROJECT_VERSION** (Default: `"1.0.0"`): Version in metadata (Example: `PROJECT_VERSION=2.1.0`)
- **PERPLEXITY_API_KEY**: For research-backed features (Example: `PERPLEXITY_API_KEY=pplx-...`)
- **PERPLEXITY_MODEL** (Default: `"sonar-medium-online"`): Perplexity model (Example: `PERPLEXITY_MODEL=sonar-large-online`)
+
+- **Determining the Next Task**
+ - Run `node scripts/dev.js next` to show the next task to work on
+ - The next command identifies tasks with all dependencies satisfied
+ - Tasks are prioritized by priority level, dependency count, and ID
+ - The command shows comprehensive task information including:
+ - Basic task details and description
+ - Implementation details
+ - Subtasks (if they exist)
+ - Contextual suggested actions
+ - Recommended before starting any new development work
+ - Respects your project's dependency structure
+ - Ensures tasks are completed in the appropriate sequence
+ - Provides ready-to-use commands for common task actions
+
+- **Viewing Specific Task Details**
+ - Run `node scripts/dev.js show --id=<id>` or `node scripts/dev.js show <id>` to view a specific task
+ - Use dot notation for subtasks: `node scripts/dev.js show 1.2` (shows subtask 2 of task 1)
+ - Displays comprehensive information similar to the next command, but for a specific task
+ - For parent tasks, shows all subtasks and their current status
+ - For subtasks, shows parent task information and relationship
+ - Provides contextual suggested actions appropriate for the specific task
+ - Useful for examining task details before implementation or checking status
+
+- **Managing Task Dependencies**
+ - Use `node scripts/dev.js add-dependency --id=<id> --depends-on=<id>` to add a dependency
+ - Use `node scripts/dev.js remove-dependency --id=<id> --depends-on=<id>` to remove a dependency
+ - The system prevents circular dependencies and duplicate dependency entries
+ - Dependencies are checked for existence before being added or removed
+ - Task files are automatically regenerated after dependency changes
+ - Dependencies are visualized with status indicators in task listings and files
+
+- **Command Reference: add-dependency**
+ - Syntax: `node scripts/dev.js add-dependency --id=<id> --depends-on=<id>`
+ - Description: Adds a dependency relationship between two tasks
+ - Parameters:
+ - `--id=<id>`: ID of task that will depend on another task (required)
+ - `--depends-on=<id>`: ID of task that will become a dependency (required)
+ - Example: `node scripts/dev.js add-dependency --id=22 --depends-on=21`
+ - Notes: Prevents circular dependencies and duplicates; updates task files automatically
+
+- **Command Reference: remove-dependency**
+ - Syntax: `node scripts/dev.js remove-dependency --id=<id> --depends-on=<id>`
+ - Description: Removes a dependency relationship between two tasks
+ - Parameters:
+ - `--id=<id>`: ID of task to remove dependency from (required)
+ - `--depends-on=<id>`: ID of task to remove as a dependency (required)
+ - Example: `node scripts/dev.js remove-dependency --id=22 --depends-on=21`
+ - Notes: Checks if dependency actually exists; updates task files automatically
diff --git a/.env.example b/.env.example
index ae6659ef..5a0640a3 100644
--- a/.env.example
+++ b/.env.example
@@ -17,5 +17,4 @@ DEFAULT_SUBTASKS=4 # Default number of subtasks when expanding
DEFAULT_PRIORITY=medium # Default priority for generated tasks (high, medium, low)
# Project Metadata (Optional)
-PROJECT_NAME=Your Project Name # Override default project name in tasks.json
-PROJECT_VERSION=1.0.0 # Override default version in tasks.json
\ No newline at end of file
+PROJECT_NAME=Your Project Name # Override default project name in tasks.json
\ No newline at end of file
diff --git a/README-task-master.md b/README-task-master.md
index 2df22a78..168aed00 100644
--- a/README-task-master.md
+++ b/README-task-master.md
@@ -312,6 +312,15 @@ npm run dev -- clear-subtasks --id=1,2,3
npm run dev -- clear-subtasks --all
```
+### Managing Task Dependencies
+```bash
+# Add a dependency to a task
+npm run dev -- add-dependency --id=<id> --depends-on=<id>
+
+# Remove a dependency from a task
+npm run dev -- remove-dependency --id=<id> --depends-on=<id>
+```
+
## Task Structure
Tasks in tasks.json have the following structure:
@@ -326,6 +335,8 @@ Tasks in tasks.json have the following structure:
- `testStrategy`: Approach for verifying the task has been completed correctly
- `subtasks`: List of smaller, more specific tasks that make up the main task
+Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) throughout the system, making it easy to see which prerequisite tasks are done and which still need work.
+
## Best Practices for AI-Driven Development
1. **Start with a detailed PRD**: The more detailed your PRD, the better the generated tasks will be.
@@ -455,3 +466,177 @@ npm run dev -- expand --all
```
This integration ensures that task expansion is informed by thorough complexity analysis, resulting in better subtask organization and more efficient development.
+
+### Finding the Next Task
+
+To find the next task to work on based on dependencies and status:
+
+```bash
+npm run dev -- next
+```
+
+This command:
+- Identifies tasks that are pending/in-progress and have all dependencies satisfied
+- Prioritizes tasks by priority level, dependency count, and task ID
+- Displays comprehensive information about the selected task:
+ - Basic task details (ID, title, priority, dependencies)
+ - Implementation details
+ - Subtasks (if they exist)
+- Provides contextual suggested actions:
+ - Command to mark the task as in-progress
+ - Command to mark the task as done
+ - Commands for working with subtasks
+
+Example Cursor AI interaction:
+```
+What's the next task I should work on?
+```
+
+### Viewing Specific Task Details
+
+To view detailed information about a specific task:
+
+```bash
+npm run dev -- show 1
+```
+or
+```bash
+npm run dev -- show --id=1.2
+```
+
+This command:
+- Displays comprehensive details about a specific task or subtask
+- Shows task status, priority, dependencies, and detailed implementation notes
+- For parent tasks, displays all subtasks and their status
+- For subtasks, shows parent task relationship
+- Provides contextual action suggestions based on the task's state
+- Works with both regular tasks and subtasks (using the format taskId.subtaskId)
+
+Example Cursor AI interaction:
+```
+Show me the details for task 3
+```
+or
+```
+Tell me more about subtask 2.1
+```
+
+## Task Structure
+
+Tasks in tasks.json have the following structure:
+
+- `id`: Unique identifier for the task
+- `title`: Brief, descriptive title of the task
+- `description`: Concise description of what the task involves
+- `status`: Current state of the task (pending, done, deferred)
+- `dependencies`: IDs of tasks that must be completed before this task
+- `priority`: Importance level of the task (high, medium, low)
+- `details`: In-depth instructions for implementing the task
+- `testStrategy`: Approach for verifying the task has been completed correctly
+- `subtasks`: List of smaller, more specific tasks that make up the main task
+
+Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) throughout the system, making it easy to see which prerequisite tasks are done and which still need work.
+
+## Best Practices for AI-Driven Development
+
+1. **Start with a detailed PRD**: The more detailed your PRD, the better the generated tasks will be.
+
+2. **Review generated tasks**: After parsing the PRD, review the tasks to ensure they make sense and have appropriate dependencies.
+
+3. **Follow the dependency chain**: Always respect task dependencies - the Cursor agent will help with this.
+
+4. **Update as you go**: If your implementation diverges from the plan, use the update command to keep future tasks aligned with your current approach.
+
+5. **Break down complex tasks**: Use the expand command to break down complex tasks into manageable subtasks.
+
+6. **Regenerate task files**: After any updates to tasks.json, regenerate the task files to keep them in sync.
+
+7. **Communicate context to the agent**: When asking the Cursor agent to help with a task, provide context about what you're trying to achieve.
+
+## Example Cursor AI Interactions
+
+### Starting a new project
+```
+I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
+Can you help me parse it and set up the initial tasks?
+```
+
+### Working on tasks
+```
+What's the next task I should work on? Please consider dependencies and priorities.
+```
+
+### Implementing a specific task
+```
+I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
+```
+
+### Managing subtasks
+```
+I need to regenerate the subtasks for task 3 with a different approach. Can you help me clear and regenerate them?
+```
+
+### Handling changes
+```
+We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
+```
+
+### Completing work
+```
+I've finished implementing the authentication system described in task 2. All tests are passing.
+Please mark it as complete and tell me what I should work on next.
+```
+
+## Documentation
+
+For more detailed documentation on the scripts and command-line options, see the [scripts/README.md](scripts/README.md) file in your initialized project.
+
+## License
+
+MIT
+
+### Analyzing Task Complexity
+
+To analyze the complexity of tasks and automatically generate expansion recommendations:
+
+```bash
+npm run dev -- analyze-complexity
+```
+
+This command:
+- Analyzes each task using AI to assess its complexity
+- Recommends optimal number of subtasks based on configured DEFAULT_SUBTASKS
+- Generates tailored prompts for expanding each task
+- Creates a comprehensive JSON report with ready-to-use commands
+- Saves the report to scripts/task-complexity-report.json by default
+
+Options:
+```bash
+# Save report to a custom location
+npm run dev -- analyze-complexity --output=my-report.json
+
+# Use a specific LLM model
+npm run dev -- analyze-complexity --model=claude-3-opus-20240229
+
+# Set a custom complexity threshold (1-10)
+npm run dev -- analyze-complexity --threshold=6
+
+# Use an alternative tasks file
+npm run dev -- analyze-complexity --file=custom-tasks.json
+
+# Use Perplexity AI for research-backed complexity analysis
+npm run dev -- analyze-complexity --research
+```
+
+The generated report contains:
+- Complexity analysis for each task (scored 1-10)
+- Recommended number of subtasks based on complexity
+- AI-generated expansion prompts customized for each task
+- Ready-to-run expansion commands directly within each task analysis
+
+### Smart Task Expansion
+
+The `expand` command now automatically checks for and uses the complexity report:
+
+```bash
+# Expand a task, using complexity report recommendations if available
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index dbba1931..5323e7e0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,19 +1,24 @@
{
"name": "claude-task-master",
- "version": "1.4.6",
+ "version": "1.4.12",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-task-master",
- "version": "1.4.6",
+ "version": "1.4.12",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.39.0",
+ "boxen": "^8.0.1",
"chalk": "^4.1.2",
+ "cli-table3": "^0.6.5",
"commander": "^11.1.0",
"dotenv": "^16.3.1",
+ "figlet": "^1.8.0",
+ "gradient-string": "^3.0.0",
"openai": "^4.86.1",
+ "ora": "^8.2.0",
"punycode": "^2.3.1"
},
"bin": {
@@ -38,6 +43,16 @@
"node-fetch": "^2.6.7"
}
},
+ "node_modules/@colors/colors": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
+ "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=0.1.90"
+ }
+ },
"node_modules/@types/node": {
"version": "18.19.79",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.79.tgz",
@@ -57,6 +72,12 @@
"form-data": "^4.0.0"
}
},
+ "node_modules/@types/tinycolor2": {
+ "version": "1.4.6",
+ "resolved": "https://registry.npmjs.org/@types/tinycolor2/-/tinycolor2-1.4.6.tgz",
+ "integrity": "sha512-iEN8J0BoMnsWBqjVbWH/c0G0Hh7O21lpR2/+PrvAVgWdzL7eexIFm4JN/Wn10PTcmNdtS6U67r499mlWMXOxNw==",
+ "license": "MIT"
+ },
"node_modules/abort-controller": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
@@ -81,6 +102,68 @@
"node": ">= 8.0.0"
}
},
+ "node_modules/ansi-align": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.1.tgz",
+ "integrity": "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==",
+ "license": "ISC",
+ "dependencies": {
+ "string-width": "^4.1.0"
+ }
+ },
+ "node_modules/ansi-align/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/ansi-align/node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "license": "MIT"
+ },
+ "node_modules/ansi-align/node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/ansi-align/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/ansi-regex": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz",
+ "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"
+ }
+ },
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
@@ -102,6 +185,40 @@
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"license": "MIT"
},
+ "node_modules/boxen": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/boxen/-/boxen-8.0.1.tgz",
+ "integrity": "sha512-F3PH5k5juxom4xktynS7MoFY+NUWH5LC4CnH11YB8NPew+HLpmBLCybSAEyb2F+4pRXhuhWqFesoQd6DAyc2hw==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-align": "^3.0.1",
+ "camelcase": "^8.0.0",
+ "chalk": "^5.3.0",
+ "cli-boxes": "^3.0.0",
+ "string-width": "^7.2.0",
+ "type-fest": "^4.21.0",
+ "widest-line": "^5.0.0",
+ "wrap-ansi": "^9.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/boxen/node_modules/chalk": {
+ "version": "5.4.1",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz",
+ "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.17.0 || ^14.13 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
@@ -115,6 +232,18 @@
"node": ">= 0.4"
}
},
+ "node_modules/camelcase": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-8.0.0.tgz",
+ "integrity": "sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -131,6 +260,101 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
+ "node_modules/cli-boxes": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz",
+ "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/cli-cursor": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz",
+ "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==",
+ "license": "MIT",
+ "dependencies": {
+ "restore-cursor": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/cli-spinners": {
+ "version": "2.9.2",
+ "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz",
+ "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/cli-table3": {
+ "version": "0.6.5",
+ "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz",
+ "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==",
+ "license": "MIT",
+ "dependencies": {
+ "string-width": "^4.2.0"
+ },
+ "engines": {
+ "node": "10.* || >= 12.*"
+ },
+ "optionalDependencies": {
+ "@colors/colors": "1.5.0"
+ }
+ },
+ "node_modules/cli-table3/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cli-table3/node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "license": "MIT"
+ },
+ "node_modules/cli-table3/node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cli-table3/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -205,6 +429,12 @@
"node": ">= 0.4"
}
},
+ "node_modules/emoji-regex": {
+ "version": "10.4.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.4.0.tgz",
+ "integrity": "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==",
+ "license": "MIT"
+ },
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -259,6 +489,18 @@
"node": ">=6"
}
},
+ "node_modules/figlet": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/figlet/-/figlet-1.8.0.tgz",
+ "integrity": "sha512-chzvGjd+Sp7KUvPHZv6EXV5Ir3Q7kYNpCr4aHrRW79qFtTefmQZNny+W1pW9kf5zeE6dikku2W50W/wAH2xWgw==",
+ "license": "MIT",
+ "bin": {
+ "figlet": "bin/index.js"
+ },
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
"node_modules/form-data": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
@@ -311,6 +553,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/get-east-asian-width": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.3.0.tgz",
+ "integrity": "sha512-vpeMIQKxczTD/0s2CdEWHcb0eeJe6TFjxb+J5xgX7hScxqrGuyjmv4c1D4A/gelKfyox0gJJwIHF+fLjeaM8kQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
@@ -360,6 +614,31 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/gradient-string": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/gradient-string/-/gradient-string-3.0.0.tgz",
+ "integrity": "sha512-frdKI4Qi8Ihp4C6wZNB565de/THpIaw3DjP5ku87M+N9rNSGmPTjfkq61SdRXB7eCaL8O1hkKDvf6CDMtOzIAg==",
+ "license": "MIT",
+ "dependencies": {
+ "chalk": "^5.3.0",
+ "tinygradient": "^1.1.5"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/gradient-string/node_modules/chalk": {
+ "version": "5.4.1",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz",
+ "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.17.0 || ^14.13 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
@@ -417,6 +696,79 @@
"ms": "^2.0.0"
}
},
+ "node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/is-interactive": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz",
+ "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-unicode-supported": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz",
+ "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/log-symbols": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-6.0.0.tgz",
+ "integrity": "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==",
+ "license": "MIT",
+ "dependencies": {
+ "chalk": "^5.3.0",
+ "is-unicode-supported": "^1.3.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/log-symbols/node_modules/chalk": {
+ "version": "5.4.1",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz",
+ "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.17.0 || ^14.13 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
+ "node_modules/log-symbols/node_modules/is-unicode-supported": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz",
+ "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -447,6 +799,18 @@
"node": ">= 0.6"
}
},
+ "node_modules/mimic-function": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz",
+ "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -492,6 +856,21 @@
}
}
},
+ "node_modules/onetime": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz",
+ "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mimic-function": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/openai": {
"version": "4.86.1",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.86.1.tgz",
@@ -522,6 +901,41 @@
}
}
},
+ "node_modules/ora": {
+ "version": "8.2.0",
+ "resolved": "https://registry.npmjs.org/ora/-/ora-8.2.0.tgz",
+ "integrity": "sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw==",
+ "license": "MIT",
+ "dependencies": {
+ "chalk": "^5.3.0",
+ "cli-cursor": "^5.0.0",
+ "cli-spinners": "^2.9.2",
+ "is-interactive": "^2.0.0",
+ "is-unicode-supported": "^2.0.0",
+ "log-symbols": "^6.0.0",
+ "stdin-discarder": "^0.2.2",
+ "string-width": "^7.2.0",
+ "strip-ansi": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/ora/node_modules/chalk": {
+ "version": "5.4.1",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz",
+ "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.17.0 || ^14.13 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -531,6 +945,78 @@
"node": ">=6"
}
},
+ "node_modules/restore-cursor": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz",
+ "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==",
+ "license": "MIT",
+ "dependencies": {
+ "onetime": "^7.0.0",
+ "signal-exit": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/signal-exit": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
+ "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/stdin-discarder": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz",
+ "integrity": "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/string-width": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^10.3.0",
+ "get-east-asian-width": "^1.0.0",
+ "strip-ansi": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/strip-ansi": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz",
+ "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"
+ }
+ },
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
@@ -543,12 +1029,40 @@
"node": ">=8"
}
},
+ "node_modules/tinycolor2": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz",
+ "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==",
+ "license": "MIT"
+ },
+ "node_modules/tinygradient": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz",
+ "integrity": "sha512-8nIfc2vgQ4TeLnk2lFj4tRLvvJwEfQuabdsmvDdQPT0xlk9TaNtpGd6nNRxXoK6vQhN6RSzj+Cnp5tTQmpxmbw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/tinycolor2": "^1.4.0",
+ "tinycolor2": "^1.0.0"
+ }
+ },
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT"
},
+ "node_modules/type-fest": {
+ "version": "4.37.0",
+ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.37.0.tgz",
+ "integrity": "sha512-S/5/0kFftkq27FPNye0XM1e2NsnoD/3FS+pBmbjmmtLT6I+i344KoOf7pvXreaFsDamWeaJX55nczA1m5PsBDg==",
+ "license": "(MIT OR CC0-1.0)",
+ "engines": {
+ "node": ">=16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
@@ -570,6 +1084,50 @@
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
+ },
+ "node_modules/widest-line": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz",
+ "integrity": "sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==",
+ "license": "MIT",
+ "dependencies": {
+ "string-width": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/wrap-ansi": {
+ "version": "9.0.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.0.tgz",
+ "integrity": "sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^6.2.1",
+ "string-width": "^7.0.0",
+ "strip-ansi": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/ansi-styles": {
+ "version": "6.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz",
+ "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
}
}
}
diff --git a/package.json b/package.json
index 1a663506..1ca7b68e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-task-master",
- "version": "1.4.10",
+ "version": "1.5.2",
"description": "A task management system for AI-driven development with Claude",
"main": "index.js",
"type": "module",
@@ -26,10 +26,15 @@
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.39.0",
+ "boxen": "^8.0.1",
"chalk": "^4.1.2",
+ "cli-table3": "^0.6.5",
"commander": "^11.1.0",
"dotenv": "^16.3.1",
+ "figlet": "^1.8.0",
+ "gradient-string": "^3.0.0",
"openai": "^4.86.1",
+ "ora": "^8.2.0",
"punycode": "^2.3.1"
},
"engines": {
diff --git a/scripts/README.md b/scripts/README.md
index 08efa586..f96062ad 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -14,6 +14,7 @@ In an AI-driven development process—particularly with tools like [Cursor](http
6. **Expand** tasks with subtasks—break down complex tasks into smaller, more manageable subtasks.
7. **Research-backed subtask generation**—use Perplexity AI to generate more informed and contextually relevant subtasks.
8. **Clear subtasks**—remove subtasks from specified tasks to allow regeneration or restructuring.
+9. **Show task details**—display detailed information about a specific task and its subtasks.
## Configuration
@@ -41,6 +42,7 @@ The script can be configured through environment variables in a `.env` file at t
- A JSON file at the project root containing an array of tasks (each with `id`, `title`, `description`, `status`, etc.).
- The `meta` field can store additional info like the project's name, version, or reference to the PRD.
- Tasks can have `subtasks` for more detailed implementation steps.
+ - Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) to easily track progress.
2. **Script Commands**
You can run the script via:
@@ -58,6 +60,8 @@ The script can be configured through environment variables in a `.env` file at t
- `set-status`: Change a task's status
- `expand`: Add subtasks to a task or all tasks
- `clear-subtasks`: Remove subtasks from specified tasks
+ - `next`: Determine the next task to work on based on dependencies
+ - `show`: Display detailed information about a specific task
Run `node scripts/dev.js` without arguments to see detailed usage information.
@@ -122,6 +126,7 @@ Notes:
- Common status values are 'done', 'pending', and 'deferred', but any string is accepted
- You can specify multiple task IDs by separating them with commas
- Subtask IDs are specified using the format `parentId.subtaskId` (e.g., `3.1`)
+- Dependencies are updated to show completion status (✅ for completed, ⏱️ for pending) throughout the system
## Expanding Tasks
@@ -270,4 +275,102 @@ The output report structure is:
// More tasks sorted by complexity score (highest first)
]
}
-```
\ No newline at end of file
+```
+
+## Finding the Next Task
+
+The `next` command helps you determine which task to work on next based on dependencies and status:
+
+```bash
+# Show the next task to work on
+node scripts/dev.js next
+
+# Specify a different tasks file
+node scripts/dev.js next --file=custom-tasks.json
+```
+
+This command:
+
+1. Identifies all **eligible tasks** - pending or in-progress tasks whose dependencies are all satisfied (marked as done)
+2. **Prioritizes** these eligible tasks by:
+ - Priority level (high > medium > low)
+ - Number of dependencies (fewer dependencies first)
+ - Task ID (lower ID first)
+3. **Displays** comprehensive information about the selected task:
+ - Basic task details (ID, title, priority, dependencies)
+ - Detailed description and implementation details
+ - Subtasks if they exist
+4. Provides **contextual suggested actions**:
+ - Command to mark the task as in-progress
+ - Command to mark the task as done when completed
+ - Commands for working with subtasks (update status or expand)
+
+This feature ensures you're always working on the most appropriate task based on your project's current state and dependency structure.
+
+## Showing Task Details
+
+The `show` command allows you to view detailed information about a specific task:
+
+```bash
+# Show details for a specific task
+node scripts/dev.js show 1
+
+# Alternative syntax with --id option
+node scripts/dev.js show --id=1
+
+# Show details for a subtask
+node scripts/dev.js show --id=1.2
+
+# Specify a different tasks file
+node scripts/dev.js show 3 --file=custom-tasks.json
+```
+
+This command:
+
+1. **Displays comprehensive information** about the specified task:
+ - Basic task details (ID, title, priority, dependencies, status)
+ - Full description and implementation details
+ - Test strategy information
+ - Subtasks if they exist
+2. **Handles both regular tasks and subtasks**:
+ - For regular tasks, shows all subtasks and their status
+ - For subtasks, shows the parent task relationship
+3. **Provides contextual suggested actions**:
+ - Commands to update the task status
+ - Commands for working with subtasks
+ - For subtasks, provides a link to view the parent task
+
+This command is particularly useful when you need to examine a specific task in detail before implementing it or when you want to check the status and details of a particular task.
+
+## Managing Task Dependencies
+
+The `add-dependency` and `remove-dependency` commands allow you to manage task dependencies:
+
+```bash
+# Add a dependency to a task
+node scripts/dev.js add-dependency --id=<id> --depends-on=<id>
+
+# Remove a dependency from a task
+node scripts/dev.js remove-dependency --id=<id> --depends-on=<id>
+```
+
+These commands:
+
+1. **Allow precise dependency management**:
+ - Add dependencies between tasks with automatic validation
+ - Remove dependencies when they're no longer needed
+ - Update task files automatically after changes
+
+2. **Include validation checks**:
+ - Prevent circular dependencies (a task depending on itself)
+ - Prevent duplicate dependencies
+ - Verify that both tasks exist before adding/removing dependencies
+ - Check if dependencies exist before attempting to remove them
+
+3. **Provide clear feedback**:
+ - Success messages confirm when dependencies are added/removed
+ - Error messages explain why operations failed (if applicable)
+
+4. **Automatically update task files**:
+ - Regenerates task files to reflect dependency changes
+ - Ensures tasks and their files stay synchronized
\ No newline at end of file
diff --git a/scripts/dev.js b/scripts/dev.js
index a3f4d7c9..d3f48f84 100755
--- a/scripts/dev.js
+++ b/scripts/dev.js
@@ -56,6 +56,31 @@
* -> Clears subtasks from specified tasks
* -> Supports comma-separated IDs for clearing multiple tasks: --id=1,2,3,1.1,1.2
* -> Use --all to clear subtasks from all tasks
+ *
+ * 9) next
+ * -> Shows the next task to work on based on dependencies and status
+ * -> Prioritizes tasks whose dependencies are all satisfied
+ * -> Orders eligible tasks by priority, dependency count, and ID
+ * -> Displays comprehensive information about the selected task
+ * -> Shows subtasks if they exist
+ * -> Provides contextual action commands for the next steps
+ *
+ * 10) show [id] or show --id=<id>
+ * -> Shows details of a specific task by ID
+ * -> Displays the same comprehensive information as the 'next' command
+ * -> Handles both regular tasks and subtasks (e.g., 1.2)
+ * -> For subtasks, shows parent task information and link
+ * -> Provides contextual action commands tailored to the specific task
+ *
+ * 11) add-dependency --id=<id> --depends-on=<id>
+ * -> Adds a dependency to a task
+ * -> Checks if the dependency already exists before adding
+ * -> Prevents circular dependencies
+ * -> Automatically sorts dependencies for clarity
+ *
+ * 12) remove-dependency --id=<id> --depends-on=<id>
+ * -> Removes a dependency from a task
+ * -> Checks if the dependency exists before attempting to remove
*
* Usage examples:
* node dev.js parse-prd --input=sample-prd.txt
@@ -73,6 +98,11 @@
* node dev.js analyze-complexity --threshold=6 --model=claude-3.7-sonnet
* node dev.js analyze-complexity --research
* node dev.js clear-subtasks --id=1,2,3 --all
+ * node dev.js next
+ * node dev.js show 1
+ * node dev.js show --id=1.2
+ * node dev.js add-dependency --id=22 --depends-on=21
+ * node dev.js remove-dependency --id=22 --depends-on=21
*/
import fs from 'fs';
@@ -85,6 +115,11 @@ import chalk from 'chalk';
import { Anthropic } from '@anthropic-ai/sdk';
import OpenAI from 'openai';
import dotenv from 'dotenv';
+import figlet from 'figlet';
+import boxen from 'boxen';
+import ora from 'ora';
+import Table from 'cli-table3';
+import gradient from 'gradient-string';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -97,11 +132,20 @@ const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
-// Configure OpenAI client for Perplexity
-const perplexity = new OpenAI({
- apiKey: process.env.PERPLEXITY_API_KEY,
- baseURL: 'https://api.perplexity.ai',
-});
+// Configure OpenAI client for Perplexity - make it lazy
+let perplexity = null;
+function getPerplexityClient() {
+ if (!perplexity) {
+ if (!process.env.PERPLEXITY_API_KEY) {
+ throw new Error("PERPLEXITY_API_KEY environment variable is missing. Set it to use research-backed features.");
+ }
+ perplexity = new OpenAI({
+ apiKey: process.env.PERPLEXITY_API_KEY,
+ baseURL: 'https://api.perplexity.ai',
+ });
+ }
+ return perplexity;
+}
// Model configuration
const MODEL = process.env.MODEL || 'claude-3-7-sonnet-20250219';
@@ -118,8 +162,8 @@ const CONFIG = {
logLevel: process.env.LOG_LEVEL || "info",
defaultSubtasks: parseInt(process.env.DEFAULT_SUBTASKS || "3"),
defaultPriority: process.env.DEFAULT_PRIORITY || "medium",
- projectName: process.env.PROJECT_NAME || "MCP SaaS MVP",
- projectVersion: process.env.PROJECT_VERSION || "1.0.0"
+ projectName: process.env.PROJECT_NAME || "Task Master",
+ projectVersion: "1.5.0" // Hardcoded version - ALWAYS use this value, ignore environment variable
};
// Set up logging based on log level
@@ -130,14 +174,63 @@ const LOG_LEVELS = {
error: 3
};
+// Create a color gradient for the banner
+const coolGradient = gradient(['#00b4d8', '#0077b6', '#03045e']);
+const warmGradient = gradient(['#fb8b24', '#e36414', '#9a031e']);
+
+// Display a fancy banner
+function displayBanner() {
+ console.clear();
+ const bannerText = figlet.textSync('Claude Task Master', {
+ font: 'Standard',
+ horizontalLayout: 'default',
+ verticalLayout: 'default'
+ });
+
+ console.log(coolGradient(bannerText));
+
+ // Read version directly from package.json
+ let version = "1.5.0"; // Default fallback
+ try {
+ const packageJsonPath = path.join(__dirname, '..', 'package.json');
+ if (fs.existsSync(packageJsonPath)) {
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
+ version = packageJson.version;
+ }
+ } catch (error) {
+ // Silently fall back to default version
+ }
+
+ console.log(boxen(chalk.white(`${chalk.bold('Version:')} ${version} ${chalk.bold('Project:')} ${CONFIG.projectName}`), {
+ padding: 1,
+ margin: { top: 0, bottom: 1 },
+ borderStyle: 'round',
+ borderColor: 'cyan'
+ }));
+}
+
function log(level, ...args) {
+ const icons = {
+ debug: chalk.gray('🔍'),
+ info: chalk.blue('ℹ️'),
+ warn: chalk.yellow('⚠️'),
+ error: chalk.red('❌'),
+ success: chalk.green('✅')
+ };
+
if (LOG_LEVELS[level] >= LOG_LEVELS[CONFIG.logLevel]) {
+ const icon = icons[level] || '';
+
if (level === 'error') {
- console.error(...args);
+ console.error(icon, chalk.red(...args));
} else if (level === 'warn') {
- console.warn(...args);
+ console.warn(icon, chalk.yellow(...args));
+ } else if (level === 'success') {
+ console.log(icon, chalk.green(...args));
+ } else if (level === 'info') {
+ console.log(icon, chalk.blue(...args));
} else {
- console.log(...args);
+ console.log(icon, ...args);
}
}
@@ -159,24 +252,21 @@ function writeJSON(filepath, data) {
fs.writeFileSync(filepath, JSON.stringify(data, null, 2), 'utf8');
}
-// Add a simple loading indicator function
+// Replace the simple loading indicator with ora spinner
function startLoadingIndicator(message) {
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
- let i = 0;
+ const spinner = ora({
+ text: message,
+ color: 'cyan',
+ spinner: 'dots'
+ }).start();
- process.stdout.write(`${message} `);
-
- return setInterval(() => {
- readline.cursorTo(process.stdout, message.length + 1);
- process.stdout.write(frames[i]);
- i = (i + 1) % frames.length;
- }, 80);
+ return spinner;
}
-function stopLoadingIndicator(interval) {
- clearInterval(interval);
- readline.cursorTo(process.stdout, 0);
- readline.clearLine(process.stdout, 0);
+function stopLoadingIndicator(spinner) {
+ if (spinner && spinner.stop) {
+ spinner.stop();
+ }
}
async function callClaude(prdContent, prdPath, numTasks, retryCount = 0) {
@@ -424,11 +514,19 @@ function processClaudeResponse(textContent, numTasks, retryCount, prdContent, pr
// 1) parse-prd
//
async function parsePRD(prdPath, tasksPath, numTasks) {
+ displayBanner();
+
if (!fs.existsSync(prdPath)) {
log('error', `PRD file not found: ${prdPath}`);
process.exit(1);
}
+ const headerBox = boxen(
+ chalk.white.bold(`Parsing PRD Document: ${chalk.cyan(path.basename(prdPath))}`),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ );
+ console.log(headerBox);
+
log('info', `Reading PRD file from: ${prdPath}`);
const prdContent = fs.readFileSync(prdPath, 'utf8');
log('info', `PRD file read successfully. Content length: ${prdContent.length} characters`);
@@ -437,9 +535,12 @@ async function parsePRD(prdPath, tasksPath, numTasks) {
log('info', "Calling Claude to generate tasks from PRD...");
try {
+ const loadingSpinner = startLoadingIndicator('Generating tasks with Claude AI');
const claudeResponse = await callClaude(prdContent, prdPath, numTasks);
let tasks = claudeResponse.tasks || [];
- log('info', `Claude generated ${tasks.length} tasks from the PRD`);
+ stopLoadingIndicator(loadingSpinner);
+
+ log('success', `Claude generated ${tasks.length} tasks from the PRD`);
// Limit the number of tasks if specified
if (numTasks && numTasks > 0 && numTasks < tasks.length) {
@@ -462,7 +563,54 @@ async function parsePRD(prdPath, tasksPath, numTasks) {
log('info', `Writing ${tasks.length} tasks to ${tasksPath}...`);
writeJSON(tasksPath, data);
- log('info', `Parsed PRD from '${prdPath}' -> wrote ${tasks.length} tasks to '${tasksPath}'.`);
+
+ // Show success message in a box
+ const successBox = boxen(
+ chalk.green(`Successfully parsed PRD from: ${chalk.cyan(prdPath)}\n`) +
+ chalk.green(`Generated ${chalk.bold(tasks.length)} tasks in: ${chalk.cyan(tasksPath)}`),
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ );
+ console.log(successBox);
+
+ // Show the first few tasks in a table
+ const previewTasks = tasks.slice(0, Math.min(5, tasks.length));
+ const taskTable = new Table({
+ head: [chalk.cyan.bold('ID'), chalk.cyan.bold('Title'), chalk.cyan.bold('Priority')],
+ colWidths: [6, 60, 12],
+ style: { head: [], border: [] }
+ });
+
+ previewTasks.forEach(task => {
+ taskTable.push([
+ task.id.toString(),
+ task.title,
+ chalk.yellow(task.priority || 'medium')
+ ]);
+ });
+
+ if (tasks.length > 5) {
+ taskTable.push([
+ '...',
+ chalk.dim(`${tasks.length - 5} more tasks`),
+ ''
+ ]);
+ }
+
+ console.log(boxen(
+ chalk.white.bold('Task Preview:'),
+ { padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'blue', borderStyle: 'round' }
+ ));
+ console.log(taskTable.toString());
+
+ // Next steps suggestion
+ console.log(boxen(
+ chalk.white.bold('Next Steps:') + '\n\n' +
+ `${chalk.cyan('1.')} Run ${chalk.yellow('node scripts/dev.js generate')} to create individual task files\n` +
+ `${chalk.cyan('2.')} Run ${chalk.yellow('node scripts/dev.js list')} to see all tasks\n` +
+ `${chalk.cyan('3.')} Run ${chalk.yellow('node scripts/dev.js analyze-complexity')} to plan task breakdown`,
+ { padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
} catch (error) {
log('error', "Failed to generate tasks:", error.message);
process.exit(1);
@@ -577,7 +725,7 @@ function generateTaskFiles(tasksPath, outputDir) {
`# Task ID: ${task.id}`,
`# Title: ${task.title}`,
`# Status: ${task.status}`,
- `# Dependencies: ${task.dependencies.join(", ")}`,
+ `# Dependencies: ${formatDependenciesWithStatus(task.dependencies, data.tasks, false)}`,
`# Priority: ${task.priority}`,
`# Description: ${task.description}`,
`# Details:\n${task.details}\n`,
@@ -589,10 +737,14 @@ function generateTaskFiles(tasksPath, outputDir) {
if (task.subtasks && task.subtasks.length > 0) {
contentParts.push(`# Subtasks:`);
task.subtasks.forEach(subtask => {
+ const subtaskDeps = subtask.dependencies
+ ? formatDependenciesWithStatus(subtask.dependencies, data.tasks, false)
+ : "";
+
contentParts.push(`## Subtask ID: ${subtask.id}`);
contentParts.push(`## Title: ${subtask.title}`);
contentParts.push(`## Status: ${subtask.status}`);
- contentParts.push(`## Dependencies: ${subtask.dependencies ? subtask.dependencies.join(", ") : ""}`);
+ contentParts.push(`## Dependencies: ${subtaskDeps}`);
contentParts.push(`## Description: ${subtask.description}`);
if (subtask.acceptanceCriteria) {
contentParts.push(`## Acceptance Criteria:\n${subtask.acceptanceCriteria}\n`);
@@ -612,6 +764,8 @@ function generateTaskFiles(tasksPath, outputDir) {
// 4) set-status
//
function setTaskStatus(tasksPath, taskIdInput, newStatus) {
+ displayBanner();
+
// Validate inputs
if (!taskIdInput || !newStatus) {
log('error', 'Task ID and new status are required');
@@ -625,18 +779,123 @@ function setTaskStatus(tasksPath, taskIdInput, newStatus) {
process.exit(1);
}
+ console.log(boxen(
+ chalk.white.bold(`Updating Task Status to: ${getStatusWithColor(newStatus)}`),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ ));
+
// Handle multiple task IDs (comma-separated)
if (typeof taskIdInput === 'string' && taskIdInput.includes(',')) {
const taskIds = taskIdInput.split(',').map(id => id.trim());
log('info', `Processing multiple task IDs: ${taskIds.join(', ')}`);
+ // Create a summary table for the updates
+ const summaryTable = new Table({
+ head: [
+ chalk.cyan.bold('ID'),
+ chalk.cyan.bold('Title'),
+ chalk.cyan.bold('Old Status'),
+ chalk.cyan.bold('New Status')
+ ],
+ colWidths: [8, 40, 15, 15],
+ style: { head: [], border: [] }
+ });
+
// Process each task ID individually
taskIds.forEach(id => {
- setTaskStatus(tasksPath, id, newStatus);
+ const result = updateSingleTaskStatus(tasksPath, id, newStatus, data);
+ if (result) {
+ summaryTable.push([
+ result.id,
+ truncate(result.title, 37),
+ getStatusWithColor(result.oldStatus),
+ getStatusWithColor(result.newStatus)
+ ]);
+
+ // Add subtask updates if any
+ if (result.subtasks && result.subtasks.length > 0) {
+ result.subtasks.forEach(sub => {
+ summaryTable.push([
+ ` ${sub.id}`,
+ ` ↳ ${truncate(sub.title, 35)}`,
+ getStatusWithColor(sub.oldStatus),
+ getStatusWithColor(sub.newStatus)
+ ]);
+ });
+ }
+ }
});
+
+ // Save the changes
+ writeJSON(tasksPath, data);
+
+ // Regenerate task files
+ log('info', "Regenerating task files...");
+ generateTaskFiles(tasksPath, path.dirname(tasksPath));
+
+ // Show the summary table
+ console.log(boxen(
+ chalk.white.bold('Status Update Summary:'),
+ { padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'blue', borderStyle: 'round' }
+ ));
+ console.log(summaryTable.toString());
+
return;
}
+ // Handle regular task ID or subtask ID
+ const result = updateSingleTaskStatus(tasksPath, taskIdInput, newStatus, data);
+
+ if (result) {
+ // Save the changes
+ writeJSON(tasksPath, data);
+
+ // Regenerate task files
+ log('info', "Regenerating task files...");
+ generateTaskFiles(tasksPath, path.dirname(tasksPath));
+
+ // Show success message
+ const successBox = boxen(
+ chalk.green(`Successfully updated task ${chalk.bold(result.id)} status:\n`) +
+ `From: ${getStatusWithColor(result.oldStatus)}\n` +
+ `To: ${getStatusWithColor(result.newStatus)}`,
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ );
+ console.log(successBox);
+
+ // If subtasks were also updated, show them
+ if (result.subtasks && result.subtasks.length > 0) {
+ const subtaskTable = new Table({
+ head: [
+ chalk.cyan.bold('ID'),
+ chalk.cyan.bold('Title'),
+ chalk.cyan.bold('Old Status'),
+ chalk.cyan.bold('New Status')
+ ],
+ colWidths: [8, 40, 15, 15],
+ style: { head: [], border: [] }
+ });
+
+ result.subtasks.forEach(sub => {
+ subtaskTable.push([
+ sub.id,
+ truncate(sub.title, 37),
+ getStatusWithColor(sub.oldStatus),
+ getStatusWithColor(sub.newStatus)
+ ]);
+ });
+
+ console.log(boxen(
+ chalk.white.bold('Subtasks Also Updated:'),
+ { padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'blue', borderStyle: 'round' }
+ ));
+ console.log(subtaskTable.toString());
+ }
+ }
+}
+
+// Helper function to update a single task status and return details for UI
+function updateSingleTaskStatus(tasksPath, taskIdInput, newStatus, data) {
// Handle subtask IDs (e.g., "1.1")
if (String(taskIdInput).includes('.')) {
const [parentIdStr, subtaskIdStr] = String(taskIdInput).split('.');
@@ -645,62 +904,67 @@ function setTaskStatus(tasksPath, taskIdInput, newStatus) {
if (isNaN(parentId) || isNaN(subtaskId)) {
log('error', `Invalid subtask ID format: ${taskIdInput}`);
- process.exit(1);
+ return null;
}
// Find the parent task
const parentTask = data.tasks.find(t => t.id === parentId);
if (!parentTask) {
log('error', `Parent task ${parentId} not found`);
- process.exit(1);
+ return null;
}
// Ensure subtasks array exists
if (!parentTask.subtasks || !Array.isArray(parentTask.subtasks)) {
log('error', `Parent task ${parentId} has no subtasks array`);
- process.exit(1);
+ return null;
}
// Find and update the subtask
const subtask = parentTask.subtasks.find(st => st.id === subtaskId);
if (!subtask) {
log('error', `Subtask ${subtaskId} not found in task ${parentId}`);
- process.exit(1);
+ return null;
}
// Update the subtask status
const oldStatus = subtask.status || 'pending';
subtask.status = newStatus;
- // Save the changes
- writeJSON(tasksPath, data);
- log('info', `Updated subtask ${parentId}.${subtaskId} status from '${oldStatus}' to '${newStatus}'`);
-
- // Add call to generate task files
- log('info', "Regenerating task files...");
- generateTaskFiles(tasksPath, path.dirname(tasksPath));
-
- return;
+ return {
+ id: `${parentId}.${subtaskId}`,
+ title: subtask.title,
+ oldStatus: oldStatus,
+ newStatus: newStatus
+ };
}
// Handle regular task ID
const taskId = parseInt(String(taskIdInput), 10);
if (isNaN(taskId)) {
log('error', `Invalid task ID: ${taskIdInput}`);
- process.exit(1);
+ return null;
}
// Find the task
const task = data.tasks.find(t => t.id === taskId);
if (!task) {
log('error', `Task ${taskId} not found`);
- process.exit(1);
+ return null;
}
// Update the task status
const oldStatus = task.status || 'pending';
task.status = newStatus;
+ const result = {
+ id: taskId.toString(),
+ title: task.title,
+ oldStatus: oldStatus,
+ newStatus: newStatus,
+ subtasks: []
+ };
+
// Automatically update subtasks if the parent task is being marked as done
if (newStatus === 'done' && task.subtasks && Array.isArray(task.subtasks) && task.subtasks.length > 0) {
log('info', `Task ${taskId} has ${task.subtasks.length} subtasks that will be marked as done too.`);
@@ -708,53 +972,202 @@ function setTaskStatus(tasksPath, taskIdInput, newStatus) {
task.subtasks.forEach(subtask => {
const oldSubtaskStatus = subtask.status || 'pending';
subtask.status = newStatus;
- log('info', ` └─ Updated subtask ${taskId}.${subtask.id} status from '${oldSubtaskStatus}' to '${newStatus}'`);
+
+ result.subtasks.push({
+ id: `${taskId}.${subtask.id}`,
+ title: subtask.title,
+ oldStatus: oldSubtaskStatus,
+ newStatus: newStatus
+ });
});
}
- // Save the changes
- writeJSON(tasksPath, data);
- log('info', `Updated task ${taskId} status from '${oldStatus}' to '${newStatus}'`);
+ return result;
+}
+
+/**
+ * Get a colored version of the status string
+ * @param {string} status - The status string
+ * @returns {string} - The colored status string
+ */
+function getStatusWithColor(status) {
+ const statusColor = {
+ 'done': chalk.green,
+ 'completed': chalk.green,
+ 'pending': chalk.yellow,
+ 'in-progress': chalk.blue,
+ 'deferred': chalk.gray
+ }[status] || chalk.white;
+
+ return statusColor(status);
+}
+
+/**
+ * Format dependencies with emoji indicators for completion status
+ * In CLI/console output use colors, in file output use emojis
+ * @param {Array} dependencies - Array of dependency IDs
+ * @param {Array} allTasks - Array of all tasks
+ * @param {boolean} forConsole - Whether this is for console output (true) or file output (false)
+ * @returns {string} - Formatted dependencies with status indicators
+ */
+function formatDependenciesWithStatus(dependencies, allTasks, forConsole = false) {
+ if (!dependencies || dependencies.length === 0) {
+ return 'None';
+ }
+
+ // Create a set of completed task IDs for quick lookup
+ const completedTaskIds = new Set(
+ allTasks
+ .filter(t => t.status === 'done' || t.status === 'completed')
+ .map(t => t.id)
+ );
- // Add call to generate task files
- log('info', "Regenerating task files...");
- generateTaskFiles(tasksPath, path.dirname(tasksPath));
+ // Map each dependency to include its status indicator
+ return dependencies.map(depId => {
+ const isDone = completedTaskIds.has(depId);
+
+ if (forConsole) {
+ // For console output, use colors
+ if (isDone) {
+ return chalk.green(depId.toString());
+ } else {
+ // Check if it's in progress
+ const depTask = allTasks.find(t => t.id === depId);
+ if (depTask && depTask.status === 'in-progress') {
+ return chalk.yellow(depId.toString());
+ } else {
+ return chalk.red(depId.toString());
+ }
+ }
+ } else {
+ // For file output, use emojis
+ const statusEmoji = isDone ? '✅' : '⏱️';
+ return `${depId} ${statusEmoji}`;
+ }
+ }).join(', ');
}
//
// 5) list tasks
//
function listTasks(tasksPath, statusFilter, withSubtasks = false) {
+ displayBanner();
+
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
log('error', "No valid tasks found.");
process.exit(1);
}
- log('info', `Tasks in ${tasksPath}:`);
-
// Filter tasks by status if a filter is provided
const filteredTasks = statusFilter
? data.tasks.filter(t => t.status === statusFilter)
: data.tasks;
+ // Create a table for better visualization
+ const table = new Table({
+ head: [
+ chalk.cyan.bold('ID'),
+ chalk.cyan.bold('Status'),
+ chalk.cyan.bold('Priority'),
+ chalk.cyan.bold('Title')
+ ],
+ colWidths: [8, 15, 12, 60],
+ style: {
+ head: [],
+ border: []
+ }
+ });
+
+ // Status colors
+ const statusColors = {
+ 'done': chalk.green,
+ 'completed': chalk.green,
+ 'pending': chalk.yellow,
+ 'deferred': chalk.gray,
+ 'in-progress': chalk.blue,
+ 'blocked': chalk.red
+ };
+
+ // Priority colors
+ const priorityColors = {
+ 'high': chalk.red.bold,
+ 'medium': chalk.yellow,
+ 'low': chalk.gray
+ };
+
filteredTasks.forEach(t => {
- log('info', `- ID=${t.id}, [${t.status}] ${t.title}`);
+ const statusColor = statusColors[t.status] || chalk.white;
+ const priorityColor = priorityColors[t.priority] || chalk.white;
+
+ table.push([
+ t.id.toString(),
+ statusColor(t.status),
+ priorityColor(t.priority || 'medium'),
+ t.title
+ ]);
// Display subtasks if requested and they exist
if (withSubtasks && t.subtasks && t.subtasks.length > 0) {
t.subtasks.forEach(st => {
- log('info', ` └─ ID=${t.id}.${st.id}, [${st.status || 'pending'}] ${st.title}`);
+ const subtaskStatusColor = statusColors[st.status || 'pending'] || chalk.white;
+ table.push([
+ ` ${t.id}.${st.id}`,
+ subtaskStatusColor(st.status || 'pending'),
+ '',
+ ` ↳ ${st.title}`
+ ]);
});
}
});
- // If no tasks match the filter, show a message
if (filteredTasks.length === 0) {
- log('info', `No tasks found${statusFilter ? ` with status '${statusFilter}'` : ''}.`);
+ console.log(boxen(
+ chalk.yellow(`No tasks found${statusFilter ? ` with status '${statusFilter}'` : ''}.`),
+ { padding: 1, borderColor: 'yellow', borderStyle: 'round' }
+ ));
+ } else {
+ // Display the header with task count and filter info
+ const header = statusFilter
+ ? `Tasks with status: ${chalk.bold(statusFilter)} (${filteredTasks.length} of ${data.tasks.length} total)`
+ : `All Tasks (${filteredTasks.length})`;
+
+ console.log(boxen(chalk.white.bold(header), {
+ padding: { left: 2, right: 2, top: 0, bottom: 0 },
+ margin: { top: 1, bottom: 1 },
+ borderColor: 'blue',
+ borderStyle: 'round'
+ }));
+
+ console.log(table.toString());
+
+ // Summary box
+ const doneCount = data.tasks.filter(t => t.status === 'done' || t.status === 'completed').length;
+ const pendingCount = data.tasks.filter(t => t.status === 'pending').length;
+ const otherCount = data.tasks.length - doneCount - pendingCount;
+
+ const progressPercent = Math.round((doneCount / data.tasks.length) * 100);
+ const progressBar = createProgressBar(progressPercent, 30);
+
+ console.log(boxen(
+ `${chalk.bold('Project Progress:')} ${progressBar} ${progressPercent}%\n` +
+ `${chalk.green.bold('Done:')} ${doneCount} ${chalk.yellow.bold('Pending:')} ${pendingCount} ${chalk.gray.bold('Other:')} ${otherCount}`,
+ { padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
+ ));
}
}
+// Helper function to create a progress bar
+function createProgressBar(percent, length) {
+ const filledLength = Math.round(length * percent / 100);
+ const emptyLength = length - filledLength;
+
+ const filled = '█'.repeat(filledLength);
+ const empty = '░'.repeat(emptyLength);
+
+ return chalk.green(filled) + chalk.gray(empty);
+}
+
//
// 6) expand task with subtasks
//
@@ -1487,7 +1900,7 @@ Format your response as specific, well-defined subtasks that could be assigned t
try {
// Try to use Perplexity first
console.log(chalk.blue('Using Perplexity AI for research-backed subtask generation...'));
- const result = await perplexity.chat.completions.create({
+ const result = await getPerplexityClient().chat.completions.create({
model: PERPLEXITY_MODEL,
messages: [
{
@@ -1558,10 +1971,32 @@ Format your response as specific, well-defined subtasks that could be assigned t
// Main CLI
// ------------------------------------------
async function main() {
+ // Add custom help
+ program.on('--help', function() {
+ displayHelp();
+ });
+
+ if (process.argv.length <= 2) {
+ displayHelp();
+ process.exit(0);
+ }
+
program
.name('dev')
.description('AI-driven development task management')
- .version('1.3.1');
+ .version(() => {
+ // Read version directly from package.json
+ try {
+ const packageJsonPath = path.join(__dirname, '..', 'package.json');
+ if (fs.existsSync(packageJsonPath)) {
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
+ return packageJson.version;
+ }
+ } catch (error) {
+ // Silently fall back to default version
+ }
+ return "1.5.0"; // Default fallback
+ });
program
.command('parse-prd')
@@ -1675,7 +2110,11 @@ async function main() {
const allFlag = options.all;
const numSubtasks = parseInt(options.num, 10);
const forceFlag = options.force;
- const useResearch = options.research !== false; // Default to true unless explicitly disabled
+ // Fix: The issue is here - research should be false when --no-research is specified
+ // This will correctly check if research is false
+ const useResearch = options.research === true;
+ // Debug log to verify the value
+ console.log(`Debug - options.research value: ${options.research}`);
const additionalContext = options.prompt || '';
if (allFlag) {
@@ -1760,566 +2199,150 @@ async function main() {
}
});
+ program
+ .command('add-task')
+ .description('Add a new task to tasks.json using AI')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .option('-p, --prompt <text>', 'Description of the task to add (required)')
+ .option('-d, --dependencies <ids>', 'Comma-separated list of task IDs this task depends on')
+ .option('--priority <priority>', 'Task priority (high, medium, low)', 'medium')
+ .action(async (options) => {
+ const tasksPath = options.file;
+ const prompt = options.prompt;
+ const dependencies = options.dependencies ? options.dependencies.split(',').map(id => parseInt(id.trim(), 10)) : [];
+ const priority = options.priority;
+
+ if (!prompt) {
+ console.error(chalk.red('Error: --prompt parameter is required. Please provide a description of the task.'));
+ process.exit(1);
+ }
+
+ console.log(chalk.blue(`Adding new task with prompt: "${prompt}"`));
+ console.log(chalk.blue(`Tasks file: ${tasksPath}`));
+
+ await addTask(tasksPath, prompt, dependencies, priority);
+ });
+
+ program
+ .command('next')
+ .description('Show the next task to work on based on dependencies and status')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .action(async (options) => {
+ const tasksPath = options.file;
+ await displayNextTask(tasksPath);
+ });
+
+ program
+ .command('show')
+ .description('Show details of a specific task by ID')
+ .argument('[id]', 'Task ID to show')
+ .option('-i, --id <id>', 'Task ID to show (alternative to argument)')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .action(async (id, options) => {
+ const taskId = id || options.id;
+
+ if (!taskId) {
+ console.error(chalk.red('Error: Task ID is required. Provide it as an argument or with --id option.'));
+ console.error(chalk.yellow('Examples:'));
+ console.error(chalk.yellow(' node scripts/dev.js show 1'));
+ console.error(chalk.yellow(' node scripts/dev.js show --id=1'));
+ process.exit(1);
+ }
+
+ const tasksPath = options.file;
+ await displayTaskById(tasksPath, taskId);
+ });
+
+ program
+ .command('add-dependency')
+ .description('Add a dependency to a task')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .option('-i, --id <id>', 'ID of the task to add dependency to')
+ .option('-d, --depends-on <id>', 'ID of the task to add as dependency')
+ .action(async (options) => {
+ const tasksPath = options.file;
+ const taskId = options.id;
+ const dependencyId = options.dependsOn;
+
+ if (!taskId || !dependencyId) {
+ console.error(chalk.red('Error: Both --id and --depends-on parameters are required.'));
+ console.error(chalk.yellow('Example:'));
+ console.error(chalk.yellow(' node scripts/dev.js add-dependency --id=22 --depends-on=21'));
+ process.exit(1);
+ }
+
+ await addDependency(tasksPath, taskId, dependencyId);
+ });
+
+ program
+ .command('remove-dependency')
+ .description('Remove a dependency from a task')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .option('-i, --id <id>', 'ID of the task to remove dependency from')
+ .option('-d, --depends-on <id>', 'ID of the task to remove as dependency')
+ .action(async (options) => {
+ const tasksPath = options.file;
+ const taskId = options.id;
+ const dependencyId = options.dependsOn;
+
+ if (!taskId || !dependencyId) {
+ console.error(chalk.red('Error: Both --id and --depends-on parameters are required.'));
+ console.error(chalk.yellow('Example:'));
+ console.error(chalk.yellow(' node scripts/dev.js remove-dependency --id=22 --depends-on=21'));
+ process.exit(1);
+ }
+
+ await removeDependency(tasksPath, taskId, dependencyId);
+ });
+
+ program
+ .command('*')
+ .description('Handle unknown commands')
+ .action(async (command) => {
+ console.error(chalk.red(`Unknown command: ${command}`));
+ displayHelp();
+ process.exit(1);
+ });
+
await program.parseAsync(process.argv);
}
/**
- * Analyzes task complexity and generates expansion recommendations
- * @param {Object} options Command options
+ * Generates the prompt for the LLM to analyze task complexity
+ * @param {Object} tasksData The tasks data from tasks.json
+ * @returns {string} The prompt for the LLM
*/
-async function analyzeTaskComplexity(options) {
- const tasksPath = options.file || 'tasks/tasks.json';
- const outputPath = options.output || 'scripts/task-complexity-report.json';
- const modelOverride = options.model;
- const thresholdScore = parseFloat(options.threshold || '5');
- const useResearch = options.research || false;
-
- console.log(chalk.blue(`Analyzing task complexity and generating expansion recommendations...`));
-
- try {
- // Read tasks.json
- console.log(chalk.blue(`Reading tasks from ${tasksPath}...`));
- const tasksData = readJSON(tasksPath);
-
- if (!tasksData || !tasksData.tasks || !Array.isArray(tasksData.tasks) || tasksData.tasks.length === 0) {
- throw new Error('No tasks found in the tasks file');
- }
-
- console.log(chalk.blue(`Found ${tasksData.tasks.length} tasks to analyze.`));
-
- // Prepare the prompt for the LLM
- const prompt = generateComplexityAnalysisPrompt(tasksData);
-
- // Start loading indicator
- const loadingIndicator = startLoadingIndicator('Calling AI to analyze task complexity...');
-
- let fullResponse = '';
- let streamingInterval = null;
-
- try {
- // If research flag is set, use Perplexity first
- if (useResearch) {
- try {
- console.log(chalk.blue('Using Perplexity AI for research-backed complexity analysis...'));
-
- // Modify prompt to include more context for Perplexity and explicitly request JSON
- const researchPrompt = `You are conducting a detailed analysis of software development tasks to determine their complexity and how they should be broken down into subtasks.
-
-Please research each task thoroughly, considering best practices, industry standards, and potential implementation challenges before providing your analysis.
+function generateComplexityAnalysisPrompt(tasksData) {
+ return `
+You are an expert software architect and project manager. Your task is to analyze the complexity of development tasks and determine how many subtasks each should be broken down into.
-CRITICAL: You MUST respond ONLY with a valid JSON array. Do not include ANY explanatory text, markdown formatting, or code block markers.
+Below is a list of development tasks with their descriptions and details. For each task:
+1. Assess its complexity on a scale of 1-10
+2. Recommend the optimal number of subtasks (between ${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)})
+3. Suggest a specific prompt that would help generate good subtasks for this task
+4. Explain your reasoning briefly
-${prompt}
+Tasks:
+${tasksData.tasks.map(task => `
+ID: ${task.id}
+Title: ${task.title}
+Description: ${task.description}
+Details: ${task.details}
+Dependencies: ${JSON.stringify(task.dependencies || [])}
+Priority: ${task.priority || 'medium'}
+`).join('\n---\n')}
-Your response must be a clean JSON array only, following exactly this format:
+Analyze each task and return a JSON array with the following structure for each task:
[
{
- "taskId": 1,
- "taskTitle": "Example Task",
- "complexityScore": 7,
- "recommendedSubtasks": 4,
- "expansionPrompt": "Detailed prompt for expansion",
- "reasoning": "Explanation of complexity assessment"
+ "taskId": number,
+ "taskTitle": string,
+ "complexityScore": number (1-10),
+ "recommendedSubtasks": number (${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)}),
+ "expansionPrompt": string (a specific prompt for generating good subtasks),
+ "reasoning": string (brief explanation of your assessment)
},
- // more tasks...
-]
-
-DO NOT include any text before or after the JSON array. No explanations, no markdown formatting.`;
-
- const result = await perplexity.chat.completions.create({
- model: PERPLEXITY_MODEL,
- messages: [
- {
- role: "system",
- content: "You are a technical analysis AI that only responds with clean, valid JSON. Never include explanatory text or markdown formatting in your response."
- },
- {
- role: "user",
- content: researchPrompt
- }
- ],
- temperature: TEMPERATURE,
- max_tokens: MAX_TOKENS,
- });
-
- // Extract the response text
- fullResponse = result.choices[0].message.content;
- console.log(chalk.green('Successfully generated complexity analysis with Perplexity AI'));
-
- if (streamingInterval) clearInterval(streamingInterval);
- stopLoadingIndicator(loadingIndicator);
-
- // ALWAYS log the first part of the response for debugging
- console.log(chalk.gray('Response first 200 chars:'));
- console.log(chalk.gray(fullResponse.substring(0, 200)));
- } catch (perplexityError) {
- console.log(chalk.yellow('Falling back to Claude for complexity analysis...'));
- console.log(chalk.gray('Perplexity error:'), perplexityError.message);
-
- // Continue to Claude as fallback
- await useClaudeForComplexityAnalysis();
- }
- } else {
- // Use Claude directly if research flag is not set
- await useClaudeForComplexityAnalysis();
- }
-
- // Helper function to use Claude for complexity analysis
- async function useClaudeForComplexityAnalysis() {
- // Call the LLM API with streaming
- const stream = await anthropic.messages.create({
- max_tokens: CONFIG.maxTokens,
- model: modelOverride || CONFIG.model,
- temperature: CONFIG.temperature,
- messages: [{ role: "user", content: prompt }],
- system: "You are an expert software architect and project manager analyzing task complexity. Respond only with valid JSON.",
- stream: true
- });
-
- // Update loading indicator to show streaming progress
- let dotCount = 0;
- streamingInterval = setInterval(() => {
- readline.cursorTo(process.stdout, 0);
- process.stdout.write(`Receiving streaming response from Claude${'.'.repeat(dotCount)}`);
- dotCount = (dotCount + 1) % 4;
- }, 500);
-
- // Process the stream
- for await (const chunk of stream) {
- if (chunk.type === 'content_block_delta' && chunk.delta.text) {
- fullResponse += chunk.delta.text;
- }
- }
-
- clearInterval(streamingInterval);
- stopLoadingIndicator(loadingIndicator);
-
- console.log(chalk.green("Completed streaming response from Claude API!"));
- }
-
- // Parse the JSON response
- console.log(chalk.blue(`Parsing complexity analysis...`));
- let complexityAnalysis;
- try {
- // Clean up the response to ensure it's valid JSON
- let cleanedResponse = fullResponse;
-
- // First check for JSON code blocks (common in markdown responses)
- const codeBlockMatch = fullResponse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
- if (codeBlockMatch) {
- cleanedResponse = codeBlockMatch[1];
- console.log(chalk.blue("Extracted JSON from code block"));
- } else {
- // Look for a complete JSON array pattern
- // This regex looks for an array of objects starting with [ and ending with ]
- const jsonArrayMatch = fullResponse.match(/(\[\s*\{\s*"[^"]*"\s*:[\s\S]*\}\s*\])/);
- if (jsonArrayMatch) {
- cleanedResponse = jsonArrayMatch[1];
- console.log(chalk.blue("Extracted JSON array pattern"));
- } else {
- // Try to find the start of a JSON array and capture to the end
- const jsonStartMatch = fullResponse.match(/(\[\s*\{[\s\S]*)/);
- if (jsonStartMatch) {
- cleanedResponse = jsonStartMatch[1];
- // Try to find a proper closing to the array
- const properEndMatch = cleanedResponse.match(/([\s\S]*\}\s*\])/);
- if (properEndMatch) {
- cleanedResponse = properEndMatch[1];
- }
- console.log(chalk.blue("Extracted JSON from start of array to end"));
- }
- }
- }
-
- // Log the cleaned response for debugging
- console.log(chalk.gray("Attempting to parse cleaned JSON..."));
- console.log(chalk.gray("Cleaned response (first 100 chars):"));
- console.log(chalk.gray(cleanedResponse.substring(0, 100)));
- console.log(chalk.gray("Last 100 chars:"));
- console.log(chalk.gray(cleanedResponse.substring(cleanedResponse.length - 100)));
-
- // More aggressive cleaning - strip any non-JSON content at the beginning or end
- const strictArrayMatch = cleanedResponse.match(/(\[\s*\{[\s\S]*\}\s*\])/);
- if (strictArrayMatch) {
- cleanedResponse = strictArrayMatch[1];
- console.log(chalk.blue("Applied strict JSON array extraction"));
- }
-
- try {
- complexityAnalysis = JSON.parse(cleanedResponse);
- } catch (jsonError) {
- console.log(chalk.yellow("Initial JSON parsing failed, attempting to fix common JSON issues..."));
-
- // Try to fix common JSON issues
- // 1. Remove any trailing commas in arrays or objects
- cleanedResponse = cleanedResponse.replace(/,(\s*[\]}])/g, '$1');
-
- // 2. Ensure property names are double-quoted
- cleanedResponse = cleanedResponse.replace(/(\s*)(\w+)(\s*):(\s*)/g, '$1"$2"$3:$4');
-
- // 3. Replace single quotes with double quotes for property values
- cleanedResponse = cleanedResponse.replace(/:(\s*)'([^']*)'(\s*[,}])/g, ':$1"$2"$3');
-
- // 4. Add a special fallback option if we're still having issues
- try {
- complexityAnalysis = JSON.parse(cleanedResponse);
- console.log(chalk.green("Successfully parsed JSON after fixing common issues"));
- } catch (fixedJsonError) {
- console.log(chalk.red("Failed to parse JSON even after fixes, attempting more aggressive cleanup..."));
-
- // Try to extract and process each task individually
- try {
- const taskMatches = cleanedResponse.match(/\{\s*"taskId"\s*:\s*(\d+)[^}]*\}/g);
- if (taskMatches && taskMatches.length > 0) {
- console.log(chalk.yellow(`Found ${taskMatches.length} task objects, attempting to process individually`));
-
- complexityAnalysis = [];
- for (const taskMatch of taskMatches) {
- try {
- // Try to parse each task object individually
- const fixedTask = taskMatch.replace(/,\s*$/, ''); // Remove trailing commas
- const taskObj = JSON.parse(`${fixedTask}`);
- if (taskObj && taskObj.taskId) {
- complexityAnalysis.push(taskObj);
- }
- } catch (taskParseError) {
- console.log(chalk.yellow(`Could not parse individual task: ${taskMatch.substring(0, 30)}...`));
- }
- }
-
- if (complexityAnalysis.length > 0) {
- console.log(chalk.green(`Successfully parsed ${complexityAnalysis.length} tasks individually`));
- } else {
- throw new Error("Could not parse any tasks individually");
- }
- } else {
- throw fixedJsonError;
- }
- } catch (individualError) {
- console.log(chalk.red("All parsing attempts failed"));
- throw jsonError; // throw the original error
- }
- }
- }
-
- // Ensure complexityAnalysis is an array
- if (!Array.isArray(complexityAnalysis)) {
- console.log(chalk.yellow('Response is not an array, checking if it contains an array property...'));
-
- // Handle the case where the response might be an object with an array property
- if (complexityAnalysis.tasks || complexityAnalysis.analysis || complexityAnalysis.results) {
- complexityAnalysis = complexityAnalysis.tasks || complexityAnalysis.analysis || complexityAnalysis.results;
- } else {
- // If no recognizable array property, wrap it as an array if it's an object
- if (typeof complexityAnalysis === 'object' && complexityAnalysis !== null) {
- console.log(chalk.yellow('Converting object to array...'));
- complexityAnalysis = [complexityAnalysis];
- } else {
- throw new Error('Response does not contain a valid array or object');
- }
- }
- }
-
- // Final check to ensure we have an array
- if (!Array.isArray(complexityAnalysis)) {
- throw new Error('Failed to extract an array from the response');
- }
-
- // Check that we have an analysis for each task in the input file
- const taskIds = tasksData.tasks.map(t => t.id);
- const analysisTaskIds = complexityAnalysis.map(a => a.taskId);
- const missingTaskIds = taskIds.filter(id => !analysisTaskIds.includes(id));
-
- if (missingTaskIds.length > 0) {
- console.log(chalk.yellow(`Missing analysis for ${missingTaskIds.length} tasks: ${missingTaskIds.join(', ')}`));
- console.log(chalk.blue(`Attempting to analyze missing tasks...`));
-
- // Create a subset of tasksData with just the missing tasks
- const missingTasks = {
- meta: tasksData.meta,
- tasks: tasksData.tasks.filter(t => missingTaskIds.includes(t.id))
- };
-
- // Generate a prompt for just the missing tasks
- const missingTasksPrompt = generateComplexityAnalysisPrompt(missingTasks);
-
- // Call the same AI model to analyze the missing tasks
- let missingAnalysisResponse = '';
-
- try {
- // Start a new loading indicator
- const missingTasksLoadingIndicator = startLoadingIndicator('Analyzing missing tasks...');
-
- // Use the same AI model as the original analysis
- if (useResearch) {
- // Create the same research prompt but for missing tasks
- const missingTasksResearchPrompt = `You are conducting a detailed analysis of software development tasks to determine their complexity and how they should be broken down into subtasks.
-
-Please research each task thoroughly, considering best practices, industry standards, and potential implementation challenges before providing your analysis.
-
-CRITICAL: You MUST respond ONLY with a valid JSON array. Do not include ANY explanatory text, markdown formatting, or code block markers.
-
-${missingTasksPrompt}
-
-Your response must be a clean JSON array only, following exactly this format:
-[
- {
- "taskId": 1,
- "taskTitle": "Example Task",
- "complexityScore": 7,
- "recommendedSubtasks": 4,
- "expansionPrompt": "Detailed prompt for expansion",
- "reasoning": "Explanation of complexity assessment"
- },
- // more tasks...
-]
-
-DO NOT include any text before or after the JSON array. No explanations, no markdown formatting.`;
-
- const result = await perplexity.chat.completions.create({
- model: PERPLEXITY_MODEL,
- messages: [
- {
- role: "system",
- content: "You are a technical analysis AI that only responds with clean, valid JSON. Never include explanatory text or markdown formatting in your response."
- },
- {
- role: "user",
- content: missingTasksResearchPrompt
- }
- ],
- temperature: TEMPERATURE,
- max_tokens: MAX_TOKENS,
- });
-
- // Extract the response
- missingAnalysisResponse = result.choices[0].message.content;
- } else {
- // Use Claude
- const stream = await anthropic.messages.create({
- max_tokens: CONFIG.maxTokens,
- model: modelOverride || CONFIG.model,
- temperature: CONFIG.temperature,
- messages: [{ role: "user", content: missingTasksPrompt }],
- system: "You are an expert software architect and project manager analyzing task complexity. Respond only with valid JSON.",
- stream: true
- });
-
- // Process the stream
- for await (const chunk of stream) {
- if (chunk.type === 'content_block_delta' && chunk.delta.text) {
- missingAnalysisResponse += chunk.delta.text;
- }
- }
- }
-
- // Stop the loading indicator
- stopLoadingIndicator(missingTasksLoadingIndicator);
-
- // Parse the response using the same parsing logic as before
- let missingAnalysis;
- try {
- // Clean up the response to ensure it's valid JSON (using same logic as above)
- let cleanedResponse = missingAnalysisResponse;
-
- // Use the same JSON extraction logic as before
- // ... (code omitted for brevity, it would be the same as the original parsing)
-
- // First check for JSON code blocks
- const codeBlockMatch = missingAnalysisResponse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
- if (codeBlockMatch) {
- cleanedResponse = codeBlockMatch[1];
- console.log(chalk.blue("Extracted JSON from code block for missing tasks"));
- } else {
- // Look for a complete JSON array pattern
- const jsonArrayMatch = missingAnalysisResponse.match(/(\[\s*\{\s*"[^"]*"\s*:[\s\S]*\}\s*\])/);
- if (jsonArrayMatch) {
- cleanedResponse = jsonArrayMatch[1];
- console.log(chalk.blue("Extracted JSON array pattern for missing tasks"));
- } else {
- // Try to find the start of a JSON array and capture to the end
- const jsonStartMatch = missingAnalysisResponse.match(/(\[\s*\{[\s\S]*)/);
- if (jsonStartMatch) {
- cleanedResponse = jsonStartMatch[1];
- // Try to find a proper closing to the array
- const properEndMatch = cleanedResponse.match(/([\s\S]*\}\s*\])/);
- if (properEndMatch) {
- cleanedResponse = properEndMatch[1];
- }
- console.log(chalk.blue("Extracted JSON from start of array to end for missing tasks"));
- }
- }
- }
-
- // More aggressive cleaning if needed
- const strictArrayMatch = cleanedResponse.match(/(\[\s*\{[\s\S]*\}\s*\])/);
- if (strictArrayMatch) {
- cleanedResponse = strictArrayMatch[1];
- console.log(chalk.blue("Applied strict JSON array extraction for missing tasks"));
- }
-
- try {
- missingAnalysis = JSON.parse(cleanedResponse);
- } catch (jsonError) {
- // Try to fix common JSON issues (same as before)
- cleanedResponse = cleanedResponse.replace(/,(\s*[\]}])/g, '$1');
- cleanedResponse = cleanedResponse.replace(/(\s*)(\w+)(\s*):(\s*)/g, '$1"$2"$3:$4');
- cleanedResponse = cleanedResponse.replace(/:(\s*)'([^']*)'(\s*[,}])/g, ':$1"$2"$3');
-
- try {
- missingAnalysis = JSON.parse(cleanedResponse);
- console.log(chalk.green("Successfully parsed JSON for missing tasks after fixing common issues"));
- } catch (fixedJsonError) {
- // Try the individual task extraction as a last resort
- console.log(chalk.red("Failed to parse JSON for missing tasks, attempting individual extraction..."));
-
- const taskMatches = cleanedResponse.match(/\{\s*"taskId"\s*:\s*(\d+)[^}]*\}/g);
- if (taskMatches && taskMatches.length > 0) {
- console.log(chalk.yellow(`Found ${taskMatches.length} task objects, attempting to process individually`));
-
- missingAnalysis = [];
- for (const taskMatch of taskMatches) {
- try {
- const fixedTask = taskMatch.replace(/,\s*$/, '');
- const taskObj = JSON.parse(`${fixedTask}`);
- if (taskObj && taskObj.taskId) {
- missingAnalysis.push(taskObj);
- }
- } catch (taskParseError) {
- console.log(chalk.yellow(`Could not parse individual task: ${taskMatch.substring(0, 30)}...`));
- }
- }
-
- if (missingAnalysis.length === 0) {
- throw new Error("Could not parse any missing tasks");
- }
- } else {
- throw fixedJsonError;
- }
- }
- }
-
- // Ensure it's an array
- if (!Array.isArray(missingAnalysis)) {
- if (missingAnalysis && typeof missingAnalysis === 'object') {
- missingAnalysis = [missingAnalysis];
- } else {
- throw new Error("Missing tasks analysis is not an array or object");
- }
- }
-
- // Add the missing analyses to the main analysis array
- console.log(chalk.green(`Successfully analyzed ${missingAnalysis.length} missing tasks`));
- complexityAnalysis = [...complexityAnalysis, ...missingAnalysis];
-
- // Re-check for missing tasks
- const updatedAnalysisTaskIds = complexityAnalysis.map(a => a.taskId);
- const stillMissingTaskIds = taskIds.filter(id => !updatedAnalysisTaskIds.includes(id));
-
- if (stillMissingTaskIds.length > 0) {
- console.log(chalk.yellow(`Warning: Still missing analysis for ${stillMissingTaskIds.length} tasks: ${stillMissingTaskIds.join(', ')}`));
- } else {
- console.log(chalk.green(`All tasks now have complexity analysis!`));
- }
- } catch (error) {
- console.error(chalk.red(`Error analyzing missing tasks: ${error.message}`));
- console.log(chalk.yellow(`Continuing with partial analysis...`));
- }
- } catch (error) {
- console.error(chalk.red(`Error during retry for missing tasks: ${error.message}`));
- console.log(chalk.yellow(`Continuing with partial analysis...`));
- }
- }
- } catch (error) {
- console.error(chalk.red(`Failed to parse LLM response as JSON: ${error.message}`));
- if (CONFIG.debug) {
- console.debug(chalk.gray(`Raw response: ${fullResponse}`));
- }
- throw new Error('Invalid response format from LLM. Expected JSON.');
- }
-
- // Create the final report
- const report = {
- meta: {
- generatedAt: new Date().toISOString(),
- tasksAnalyzed: tasksData.tasks.length,
- thresholdScore: thresholdScore,
- projectName: tasksData.meta?.projectName || 'Your Project Name',
- usedResearch: useResearch
- },
- complexityAnalysis: complexityAnalysis
- };
-
- // Write the report to file
- console.log(chalk.blue(`Writing complexity report to ${outputPath}...`));
- writeJSON(outputPath, report);
-
- console.log(chalk.green(`Task complexity analysis complete. Report written to ${outputPath}`));
-
- // Display a summary of findings
- const highComplexity = complexityAnalysis.filter(t => t.complexityScore >= 8).length;
- const mediumComplexity = complexityAnalysis.filter(t => t.complexityScore >= 5 && t.complexityScore < 8).length;
- const lowComplexity = complexityAnalysis.filter(t => t.complexityScore < 5).length;
- const totalAnalyzed = complexityAnalysis.length;
-
- console.log('\nComplexity Analysis Summary:');
- console.log('----------------------------');
- console.log(`Tasks in input file: ${tasksData.tasks.length}`);
- console.log(`Tasks successfully analyzed: ${totalAnalyzed}`);
- console.log(`High complexity tasks: ${highComplexity}`);
- console.log(`Medium complexity tasks: ${mediumComplexity}`);
- console.log(`Low complexity tasks: ${lowComplexity}`);
- console.log(`Sum verification: ${highComplexity + mediumComplexity + lowComplexity} (should equal ${totalAnalyzed})`);
- console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`);
- console.log(`\nSee ${outputPath} for the full report and expansion commands.`);
-
- } catch (error) {
- if (streamingInterval) clearInterval(streamingInterval);
- stopLoadingIndicator(loadingIndicator);
- throw error;
- }
- } catch (error) {
- console.error(chalk.red(`Error analyzing task complexity: ${error.message}`));
- process.exit(1);
- }
-}
-
-/**
- * Generates the prompt for the LLM to analyze task complexity
- * @param {Object} tasksData The tasks data from tasks.json
- * @returns {string} The prompt for the LLM
- */
-function generateComplexityAnalysisPrompt(tasksData) {
- return `
-You are an expert software architect and project manager. Your task is to analyze the complexity of development tasks and determine how many subtasks each should be broken down into.
-
-Below is a list of development tasks with their descriptions and details. For each task:
-1. Assess its complexity on a scale of 1-10
-2. Recommend the optimal number of subtasks (between ${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)})
-3. Suggest a specific prompt that would help generate good subtasks for this task
-4. Explain your reasoning briefly
-
-Tasks:
-${tasksData.tasks.map(task => `
-ID: ${task.id}
-Title: ${task.title}
-Description: ${task.description}
-Details: ${task.details}
-Dependencies: ${JSON.stringify(task.dependencies || [])}
-Priority: ${task.priority || 'medium'}
-`).join('\n---\n')}
-
-Analyze each task and return a JSON array with the following structure for each task:
-[
- {
- "taskId": number,
- "taskTitle": string,
- "complexityScore": number (1-10),
- "recommendedSubtasks": number (${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)}),
- "expansionPrompt": string (a specific prompt for generating good subtasks),
- "reasoning": string (brief explanation of your assessment)
- },
- ...
+ ...
]
IMPORTANT: Make sure to include an analysis for EVERY task listed above, with the correct taskId matching each task's ID.
@@ -2374,6 +2397,8 @@ function findTaskInComplexityReport(report, taskId) {
// Clear subtasks from tasks
//
function clearSubtasks(tasksPath, taskIds) {
+ displayBanner();
+
log('info', `Reading tasks from ${tasksPath}...`);
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
@@ -2381,9 +2406,25 @@ function clearSubtasks(tasksPath, taskIds) {
process.exit(1);
}
+ console.log(boxen(
+ chalk.white.bold('Clearing Subtasks'),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ ));
+
// Handle multiple task IDs (comma-separated)
const taskIdArray = taskIds.split(',').map(id => id.trim());
let clearedCount = 0;
+
+ // Create a summary table for the cleared subtasks
+ const summaryTable = new Table({
+ head: [
+ chalk.cyan.bold('Task ID'),
+ chalk.cyan.bold('Task Title'),
+ chalk.cyan.bold('Subtasks Cleared')
+ ],
+ colWidths: [10, 50, 20],
+ style: { head: [], border: [] }
+ });
taskIdArray.forEach(taskId => {
const id = parseInt(taskId, 10);
@@ -2400,6 +2441,11 @@ function clearSubtasks(tasksPath, taskIds) {
if (!task.subtasks || task.subtasks.length === 0) {
log('info', `Task ${id} has no subtasks to clear`);
+ summaryTable.push([
+ id.toString(),
+ truncate(task.title, 47),
+ chalk.yellow('No subtasks')
+ ]);
return;
}
@@ -2407,21 +2453,865 @@ function clearSubtasks(tasksPath, taskIds) {
task.subtasks = [];
clearedCount++;
log('info', `Cleared ${subtaskCount} subtasks from task ${id}`);
+
+ summaryTable.push([
+ id.toString(),
+ truncate(task.title, 47),
+ chalk.green(`${subtaskCount} subtasks cleared`)
+ ]);
});
if (clearedCount > 0) {
writeJSON(tasksPath, data);
- log('info', `Successfully cleared subtasks from ${clearedCount} task(s)`);
-
+
+ // Show summary table
+ console.log(boxen(
+ chalk.white.bold('Subtask Clearing Summary:'),
+ { padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'blue', borderStyle: 'round' }
+ ));
+ console.log(summaryTable.toString());
+
// Regenerate task files to reflect changes
log('info', "Regenerating task files...");
generateTaskFiles(tasksPath, path.dirname(tasksPath));
+
+ // Success message
+ console.log(boxen(
+ chalk.green(`Successfully cleared subtasks from ${chalk.bold(clearedCount)} task(s)`),
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ // Next steps suggestion
+ console.log(boxen(
+ chalk.white.bold('Next Steps:') + '\n\n' +
+ `${chalk.cyan('1.')} Run ${chalk.yellow('node scripts/dev.js expand --id=<id>')} to generate new subtasks\n` +
+ `${chalk.cyan('2.')} Run ${chalk.yellow('node scripts/dev.js list --with-subtasks')} to verify changes`,
+ { padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ } else {
+ console.log(boxen(
+ chalk.yellow('No subtasks were cleared'),
+ { padding: 1, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
+ ));
+ }
+}
+
+// ----------------------------------------
+// Custom help display
+// ----------------------------------------
+function displayHelp() {
+ displayBanner();
+
+ console.log(boxen(
+ chalk.white.bold('Claude Task Master CLI'),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ ));
+
+ // Command categories
+ const commandCategories = [
+ {
+ title: 'Task Generation',
+ color: 'cyan',
+ commands: [
+ { name: 'parse-prd', args: '--input=<file.txt> [--tasks=10]',
+ desc: 'Generate tasks from a PRD document' },
+ { name: 'generate', args: '',
+ desc: 'Create individual task files from tasks.json' }
+ ]
+ },
+ {
+ title: 'Task Management',
+ color: 'green',
+ commands: [
+ { name: 'list', args: '[--status=<status>] [--with-subtasks]',
+ desc: 'List all tasks with their status' },
+ { name: 'set-status', args: '--id=<id> --status=<status>',
+ desc: 'Update task status (done, pending, etc.)' },
+ { name: 'update', args: '--from=<id> --prompt="<context>"',
+ desc: 'Update tasks based on new requirements' },
+ { name: 'add-dependency', args: '--id=<id> --depends-on=<id>',
+ desc: 'Add a dependency to a task' },
+ { name: 'remove-dependency', args: '--id=<id> --depends-on=<id>',
+ desc: 'Remove a dependency from a task' }
+ ]
+ },
+ {
+ title: 'Task Analysis & Detail',
+ color: 'yellow',
+ commands: [
+ { name: 'analyze-complexity', args: '[--research] [--threshold=5]',
+ desc: 'Analyze tasks and generate expansion recommendations' },
+ { name: 'expand', args: '--id=<id> [--num=5] [--research] [--prompt="<context>"]',
+ desc: 'Break down tasks into detailed subtasks' },
+ { name: 'expand --all', args: '[--force] [--research]',
+ desc: 'Expand all pending tasks with subtasks' },
+ { name: 'clear-subtasks', args: '--id=<id>',
+ desc: 'Remove subtasks from specified tasks' }
+ ]
+ }
+ ];
+
+ // Display each category
+ commandCategories.forEach(category => {
+ console.log(boxen(
+ chalk[category.color].bold(category.title),
+ {
+ padding: { left: 2, right: 2, top: 0, bottom: 0 },
+ margin: { top: 1, bottom: 0 },
+ borderColor: category.color,
+ borderStyle: 'round'
+ }
+ ));
+
+ const commandTable = new Table({
+ colWidths: [20, 40, 50],
+ chars: {
+ 'top': '', 'top-mid': '', 'top-left': '', 'top-right': '',
+ 'bottom': '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
+ 'left': '', 'left-mid': '', 'mid': '', 'mid-mid': '',
+ 'right': '', 'right-mid': '', 'middle': ' '
+ },
+ style: { border: [], 'padding-left': 4 }
+ });
+
+ category.commands.forEach(cmd => {
+ commandTable.push([
+ chalk.bold(cmd.name),
+ chalk.blue(cmd.args),
+ cmd.desc
+ ]);
+ });
+
+ console.log(commandTable.toString());
+ });
+
+ // Environment variables section
+ console.log(boxen(
+ chalk.magenta.bold('Environment Variables'),
+ {
+ padding: { left: 2, right: 2, top: 0, bottom: 0 },
+ margin: { top: 1, bottom: 0 },
+ borderColor: 'magenta',
+ borderStyle: 'round'
+ }
+ ));
+
+ const envTable = new Table({
+ colWidths: [25, 20, 65],
+ chars: {
+ 'top': '', 'top-mid': '', 'top-left': '', 'top-right': '',
+ 'bottom': '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
+ 'left': '', 'left-mid': '', 'mid': '', 'mid-mid': '',
+ 'right': '', 'right-mid': '', 'middle': ' '
+ },
+ style: { border: [], 'padding-left': 4 }
+ });
+
+ envTable.push(
+ [chalk.bold('ANTHROPIC_API_KEY'), chalk.red('Required'), 'Your Anthropic API key for Claude'],
+ [chalk.bold('MODEL'), chalk.gray('Optional'), `Claude model to use (default: ${MODEL})`],
+ [chalk.bold('PERPLEXITY_API_KEY'), chalk.gray('Optional'), 'API key for research-backed features'],
+ [chalk.bold('PROJECT_NAME'), chalk.gray('Optional'), `Project name in metadata (default: ${CONFIG.projectName})`]
+ );
+
+ console.log(envTable.toString());
+
+ // Example usage section
+ console.log(boxen(
+ chalk.white.bold('Example Workflow'),
+ {
+ padding: 1,
+ margin: { top: 1, bottom: 1 },
+ borderColor: 'white',
+ borderStyle: 'round'
+ }
+ ));
+
+ console.log(chalk.cyan(' 1. Generate tasks:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js parse-prd --input=prd.txt')}`);
+ console.log(chalk.cyan(' 2. Generate task files:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js generate')}`);
+ console.log(chalk.cyan(' 3. Analyze task complexity:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js analyze-complexity --research')}`);
+ console.log(chalk.cyan(' 4. Break down complex tasks:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js expand --id=3 --research')}`);
+ console.log(chalk.cyan(' 5. Track progress:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js list --with-subtasks')}`);
+ console.log(chalk.cyan(' 6. Update task status:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js set-status --id=1 --status=done')}`);
+
+ console.log('\n');
+}
+
+async function addTask(tasksPath, prompt, dependencies = [], priority = 'medium') {
+ displayBanner();
+
+ // Read the existing tasks
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "Invalid or missing tasks.json.");
+ process.exit(1);
+ }
+
+ // Find the highest task ID to determine the next ID
+ const highestId = Math.max(...data.tasks.map(t => t.id));
+ const newTaskId = highestId + 1;
+
+ console.log(boxen(
+ chalk.white.bold(`Creating New Task #${newTaskId}`),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ ));
+
+ // Create the system prompt for Claude
+ const systemPrompt = "You are a helpful assistant that creates well-structured tasks for a software development project. Generate a single new task based on the user's description.";
+
+ // Create the user prompt with context from existing tasks
+ let contextTasks = '';
+ if (dependencies.length > 0) {
+ // Provide context for the dependent tasks
+ const dependentTasks = data.tasks.filter(t => dependencies.includes(t.id));
+ contextTasks = `\nThis task depends on the following tasks:\n${dependentTasks.map(t =>
+ `- Task ${t.id}: ${t.title} - ${t.description}`).join('\n')}`;
+ } else {
+ // Provide a few recent tasks as context
+ const recentTasks = [...data.tasks].sort((a, b) => b.id - a.id).slice(0, 3);
+ contextTasks = `\nRecent tasks in the project:\n${recentTasks.map(t =>
+ `- Task ${t.id}: ${t.title} - ${t.description}`).join('\n')}`;
+ }
+
+ const taskStructure = `
+ {
+ "title": "Task title goes here",
+ "description": "A concise one or two sentence description of what the task involves",
+ "details": "In-depth details including specifics on implementation, considerations, and anything important for the developer to know. This should be detailed enough to guide implementation.",
+ "testStrategy": "A detailed approach for verifying the task has been correctly implemented. Include specific test cases or validation methods."
+ }`;
+
+ const userPrompt = `Create a comprehensive new task (Task #${newTaskId}) for a software development project based on this description: "${prompt}"
+
+ ${contextTasks}
+
+ Return your answer as a single JSON object with the following structure:
+ ${taskStructure}
+
+ Don't include the task ID, status, dependencies, or priority as those will be added automatically.
+ Make sure the details and test strategy are thorough and specific.
+
+ IMPORTANT: Return ONLY the JSON object, nothing else.`;
+
+ // Start the loading indicator
+ const loadingIndicator = startLoadingIndicator('Generating new task with Claude AI...');
+
+ let fullResponse = '';
+ let streamingInterval = null;
+
+ try {
+ // Call Claude with streaming enabled
+ const stream = await anthropic.messages.create({
+ max_tokens: CONFIG.maxTokens,
+ model: CONFIG.model,
+ temperature: CONFIG.temperature,
+ messages: [{ role: "user", content: userPrompt }],
+ system: systemPrompt,
+ stream: true
+ });
+
+ // Update loading indicator to show streaming progress
+ let dotCount = 0;
+ streamingInterval = setInterval(() => {
+ readline.cursorTo(process.stdout, 0);
+ process.stdout.write(`Receiving streaming response from Claude${'.'.repeat(dotCount)}`);
+ dotCount = (dotCount + 1) % 4;
+ }, 500);
+
+ // Process the stream
+ for await (const chunk of stream) {
+ if (chunk.type === 'content_block_delta' && chunk.delta.text) {
+ fullResponse += chunk.delta.text;
+ }
+ }
+
+ if (streamingInterval) clearInterval(streamingInterval);
+ stopLoadingIndicator(loadingIndicator);
+
+ log('info', "Completed streaming response from Claude API!");
+ log('debug', `Streaming response length: ${fullResponse.length} characters`);
+
+ // Parse the response - handle potential JSON formatting issues
+ let taskData;
+ try {
+ // Check if the response is wrapped in a code block
+ const jsonMatch = fullResponse.match(/```(?:json)?([^`]+)```/);
+ const jsonContent = jsonMatch ? jsonMatch[1] : fullResponse;
+
+ // Parse the JSON
+ taskData = JSON.parse(jsonContent);
+
+ // Check that we have the required fields
+ if (!taskData.title || !taskData.description) {
+ throw new Error("Missing required fields in the generated task");
+ }
+ } catch (error) {
+ log('error', "Failed to parse Claude's response as valid task JSON:", error);
+ log('debug', "Response content:", fullResponse);
+ process.exit(1);
+ }
+
+ // Create the new task object
+ const newTask = {
+ id: newTaskId,
+ title: taskData.title,
+ description: taskData.description,
+ status: "pending",
+ dependencies: dependencies,
+ priority: priority,
+ details: taskData.details || "",
+ testStrategy: taskData.testStrategy || "Manually verify the implementation works as expected."
+ };
+
+ // Add the new task to the tasks array
+ data.tasks.push(newTask);
+
+ // Write the updated tasks back to the file
+ writeJSON(tasksPath, data);
+
+ // Show success message
+ const successBox = boxen(
+ chalk.green(`Successfully added new task #${newTaskId}:\n`) +
+ chalk.white.bold(newTask.title) + "\n\n" +
+ chalk.white(newTask.description),
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ );
+ console.log(successBox);
+
+ // Next steps suggestion
+ console.log(boxen(
+ chalk.white.bold('Next Steps:') + '\n\n' +
+ `${chalk.cyan('1.')} Run ${chalk.yellow('node scripts/dev.js generate')} to update task files\n` +
+ `${chalk.cyan('2.')} Run ${chalk.yellow('node scripts/dev.js expand --id=' + newTaskId)} to break it down into subtasks\n` +
+ `${chalk.cyan('3.')} Run ${chalk.yellow('node scripts/dev.js list --with-subtasks')} to see all tasks`,
+ { padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ return newTaskId;
+ } catch (error) {
+ if (streamingInterval) clearInterval(streamingInterval);
+ stopLoadingIndicator(loadingIndicator);
+ log('error', "Error generating task:", error.message);
+ process.exit(1);
+ }
+}
+
+/**
+ * Find the next pending task based on dependencies
+ * @param {Object[]} tasks - The array of tasks
+ * @returns {Object|null} The next task to work on or null if no eligible tasks
+ */
+function findNextTask(tasks) {
+ // Get all completed task IDs
+ const completedTaskIds = new Set(
+ tasks
+ .filter(t => t.status === 'done' || t.status === 'completed')
+ .map(t => t.id)
+ );
+
+ // Filter for pending tasks whose dependencies are all satisfied
+ const eligibleTasks = tasks.filter(task =>
+ (task.status === 'pending' || task.status === 'in-progress') &&
+ task.dependencies && // Make sure dependencies array exists
+ task.dependencies.every(depId => completedTaskIds.has(depId))
+ );
+
+ if (eligibleTasks.length === 0) {
+ return null;
+ }
+
+ // Sort eligible tasks by:
+ // 1. Priority (high > medium > low)
+ // 2. Dependencies count (fewer dependencies first)
+ // 3. ID (lower ID first)
+ const priorityValues = { 'high': 3, 'medium': 2, 'low': 1 };
+
+ const nextTask = eligibleTasks.sort((a, b) => {
+ // Sort by priority first
+ const priorityA = priorityValues[a.priority || 'medium'] || 2;
+ const priorityB = priorityValues[b.priority || 'medium'] || 2;
+
+ if (priorityB !== priorityA) {
+ return priorityB - priorityA; // Higher priority first
+ }
+
+ // If priority is the same, sort by dependency count
+ if (a.dependencies && b.dependencies && a.dependencies.length !== b.dependencies.length) {
+ return a.dependencies.length - b.dependencies.length; // Fewer dependencies first
+ }
+
+ // If dependency count is the same, sort by ID
+ return a.id - b.id; // Lower ID first
+ })[0]; // Return the first (highest priority) task
+
+ return nextTask;
+}
+
+/**
+ * Display the next task to work on
+ * @param {string} tasksPath - Path to the tasks.json file
+ */
+async function displayNextTask(tasksPath) {
+ displayBanner();
+
+ // Read the tasks file
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "No valid tasks found.");
+ process.exit(1);
+ }
+
+ // Find the next task
+ const nextTask = findNextTask(data.tasks);
+
+ if (!nextTask) {
+ console.log(boxen(
+ chalk.yellow('No eligible tasks found!\n\n') +
+ 'All pending tasks have unsatisfied dependencies, or all tasks are completed.',
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
+ ));
+ return;
+ }
+
+ // Display the task in a nice format
+ console.log(boxen(
+ chalk.white.bold(`Next Task: #${nextTask.id} - ${nextTask.title}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+
+ // Create a table with task details
+ const taskTable = new Table({
+ style: { head: [], border: [] },
+ colWidths: [15, 75] // Adjusted column widths to be more reasonable
+ });
+
+ // Priority with color
+ const priorityColors = {
+ 'high': chalk.red.bold,
+ 'medium': chalk.yellow,
+ 'low': chalk.gray
+ };
+ const priorityColor = priorityColors[nextTask.priority || 'medium'] || chalk.white;
+
+ // Add task details to table
+ taskTable.push(
+ [chalk.cyan.bold('ID:'), nextTask.id.toString()],
+ [chalk.cyan.bold('Title:'), nextTask.title],
+ [chalk.cyan.bold('Priority:'), priorityColor(nextTask.priority || 'medium')],
+ [chalk.cyan.bold('Dependencies:'), formatDependenciesWithStatus(nextTask.dependencies, data.tasks, true)],
+ [chalk.cyan.bold('Description:'), nextTask.description]
+ );
+
+ console.log(taskTable.toString());
+
+ // If task has details, show them in a separate box
+ if (nextTask.details && nextTask.details.trim().length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Implementation Details:') + '\n\n' +
+ nextTask.details,
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+ }
+
+ // Show subtasks if they exist
+ if (nextTask.subtasks && nextTask.subtasks.length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Subtasks'),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, margin: { top: 1, bottom: 0 }, borderColor: 'magenta', borderStyle: 'round' }
+ ));
+
+ // Create a table for subtasks
+ const subtaskTable = new Table({
+ head: [
+ chalk.magenta.bold('ID'),
+ chalk.magenta.bold('Status'),
+ chalk.magenta.bold('Title')
+ ],
+ colWidths: [6, 12, 65], // Reduced column widths
+ style: { head: [], border: [] }
+ });
+
+ // Add subtasks to table
+ nextTask.subtasks.forEach(st => {
+ const statusColor = {
+ 'done': chalk.green,
+ 'completed': chalk.green,
+ 'pending': chalk.yellow,
+ 'in-progress': chalk.blue
+ }[st.status || 'pending'] || chalk.white;
+
+ subtaskTable.push([
+ `${nextTask.id}.${st.id}`,
+ statusColor(st.status || 'pending'),
+ st.title
+ ]);
+ });
+
+ console.log(subtaskTable.toString());
} else {
- log('info', "No subtasks were cleared");
+ // Suggest expanding if no subtasks
+ console.log(boxen(
+ chalk.yellow('No subtasks found. Consider breaking down this task:') + '\n' +
+ chalk.white(`Run: ${chalk.cyan(`node scripts/dev.js expand --id=${nextTask.id}`)}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
}
+
+ // Show action suggestions
+ console.log(boxen(
+ chalk.white.bold('Suggested Actions:') + '\n' +
+ `${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`node scripts/dev.js set-status --id=${nextTask.id} --status=in-progress`)}\n` +
+ `${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`node scripts/dev.js set-status --id=${nextTask.id} --status=done`)}\n` +
+ (nextTask.subtasks && nextTask.subtasks.length > 0
+ ? `${chalk.cyan('3.')} Update subtask status: ${chalk.yellow(`node scripts/dev.js set-status --id=${nextTask.id}.1 --status=done`)}`
+ : `${chalk.cyan('3.')} Break down into subtasks: ${chalk.yellow(`node scripts/dev.js expand --id=${nextTask.id}`)}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
}
+/**
+ * Find a task by its ID
+ * @param {Array} tasks - The array of tasks from tasks.json
+ * @param {string|number} taskId - The ID of the task to find (can be a subtask ID like "1.1")
+ * @returns {Object|null} - The found task or null if not found
+ */
+function findTaskById(tasks, taskId) {
+ // Convert to string for comparison
+ const idStr = String(taskId);
+
+ // Check if it's a subtask ID (contains a dot)
+ if (idStr.includes('.')) {
+ const [parentId, subtaskId] = idStr.split('.');
+
+ // Find the parent task
+ const parentTask = tasks.find(t => String(t.id) === parentId);
+
+ // If parent found and has subtasks, find the specific subtask
+ if (parentTask && parentTask.subtasks && parentTask.subtasks.length > 0) {
+ const subtask = parentTask.subtasks.find(st => String(st.id) === subtaskId);
+ if (subtask) {
+ // Create a copy with parent information
+ return {
+ ...subtask,
+ parentId: parentTask.id,
+ parentTitle: parentTask.title
+ };
+ }
+ }
+ return null;
+ }
+
+ // Regular task ID
+ return tasks.find(t => String(t.id) === idStr) || null;
+}
+
+/**
+ * Display a specific task by ID
+ * @param {string} tasksPath - Path to the tasks.json file
+ * @param {string|number} taskId - The ID of the task to display
+ */
+async function displayTaskById(tasksPath, taskId) {
+ displayBanner();
+
+ // Read the tasks file
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "No valid tasks found.");
+ process.exit(1);
+ }
+
+ // Find the task by ID
+ const task = findTaskById(data.tasks, taskId);
+
+ if (!task) {
+ console.log(boxen(
+ chalk.yellow(`Task with ID ${taskId} not found!`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
+ ));
+ return;
+ }
+
+ // Handle subtask display specially
+ if (task.parentId !== undefined) {
+ console.log(boxen(
+ chalk.white.bold(`Subtask: #${task.parentId}.${task.id} - ${task.title}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'magenta', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+
+ // Create a table with subtask details
+ const taskTable = new Table({
+ style: { head: [], border: [] },
+ colWidths: [15, 75]
+ });
+
+ // Add subtask details to table
+ taskTable.push(
+ [chalk.cyan.bold('ID:'), `${task.parentId}.${task.id}`],
+ [chalk.cyan.bold('Parent Task:'), `#${task.parentId} - ${task.parentTitle}`],
+ [chalk.cyan.bold('Title:'), task.title],
+ [chalk.cyan.bold('Status:'), getStatusWithColor(task.status || 'pending')],
+ [chalk.cyan.bold('Description:'), task.description || 'No description provided.']
+ );
+
+ console.log(taskTable.toString());
+
+ // Show action suggestions for subtask
+ console.log(boxen(
+ chalk.white.bold('Suggested Actions:') + '\n' +
+ `${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.parentId}.${task.id} --status=in-progress`)}\n` +
+ `${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.parentId}.${task.id} --status=done`)}\n` +
+ `${chalk.cyan('3.')} View parent task: ${chalk.yellow(`node scripts/dev.js show --id=${task.parentId}`)}`,
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ return;
+ }
+
+ // Display a regular task
+ console.log(boxen(
+ chalk.white.bold(`Task: #${task.id} - ${task.title}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+
+ // Create a table with task details
+ const taskTable = new Table({
+ style: { head: [], border: [] },
+ colWidths: [15, 75]
+ });
+
+ // Priority with color
+ const priorityColors = {
+ 'high': chalk.red.bold,
+ 'medium': chalk.yellow,
+ 'low': chalk.gray
+ };
+ const priorityColor = priorityColors[task.priority || 'medium'] || chalk.white;
+
+ // Add task details to table
+ taskTable.push(
+ [chalk.cyan.bold('ID:'), task.id.toString()],
+ [chalk.cyan.bold('Title:'), task.title],
+ [chalk.cyan.bold('Status:'), getStatusWithColor(task.status || 'pending')],
+ [chalk.cyan.bold('Priority:'), priorityColor(task.priority || 'medium')],
+ [chalk.cyan.bold('Dependencies:'), formatDependenciesWithStatus(task.dependencies, data.tasks, true)],
+ [chalk.cyan.bold('Description:'), task.description]
+ );
+
+ console.log(taskTable.toString());
+
+ // If task has details, show them in a separate box
+ if (task.details && task.details.trim().length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Implementation Details:') + '\n\n' +
+ task.details,
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+ }
+
+ // Show test strategy if available
+ if (task.testStrategy && task.testStrategy.trim().length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Test Strategy:') + '\n\n' +
+ task.testStrategy,
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+ }
+
+ // Show subtasks if they exist
+ if (task.subtasks && task.subtasks.length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Subtasks'),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, margin: { top: 1, bottom: 0 }, borderColor: 'magenta', borderStyle: 'round' }
+ ));
+
+ // Create a table for subtasks
+ const subtaskTable = new Table({
+ head: [
+ chalk.magenta.bold('ID'),
+ chalk.magenta.bold('Status'),
+ chalk.magenta.bold('Title')
+ ],
+ colWidths: [6, 12, 65],
+ style: { head: [], border: [] }
+ });
+
+ // Add subtasks to table
+ task.subtasks.forEach(st => {
+ const statusColor = {
+ 'done': chalk.green,
+ 'completed': chalk.green,
+ 'pending': chalk.yellow,
+ 'in-progress': chalk.blue
+ }[st.status || 'pending'] || chalk.white;
+
+ subtaskTable.push([
+ `${task.id}.${st.id}`,
+ statusColor(st.status || 'pending'),
+ st.title
+ ]);
+ });
+
+ console.log(subtaskTable.toString());
+ } else {
+ // Suggest expanding if no subtasks
+ console.log(boxen(
+ chalk.yellow('No subtasks found. Consider breaking down this task:') + '\n' +
+ chalk.white(`Run: ${chalk.cyan(`node scripts/dev.js expand --id=${task.id}`)}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+ }
+
+ // Show action suggestions
+ console.log(boxen(
+ chalk.white.bold('Suggested Actions:') + '\n' +
+ `${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.id} --status=in-progress`)}\n` +
+ `${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.id} --status=done`)}\n` +
+ (task.subtasks && task.subtasks.length > 0
+ ? `${chalk.cyan('3.')} Update subtask status: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.id}.1 --status=done`)}`
+ : `${chalk.cyan('3.')} Break down into subtasks: ${chalk.yellow(`node scripts/dev.js expand --id=${task.id}`)}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+}
+
+/**
+ * Add a dependency to a task
+ * @param {string} tasksPath - Path to the tasks.json file
+ * @param {number|string} taskId - ID of the task to add dependency to
+ * @param {number|string} dependencyId - ID of the task to add as dependency
+ */
+async function addDependency(tasksPath, taskId, dependencyId) {
+ // Convert IDs to numbers for consistent comparison
+ const taskIdNum = parseInt(taskId, 10);
+ const dependencyIdNum = parseInt(dependencyId, 10);
+
+ // Read tasks file
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "No valid tasks found.");
+ process.exit(1);
+ }
+
+ // Find the task to modify
+ const taskToModify = data.tasks.find(t => t.id === taskIdNum);
+ if (!taskToModify) {
+ log('error', `Task with ID ${taskIdNum} was not found.`);
+ process.exit(1);
+ }
+
+ // Find the dependency task to ensure it exists
+ const dependencyTask = data.tasks.find(t => t.id === dependencyIdNum);
+ if (!dependencyTask) {
+ log('error', `Dependency task with ID ${dependencyIdNum} was not found.`);
+ process.exit(1);
+ }
+
+ // Prevent circular dependencies
+ if (taskIdNum === dependencyIdNum) {
+ log('error', "A task cannot depend on itself.");
+ process.exit(1);
+ }
+
+ // Initialize dependencies array if it doesn't exist
+ if (!taskToModify.dependencies) {
+ taskToModify.dependencies = [];
+ }
+
+ // Check if dependency already exists
+ if (taskToModify.dependencies.includes(dependencyIdNum)) {
+ log('info', `Task #${taskIdNum} already depends on task #${dependencyIdNum}, no changes made.`);
+ return;
+ }
+
+ // Add the dependency
+ taskToModify.dependencies.push(dependencyIdNum);
+
+ // Sort dependencies for clarity
+ taskToModify.dependencies.sort((a, b) => a - b);
+
+ // Save the updated tasks
+ writeJSON(tasksPath, data);
+
+ // Success message
+ log('success', `Added dependency: Task #${taskIdNum} now depends on task #${dependencyIdNum}`);
+
+ // Display a more visually appealing success message
+ console.log(boxen(
+ chalk.green(`Successfully added dependency:\n\n`) +
+ `Task ${chalk.bold(`#${taskIdNum}`)} now depends on task ${chalk.bold(`#${dependencyIdNum}`)}`,
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ // Regenerate task files
+ await generateTaskFiles(tasksPath, 'tasks');
+}
+
+/**
+ * Remove a dependency from a task
+ * @param {string} tasksPath - Path to the tasks.json file
+ * @param {number|string} taskId - ID of the task to remove dependency from
+ * @param {number|string} dependencyId - ID of the task to remove as dependency
+ */
+async function removeDependency(tasksPath, taskId, dependencyId) {
+ // Convert IDs to numbers for consistent comparison
+ const taskIdNum = parseInt(taskId, 10);
+ const dependencyIdNum = parseInt(dependencyId, 10);
+
+ // Read tasks file
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "No valid tasks found.");
+ process.exit(1);
+ }
+
+ // Find the task to modify
+ const taskToModify = data.tasks.find(t => t.id === taskIdNum);
+ if (!taskToModify) {
+ log('error', `Task with ID ${taskIdNum} was not found.`);
+ process.exit(1);
+ }
+
+ // Check if the task has any dependencies
+ if (!taskToModify.dependencies || taskToModify.dependencies.length === 0) {
+ log('info', `Task #${taskIdNum} has no dependencies, nothing to remove.`);
+ return;
+ }
+
+ // Check if the dependency exists
+ if (!taskToModify.dependencies.includes(dependencyIdNum)) {
+ log('info', `Task #${taskIdNum} does not depend on task #${dependencyIdNum}, no changes made.`);
+ return;
+ }
+
+ // Remove the dependency
+ taskToModify.dependencies = taskToModify.dependencies.filter(depId => depId !== dependencyIdNum);
+
+ // Save the updated tasks
+ writeJSON(tasksPath, data);
+
+ // Success message
+ log('success', `Removed dependency: Task #${taskIdNum} no longer depends on task #${dependencyIdNum}`);
+
+ // Display a more visually appealing success message
+ console.log(boxen(
+ chalk.green(`Successfully removed dependency:\n\n`) +
+ `Task ${chalk.bold(`#${taskIdNum}`)} no longer depends on task ${chalk.bold(`#${dependencyIdNum}`)}`,
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ // Regenerate task files
+ await generateTaskFiles(tasksPath, 'tasks');
+}
+
+
+// At the very end of the file
main().catch(err => {
- log('error', err);
+ console.error('ERROR in main:', err);
process.exit(1);
});
\ No newline at end of file
diff --git a/templates/README-task-master.md b/templates/README-task-master.md
index 2df22a78..168aed00 100644
--- a/templates/README-task-master.md
+++ b/templates/README-task-master.md
@@ -312,6 +312,15 @@ npm run dev -- clear-subtasks --id=1,2,3
npm run dev -- clear-subtasks --all
```
+### Managing Task Dependencies
+```bash
+# Add a dependency to a task
+npm run dev -- add-dependency --id=<id> --depends-on=<id>
+
+# Remove a dependency from a task
+npm run dev -- remove-dependency --id=<id> --depends-on=<id>
+```
+
## Task Structure
Tasks in tasks.json have the following structure:
@@ -326,6 +335,8 @@ Tasks in tasks.json have the following structure:
- `testStrategy`: Approach for verifying the task has been completed correctly
- `subtasks`: List of smaller, more specific tasks that make up the main task
+Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) throughout the system, making it easy to see which prerequisite tasks are done and which still need work.
+
## Best Practices for AI-Driven Development
1. **Start with a detailed PRD**: The more detailed your PRD, the better the generated tasks will be.
@@ -455,3 +466,177 @@ npm run dev -- expand --all
```
This integration ensures that task expansion is informed by thorough complexity analysis, resulting in better subtask organization and more efficient development.
+
+### Finding the Next Task
+
+To find the next task to work on based on dependencies and status:
+
+```bash
+npm run dev -- next
+```
+
+This command:
+- Identifies tasks that are pending/in-progress and have all dependencies satisfied
+- Prioritizes tasks by priority level, dependency count, and task ID
+- Displays comprehensive information about the selected task:
+ - Basic task details (ID, title, priority, dependencies)
+ - Implementation details
+ - Subtasks (if they exist)
+- Provides contextual suggested actions:
+ - Command to mark the task as in-progress
+ - Command to mark the task as done
+ - Commands for working with subtasks
+
+Example Cursor AI interaction:
+```
+What's the next task I should work on?
+```
+
+### Viewing Specific Task Details
+
+To view detailed information about a specific task:
+
+```bash
+npm run dev -- show 1
+```
+or
+```bash
+npm run dev -- show --id=1.2
+```
+
+This command:
+- Displays comprehensive details about a specific task or subtask
+- Shows task status, priority, dependencies, and detailed implementation notes
+- For parent tasks, displays all subtasks and their status
+- For subtasks, shows parent task relationship
+- Provides contextual action suggestions based on the task's state
+- Works with both regular tasks and subtasks (using the format taskId.subtaskId)
+
+Example Cursor AI interaction:
+```
+Show me the details for task 3
+```
+or
+```
+Tell me more about subtask 2.1
+```
+
+## Task Structure
+
+Tasks in tasks.json have the following structure:
+
+- `id`: Unique identifier for the task
+- `title`: Brief, descriptive title of the task
+- `description`: Concise description of what the task involves
+- `status`: Current state of the task (pending, done, deferred)
+- `dependencies`: IDs of tasks that must be completed before this task
+- `priority`: Importance level of the task (high, medium, low)
+- `details`: In-depth instructions for implementing the task
+- `testStrategy`: Approach for verifying the task has been completed correctly
+- `subtasks`: List of smaller, more specific tasks that make up the main task
+
+Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) throughout the system, making it easy to see which prerequisite tasks are done and which still need work.
+
+## Best Practices for AI-Driven Development
+
+1. **Start with a detailed PRD**: The more detailed your PRD, the better the generated tasks will be.
+
+2. **Review generated tasks**: After parsing the PRD, review the tasks to ensure they make sense and have appropriate dependencies.
+
+3. **Follow the dependency chain**: Always respect task dependencies - the Cursor agent will help with this.
+
+4. **Update as you go**: If your implementation diverges from the plan, use the update command to keep future tasks aligned with your current approach.
+
+5. **Break down complex tasks**: Use the expand command to break down complex tasks into manageable subtasks.
+
+6. **Regenerate task files**: After any updates to tasks.json, regenerate the task files to keep them in sync.
+
+7. **Communicate context to the agent**: When asking the Cursor agent to help with a task, provide context about what you're trying to achieve.
+
+## Example Cursor AI Interactions
+
+### Starting a new project
+```
+I've just initialized a new project with Claude Task Master. I have a PRD at scripts/prd.txt.
+Can you help me parse it and set up the initial tasks?
+```
+
+### Working on tasks
+```
+What's the next task I should work on? Please consider dependencies and priorities.
+```
+
+### Implementing a specific task
+```
+I'd like to implement task 4. Can you help me understand what needs to be done and how to approach it?
+```
+
+### Managing subtasks
+```
+I need to regenerate the subtasks for task 3 with a different approach. Can you help me clear and regenerate them?
+```
+
+### Handling changes
+```
+We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
+```
+
+### Completing work
+```
+I've finished implementing the authentication system described in task 2. All tests are passing.
+Please mark it as complete and tell me what I should work on next.
+```
+
+## Documentation
+
+For more detailed documentation on the scripts and command-line options, see the [scripts/README.md](scripts/README.md) file in your initialized project.
+
+## License
+
+MIT
+
+### Analyzing Task Complexity
+
+To analyze the complexity of tasks and automatically generate expansion recommendations:
+
+```bash
+npm run dev -- analyze-complexity
+```
+
+This command:
+- Analyzes each task using AI to assess its complexity
+- Recommends optimal number of subtasks based on configured DEFAULT_SUBTASKS
+- Generates tailored prompts for expanding each task
+- Creates a comprehensive JSON report with ready-to-use commands
+- Saves the report to scripts/task-complexity-report.json by default
+
+Options:
+```bash
+# Save report to a custom location
+npm run dev -- analyze-complexity --output=my-report.json
+
+# Use a specific LLM model
+npm run dev -- analyze-complexity --model=claude-3-opus-20240229
+
+# Set a custom complexity threshold (1-10)
+npm run dev -- analyze-complexity --threshold=6
+
+# Use an alternative tasks file
+npm run dev -- analyze-complexity --file=custom-tasks.json
+
+# Use Perplexity AI for research-backed complexity analysis
+npm run dev -- analyze-complexity --research
+```
+
+The generated report contains:
+- Complexity analysis for each task (scored 1-10)
+- Recommended number of subtasks based on complexity
+- AI-generated expansion prompts customized for each task
+- Ready-to-run expansion commands directly within each task analysis
+
+### Smart Task Expansion
+
+The `expand` command now automatically checks for and uses the complexity report:
+
+```bash
+# Expand a task, using complexity report recommendations if available
\ No newline at end of file
diff --git a/templates/dev.js b/templates/dev.js
index a3f4d7c9..d3f48f84 100755
--- a/templates/dev.js
+++ b/templates/dev.js
@@ -56,6 +56,31 @@
* -> Clears subtasks from specified tasks
* -> Supports comma-separated IDs for clearing multiple tasks: --id=1,2,3,1.1,1.2
* -> Use --all to clear subtasks from all tasks
+ *
+ * 9) next
+ * -> Shows the next task to work on based on dependencies and status
+ * -> Prioritizes tasks whose dependencies are all satisfied
+ * -> Orders eligible tasks by priority, dependency count, and ID
+ * -> Displays comprehensive information about the selected task
+ * -> Shows subtasks if they exist
+ * -> Provides contextual action commands for the next steps
+ *
+ * 10) show [id] or show --id=<id>
+ * -> Shows details of a specific task by ID
+ * -> Displays the same comprehensive information as the 'next' command
+ * -> Handles both regular tasks and subtasks (e.g., 1.2)
+ * -> For subtasks, shows parent task information and link
+ * -> Provides contextual action commands tailored to the specific task
+ *
+ * 11) add-dependency --id=<id> --depends-on=<id>
+ * -> Adds a dependency to a task
+ * -> Checks if the dependency already exists before adding
+ * -> Prevents circular dependencies
+ * -> Automatically sorts dependencies for clarity
+ *
+ * 12) remove-dependency --id=<id> --depends-on=<id>
+ * -> Removes a dependency from a task
+ * -> Checks if the dependency exists before attempting to remove
*
* Usage examples:
* node dev.js parse-prd --input=sample-prd.txt
@@ -73,6 +98,11 @@
* node dev.js analyze-complexity --threshold=6 --model=claude-3.7-sonnet
* node dev.js analyze-complexity --research
* node dev.js clear-subtasks --id=1,2,3 --all
+ * node dev.js next
+ * node dev.js show 1
+ * node dev.js show --id=1.2
+ * node dev.js add-dependency --id=22 --depends-on=21
+ * node dev.js remove-dependency --id=22 --depends-on=21
*/
import fs from 'fs';
@@ -85,6 +115,11 @@ import chalk from 'chalk';
import { Anthropic } from '@anthropic-ai/sdk';
import OpenAI from 'openai';
import dotenv from 'dotenv';
+import figlet from 'figlet';
+import boxen from 'boxen';
+import ora from 'ora';
+import Table from 'cli-table3';
+import gradient from 'gradient-string';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -97,11 +132,20 @@ const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
-// Configure OpenAI client for Perplexity
-const perplexity = new OpenAI({
- apiKey: process.env.PERPLEXITY_API_KEY,
- baseURL: 'https://api.perplexity.ai',
-});
+// Configure OpenAI client for Perplexity - make it lazy
+let perplexity = null;
+function getPerplexityClient() {
+ if (!perplexity) {
+ if (!process.env.PERPLEXITY_API_KEY) {
+ throw new Error("PERPLEXITY_API_KEY environment variable is missing. Set it to use research-backed features.");
+ }
+ perplexity = new OpenAI({
+ apiKey: process.env.PERPLEXITY_API_KEY,
+ baseURL: 'https://api.perplexity.ai',
+ });
+ }
+ return perplexity;
+}
// Model configuration
const MODEL = process.env.MODEL || 'claude-3-7-sonnet-20250219';
@@ -118,8 +162,8 @@ const CONFIG = {
logLevel: process.env.LOG_LEVEL || "info",
defaultSubtasks: parseInt(process.env.DEFAULT_SUBTASKS || "3"),
defaultPriority: process.env.DEFAULT_PRIORITY || "medium",
- projectName: process.env.PROJECT_NAME || "MCP SaaS MVP",
- projectVersion: process.env.PROJECT_VERSION || "1.0.0"
+ projectName: process.env.PROJECT_NAME || "Task Master",
+ projectVersion: "1.5.0" // Hardcoded version - ALWAYS use this value, ignore environment variable
};
// Set up logging based on log level
@@ -130,14 +174,63 @@ const LOG_LEVELS = {
error: 3
};
+// Create a color gradient for the banner
+const coolGradient = gradient(['#00b4d8', '#0077b6', '#03045e']);
+const warmGradient = gradient(['#fb8b24', '#e36414', '#9a031e']);
+
+// Display a fancy banner
+function displayBanner() {
+ console.clear();
+ const bannerText = figlet.textSync('Claude Task Master', {
+ font: 'Standard',
+ horizontalLayout: 'default',
+ verticalLayout: 'default'
+ });
+
+ console.log(coolGradient(bannerText));
+
+ // Read version directly from package.json
+ let version = "1.5.0"; // Default fallback
+ try {
+ const packageJsonPath = path.join(__dirname, '..', 'package.json');
+ if (fs.existsSync(packageJsonPath)) {
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
+ version = packageJson.version;
+ }
+ } catch (error) {
+ // Silently fall back to default version
+ }
+
+ console.log(boxen(chalk.white(`${chalk.bold('Version:')} ${version} ${chalk.bold('Project:')} ${CONFIG.projectName}`), {
+ padding: 1,
+ margin: { top: 0, bottom: 1 },
+ borderStyle: 'round',
+ borderColor: 'cyan'
+ }));
+}
+
function log(level, ...args) {
+ const icons = {
+ debug: chalk.gray('🔍'),
+ info: chalk.blue('ℹ️'),
+ warn: chalk.yellow('⚠️'),
+ error: chalk.red('❌'),
+ success: chalk.green('✅')
+ };
+
if (LOG_LEVELS[level] >= LOG_LEVELS[CONFIG.logLevel]) {
+ const icon = icons[level] || '';
+
if (level === 'error') {
- console.error(...args);
+ console.error(icon, chalk.red(...args));
} else if (level === 'warn') {
- console.warn(...args);
+ console.warn(icon, chalk.yellow(...args));
+ } else if (level === 'success') {
+ console.log(icon, chalk.green(...args));
+ } else if (level === 'info') {
+ console.log(icon, chalk.blue(...args));
} else {
- console.log(...args);
+ console.log(icon, ...args);
}
}
@@ -159,24 +252,21 @@ function writeJSON(filepath, data) {
fs.writeFileSync(filepath, JSON.stringify(data, null, 2), 'utf8');
}
-// Add a simple loading indicator function
+// Replace the simple loading indicator with ora spinner
function startLoadingIndicator(message) {
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
- let i = 0;
+ const spinner = ora({
+ text: message,
+ color: 'cyan',
+ spinner: 'dots'
+ }).start();
- process.stdout.write(`${message} `);
-
- return setInterval(() => {
- readline.cursorTo(process.stdout, message.length + 1);
- process.stdout.write(frames[i]);
- i = (i + 1) % frames.length;
- }, 80);
+ return spinner;
}
-function stopLoadingIndicator(interval) {
- clearInterval(interval);
- readline.cursorTo(process.stdout, 0);
- readline.clearLine(process.stdout, 0);
+function stopLoadingIndicator(spinner) {
+ if (spinner && spinner.stop) {
+ spinner.stop();
+ }
}
async function callClaude(prdContent, prdPath, numTasks, retryCount = 0) {
@@ -424,11 +514,19 @@ function processClaudeResponse(textContent, numTasks, retryCount, prdContent, pr
// 1) parse-prd
//
async function parsePRD(prdPath, tasksPath, numTasks) {
+ displayBanner();
+
if (!fs.existsSync(prdPath)) {
log('error', `PRD file not found: ${prdPath}`);
process.exit(1);
}
+ const headerBox = boxen(
+ chalk.white.bold(`Parsing PRD Document: ${chalk.cyan(path.basename(prdPath))}`),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ );
+ console.log(headerBox);
+
log('info', `Reading PRD file from: ${prdPath}`);
const prdContent = fs.readFileSync(prdPath, 'utf8');
log('info', `PRD file read successfully. Content length: ${prdContent.length} characters`);
@@ -437,9 +535,12 @@ async function parsePRD(prdPath, tasksPath, numTasks) {
log('info', "Calling Claude to generate tasks from PRD...");
try {
+ const loadingSpinner = startLoadingIndicator('Generating tasks with Claude AI');
const claudeResponse = await callClaude(prdContent, prdPath, numTasks);
let tasks = claudeResponse.tasks || [];
- log('info', `Claude generated ${tasks.length} tasks from the PRD`);
+ stopLoadingIndicator(loadingSpinner);
+
+ log('success', `Claude generated ${tasks.length} tasks from the PRD`);
// Limit the number of tasks if specified
if (numTasks && numTasks > 0 && numTasks < tasks.length) {
@@ -462,7 +563,54 @@ async function parsePRD(prdPath, tasksPath, numTasks) {
log('info', `Writing ${tasks.length} tasks to ${tasksPath}...`);
writeJSON(tasksPath, data);
- log('info', `Parsed PRD from '${prdPath}' -> wrote ${tasks.length} tasks to '${tasksPath}'.`);
+
+ // Show success message in a box
+ const successBox = boxen(
+ chalk.green(`Successfully parsed PRD from: ${chalk.cyan(prdPath)}\n`) +
+ chalk.green(`Generated ${chalk.bold(tasks.length)} tasks in: ${chalk.cyan(tasksPath)}`),
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ );
+ console.log(successBox);
+
+ // Show the first few tasks in a table
+ const previewTasks = tasks.slice(0, Math.min(5, tasks.length));
+ const taskTable = new Table({
+ head: [chalk.cyan.bold('ID'), chalk.cyan.bold('Title'), chalk.cyan.bold('Priority')],
+ colWidths: [6, 60, 12],
+ style: { head: [], border: [] }
+ });
+
+ previewTasks.forEach(task => {
+ taskTable.push([
+ task.id.toString(),
+ task.title,
+ chalk.yellow(task.priority || 'medium')
+ ]);
+ });
+
+ if (tasks.length > 5) {
+ taskTable.push([
+ '...',
+ chalk.dim(`${tasks.length - 5} more tasks`),
+ ''
+ ]);
+ }
+
+ console.log(boxen(
+ chalk.white.bold('Task Preview:'),
+ { padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'blue', borderStyle: 'round' }
+ ));
+ console.log(taskTable.toString());
+
+ // Next steps suggestion
+ console.log(boxen(
+ chalk.white.bold('Next Steps:') + '\n\n' +
+ `${chalk.cyan('1.')} Run ${chalk.yellow('node scripts/dev.js generate')} to create individual task files\n` +
+ `${chalk.cyan('2.')} Run ${chalk.yellow('node scripts/dev.js list')} to see all tasks\n` +
+ `${chalk.cyan('3.')} Run ${chalk.yellow('node scripts/dev.js analyze-complexity')} to plan task breakdown`,
+ { padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
} catch (error) {
log('error', "Failed to generate tasks:", error.message);
process.exit(1);
@@ -577,7 +725,7 @@ function generateTaskFiles(tasksPath, outputDir) {
`# Task ID: ${task.id}`,
`# Title: ${task.title}`,
`# Status: ${task.status}`,
- `# Dependencies: ${task.dependencies.join(", ")}`,
+ `# Dependencies: ${formatDependenciesWithStatus(task.dependencies, data.tasks, false)}`,
`# Priority: ${task.priority}`,
`# Description: ${task.description}`,
`# Details:\n${task.details}\n`,
@@ -589,10 +737,14 @@ function generateTaskFiles(tasksPath, outputDir) {
if (task.subtasks && task.subtasks.length > 0) {
contentParts.push(`# Subtasks:`);
task.subtasks.forEach(subtask => {
+ const subtaskDeps = subtask.dependencies
+ ? formatDependenciesWithStatus(subtask.dependencies, data.tasks, false)
+ : "";
+
contentParts.push(`## Subtask ID: ${subtask.id}`);
contentParts.push(`## Title: ${subtask.title}`);
contentParts.push(`## Status: ${subtask.status}`);
- contentParts.push(`## Dependencies: ${subtask.dependencies ? subtask.dependencies.join(", ") : ""}`);
+ contentParts.push(`## Dependencies: ${subtaskDeps}`);
contentParts.push(`## Description: ${subtask.description}`);
if (subtask.acceptanceCriteria) {
contentParts.push(`## Acceptance Criteria:\n${subtask.acceptanceCriteria}\n`);
@@ -612,6 +764,8 @@ function generateTaskFiles(tasksPath, outputDir) {
// 4) set-status
//
function setTaskStatus(tasksPath, taskIdInput, newStatus) {
+ displayBanner();
+
// Validate inputs
if (!taskIdInput || !newStatus) {
log('error', 'Task ID and new status are required');
@@ -625,18 +779,123 @@ function setTaskStatus(tasksPath, taskIdInput, newStatus) {
process.exit(1);
}
+ console.log(boxen(
+ chalk.white.bold(`Updating Task Status to: ${getStatusWithColor(newStatus)}`),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ ));
+
// Handle multiple task IDs (comma-separated)
if (typeof taskIdInput === 'string' && taskIdInput.includes(',')) {
const taskIds = taskIdInput.split(',').map(id => id.trim());
log('info', `Processing multiple task IDs: ${taskIds.join(', ')}`);
+ // Create a summary table for the updates
+ const summaryTable = new Table({
+ head: [
+ chalk.cyan.bold('ID'),
+ chalk.cyan.bold('Title'),
+ chalk.cyan.bold('Old Status'),
+ chalk.cyan.bold('New Status')
+ ],
+ colWidths: [8, 40, 15, 15],
+ style: { head: [], border: [] }
+ });
+
// Process each task ID individually
taskIds.forEach(id => {
- setTaskStatus(tasksPath, id, newStatus);
+ const result = updateSingleTaskStatus(tasksPath, id, newStatus, data);
+ if (result) {
+ summaryTable.push([
+ result.id,
+ truncate(result.title, 37),
+ getStatusWithColor(result.oldStatus),
+ getStatusWithColor(result.newStatus)
+ ]);
+
+ // Add subtask updates if any
+ if (result.subtasks && result.subtasks.length > 0) {
+ result.subtasks.forEach(sub => {
+ summaryTable.push([
+ ` ${sub.id}`,
+ ` ↳ ${truncate(sub.title, 35)}`,
+ getStatusWithColor(sub.oldStatus),
+ getStatusWithColor(sub.newStatus)
+ ]);
+ });
+ }
+ }
});
+
+ // Save the changes
+ writeJSON(tasksPath, data);
+
+ // Regenerate task files
+ log('info', "Regenerating task files...");
+ generateTaskFiles(tasksPath, path.dirname(tasksPath));
+
+ // Show the summary table
+ console.log(boxen(
+ chalk.white.bold('Status Update Summary:'),
+ { padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'blue', borderStyle: 'round' }
+ ));
+ console.log(summaryTable.toString());
+
return;
}
+ // Handle regular task ID or subtask ID
+ const result = updateSingleTaskStatus(tasksPath, taskIdInput, newStatus, data);
+
+ if (result) {
+ // Save the changes
+ writeJSON(tasksPath, data);
+
+ // Regenerate task files
+ log('info', "Regenerating task files...");
+ generateTaskFiles(tasksPath, path.dirname(tasksPath));
+
+ // Show success message
+ const successBox = boxen(
+ chalk.green(`Successfully updated task ${chalk.bold(result.id)} status:\n`) +
+ `From: ${getStatusWithColor(result.oldStatus)}\n` +
+ `To: ${getStatusWithColor(result.newStatus)}`,
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ );
+ console.log(successBox);
+
+ // If subtasks were also updated, show them
+ if (result.subtasks && result.subtasks.length > 0) {
+ const subtaskTable = new Table({
+ head: [
+ chalk.cyan.bold('ID'),
+ chalk.cyan.bold('Title'),
+ chalk.cyan.bold('Old Status'),
+ chalk.cyan.bold('New Status')
+ ],
+ colWidths: [8, 40, 15, 15],
+ style: { head: [], border: [] }
+ });
+
+ result.subtasks.forEach(sub => {
+ subtaskTable.push([
+ sub.id,
+ truncate(sub.title, 37),
+ getStatusWithColor(sub.oldStatus),
+ getStatusWithColor(sub.newStatus)
+ ]);
+ });
+
+ console.log(boxen(
+ chalk.white.bold('Subtasks Also Updated:'),
+ { padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'blue', borderStyle: 'round' }
+ ));
+ console.log(subtaskTable.toString());
+ }
+ }
+}
+
+// Helper function to update a single task status and return details for UI
+function updateSingleTaskStatus(tasksPath, taskIdInput, newStatus, data) {
// Handle subtask IDs (e.g., "1.1")
if (String(taskIdInput).includes('.')) {
const [parentIdStr, subtaskIdStr] = String(taskIdInput).split('.');
@@ -645,62 +904,67 @@ function setTaskStatus(tasksPath, taskIdInput, newStatus) {
if (isNaN(parentId) || isNaN(subtaskId)) {
log('error', `Invalid subtask ID format: ${taskIdInput}`);
- process.exit(1);
+ return null;
}
// Find the parent task
const parentTask = data.tasks.find(t => t.id === parentId);
if (!parentTask) {
log('error', `Parent task ${parentId} not found`);
- process.exit(1);
+ return null;
}
// Ensure subtasks array exists
if (!parentTask.subtasks || !Array.isArray(parentTask.subtasks)) {
log('error', `Parent task ${parentId} has no subtasks array`);
- process.exit(1);
+ return null;
}
// Find and update the subtask
const subtask = parentTask.subtasks.find(st => st.id === subtaskId);
if (!subtask) {
log('error', `Subtask ${subtaskId} not found in task ${parentId}`);
- process.exit(1);
+ return null;
}
// Update the subtask status
const oldStatus = subtask.status || 'pending';
subtask.status = newStatus;
- // Save the changes
- writeJSON(tasksPath, data);
- log('info', `Updated subtask ${parentId}.${subtaskId} status from '${oldStatus}' to '${newStatus}'`);
-
- // Add call to generate task files
- log('info', "Regenerating task files...");
- generateTaskFiles(tasksPath, path.dirname(tasksPath));
-
- return;
+ return {
+ id: `${parentId}.${subtaskId}`,
+ title: subtask.title,
+ oldStatus: oldStatus,
+ newStatus: newStatus
+ };
}
// Handle regular task ID
const taskId = parseInt(String(taskIdInput), 10);
if (isNaN(taskId)) {
log('error', `Invalid task ID: ${taskIdInput}`);
- process.exit(1);
+ return null;
}
// Find the task
const task = data.tasks.find(t => t.id === taskId);
if (!task) {
log('error', `Task ${taskId} not found`);
- process.exit(1);
+ return null;
}
// Update the task status
const oldStatus = task.status || 'pending';
task.status = newStatus;
+ const result = {
+ id: taskId.toString(),
+ title: task.title,
+ oldStatus: oldStatus,
+ newStatus: newStatus,
+ subtasks: []
+ };
+
// Automatically update subtasks if the parent task is being marked as done
if (newStatus === 'done' && task.subtasks && Array.isArray(task.subtasks) && task.subtasks.length > 0) {
log('info', `Task ${taskId} has ${task.subtasks.length} subtasks that will be marked as done too.`);
@@ -708,53 +972,202 @@ function setTaskStatus(tasksPath, taskIdInput, newStatus) {
task.subtasks.forEach(subtask => {
const oldSubtaskStatus = subtask.status || 'pending';
subtask.status = newStatus;
- log('info', ` └─ Updated subtask ${taskId}.${subtask.id} status from '${oldSubtaskStatus}' to '${newStatus}'`);
+
+ result.subtasks.push({
+ id: `${taskId}.${subtask.id}`,
+ title: subtask.title,
+ oldStatus: oldSubtaskStatus,
+ newStatus: newStatus
+ });
});
}
- // Save the changes
- writeJSON(tasksPath, data);
- log('info', `Updated task ${taskId} status from '${oldStatus}' to '${newStatus}'`);
+ return result;
+}
+
+/**
+ * Get a colored version of the status string
+ * @param {string} status - The status string
+ * @returns {string} - The colored status string
+ */
+function getStatusWithColor(status) {
+ const statusColor = {
+ 'done': chalk.green,
+ 'completed': chalk.green,
+ 'pending': chalk.yellow,
+ 'in-progress': chalk.blue,
+ 'deferred': chalk.gray
+ }[status] || chalk.white;
+
+ return statusColor(status);
+}
+
+/**
+ * Format dependencies with emoji indicators for completion status
+ * In CLI/console output use colors, in file output use emojis
+ * @param {Array} dependencies - Array of dependency IDs
+ * @param {Array} allTasks - Array of all tasks
+ * @param {boolean} forConsole - Whether this is for console output (true) or file output (false)
+ * @returns {string} - Formatted dependencies with status indicators
+ */
+function formatDependenciesWithStatus(dependencies, allTasks, forConsole = false) {
+ if (!dependencies || dependencies.length === 0) {
+ return 'None';
+ }
+
+ // Create a set of completed task IDs for quick lookup
+ const completedTaskIds = new Set(
+ allTasks
+ .filter(t => t.status === 'done' || t.status === 'completed')
+ .map(t => t.id)
+ );
- // Add call to generate task files
- log('info', "Regenerating task files...");
- generateTaskFiles(tasksPath, path.dirname(tasksPath));
+ // Map each dependency to include its status indicator
+ return dependencies.map(depId => {
+ const isDone = completedTaskIds.has(depId);
+
+ if (forConsole) {
+ // For console output, use colors
+ if (isDone) {
+ return chalk.green(depId.toString());
+ } else {
+ // Check if it's in progress
+ const depTask = allTasks.find(t => t.id === depId);
+ if (depTask && depTask.status === 'in-progress') {
+ return chalk.yellow(depId.toString());
+ } else {
+ return chalk.red(depId.toString());
+ }
+ }
+ } else {
+ // For file output, use emojis
+ const statusEmoji = isDone ? '✅' : '⏱️';
+ return `${depId} ${statusEmoji}`;
+ }
+ }).join(', ');
}
//
// 5) list tasks
//
function listTasks(tasksPath, statusFilter, withSubtasks = false) {
+ displayBanner();
+
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
log('error', "No valid tasks found.");
process.exit(1);
}
- log('info', `Tasks in ${tasksPath}:`);
-
// Filter tasks by status if a filter is provided
const filteredTasks = statusFilter
? data.tasks.filter(t => t.status === statusFilter)
: data.tasks;
+ // Create a table for better visualization
+ const table = new Table({
+ head: [
+ chalk.cyan.bold('ID'),
+ chalk.cyan.bold('Status'),
+ chalk.cyan.bold('Priority'),
+ chalk.cyan.bold('Title')
+ ],
+ colWidths: [8, 15, 12, 60],
+ style: {
+ head: [],
+ border: []
+ }
+ });
+
+ // Status colors
+ const statusColors = {
+ 'done': chalk.green,
+ 'completed': chalk.green,
+ 'pending': chalk.yellow,
+ 'deferred': chalk.gray,
+ 'in-progress': chalk.blue,
+ 'blocked': chalk.red
+ };
+
+ // Priority colors
+ const priorityColors = {
+ 'high': chalk.red.bold,
+ 'medium': chalk.yellow,
+ 'low': chalk.gray
+ };
+
filteredTasks.forEach(t => {
- log('info', `- ID=${t.id}, [${t.status}] ${t.title}`);
+ const statusColor = statusColors[t.status] || chalk.white;
+ const priorityColor = priorityColors[t.priority] || chalk.white;
+
+ table.push([
+ t.id.toString(),
+ statusColor(t.status),
+ priorityColor(t.priority || 'medium'),
+ t.title
+ ]);
// Display subtasks if requested and they exist
if (withSubtasks && t.subtasks && t.subtasks.length > 0) {
t.subtasks.forEach(st => {
- log('info', ` └─ ID=${t.id}.${st.id}, [${st.status || 'pending'}] ${st.title}`);
+ const subtaskStatusColor = statusColors[st.status || 'pending'] || chalk.white;
+ table.push([
+ ` ${t.id}.${st.id}`,
+ subtaskStatusColor(st.status || 'pending'),
+ '',
+ ` ↳ ${st.title}`
+ ]);
});
}
});
- // If no tasks match the filter, show a message
if (filteredTasks.length === 0) {
- log('info', `No tasks found${statusFilter ? ` with status '${statusFilter}'` : ''}.`);
+ console.log(boxen(
+ chalk.yellow(`No tasks found${statusFilter ? ` with status '${statusFilter}'` : ''}.`),
+ { padding: 1, borderColor: 'yellow', borderStyle: 'round' }
+ ));
+ } else {
+ // Display the header with task count and filter info
+ const header = statusFilter
+ ? `Tasks with status: ${chalk.bold(statusFilter)} (${filteredTasks.length} of ${data.tasks.length} total)`
+ : `All Tasks (${filteredTasks.length})`;
+
+ console.log(boxen(chalk.white.bold(header), {
+ padding: { left: 2, right: 2, top: 0, bottom: 0 },
+ margin: { top: 1, bottom: 1 },
+ borderColor: 'blue',
+ borderStyle: 'round'
+ }));
+
+ console.log(table.toString());
+
+ // Summary box
+ const doneCount = data.tasks.filter(t => t.status === 'done' || t.status === 'completed').length;
+ const pendingCount = data.tasks.filter(t => t.status === 'pending').length;
+ const otherCount = data.tasks.length - doneCount - pendingCount;
+
+ const progressPercent = Math.round((doneCount / data.tasks.length) * 100);
+ const progressBar = createProgressBar(progressPercent, 30);
+
+ console.log(boxen(
+ `${chalk.bold('Project Progress:')} ${progressBar} ${progressPercent}%\n` +
+ `${chalk.green.bold('Done:')} ${doneCount} ${chalk.yellow.bold('Pending:')} ${pendingCount} ${chalk.gray.bold('Other:')} ${otherCount}`,
+ { padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
+ ));
}
}
+// Helper function to create a progress bar
+function createProgressBar(percent, length) {
+ const filledLength = Math.round(length * percent / 100);
+ const emptyLength = length - filledLength;
+
+ const filled = '█'.repeat(filledLength);
+ const empty = '░'.repeat(emptyLength);
+
+ return chalk.green(filled) + chalk.gray(empty);
+}
+
//
// 6) expand task with subtasks
//
@@ -1487,7 +1900,7 @@ Format your response as specific, well-defined subtasks that could be assigned t
try {
// Try to use Perplexity first
console.log(chalk.blue('Using Perplexity AI for research-backed subtask generation...'));
- const result = await perplexity.chat.completions.create({
+ const result = await getPerplexityClient().chat.completions.create({
model: PERPLEXITY_MODEL,
messages: [
{
@@ -1558,10 +1971,32 @@ Format your response as specific, well-defined subtasks that could be assigned t
// Main CLI
// ------------------------------------------
async function main() {
+ // Add custom help
+ program.on('--help', function() {
+ displayHelp();
+ });
+
+ if (process.argv.length <= 2) {
+ displayHelp();
+ process.exit(0);
+ }
+
program
.name('dev')
.description('AI-driven development task management')
- .version('1.3.1');
+ .version(() => {
+ // Read version directly from package.json
+ try {
+ const packageJsonPath = path.join(__dirname, '..', 'package.json');
+ if (fs.existsSync(packageJsonPath)) {
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
+ return packageJson.version;
+ }
+ } catch (error) {
+ // Silently fall back to default version
+ }
+ return "1.5.0"; // Default fallback
+ });
program
.command('parse-prd')
@@ -1675,7 +2110,11 @@ async function main() {
const allFlag = options.all;
const numSubtasks = parseInt(options.num, 10);
const forceFlag = options.force;
- const useResearch = options.research !== false; // Default to true unless explicitly disabled
+ // Fix: The issue is here - research should be false when --no-research is specified
+ // This will correctly check if research is false
+ const useResearch = options.research === true;
+ // Debug log to verify the value
+ console.log(`Debug - options.research value: ${options.research}`);
const additionalContext = options.prompt || '';
if (allFlag) {
@@ -1760,566 +2199,150 @@ async function main() {
}
});
+ program
+ .command('add-task')
+ .description('Add a new task to tasks.json using AI')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .option('-p, --prompt <text>', 'Description of the task to add (required)')
+ .option('-d, --dependencies <ids>', 'Comma-separated list of task IDs this task depends on')
+ .option('--priority <priority>', 'Task priority (high, medium, low)', 'medium')
+ .action(async (options) => {
+ const tasksPath = options.file;
+ const prompt = options.prompt;
+ const dependencies = options.dependencies ? options.dependencies.split(',').map(id => parseInt(id.trim(), 10)) : [];
+ const priority = options.priority;
+
+ if (!prompt) {
+ console.error(chalk.red('Error: --prompt parameter is required. Please provide a description of the task.'));
+ process.exit(1);
+ }
+
+ console.log(chalk.blue(`Adding new task with prompt: "${prompt}"`));
+ console.log(chalk.blue(`Tasks file: ${tasksPath}`));
+
+ await addTask(tasksPath, prompt, dependencies, priority);
+ });
+
+ program
+ .command('next')
+ .description('Show the next task to work on based on dependencies and status')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .action(async (options) => {
+ const tasksPath = options.file;
+ await displayNextTask(tasksPath);
+ });
+
+ program
+ .command('show')
+ .description('Show details of a specific task by ID')
+ .argument('[id]', 'Task ID to show')
+ .option('-i, --id <id>', 'Task ID to show (alternative to argument)')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .action(async (id, options) => {
+ const taskId = id || options.id;
+
+ if (!taskId) {
+ console.error(chalk.red('Error: Task ID is required. Provide it as an argument or with --id option.'));
+ console.error(chalk.yellow('Examples:'));
+ console.error(chalk.yellow(' node scripts/dev.js show 1'));
+ console.error(chalk.yellow(' node scripts/dev.js show --id=1'));
+ process.exit(1);
+ }
+
+ const tasksPath = options.file;
+ await displayTaskById(tasksPath, taskId);
+ });
+
+ program
+ .command('add-dependency')
+ .description('Add a dependency to a task')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .option('-i, --id <id>', 'ID of the task to add dependency to')
+ .option('-d, --depends-on <id>', 'ID of the task to add as dependency')
+ .action(async (options) => {
+ const tasksPath = options.file;
+ const taskId = options.id;
+ const dependencyId = options.dependsOn;
+
+ if (!taskId || !dependencyId) {
+ console.error(chalk.red('Error: Both --id and --depends-on parameters are required.'));
+ console.error(chalk.yellow('Example:'));
+ console.error(chalk.yellow(' node scripts/dev.js add-dependency --id=22 --depends-on=21'));
+ process.exit(1);
+ }
+
+ await addDependency(tasksPath, taskId, dependencyId);
+ });
+
+ program
+ .command('remove-dependency')
+ .description('Remove a dependency from a task')
+ .option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
+ .option('-i, --id <id>', 'ID of the task to remove dependency from')
+ .option('-d, --depends-on <id>', 'ID of the task to remove as dependency')
+ .action(async (options) => {
+ const tasksPath = options.file;
+ const taskId = options.id;
+ const dependencyId = options.dependsOn;
+
+ if (!taskId || !dependencyId) {
+ console.error(chalk.red('Error: Both --id and --depends-on parameters are required.'));
+ console.error(chalk.yellow('Example:'));
+ console.error(chalk.yellow(' node scripts/dev.js remove-dependency --id=22 --depends-on=21'));
+ process.exit(1);
+ }
+
+ await removeDependency(tasksPath, taskId, dependencyId);
+ });
+
+ program
+ .command('*')
+ .description('Handle unknown commands')
+ .action(async (command) => {
+ console.error(chalk.red(`Unknown command: ${command}`));
+ displayHelp();
+ process.exit(1);
+ });
+
await program.parseAsync(process.argv);
}
/**
- * Analyzes task complexity and generates expansion recommendations
- * @param {Object} options Command options
+ * Generates the prompt for the LLM to analyze task complexity
+ * @param {Object} tasksData The tasks data from tasks.json
+ * @returns {string} The prompt for the LLM
*/
-async function analyzeTaskComplexity(options) {
- const tasksPath = options.file || 'tasks/tasks.json';
- const outputPath = options.output || 'scripts/task-complexity-report.json';
- const modelOverride = options.model;
- const thresholdScore = parseFloat(options.threshold || '5');
- const useResearch = options.research || false;
-
- console.log(chalk.blue(`Analyzing task complexity and generating expansion recommendations...`));
-
- try {
- // Read tasks.json
- console.log(chalk.blue(`Reading tasks from ${tasksPath}...`));
- const tasksData = readJSON(tasksPath);
-
- if (!tasksData || !tasksData.tasks || !Array.isArray(tasksData.tasks) || tasksData.tasks.length === 0) {
- throw new Error('No tasks found in the tasks file');
- }
-
- console.log(chalk.blue(`Found ${tasksData.tasks.length} tasks to analyze.`));
-
- // Prepare the prompt for the LLM
- const prompt = generateComplexityAnalysisPrompt(tasksData);
-
- // Start loading indicator
- const loadingIndicator = startLoadingIndicator('Calling AI to analyze task complexity...');
-
- let fullResponse = '';
- let streamingInterval = null;
-
- try {
- // If research flag is set, use Perplexity first
- if (useResearch) {
- try {
- console.log(chalk.blue('Using Perplexity AI for research-backed complexity analysis...'));
-
- // Modify prompt to include more context for Perplexity and explicitly request JSON
- const researchPrompt = `You are conducting a detailed analysis of software development tasks to determine their complexity and how they should be broken down into subtasks.
-
-Please research each task thoroughly, considering best practices, industry standards, and potential implementation challenges before providing your analysis.
+function generateComplexityAnalysisPrompt(tasksData) {
+ return `
+You are an expert software architect and project manager. Your task is to analyze the complexity of development tasks and determine how many subtasks each should be broken down into.
-CRITICAL: You MUST respond ONLY with a valid JSON array. Do not include ANY explanatory text, markdown formatting, or code block markers.
+Below is a list of development tasks with their descriptions and details. For each task:
+1. Assess its complexity on a scale of 1-10
+2. Recommend the optimal number of subtasks (between ${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)})
+3. Suggest a specific prompt that would help generate good subtasks for this task
+4. Explain your reasoning briefly
-${prompt}
+Tasks:
+${tasksData.tasks.map(task => `
+ID: ${task.id}
+Title: ${task.title}
+Description: ${task.description}
+Details: ${task.details}
+Dependencies: ${JSON.stringify(task.dependencies || [])}
+Priority: ${task.priority || 'medium'}
+`).join('\n---\n')}
-Your response must be a clean JSON array only, following exactly this format:
+Analyze each task and return a JSON array with the following structure for each task:
[
{
- "taskId": 1,
- "taskTitle": "Example Task",
- "complexityScore": 7,
- "recommendedSubtasks": 4,
- "expansionPrompt": "Detailed prompt for expansion",
- "reasoning": "Explanation of complexity assessment"
+ "taskId": number,
+ "taskTitle": string,
+ "complexityScore": number (1-10),
+ "recommendedSubtasks": number (${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)}),
+ "expansionPrompt": string (a specific prompt for generating good subtasks),
+ "reasoning": string (brief explanation of your assessment)
},
- // more tasks...
-]
-
-DO NOT include any text before or after the JSON array. No explanations, no markdown formatting.`;
-
- const result = await perplexity.chat.completions.create({
- model: PERPLEXITY_MODEL,
- messages: [
- {
- role: "system",
- content: "You are a technical analysis AI that only responds with clean, valid JSON. Never include explanatory text or markdown formatting in your response."
- },
- {
- role: "user",
- content: researchPrompt
- }
- ],
- temperature: TEMPERATURE,
- max_tokens: MAX_TOKENS,
- });
-
- // Extract the response text
- fullResponse = result.choices[0].message.content;
- console.log(chalk.green('Successfully generated complexity analysis with Perplexity AI'));
-
- if (streamingInterval) clearInterval(streamingInterval);
- stopLoadingIndicator(loadingIndicator);
-
- // ALWAYS log the first part of the response for debugging
- console.log(chalk.gray('Response first 200 chars:'));
- console.log(chalk.gray(fullResponse.substring(0, 200)));
- } catch (perplexityError) {
- console.log(chalk.yellow('Falling back to Claude for complexity analysis...'));
- console.log(chalk.gray('Perplexity error:'), perplexityError.message);
-
- // Continue to Claude as fallback
- await useClaudeForComplexityAnalysis();
- }
- } else {
- // Use Claude directly if research flag is not set
- await useClaudeForComplexityAnalysis();
- }
-
- // Helper function to use Claude for complexity analysis
- async function useClaudeForComplexityAnalysis() {
- // Call the LLM API with streaming
- const stream = await anthropic.messages.create({
- max_tokens: CONFIG.maxTokens,
- model: modelOverride || CONFIG.model,
- temperature: CONFIG.temperature,
- messages: [{ role: "user", content: prompt }],
- system: "You are an expert software architect and project manager analyzing task complexity. Respond only with valid JSON.",
- stream: true
- });
-
- // Update loading indicator to show streaming progress
- let dotCount = 0;
- streamingInterval = setInterval(() => {
- readline.cursorTo(process.stdout, 0);
- process.stdout.write(`Receiving streaming response from Claude${'.'.repeat(dotCount)}`);
- dotCount = (dotCount + 1) % 4;
- }, 500);
-
- // Process the stream
- for await (const chunk of stream) {
- if (chunk.type === 'content_block_delta' && chunk.delta.text) {
- fullResponse += chunk.delta.text;
- }
- }
-
- clearInterval(streamingInterval);
- stopLoadingIndicator(loadingIndicator);
-
- console.log(chalk.green("Completed streaming response from Claude API!"));
- }
-
- // Parse the JSON response
- console.log(chalk.blue(`Parsing complexity analysis...`));
- let complexityAnalysis;
- try {
- // Clean up the response to ensure it's valid JSON
- let cleanedResponse = fullResponse;
-
- // First check for JSON code blocks (common in markdown responses)
- const codeBlockMatch = fullResponse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
- if (codeBlockMatch) {
- cleanedResponse = codeBlockMatch[1];
- console.log(chalk.blue("Extracted JSON from code block"));
- } else {
- // Look for a complete JSON array pattern
- // This regex looks for an array of objects starting with [ and ending with ]
- const jsonArrayMatch = fullResponse.match(/(\[\s*\{\s*"[^"]*"\s*:[\s\S]*\}\s*\])/);
- if (jsonArrayMatch) {
- cleanedResponse = jsonArrayMatch[1];
- console.log(chalk.blue("Extracted JSON array pattern"));
- } else {
- // Try to find the start of a JSON array and capture to the end
- const jsonStartMatch = fullResponse.match(/(\[\s*\{[\s\S]*)/);
- if (jsonStartMatch) {
- cleanedResponse = jsonStartMatch[1];
- // Try to find a proper closing to the array
- const properEndMatch = cleanedResponse.match(/([\s\S]*\}\s*\])/);
- if (properEndMatch) {
- cleanedResponse = properEndMatch[1];
- }
- console.log(chalk.blue("Extracted JSON from start of array to end"));
- }
- }
- }
-
- // Log the cleaned response for debugging
- console.log(chalk.gray("Attempting to parse cleaned JSON..."));
- console.log(chalk.gray("Cleaned response (first 100 chars):"));
- console.log(chalk.gray(cleanedResponse.substring(0, 100)));
- console.log(chalk.gray("Last 100 chars:"));
- console.log(chalk.gray(cleanedResponse.substring(cleanedResponse.length - 100)));
-
- // More aggressive cleaning - strip any non-JSON content at the beginning or end
- const strictArrayMatch = cleanedResponse.match(/(\[\s*\{[\s\S]*\}\s*\])/);
- if (strictArrayMatch) {
- cleanedResponse = strictArrayMatch[1];
- console.log(chalk.blue("Applied strict JSON array extraction"));
- }
-
- try {
- complexityAnalysis = JSON.parse(cleanedResponse);
- } catch (jsonError) {
- console.log(chalk.yellow("Initial JSON parsing failed, attempting to fix common JSON issues..."));
-
- // Try to fix common JSON issues
- // 1. Remove any trailing commas in arrays or objects
- cleanedResponse = cleanedResponse.replace(/,(\s*[\]}])/g, '$1');
-
- // 2. Ensure property names are double-quoted
- cleanedResponse = cleanedResponse.replace(/(\s*)(\w+)(\s*):(\s*)/g, '$1"$2"$3:$4');
-
- // 3. Replace single quotes with double quotes for property values
- cleanedResponse = cleanedResponse.replace(/:(\s*)'([^']*)'(\s*[,}])/g, ':$1"$2"$3');
-
- // 4. Add a special fallback option if we're still having issues
- try {
- complexityAnalysis = JSON.parse(cleanedResponse);
- console.log(chalk.green("Successfully parsed JSON after fixing common issues"));
- } catch (fixedJsonError) {
- console.log(chalk.red("Failed to parse JSON even after fixes, attempting more aggressive cleanup..."));
-
- // Try to extract and process each task individually
- try {
- const taskMatches = cleanedResponse.match(/\{\s*"taskId"\s*:\s*(\d+)[^}]*\}/g);
- if (taskMatches && taskMatches.length > 0) {
- console.log(chalk.yellow(`Found ${taskMatches.length} task objects, attempting to process individually`));
-
- complexityAnalysis = [];
- for (const taskMatch of taskMatches) {
- try {
- // Try to parse each task object individually
- const fixedTask = taskMatch.replace(/,\s*$/, ''); // Remove trailing commas
- const taskObj = JSON.parse(`${fixedTask}`);
- if (taskObj && taskObj.taskId) {
- complexityAnalysis.push(taskObj);
- }
- } catch (taskParseError) {
- console.log(chalk.yellow(`Could not parse individual task: ${taskMatch.substring(0, 30)}...`));
- }
- }
-
- if (complexityAnalysis.length > 0) {
- console.log(chalk.green(`Successfully parsed ${complexityAnalysis.length} tasks individually`));
- } else {
- throw new Error("Could not parse any tasks individually");
- }
- } else {
- throw fixedJsonError;
- }
- } catch (individualError) {
- console.log(chalk.red("All parsing attempts failed"));
- throw jsonError; // throw the original error
- }
- }
- }
-
- // Ensure complexityAnalysis is an array
- if (!Array.isArray(complexityAnalysis)) {
- console.log(chalk.yellow('Response is not an array, checking if it contains an array property...'));
-
- // Handle the case where the response might be an object with an array property
- if (complexityAnalysis.tasks || complexityAnalysis.analysis || complexityAnalysis.results) {
- complexityAnalysis = complexityAnalysis.tasks || complexityAnalysis.analysis || complexityAnalysis.results;
- } else {
- // If no recognizable array property, wrap it as an array if it's an object
- if (typeof complexityAnalysis === 'object' && complexityAnalysis !== null) {
- console.log(chalk.yellow('Converting object to array...'));
- complexityAnalysis = [complexityAnalysis];
- } else {
- throw new Error('Response does not contain a valid array or object');
- }
- }
- }
-
- // Final check to ensure we have an array
- if (!Array.isArray(complexityAnalysis)) {
- throw new Error('Failed to extract an array from the response');
- }
-
- // Check that we have an analysis for each task in the input file
- const taskIds = tasksData.tasks.map(t => t.id);
- const analysisTaskIds = complexityAnalysis.map(a => a.taskId);
- const missingTaskIds = taskIds.filter(id => !analysisTaskIds.includes(id));
-
- if (missingTaskIds.length > 0) {
- console.log(chalk.yellow(`Missing analysis for ${missingTaskIds.length} tasks: ${missingTaskIds.join(', ')}`));
- console.log(chalk.blue(`Attempting to analyze missing tasks...`));
-
- // Create a subset of tasksData with just the missing tasks
- const missingTasks = {
- meta: tasksData.meta,
- tasks: tasksData.tasks.filter(t => missingTaskIds.includes(t.id))
- };
-
- // Generate a prompt for just the missing tasks
- const missingTasksPrompt = generateComplexityAnalysisPrompt(missingTasks);
-
- // Call the same AI model to analyze the missing tasks
- let missingAnalysisResponse = '';
-
- try {
- // Start a new loading indicator
- const missingTasksLoadingIndicator = startLoadingIndicator('Analyzing missing tasks...');
-
- // Use the same AI model as the original analysis
- if (useResearch) {
- // Create the same research prompt but for missing tasks
- const missingTasksResearchPrompt = `You are conducting a detailed analysis of software development tasks to determine their complexity and how they should be broken down into subtasks.
-
-Please research each task thoroughly, considering best practices, industry standards, and potential implementation challenges before providing your analysis.
-
-CRITICAL: You MUST respond ONLY with a valid JSON array. Do not include ANY explanatory text, markdown formatting, or code block markers.
-
-${missingTasksPrompt}
-
-Your response must be a clean JSON array only, following exactly this format:
-[
- {
- "taskId": 1,
- "taskTitle": "Example Task",
- "complexityScore": 7,
- "recommendedSubtasks": 4,
- "expansionPrompt": "Detailed prompt for expansion",
- "reasoning": "Explanation of complexity assessment"
- },
- // more tasks...
-]
-
-DO NOT include any text before or after the JSON array. No explanations, no markdown formatting.`;
-
- const result = await perplexity.chat.completions.create({
- model: PERPLEXITY_MODEL,
- messages: [
- {
- role: "system",
- content: "You are a technical analysis AI that only responds with clean, valid JSON. Never include explanatory text or markdown formatting in your response."
- },
- {
- role: "user",
- content: missingTasksResearchPrompt
- }
- ],
- temperature: TEMPERATURE,
- max_tokens: MAX_TOKENS,
- });
-
- // Extract the response
- missingAnalysisResponse = result.choices[0].message.content;
- } else {
- // Use Claude
- const stream = await anthropic.messages.create({
- max_tokens: CONFIG.maxTokens,
- model: modelOverride || CONFIG.model,
- temperature: CONFIG.temperature,
- messages: [{ role: "user", content: missingTasksPrompt }],
- system: "You are an expert software architect and project manager analyzing task complexity. Respond only with valid JSON.",
- stream: true
- });
-
- // Process the stream
- for await (const chunk of stream) {
- if (chunk.type === 'content_block_delta' && chunk.delta.text) {
- missingAnalysisResponse += chunk.delta.text;
- }
- }
- }
-
- // Stop the loading indicator
- stopLoadingIndicator(missingTasksLoadingIndicator);
-
- // Parse the response using the same parsing logic as before
- let missingAnalysis;
- try {
- // Clean up the response to ensure it's valid JSON (using same logic as above)
- let cleanedResponse = missingAnalysisResponse;
-
- // Use the same JSON extraction logic as before
- // ... (code omitted for brevity, it would be the same as the original parsing)
-
- // First check for JSON code blocks
- const codeBlockMatch = missingAnalysisResponse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
- if (codeBlockMatch) {
- cleanedResponse = codeBlockMatch[1];
- console.log(chalk.blue("Extracted JSON from code block for missing tasks"));
- } else {
- // Look for a complete JSON array pattern
- const jsonArrayMatch = missingAnalysisResponse.match(/(\[\s*\{\s*"[^"]*"\s*:[\s\S]*\}\s*\])/);
- if (jsonArrayMatch) {
- cleanedResponse = jsonArrayMatch[1];
- console.log(chalk.blue("Extracted JSON array pattern for missing tasks"));
- } else {
- // Try to find the start of a JSON array and capture to the end
- const jsonStartMatch = missingAnalysisResponse.match(/(\[\s*\{[\s\S]*)/);
- if (jsonStartMatch) {
- cleanedResponse = jsonStartMatch[1];
- // Try to find a proper closing to the array
- const properEndMatch = cleanedResponse.match(/([\s\S]*\}\s*\])/);
- if (properEndMatch) {
- cleanedResponse = properEndMatch[1];
- }
- console.log(chalk.blue("Extracted JSON from start of array to end for missing tasks"));
- }
- }
- }
-
- // More aggressive cleaning if needed
- const strictArrayMatch = cleanedResponse.match(/(\[\s*\{[\s\S]*\}\s*\])/);
- if (strictArrayMatch) {
- cleanedResponse = strictArrayMatch[1];
- console.log(chalk.blue("Applied strict JSON array extraction for missing tasks"));
- }
-
- try {
- missingAnalysis = JSON.parse(cleanedResponse);
- } catch (jsonError) {
- // Try to fix common JSON issues (same as before)
- cleanedResponse = cleanedResponse.replace(/,(\s*[\]}])/g, '$1');
- cleanedResponse = cleanedResponse.replace(/(\s*)(\w+)(\s*):(\s*)/g, '$1"$2"$3:$4');
- cleanedResponse = cleanedResponse.replace(/:(\s*)'([^']*)'(\s*[,}])/g, ':$1"$2"$3');
-
- try {
- missingAnalysis = JSON.parse(cleanedResponse);
- console.log(chalk.green("Successfully parsed JSON for missing tasks after fixing common issues"));
- } catch (fixedJsonError) {
- // Try the individual task extraction as a last resort
- console.log(chalk.red("Failed to parse JSON for missing tasks, attempting individual extraction..."));
-
- const taskMatches = cleanedResponse.match(/\{\s*"taskId"\s*:\s*(\d+)[^}]*\}/g);
- if (taskMatches && taskMatches.length > 0) {
- console.log(chalk.yellow(`Found ${taskMatches.length} task objects, attempting to process individually`));
-
- missingAnalysis = [];
- for (const taskMatch of taskMatches) {
- try {
- const fixedTask = taskMatch.replace(/,\s*$/, '');
- const taskObj = JSON.parse(`${fixedTask}`);
- if (taskObj && taskObj.taskId) {
- missingAnalysis.push(taskObj);
- }
- } catch (taskParseError) {
- console.log(chalk.yellow(`Could not parse individual task: ${taskMatch.substring(0, 30)}...`));
- }
- }
-
- if (missingAnalysis.length === 0) {
- throw new Error("Could not parse any missing tasks");
- }
- } else {
- throw fixedJsonError;
- }
- }
- }
-
- // Ensure it's an array
- if (!Array.isArray(missingAnalysis)) {
- if (missingAnalysis && typeof missingAnalysis === 'object') {
- missingAnalysis = [missingAnalysis];
- } else {
- throw new Error("Missing tasks analysis is not an array or object");
- }
- }
-
- // Add the missing analyses to the main analysis array
- console.log(chalk.green(`Successfully analyzed ${missingAnalysis.length} missing tasks`));
- complexityAnalysis = [...complexityAnalysis, ...missingAnalysis];
-
- // Re-check for missing tasks
- const updatedAnalysisTaskIds = complexityAnalysis.map(a => a.taskId);
- const stillMissingTaskIds = taskIds.filter(id => !updatedAnalysisTaskIds.includes(id));
-
- if (stillMissingTaskIds.length > 0) {
- console.log(chalk.yellow(`Warning: Still missing analysis for ${stillMissingTaskIds.length} tasks: ${stillMissingTaskIds.join(', ')}`));
- } else {
- console.log(chalk.green(`All tasks now have complexity analysis!`));
- }
- } catch (error) {
- console.error(chalk.red(`Error analyzing missing tasks: ${error.message}`));
- console.log(chalk.yellow(`Continuing with partial analysis...`));
- }
- } catch (error) {
- console.error(chalk.red(`Error during retry for missing tasks: ${error.message}`));
- console.log(chalk.yellow(`Continuing with partial analysis...`));
- }
- }
- } catch (error) {
- console.error(chalk.red(`Failed to parse LLM response as JSON: ${error.message}`));
- if (CONFIG.debug) {
- console.debug(chalk.gray(`Raw response: ${fullResponse}`));
- }
- throw new Error('Invalid response format from LLM. Expected JSON.');
- }
-
- // Create the final report
- const report = {
- meta: {
- generatedAt: new Date().toISOString(),
- tasksAnalyzed: tasksData.tasks.length,
- thresholdScore: thresholdScore,
- projectName: tasksData.meta?.projectName || 'Your Project Name',
- usedResearch: useResearch
- },
- complexityAnalysis: complexityAnalysis
- };
-
- // Write the report to file
- console.log(chalk.blue(`Writing complexity report to ${outputPath}...`));
- writeJSON(outputPath, report);
-
- console.log(chalk.green(`Task complexity analysis complete. Report written to ${outputPath}`));
-
- // Display a summary of findings
- const highComplexity = complexityAnalysis.filter(t => t.complexityScore >= 8).length;
- const mediumComplexity = complexityAnalysis.filter(t => t.complexityScore >= 5 && t.complexityScore < 8).length;
- const lowComplexity = complexityAnalysis.filter(t => t.complexityScore < 5).length;
- const totalAnalyzed = complexityAnalysis.length;
-
- console.log('\nComplexity Analysis Summary:');
- console.log('----------------------------');
- console.log(`Tasks in input file: ${tasksData.tasks.length}`);
- console.log(`Tasks successfully analyzed: ${totalAnalyzed}`);
- console.log(`High complexity tasks: ${highComplexity}`);
- console.log(`Medium complexity tasks: ${mediumComplexity}`);
- console.log(`Low complexity tasks: ${lowComplexity}`);
- console.log(`Sum verification: ${highComplexity + mediumComplexity + lowComplexity} (should equal ${totalAnalyzed})`);
- console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`);
- console.log(`\nSee ${outputPath} for the full report and expansion commands.`);
-
- } catch (error) {
- if (streamingInterval) clearInterval(streamingInterval);
- stopLoadingIndicator(loadingIndicator);
- throw error;
- }
- } catch (error) {
- console.error(chalk.red(`Error analyzing task complexity: ${error.message}`));
- process.exit(1);
- }
-}
-
-/**
- * Generates the prompt for the LLM to analyze task complexity
- * @param {Object} tasksData The tasks data from tasks.json
- * @returns {string} The prompt for the LLM
- */
-function generateComplexityAnalysisPrompt(tasksData) {
- return `
-You are an expert software architect and project manager. Your task is to analyze the complexity of development tasks and determine how many subtasks each should be broken down into.
-
-Below is a list of development tasks with their descriptions and details. For each task:
-1. Assess its complexity on a scale of 1-10
-2. Recommend the optimal number of subtasks (between ${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)})
-3. Suggest a specific prompt that would help generate good subtasks for this task
-4. Explain your reasoning briefly
-
-Tasks:
-${tasksData.tasks.map(task => `
-ID: ${task.id}
-Title: ${task.title}
-Description: ${task.description}
-Details: ${task.details}
-Dependencies: ${JSON.stringify(task.dependencies || [])}
-Priority: ${task.priority || 'medium'}
-`).join('\n---\n')}
-
-Analyze each task and return a JSON array with the following structure for each task:
-[
- {
- "taskId": number,
- "taskTitle": string,
- "complexityScore": number (1-10),
- "recommendedSubtasks": number (${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)}),
- "expansionPrompt": string (a specific prompt for generating good subtasks),
- "reasoning": string (brief explanation of your assessment)
- },
- ...
+ ...
]
IMPORTANT: Make sure to include an analysis for EVERY task listed above, with the correct taskId matching each task's ID.
@@ -2374,6 +2397,8 @@ function findTaskInComplexityReport(report, taskId) {
// Clear subtasks from tasks
//
function clearSubtasks(tasksPath, taskIds) {
+ displayBanner();
+
log('info', `Reading tasks from ${tasksPath}...`);
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
@@ -2381,9 +2406,25 @@ function clearSubtasks(tasksPath, taskIds) {
process.exit(1);
}
+ console.log(boxen(
+ chalk.white.bold('Clearing Subtasks'),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ ));
+
// Handle multiple task IDs (comma-separated)
const taskIdArray = taskIds.split(',').map(id => id.trim());
let clearedCount = 0;
+
+ // Create a summary table for the cleared subtasks
+ const summaryTable = new Table({
+ head: [
+ chalk.cyan.bold('Task ID'),
+ chalk.cyan.bold('Task Title'),
+ chalk.cyan.bold('Subtasks Cleared')
+ ],
+ colWidths: [10, 50, 20],
+ style: { head: [], border: [] }
+ });
taskIdArray.forEach(taskId => {
const id = parseInt(taskId, 10);
@@ -2400,6 +2441,11 @@ function clearSubtasks(tasksPath, taskIds) {
if (!task.subtasks || task.subtasks.length === 0) {
log('info', `Task ${id} has no subtasks to clear`);
+ summaryTable.push([
+ id.toString(),
+ truncate(task.title, 47),
+ chalk.yellow('No subtasks')
+ ]);
return;
}
@@ -2407,21 +2453,865 @@ function clearSubtasks(tasksPath, taskIds) {
task.subtasks = [];
clearedCount++;
log('info', `Cleared ${subtaskCount} subtasks from task ${id}`);
+
+ summaryTable.push([
+ id.toString(),
+ truncate(task.title, 47),
+ chalk.green(`${subtaskCount} subtasks cleared`)
+ ]);
});
if (clearedCount > 0) {
writeJSON(tasksPath, data);
- log('info', `Successfully cleared subtasks from ${clearedCount} task(s)`);
-
+
+ // Show summary table
+ console.log(boxen(
+ chalk.white.bold('Subtask Clearing Summary:'),
+ { padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'blue', borderStyle: 'round' }
+ ));
+ console.log(summaryTable.toString());
+
// Regenerate task files to reflect changes
log('info', "Regenerating task files...");
generateTaskFiles(tasksPath, path.dirname(tasksPath));
+
+ // Success message
+ console.log(boxen(
+ chalk.green(`Successfully cleared subtasks from ${chalk.bold(clearedCount)} task(s)`),
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ // Next steps suggestion
+ console.log(boxen(
+ chalk.white.bold('Next Steps:') + '\n\n' +
+ `${chalk.cyan('1.')} Run ${chalk.yellow('node scripts/dev.js expand --id=<id>')} to generate new subtasks\n` +
+ `${chalk.cyan('2.')} Run ${chalk.yellow('node scripts/dev.js list --with-subtasks')} to verify changes`,
+ { padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ } else {
+ console.log(boxen(
+ chalk.yellow('No subtasks were cleared'),
+ { padding: 1, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
+ ));
+ }
+}
+
+// ----------------------------------------
+// Custom help display
+// ----------------------------------------
+function displayHelp() {
+ displayBanner();
+
+ console.log(boxen(
+ chalk.white.bold('Claude Task Master CLI'),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ ));
+
+ // Command categories
+ const commandCategories = [
+ {
+ title: 'Task Generation',
+ color: 'cyan',
+ commands: [
+ { name: 'parse-prd', args: '--input=<file.txt> [--tasks=10]',
+ desc: 'Generate tasks from a PRD document' },
+ { name: 'generate', args: '',
+ desc: 'Create individual task files from tasks.json' }
+ ]
+ },
+ {
+ title: 'Task Management',
+ color: 'green',
+ commands: [
+ { name: 'list', args: '[--status=<status>] [--with-subtasks]',
+ desc: 'List all tasks with their status' },
+ { name: 'set-status', args: '--id=<id> --status=<status>',
+ desc: 'Update task status (done, pending, etc.)' },
+ { name: 'update', args: '--from=<id> --prompt="<context>"',
+ desc: 'Update tasks based on new requirements' },
+ { name: 'add-dependency', args: '--id=<id> --depends-on=<id>',
+ desc: 'Add a dependency to a task' },
+ { name: 'remove-dependency', args: '--id=<id> --depends-on=<id>',
+ desc: 'Remove a dependency from a task' }
+ ]
+ },
+ {
+ title: 'Task Analysis & Detail',
+ color: 'yellow',
+ commands: [
+ { name: 'analyze-complexity', args: '[--research] [--threshold=5]',
+ desc: 'Analyze tasks and generate expansion recommendations' },
+ { name: 'expand', args: '--id=<id> [--num=5] [--research] [--prompt="<context>"]',
+ desc: 'Break down tasks into detailed subtasks' },
+ { name: 'expand --all', args: '[--force] [--research]',
+ desc: 'Expand all pending tasks with subtasks' },
+ { name: 'clear-subtasks', args: '--id=<id>',
+ desc: 'Remove subtasks from specified tasks' }
+ ]
+ }
+ ];
+
+ // Display each category
+ commandCategories.forEach(category => {
+ console.log(boxen(
+ chalk[category.color].bold(category.title),
+ {
+ padding: { left: 2, right: 2, top: 0, bottom: 0 },
+ margin: { top: 1, bottom: 0 },
+ borderColor: category.color,
+ borderStyle: 'round'
+ }
+ ));
+
+ const commandTable = new Table({
+ colWidths: [20, 40, 50],
+ chars: {
+ 'top': '', 'top-mid': '', 'top-left': '', 'top-right': '',
+ 'bottom': '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
+ 'left': '', 'left-mid': '', 'mid': '', 'mid-mid': '',
+ 'right': '', 'right-mid': '', 'middle': ' '
+ },
+ style: { border: [], 'padding-left': 4 }
+ });
+
+ category.commands.forEach(cmd => {
+ commandTable.push([
+ chalk.bold(cmd.name),
+ chalk.blue(cmd.args),
+ cmd.desc
+ ]);
+ });
+
+ console.log(commandTable.toString());
+ });
+
+ // Environment variables section
+ console.log(boxen(
+ chalk.magenta.bold('Environment Variables'),
+ {
+ padding: { left: 2, right: 2, top: 0, bottom: 0 },
+ margin: { top: 1, bottom: 0 },
+ borderColor: 'magenta',
+ borderStyle: 'round'
+ }
+ ));
+
+ const envTable = new Table({
+ colWidths: [25, 20, 65],
+ chars: {
+ 'top': '', 'top-mid': '', 'top-left': '', 'top-right': '',
+ 'bottom': '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
+ 'left': '', 'left-mid': '', 'mid': '', 'mid-mid': '',
+ 'right': '', 'right-mid': '', 'middle': ' '
+ },
+ style: { border: [], 'padding-left': 4 }
+ });
+
+ envTable.push(
+ [chalk.bold('ANTHROPIC_API_KEY'), chalk.red('Required'), 'Your Anthropic API key for Claude'],
+ [chalk.bold('MODEL'), chalk.gray('Optional'), `Claude model to use (default: ${MODEL})`],
+ [chalk.bold('PERPLEXITY_API_KEY'), chalk.gray('Optional'), 'API key for research-backed features'],
+ [chalk.bold('PROJECT_NAME'), chalk.gray('Optional'), `Project name in metadata (default: ${CONFIG.projectName})`]
+ );
+
+ console.log(envTable.toString());
+
+ // Example usage section
+ console.log(boxen(
+ chalk.white.bold('Example Workflow'),
+ {
+ padding: 1,
+ margin: { top: 1, bottom: 1 },
+ borderColor: 'white',
+ borderStyle: 'round'
+ }
+ ));
+
+ console.log(chalk.cyan(' 1. Generate tasks:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js parse-prd --input=prd.txt')}`);
+ console.log(chalk.cyan(' 2. Generate task files:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js generate')}`);
+ console.log(chalk.cyan(' 3. Analyze task complexity:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js analyze-complexity --research')}`);
+ console.log(chalk.cyan(' 4. Break down complex tasks:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js expand --id=3 --research')}`);
+ console.log(chalk.cyan(' 5. Track progress:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js list --with-subtasks')}`);
+ console.log(chalk.cyan(' 6. Update task status:'));
+ console.log(` ${chalk.yellow('node scripts/dev.js set-status --id=1 --status=done')}`);
+
+ console.log('\n');
+}
+
+async function addTask(tasksPath, prompt, dependencies = [], priority = 'medium') {
+ displayBanner();
+
+ // Read the existing tasks
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "Invalid or missing tasks.json.");
+ process.exit(1);
+ }
+
+ // Find the highest task ID to determine the next ID
+ const highestId = Math.max(...data.tasks.map(t => t.id));
+ const newTaskId = highestId + 1;
+
+ console.log(boxen(
+ chalk.white.bold(`Creating New Task #${newTaskId}`),
+ { padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
+ ));
+
+ // Create the system prompt for Claude
+ const systemPrompt = "You are a helpful assistant that creates well-structured tasks for a software development project. Generate a single new task based on the user's description.";
+
+ // Create the user prompt with context from existing tasks
+ let contextTasks = '';
+ if (dependencies.length > 0) {
+ // Provide context for the dependent tasks
+ const dependentTasks = data.tasks.filter(t => dependencies.includes(t.id));
+ contextTasks = `\nThis task depends on the following tasks:\n${dependentTasks.map(t =>
+ `- Task ${t.id}: ${t.title} - ${t.description}`).join('\n')}`;
+ } else {
+ // Provide a few recent tasks as context
+ const recentTasks = [...data.tasks].sort((a, b) => b.id - a.id).slice(0, 3);
+ contextTasks = `\nRecent tasks in the project:\n${recentTasks.map(t =>
+ `- Task ${t.id}: ${t.title} - ${t.description}`).join('\n')}`;
+ }
+
+ const taskStructure = `
+ {
+ "title": "Task title goes here",
+ "description": "A concise one or two sentence description of what the task involves",
+ "details": "In-depth details including specifics on implementation, considerations, and anything important for the developer to know. This should be detailed enough to guide implementation.",
+ "testStrategy": "A detailed approach for verifying the task has been correctly implemented. Include specific test cases or validation methods."
+ }`;
+
+ const userPrompt = `Create a comprehensive new task (Task #${newTaskId}) for a software development project based on this description: "${prompt}"
+
+ ${contextTasks}
+
+ Return your answer as a single JSON object with the following structure:
+ ${taskStructure}
+
+ Don't include the task ID, status, dependencies, or priority as those will be added automatically.
+ Make sure the details and test strategy are thorough and specific.
+
+ IMPORTANT: Return ONLY the JSON object, nothing else.`;
+
+ // Start the loading indicator
+ const loadingIndicator = startLoadingIndicator('Generating new task with Claude AI...');
+
+ let fullResponse = '';
+ let streamingInterval = null;
+
+ try {
+ // Call Claude with streaming enabled
+ const stream = await anthropic.messages.create({
+ max_tokens: CONFIG.maxTokens,
+ model: CONFIG.model,
+ temperature: CONFIG.temperature,
+ messages: [{ role: "user", content: userPrompt }],
+ system: systemPrompt,
+ stream: true
+ });
+
+ // Update loading indicator to show streaming progress
+ let dotCount = 0;
+ streamingInterval = setInterval(() => {
+ readline.cursorTo(process.stdout, 0);
+ process.stdout.write(`Receiving streaming response from Claude${'.'.repeat(dotCount)}`);
+ dotCount = (dotCount + 1) % 4;
+ }, 500);
+
+ // Process the stream
+ for await (const chunk of stream) {
+ if (chunk.type === 'content_block_delta' && chunk.delta.text) {
+ fullResponse += chunk.delta.text;
+ }
+ }
+
+ if (streamingInterval) clearInterval(streamingInterval);
+ stopLoadingIndicator(loadingIndicator);
+
+ log('info', "Completed streaming response from Claude API!");
+ log('debug', `Streaming response length: ${fullResponse.length} characters`);
+
+ // Parse the response - handle potential JSON formatting issues
+ let taskData;
+ try {
+ // Check if the response is wrapped in a code block
+ const jsonMatch = fullResponse.match(/```(?:json)?([^`]+)```/);
+ const jsonContent = jsonMatch ? jsonMatch[1] : fullResponse;
+
+ // Parse the JSON
+ taskData = JSON.parse(jsonContent);
+
+ // Check that we have the required fields
+ if (!taskData.title || !taskData.description) {
+ throw new Error("Missing required fields in the generated task");
+ }
+ } catch (error) {
+ log('error', "Failed to parse Claude's response as valid task JSON:", error);
+ log('debug', "Response content:", fullResponse);
+ process.exit(1);
+ }
+
+ // Create the new task object
+ const newTask = {
+ id: newTaskId,
+ title: taskData.title,
+ description: taskData.description,
+ status: "pending",
+ dependencies: dependencies,
+ priority: priority,
+ details: taskData.details || "",
+ testStrategy: taskData.testStrategy || "Manually verify the implementation works as expected."
+ };
+
+ // Add the new task to the tasks array
+ data.tasks.push(newTask);
+
+ // Write the updated tasks back to the file
+ writeJSON(tasksPath, data);
+
+ // Show success message
+ const successBox = boxen(
+ chalk.green(`Successfully added new task #${newTaskId}:\n`) +
+ chalk.white.bold(newTask.title) + "\n\n" +
+ chalk.white(newTask.description),
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ );
+ console.log(successBox);
+
+ // Next steps suggestion
+ console.log(boxen(
+ chalk.white.bold('Next Steps:') + '\n\n' +
+ `${chalk.cyan('1.')} Run ${chalk.yellow('node scripts/dev.js generate')} to update task files\n` +
+ `${chalk.cyan('2.')} Run ${chalk.yellow('node scripts/dev.js expand --id=' + newTaskId)} to break it down into subtasks\n` +
+ `${chalk.cyan('3.')} Run ${chalk.yellow('node scripts/dev.js list --with-subtasks')} to see all tasks`,
+ { padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ return newTaskId;
+ } catch (error) {
+ if (streamingInterval) clearInterval(streamingInterval);
+ stopLoadingIndicator(loadingIndicator);
+ log('error', "Error generating task:", error.message);
+ process.exit(1);
+ }
+}
+
+/**
+ * Find the next pending task based on dependencies
+ * @param {Object[]} tasks - The array of tasks
+ * @returns {Object|null} The next task to work on or null if no eligible tasks
+ */
+function findNextTask(tasks) {
+ // Get all completed task IDs
+ const completedTaskIds = new Set(
+ tasks
+ .filter(t => t.status === 'done' || t.status === 'completed')
+ .map(t => t.id)
+ );
+
+ // Filter for pending tasks whose dependencies are all satisfied
+ const eligibleTasks = tasks.filter(task =>
+ (task.status === 'pending' || task.status === 'in-progress') &&
+ task.dependencies && // Make sure dependencies array exists
+ task.dependencies.every(depId => completedTaskIds.has(depId))
+ );
+
+ if (eligibleTasks.length === 0) {
+ return null;
+ }
+
+ // Sort eligible tasks by:
+ // 1. Priority (high > medium > low)
+ // 2. Dependencies count (fewer dependencies first)
+ // 3. ID (lower ID first)
+ const priorityValues = { 'high': 3, 'medium': 2, 'low': 1 };
+
+ const nextTask = eligibleTasks.sort((a, b) => {
+ // Sort by priority first
+ const priorityA = priorityValues[a.priority || 'medium'] || 2;
+ const priorityB = priorityValues[b.priority || 'medium'] || 2;
+
+ if (priorityB !== priorityA) {
+ return priorityB - priorityA; // Higher priority first
+ }
+
+ // If priority is the same, sort by dependency count
+ if (a.dependencies && b.dependencies && a.dependencies.length !== b.dependencies.length) {
+ return a.dependencies.length - b.dependencies.length; // Fewer dependencies first
+ }
+
+ // If dependency count is the same, sort by ID
+ return a.id - b.id; // Lower ID first
+ })[0]; // Return the first (highest priority) task
+
+ return nextTask;
+}
+
+/**
+ * Display the next task to work on
+ * @param {string} tasksPath - Path to the tasks.json file
+ */
+async function displayNextTask(tasksPath) {
+ displayBanner();
+
+ // Read the tasks file
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "No valid tasks found.");
+ process.exit(1);
+ }
+
+ // Find the next task
+ const nextTask = findNextTask(data.tasks);
+
+ if (!nextTask) {
+ console.log(boxen(
+ chalk.yellow('No eligible tasks found!\n\n') +
+ 'All pending tasks have unsatisfied dependencies, or all tasks are completed.',
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
+ ));
+ return;
+ }
+
+ // Display the task in a nice format
+ console.log(boxen(
+ chalk.white.bold(`Next Task: #${nextTask.id} - ${nextTask.title}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+
+ // Create a table with task details
+ const taskTable = new Table({
+ style: { head: [], border: [] },
+ colWidths: [15, 75] // Adjusted column widths to be more reasonable
+ });
+
+ // Priority with color
+ const priorityColors = {
+ 'high': chalk.red.bold,
+ 'medium': chalk.yellow,
+ 'low': chalk.gray
+ };
+ const priorityColor = priorityColors[nextTask.priority || 'medium'] || chalk.white;
+
+ // Add task details to table
+ taskTable.push(
+ [chalk.cyan.bold('ID:'), nextTask.id.toString()],
+ [chalk.cyan.bold('Title:'), nextTask.title],
+ [chalk.cyan.bold('Priority:'), priorityColor(nextTask.priority || 'medium')],
+ [chalk.cyan.bold('Dependencies:'), formatDependenciesWithStatus(nextTask.dependencies, data.tasks, true)],
+ [chalk.cyan.bold('Description:'), nextTask.description]
+ );
+
+ console.log(taskTable.toString());
+
+ // If task has details, show them in a separate box
+ if (nextTask.details && nextTask.details.trim().length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Implementation Details:') + '\n\n' +
+ nextTask.details,
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+ }
+
+ // Show subtasks if they exist
+ if (nextTask.subtasks && nextTask.subtasks.length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Subtasks'),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, margin: { top: 1, bottom: 0 }, borderColor: 'magenta', borderStyle: 'round' }
+ ));
+
+ // Create a table for subtasks
+ const subtaskTable = new Table({
+ head: [
+ chalk.magenta.bold('ID'),
+ chalk.magenta.bold('Status'),
+ chalk.magenta.bold('Title')
+ ],
+ colWidths: [6, 12, 65], // Reduced column widths
+ style: { head: [], border: [] }
+ });
+
+ // Add subtasks to table
+ nextTask.subtasks.forEach(st => {
+ const statusColor = {
+ 'done': chalk.green,
+ 'completed': chalk.green,
+ 'pending': chalk.yellow,
+ 'in-progress': chalk.blue
+ }[st.status || 'pending'] || chalk.white;
+
+ subtaskTable.push([
+ `${nextTask.id}.${st.id}`,
+ statusColor(st.status || 'pending'),
+ st.title
+ ]);
+ });
+
+ console.log(subtaskTable.toString());
} else {
- log('info', "No subtasks were cleared");
+ // Suggest expanding if no subtasks
+ console.log(boxen(
+ chalk.yellow('No subtasks found. Consider breaking down this task:') + '\n' +
+ chalk.white(`Run: ${chalk.cyan(`node scripts/dev.js expand --id=${nextTask.id}`)}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
}
+
+ // Show action suggestions
+ console.log(boxen(
+ chalk.white.bold('Suggested Actions:') + '\n' +
+ `${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`node scripts/dev.js set-status --id=${nextTask.id} --status=in-progress`)}\n` +
+ `${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`node scripts/dev.js set-status --id=${nextTask.id} --status=done`)}\n` +
+ (nextTask.subtasks && nextTask.subtasks.length > 0
+ ? `${chalk.cyan('3.')} Update subtask status: ${chalk.yellow(`node scripts/dev.js set-status --id=${nextTask.id}.1 --status=done`)}`
+ : `${chalk.cyan('3.')} Break down into subtasks: ${chalk.yellow(`node scripts/dev.js expand --id=${nextTask.id}`)}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
}
+/**
+ * Find a task by its ID
+ * @param {Array} tasks - The array of tasks from tasks.json
+ * @param {string|number} taskId - The ID of the task to find (can be a subtask ID like "1.1")
+ * @returns {Object|null} - The found task or null if not found
+ */
+function findTaskById(tasks, taskId) {
+ // Convert to string for comparison
+ const idStr = String(taskId);
+
+ // Check if it's a subtask ID (contains a dot)
+ if (idStr.includes('.')) {
+ const [parentId, subtaskId] = idStr.split('.');
+
+ // Find the parent task
+ const parentTask = tasks.find(t => String(t.id) === parentId);
+
+ // If parent found and has subtasks, find the specific subtask
+ if (parentTask && parentTask.subtasks && parentTask.subtasks.length > 0) {
+ const subtask = parentTask.subtasks.find(st => String(st.id) === subtaskId);
+ if (subtask) {
+ // Create a copy with parent information
+ return {
+ ...subtask,
+ parentId: parentTask.id,
+ parentTitle: parentTask.title
+ };
+ }
+ }
+ return null;
+ }
+
+ // Regular task ID
+ return tasks.find(t => String(t.id) === idStr) || null;
+}
+
+/**
+ * Display a specific task by ID
+ * @param {string} tasksPath - Path to the tasks.json file
+ * @param {string|number} taskId - The ID of the task to display
+ */
+async function displayTaskById(tasksPath, taskId) {
+ displayBanner();
+
+ // Read the tasks file
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "No valid tasks found.");
+ process.exit(1);
+ }
+
+ // Find the task by ID
+ const task = findTaskById(data.tasks, taskId);
+
+ if (!task) {
+ console.log(boxen(
+ chalk.yellow(`Task with ID ${taskId} not found!`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
+ ));
+ return;
+ }
+
+ // Handle subtask display specially
+ if (task.parentId !== undefined) {
+ console.log(boxen(
+ chalk.white.bold(`Subtask: #${task.parentId}.${task.id} - ${task.title}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'magenta', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+
+ // Create a table with subtask details
+ const taskTable = new Table({
+ style: { head: [], border: [] },
+ colWidths: [15, 75]
+ });
+
+ // Add subtask details to table
+ taskTable.push(
+ [chalk.cyan.bold('ID:'), `${task.parentId}.${task.id}`],
+ [chalk.cyan.bold('Parent Task:'), `#${task.parentId} - ${task.parentTitle}`],
+ [chalk.cyan.bold('Title:'), task.title],
+ [chalk.cyan.bold('Status:'), getStatusWithColor(task.status || 'pending')],
+ [chalk.cyan.bold('Description:'), task.description || 'No description provided.']
+ );
+
+ console.log(taskTable.toString());
+
+ // Show action suggestions for subtask
+ console.log(boxen(
+ chalk.white.bold('Suggested Actions:') + '\n' +
+ `${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.parentId}.${task.id} --status=in-progress`)}\n` +
+ `${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.parentId}.${task.id} --status=done`)}\n` +
+ `${chalk.cyan('3.')} View parent task: ${chalk.yellow(`node scripts/dev.js show --id=${task.parentId}`)}`,
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ return;
+ }
+
+ // Display a regular task
+ console.log(boxen(
+ chalk.white.bold(`Task: #${task.id} - ${task.title}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+
+ // Create a table with task details
+ const taskTable = new Table({
+ style: { head: [], border: [] },
+ colWidths: [15, 75]
+ });
+
+ // Priority with color
+ const priorityColors = {
+ 'high': chalk.red.bold,
+ 'medium': chalk.yellow,
+ 'low': chalk.gray
+ };
+ const priorityColor = priorityColors[task.priority || 'medium'] || chalk.white;
+
+ // Add task details to table
+ taskTable.push(
+ [chalk.cyan.bold('ID:'), task.id.toString()],
+ [chalk.cyan.bold('Title:'), task.title],
+ [chalk.cyan.bold('Status:'), getStatusWithColor(task.status || 'pending')],
+ [chalk.cyan.bold('Priority:'), priorityColor(task.priority || 'medium')],
+ [chalk.cyan.bold('Dependencies:'), formatDependenciesWithStatus(task.dependencies, data.tasks, true)],
+ [chalk.cyan.bold('Description:'), task.description]
+ );
+
+ console.log(taskTable.toString());
+
+ // If task has details, show them in a separate box
+ if (task.details && task.details.trim().length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Implementation Details:') + '\n\n' +
+ task.details,
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+ }
+
+ // Show test strategy if available
+ if (task.testStrategy && task.testStrategy.trim().length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Test Strategy:') + '\n\n' +
+ task.testStrategy,
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+ }
+
+ // Show subtasks if they exist
+ if (task.subtasks && task.subtasks.length > 0) {
+ console.log(boxen(
+ chalk.white.bold('Subtasks'),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, margin: { top: 1, bottom: 0 }, borderColor: 'magenta', borderStyle: 'round' }
+ ));
+
+ // Create a table for subtasks
+ const subtaskTable = new Table({
+ head: [
+ chalk.magenta.bold('ID'),
+ chalk.magenta.bold('Status'),
+ chalk.magenta.bold('Title')
+ ],
+ colWidths: [6, 12, 65],
+ style: { head: [], border: [] }
+ });
+
+ // Add subtasks to table
+ task.subtasks.forEach(st => {
+ const statusColor = {
+ 'done': chalk.green,
+ 'completed': chalk.green,
+ 'pending': chalk.yellow,
+ 'in-progress': chalk.blue
+ }[st.status || 'pending'] || chalk.white;
+
+ subtaskTable.push([
+ `${task.id}.${st.id}`,
+ statusColor(st.status || 'pending'),
+ st.title
+ ]);
+ });
+
+ console.log(subtaskTable.toString());
+ } else {
+ // Suggest expanding if no subtasks
+ console.log(boxen(
+ chalk.yellow('No subtasks found. Consider breaking down this task:') + '\n' +
+ chalk.white(`Run: ${chalk.cyan(`node scripts/dev.js expand --id=${task.id}`)}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
+ ));
+ }
+
+ // Show action suggestions
+ console.log(boxen(
+ chalk.white.bold('Suggested Actions:') + '\n' +
+ `${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.id} --status=in-progress`)}\n` +
+ `${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.id} --status=done`)}\n` +
+ (task.subtasks && task.subtasks.length > 0
+ ? `${chalk.cyan('3.')} Update subtask status: ${chalk.yellow(`node scripts/dev.js set-status --id=${task.id}.1 --status=done`)}`
+ : `${chalk.cyan('3.')} Break down into subtasks: ${chalk.yellow(`node scripts/dev.js expand --id=${task.id}`)}`),
+ { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+}
+
+/**
+ * Add a dependency to a task
+ * @param {string} tasksPath - Path to the tasks.json file
+ * @param {number|string} taskId - ID of the task to add dependency to
+ * @param {number|string} dependencyId - ID of the task to add as dependency
+ */
+async function addDependency(tasksPath, taskId, dependencyId) {
+ // Convert IDs to numbers for consistent comparison
+ const taskIdNum = parseInt(taskId, 10);
+ const dependencyIdNum = parseInt(dependencyId, 10);
+
+ // Read tasks file
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "No valid tasks found.");
+ process.exit(1);
+ }
+
+ // Find the task to modify
+ const taskToModify = data.tasks.find(t => t.id === taskIdNum);
+ if (!taskToModify) {
+ log('error', `Task with ID ${taskIdNum} was not found.`);
+ process.exit(1);
+ }
+
+ // Find the dependency task to ensure it exists
+ const dependencyTask = data.tasks.find(t => t.id === dependencyIdNum);
+ if (!dependencyTask) {
+ log('error', `Dependency task with ID ${dependencyIdNum} was not found.`);
+ process.exit(1);
+ }
+
+ // Prevent circular dependencies
+ if (taskIdNum === dependencyIdNum) {
+ log('error', "A task cannot depend on itself.");
+ process.exit(1);
+ }
+
+ // Initialize dependencies array if it doesn't exist
+ if (!taskToModify.dependencies) {
+ taskToModify.dependencies = [];
+ }
+
+ // Check if dependency already exists
+ if (taskToModify.dependencies.includes(dependencyIdNum)) {
+ log('info', `Task #${taskIdNum} already depends on task #${dependencyIdNum}, no changes made.`);
+ return;
+ }
+
+ // Add the dependency
+ taskToModify.dependencies.push(dependencyIdNum);
+
+ // Sort dependencies for clarity
+ taskToModify.dependencies.sort((a, b) => a - b);
+
+ // Save the updated tasks
+ writeJSON(tasksPath, data);
+
+ // Success message
+ log('success', `Added dependency: Task #${taskIdNum} now depends on task #${dependencyIdNum}`);
+
+ // Display a more visually appealing success message
+ console.log(boxen(
+ chalk.green(`Successfully added dependency:\n\n`) +
+ `Task ${chalk.bold(`#${taskIdNum}`)} now depends on task ${chalk.bold(`#${dependencyIdNum}`)}`,
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ // Regenerate task files
+ await generateTaskFiles(tasksPath, 'tasks');
+}
+
+/**
+ * Remove a dependency from a task
+ * @param {string} tasksPath - Path to the tasks.json file
+ * @param {number|string} taskId - ID of the task to remove dependency from
+ * @param {number|string} dependencyId - ID of the task to remove as dependency
+ */
+async function removeDependency(tasksPath, taskId, dependencyId) {
+ // Convert IDs to numbers for consistent comparison
+ const taskIdNum = parseInt(taskId, 10);
+ const dependencyIdNum = parseInt(dependencyId, 10);
+
+ // Read tasks file
+ const data = readJSON(tasksPath);
+ if (!data || !data.tasks) {
+ log('error', "No valid tasks found.");
+ process.exit(1);
+ }
+
+ // Find the task to modify
+ const taskToModify = data.tasks.find(t => t.id === taskIdNum);
+ if (!taskToModify) {
+ log('error', `Task with ID ${taskIdNum} was not found.`);
+ process.exit(1);
+ }
+
+ // Check if the task has any dependencies
+ if (!taskToModify.dependencies || taskToModify.dependencies.length === 0) {
+ log('info', `Task #${taskIdNum} has no dependencies, nothing to remove.`);
+ return;
+ }
+
+ // Check if the dependency exists
+ if (!taskToModify.dependencies.includes(dependencyIdNum)) {
+ log('info', `Task #${taskIdNum} does not depend on task #${dependencyIdNum}, no changes made.`);
+ return;
+ }
+
+ // Remove the dependency
+ taskToModify.dependencies = taskToModify.dependencies.filter(depId => depId !== dependencyIdNum);
+
+ // Save the updated tasks
+ writeJSON(tasksPath, data);
+
+ // Success message
+ log('success', `Removed dependency: Task #${taskIdNum} no longer depends on task #${dependencyIdNum}`);
+
+ // Display a more visually appealing success message
+ console.log(boxen(
+ chalk.green(`Successfully removed dependency:\n\n`) +
+ `Task ${chalk.bold(`#${taskIdNum}`)} no longer depends on task ${chalk.bold(`#${dependencyIdNum}`)}`,
+ { padding: 1, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
+ ));
+
+ // Regenerate task files
+ await generateTaskFiles(tasksPath, 'tasks');
+}
+
+
+// At the very end of the file
main().catch(err => {
- log('error', err);
+ console.error('ERROR in main:', err);
process.exit(1);
});
\ No newline at end of file
diff --git a/templates/dev_workflow.mdc b/templates/dev_workflow.mdc
index e5175c32..8a599186 100644
--- a/templates/dev_workflow.mdc
+++ b/templates/dev_workflow.mdc
@@ -10,6 +10,7 @@ alwaysApply: true
- Analyze task complexity with `node scripts/dev.js analyze-complexity --research` before breaking down tasks
- Select tasks based on dependencies (all marked 'done'), priority level, and ID order
- Clarify tasks by checking task files in tasks/ directory or asking for user input
+ - View specific task details using `node scripts/dev.js show --id=<id>` to understand implementation requirements
- Break down complex tasks using `node scripts/dev.js expand --id=<id>` with appropriate flags
- Clear existing subtasks if needed using `node scripts/dev.js clear-subtasks --id=<id>` before regenerating
- Implement code following task details, dependencies, and project standards
@@ -149,6 +150,8 @@ alwaysApply: true
- **description**: Concise summary of what the task involves (Example: `"Create a new repository, set up initial structure."`)
- **status**: Current state of the task (Example: `"pending"`, `"done"`, `"deferred"`)
- **dependencies**: IDs of prerequisite tasks (Example: `[1, 2]`)
+ - Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending)
+ - This helps quickly identify which prerequisite tasks are blocking work
- **priority**: Importance level (Example: `"high"`, `"medium"`, `"low"`)
- **details**: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`)
- **testStrategy**: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`)
@@ -167,3 +170,52 @@ alwaysApply: true
- **PROJECT_VERSION** (Default: `"1.0.0"`): Version in metadata (Example: `PROJECT_VERSION=2.1.0`)
- **PERPLEXITY_API_KEY**: For research-backed features (Example: `PERPLEXITY_API_KEY=pplx-...`)
- **PERPLEXITY_MODEL** (Default: `"sonar-medium-online"`): Perplexity model (Example: `PERPLEXITY_MODEL=sonar-large-online`)
+
+- **Determining the Next Task**
+ - Run `node scripts/dev.js next` to show the next task to work on
+ - The next command identifies tasks with all dependencies satisfied
+ - Tasks are prioritized by priority level, dependency count, and ID
+ - The command shows comprehensive task information including:
+ - Basic task details and description
+ - Implementation details
+ - Subtasks (if they exist)
+ - Contextual suggested actions
+ - Recommended before starting any new development work
+ - Respects your project's dependency structure
+ - Ensures tasks are completed in the appropriate sequence
+ - Provides ready-to-use commands for common task actions
+
+- **Viewing Specific Task Details**
+ - Run `node scripts/dev.js show --id=<id>` or `node scripts/dev.js show <id>` to view a specific task
+ - Use dot notation for subtasks: `node scripts/dev.js show 1.2` (shows subtask 2 of task 1)
+ - Displays comprehensive information similar to the next command, but for a specific task
+ - For parent tasks, shows all subtasks and their current status
+ - For subtasks, shows parent task information and relationship
+ - Provides contextual suggested actions appropriate for the specific task
+ - Useful for examining task details before implementation or checking status
+
+- **Managing Task Dependencies**
+ - Use `node scripts/dev.js add-dependency --id=<id> --depends-on=<id>` to add a dependency
+ - Use `node scripts/dev.js remove-dependency --id=<id> --depends-on=<id>` to remove a dependency
+ - The system prevents circular dependencies and duplicate dependency entries
+ - Dependencies are checked for existence before being added or removed
+ - Task files are automatically regenerated after dependency changes
+ - Dependencies are visualized with status indicators in task listings and files
+
+- **Command Reference: add-dependency**
+ - Syntax: `node scripts/dev.js add-dependency --id=<id> --depends-on=<id>`
+ - Description: Adds a dependency relationship between two tasks
+ - Parameters:
+ - `--id=<id>`: ID of task that will depend on another task (required)
+ - `--depends-on=<id>`: ID of task that will become a dependency (required)
+ - Example: `node scripts/dev.js add-dependency --id=22 --depends-on=21`
+ - Notes: Prevents circular dependencies and duplicates; updates task files automatically
+
+- **Command Reference: remove-dependency**
+ - Syntax: `node scripts/dev.js remove-dependency --id=<id> --depends-on=<id>`
+ - Description: Removes a dependency relationship between two tasks
+ - Parameters:
+ - `--id=<id>`: ID of task to remove dependency from (required)
+ - `--depends-on=<id>`: ID of task to remove as a dependency (required)
+ - Example: `node scripts/dev.js remove-dependency --id=22 --depends-on=21`
+ - Notes: Checks if dependency actually exists; updates task files automatically
diff --git a/templates/scripts_README.md b/templates/scripts_README.md
index 08efa586..f96062ad 100644
--- a/templates/scripts_README.md
+++ b/templates/scripts_README.md
@@ -14,6 +14,7 @@ In an AI-driven development process—particularly with tools like [Cursor](http
6. **Expand** tasks with subtasks—break down complex tasks into smaller, more manageable subtasks.
7. **Research-backed subtask generation**—use Perplexity AI to generate more informed and contextually relevant subtasks.
8. **Clear subtasks**—remove subtasks from specified tasks to allow regeneration or restructuring.
+9. **Show task details**—display detailed information about a specific task and its subtasks.
## Configuration
@@ -41,6 +42,7 @@ The script can be configured through environment variables in a `.env` file at t
- A JSON file at the project root containing an array of tasks (each with `id`, `title`, `description`, `status`, etc.).
- The `meta` field can store additional info like the project's name, version, or reference to the PRD.
- Tasks can have `subtasks` for more detailed implementation steps.
+ - Dependencies are displayed with status indicators (✅ for completed, ⏱️ for pending) to easily track progress.
2. **Script Commands**
You can run the script via:
@@ -58,6 +60,8 @@ The script can be configured through environment variables in a `.env` file at t
- `set-status`: Change a task's status
- `expand`: Add subtasks to a task or all tasks
- `clear-subtasks`: Remove subtasks from specified tasks
+ - `next`: Determine the next task to work on based on dependencies
+ - `show`: Display detailed information about a specific task
Run `node scripts/dev.js` without arguments to see detailed usage information.
@@ -122,6 +126,7 @@ Notes:
- Common status values are 'done', 'pending', and 'deferred', but any string is accepted
- You can specify multiple task IDs by separating them with commas
- Subtask IDs are specified using the format `parentId.subtaskId` (e.g., `3.1`)
+- Dependencies are updated to show completion status (✅ for completed, ⏱️ for pending) throughout the system
## Expanding Tasks
@@ -270,4 +275,102 @@ The output report structure is:
// More tasks sorted by complexity score (highest first)
]
}
-```
\ No newline at end of file
+```
+
+## Finding the Next Task
+
+The `next` command helps you determine which task to work on next based on dependencies and status:
+
+```bash
+# Show the next task to work on
+node scripts/dev.js next
+
+# Specify a different tasks file
+node scripts/dev.js next --file=custom-tasks.json
+```
+
+This command:
+
+1. Identifies all **eligible tasks** - pending or in-progress tasks whose dependencies are all satisfied (marked as done)
+2. **Prioritizes** these eligible tasks by:
+ - Priority level (high > medium > low)
+ - Number of dependencies (fewer dependencies first)
+ - Task ID (lower ID first)
+3. **Displays** comprehensive information about the selected task:
+ - Basic task details (ID, title, priority, dependencies)
+ - Detailed description and implementation details
+ - Subtasks if they exist
+4. Provides **contextual suggested actions**:
+ - Command to mark the task as in-progress
+ - Command to mark the task as done when completed
+ - Commands for working with subtasks (update status or expand)
+
+This feature ensures you're always working on the most appropriate task based on your project's current state and dependency structure.
+
+## Showing Task Details
+
+The `show` command allows you to view detailed information about a specific task:
+
+```bash
+# Show details for a specific task
+node scripts/dev.js show 1
+
+# Alternative syntax with --id option
+node scripts/dev.js show --id=1
+
+# Show details for a subtask
+node scripts/dev.js show --id=1.2
+
+# Specify a different tasks file
+node scripts/dev.js show 3 --file=custom-tasks.json
+```
+
+This command:
+
+1. **Displays comprehensive information** about the specified task:
+ - Basic task details (ID, title, priority, dependencies, status)
+ - Full description and implementation details
+ - Test strategy information
+ - Subtasks if they exist
+2. **Handles both regular tasks and subtasks**:
+ - For regular tasks, shows all subtasks and their status
+ - For subtasks, shows the parent task relationship
+3. **Provides contextual suggested actions**:
+ - Commands to update the task status
+ - Commands for working with subtasks
+ - For subtasks, provides a link to view the parent task
+
+This command is particularly useful when you need to examine a specific task in detail before implementing it or when you want to check the status and details of a particular task.
+
+## Managing Task Dependencies
+
+The `add-dependency` and `remove-dependency` commands allow you to manage task dependencies:
+
+```bash
+# Add a dependency to a task
+node scripts/dev.js add-dependency --id=<id> --depends-on=<id>
+
+# Remove a dependency from a task
+node scripts/dev.js remove-dependency --id=<id> --depends-on=<id>
+```
+
+These commands:
+
+1. **Allow precise dependency management**:
+ - Add dependencies between tasks with automatic validation
+ - Remove dependencies when they're no longer needed
+ - Update task files automatically after changes
+
+2. **Include validation checks**:
+ - Prevent circular dependencies (a task depending on itself)
+ - Prevent duplicate dependencies
+ - Verify that both tasks exist before adding/removing dependencies
+ - Check if dependencies exist before attempting to remove them
+
+3. **Provide clear feedback**:
+ - Success messages confirm when dependencies are added/removed
+ - Error messages explain why operations failed (if applicable)
+
+4. **Automatically update task files**:
+ - Regenerates task files to reflect dependency changes
+ - Ensures tasks and their files stay synchronized
\ No newline at end of file