AIStoreHub Package Vault: Claude Task Master
Package Slug: claude-task-master
Archetype: mcp_server
Upstream Repository: https://github.com/eyaltoledano/claude-task-master
Workspace Files & Specifications (67 files)
- .claude-plugin/marketplace.json (853 bytes)
{ "name": "taskmaster", "owner": { "name": "Hamster", "email": "[email protected]" }, "metadata": { "description": "Official marketplace for Taskmaster AI - AI-powered task management for ambitious development", "version": "1.0.0" }, "plugins": [ { "name": "taskmaster", "source": "./packages/claude-code-plugin", "description": "AI-powered task management system for ambitious development workflows with intelligent orchestration, complexity analysis, and automated coordination", "author": { "name": "Hamster" }, "homepage": "https://github.com/eyaltoledano/claude-task-master", "repository": "https://github.com/eyaltoledano/claude-task-master", "keywords": [ "task-management", "ai", "workflow", "orchestration", "automation", "mcp" ], "category": "productivity" } ] } - .claude/commands/dedupe.md (1850 bytes)
--- allowed-tools: Bash(gh issue view:*), Bash(gh search:*), Bash(gh issue list:*), Bash(gh api:*), Bash(gh issue comment:*) description: Find duplicate GitHub issues --- Find up to 3 likely duplicate issues for a given GitHub issue. To do this, follow these steps precisely: 1. Use an agent to check if the Github issue (a) is closed, (b) does not need to be deduped (eg. because it is broad product feedback without a specific solution, or positive feedback), or (c) already has a duplicates comment that you made earlier. If so, do not proceed. 2. Use an agent to view a Github issue, and ask the agent to return a summary of the issue 3. Then, launch 5 parallel agents to search Github for duplicates of this issue, using diverse keywords and search approaches, using the summary from #1 4. Next, feed the results from #1 and #2 into another agent, so that it can filter out false positives, that are likely not actually duplicates of the original issue. If there are no duplicates remaining, do not proceed. 5. Finally, comment back on the issue with a list of up to three duplicate issues (or zero, if there are no likely duplicates) Notes (be sure to tell this to your agents, too): - Use `gh` to interact with Github, rather than web fetch - Do not use other tools, beyond `gh` (eg. don't use other MCP servers, file edit, etc.) - Make a todo list first - For your comment, follow the following format precisely (assuming for this example that you found 3 suspected duplicates): --- Found 3 possible duplicate issues: 1. <link to issue> 2. <link to issue> 3. <link to issue> This issue will be automatically closed as a duplicate in 3 days. - If your issue is a duplicate, please close it and π the existing issue instead - To prevent auto-closure, add a comment or π this comment π€ Generated with \[Task Master Bot\] ---
- .claude/commands/go/ham.md (5530 bytes)
# Hamster (Go ham!) Run Task Workflow This command initiates the HAM (Hamster Automated Management) workflow for task execution. ## Usage ``` /go:ham [task-id] ``` - `task-id` (optional): Specific task identifier to work on (e.g., "1", "1.2", "2.3.1") - If provided, start working on that specific task immediately - If omitted, automatically identify the next available task ## Process When the user invokes this command, follow these steps: ### 1. Task Selection #### If task-id is provided ($ARGUMENTS is not empty): ```bash tm show $ARGUMENTS ``` Start working on the specified task immediately, skipping to step 3. #### If no task-id is provided ($ARGUMENTS is empty): ```bash tm list ``` Display all tasks with their current status to provide context. ### 2. Identify Next Task (only if no task-id provided) Determine which task should be worked on next based on: - Dependencies - Priority - Current status (pending tasks only) ### 3. Show Task Details (only if task wasn't specified in step 1) ```bash tm show <task-id> ``` Display the full details of the identified task including: - Title and description - Dependencies - Test strategy - Subtasks (if any) ### 4. Kickoff Workflow Based on the task type, follow the appropriate workflow: #### For Main Tasks (e.g., "1", "2", "3") - Review the task's subtasks - If no subtasks exist, suggest expanding the task first - Identify the first pending subtask - Begin implementation following the subtask's requirements #### For Subtasks (e.g., "1.1", "2.3") - Mark the subtask as in-progress: ```bash tm set-status --id=<subtask-id> --status=in-progress ``` - Review the task details and requirements - Check for related code files or dependencies - Create an implementation plan - Begin implementation following project conventions ### 5. Implementation Guidelines Follow these principles during implementation: 1. **Understand First**: Read related files and understand the current architecture 2. **Plan**: Create a mental model or brief plan before coding 3. **Follow Conventions**: Adhere to project structure and coding standards 4. **Test As You Go**: Validate changes incrementally 5. **Stay Focused**: Complete the current subtask before moving to the next ### 6. Task Completion When the subtask is complete: ```bash tm set-status --id=<subtask-id> --status=done ``` Then automatically check for the next available task by repeating from step 2. ## Example Flows ### With Specific Task ID ``` User: "/go:ham 1.2" 1. Claude runs: tm show 1.2 β Displays full task details 2. Claude analyzes the task and creates an implementation plan 3. Claude marks task in-progress: tm set-status --id=1.2 --status=in-progress 4. Claude begins implementation following the task requirements 5. Upon completion, Claude runs: tm set-status --id=1.2 --status=done 6. Claude automatically identifies next task with tm list ``` ### Without Specific Task ID (Auto-discovery) ``` User: "/go:ham" 1. Claude runs: tm list 2. Claude identifies next available task (e.g., 1.2) 3. Claude runs: tm show 1.2 β Displays full task details 4. Claude analyzes the task and creates an implementation plan 5. Claude marks task in-progress: tm set-status --id=1.2 --status=in-progress 6. Claude begins implementation following the task requirements 7. Upon completion, Claude runs: tm set-status --id=1.2 --status=done 8. Claude automatically identifies next task with tm list ``` ## Notes - Always verify task dependencies are complete before starting - If a task is blocked, mark it as such and move to the next available task - Keep the user informed of progress at each major step - Ask for clarification if task requirements are unclear - Follow the project's CLAUDE.md and .cursor/rules/* guidelines at all times - Unlike the usual Taskmaster process, do not bother using update-task nor update-subtask as they do not work with Hamster tasks yet. - Use only `tm list`, `tm show <sub/task id>` and `tm set status` - other commands don't yet work with it. - Do not use the MCP tools when connected with Hamster briefs - that is not yet up to date. - Use `.cursor/rules/git_workflow.mdc` as a guide for the workflow - When starting a task, mark it as in-progress. You can mark multiple task statuses at once with comma separation (i.e. `tm set-status -i 1,1.1 -s in-progress`) - Read the task, then if it has subtasks, begin implementing the subtasks one at a time. - When the subtask is done, run lint and typecheck, mark the task as done if it passes, and commit. - Continue until all subtasks are done, then run a final lint and typecheck (`npm lint` and `npm typecheck`) and create a PR using `gh` cli for that Task. - Keep committing to the same PR as long as the scope is maintained. An entire task list (brief) might fit into a single PR but not if it ends up being huge. It is preferred for everything to land in one PR if it is possible, otherwise commit to different PRs that build on top of the previous ones. Confirm with the human when doing this. - When the parent task is completed, ensure you mark is as done. - When the first task is done, repeat this process for all tasks until all tasks are done. - If you run into an issue where the JWT seems expired or commands don't work, ensure you use `tm auth refresh` to refresh the token and if that does not work, use `tm context <brief url>` to reconnect the context. If you do not have the brief url, ask the user for it (perhaps use it at the beginning) You're a fast hamster. Go go go.
- .claude/commands/go/pr-comments.md (4583 bytes)
Fix PR review comments: PR # $ARGUMENTS This command collects all review comments from a GitHub PR (including CodeRabbit, human reviewers, and other bots), consolidates them by author and severity, shows them to you for approval, then implements the approved fixes. Steps: 1. **Collect PR comments** - Run: `gh pr view $ARGUMENTS --comments` to get ALL comments (no truncation) - Parse and extract all review comments from: - PR review comments (file-level) - General comments - Review threads - Include author information for each comment - IMPORTANT: Do NOT use `head`, `tail`, or any truncation - we need complete comment history 2. **Consolidate comments** - Group comments by: - Author (CodeRabbit, human reviewers, other bots) - Severity (π¨ Critical, β οΈ Important, π‘ Suggestion, βΉοΈ Info) - Category (Security, Performance, Best Practices, Style, etc.) - Remove duplicates and group similar issues - Present in a clear, numbered list format showing author for each 3. **Show consolidated issues for approval** - Display the organized list with: - Issue number for reference - Severity indicator - File location - Description - Suggested fix - Ask: "Which issues would you like me to fix? (Enter numbers separated by commas, or 'all' for everything)" - Wait for user confirmation 4. **Implement approved fixes** - For each approved issue: - Read the relevant file(s) - Implement the suggested fix - Log what was changed 5. **Validate changes** - Run: `pnpm typecheck` - If fails: review errors, fix them, retry - Run: `pnpm lint` - If fails: review errors, fix them, retry - Continue until both pass 6. **Commit and push** - Stage changes: `git add .` - Create commit: `git commit -m "fix: address review comments from PR #$ARGUMENTS"` - Push: `git push` - Confirm completion with summary of fixes applied Notes: - If no review comments found, inform user and exit - If typecheck/lint fails after fixes, show errors and ask for guidance - Keep fixes focused on reviewers' specific suggestions - Preserve existing code style and patterns - Group related fixes in the commit message if many changes - Treat all reviewers equally - human and bot feedback both matter You previously got all the PR comments in a temporary JSON file and then ran something like this; cat > /tmp/parse_comments.js << 'EOF' const fs = require('fs'); const comments = JSON.parse(fs.readFileSync('/tmp/all-pr-comments.json', 'utf8')); const byFile = {}; const bySeverity = { critical: [], important: [], suggestion: [], info: [] }; comments.forEach((c, idx) => { const file = c.path; const author = c.user.login; const line = c.line || c.original_line || 'N/A'; const body = c.body; if (!byFile[file]) byFile[file] = []; const comment = { num: idx + 1, author, line, body: body.substring(0, 200) + (body.length > 200 ? '...' : ''), fullBody: body }; byFile[file].push(comment); // Categorize by severity const lower = body.toLowerCase(); if (lower.includes('critical') || lower.includes('security') || lower.includes('bug:')) { bySeverity.critical.push({...comment, file}); } else if (lower.includes('important') || lower.includes('error') || lower.includes('fail')) { bySeverity.important.push({...comment, file}); } else if (lower.includes('suggestion') || lower.includes('consider') || lower.includes('recommend')) { bySeverity.suggestion.push({...comment, file}); } else { bySeverity.info.push({...comment, file}); } }); console.log('\n=== SUMMARY BY SEVERITY ===\n'); console.log(`π¨ Critical: ${bySeverity.critical.length}`); console.log(`β οΈ Important: ${bySeverity.important.length}`); console.log(`π‘ Suggestion: ${bySeverity.suggestion.length}`); console.log(`βΉοΈ Info: ${bySeverity.info.length}`); console.log('\n=== SUMMARY BY FILE ===\n'); Object.entries(byFile) .sort((a, b) => b[1].length - a[1].length) .forEach(([file, comments]) => { console.log(`${file}: ${comments.length} comments`); }); console.log('\n=== CRITICAL ISSUES ===\n'); bySeverity.critical.forEach(c => { console.log(`\n#${c.num} [${c.author}] ${c.file}:${c.line}`); console.log(c.body); }); console.log('\n=== IMPORTANT ISSUES ===\n'); bySeverity.important.slice(0, 10).forEach(c => { console.log(`\n#${c.num} [${c.author}] ${c.file}:${c.line}`); console.log(c.body); }); EOF node /tmp/parse_comments.js And got a nice report you could act on. - .claude/hamster.md (4626 bytes)
# Hamster Integration Workflow This guide outlines the process for working with tasks imported from Hamster briefs using Task Master. When connected to a Hamster brief, follow these specific guidelines to ensure proper task management and workflow execution. ## Command Restrictions ### Supported Commands Use only these Task Master CLI commands when working with Hamster briefs: ```bash tm list # List all tasks tm show <sub/task id> --json # Show task details (--json saves tokens) tm set-status # Update task status tm auth refresh # Refresh authentication token tm context <brief url> # Reconnect to Hamster brief context ``` ### Unsupported Commands - Do not use MCP tools when connected with Hamster briefs - they are not yet up to date with Hamster integration - Do not use other Task Master CLI commands that haven't been verified to work with Hamster integration ## Task Workflow Process ### Starting a Task ```bash # Mark task and subtasks as in-progress when starting tm set-status -i 1,1.1 -s in-progress # Multiple tasks/subtasks can be marked at once using comma separation tm set-status -i 1,1.1,1.2,2 -s in-progress ``` ### Task Implementation Flow 1. **Read the Task**: Use `tm show <id> --json` to understand the task requirements 2. **Check for Subtasks**: If the task has subtasks, implement them one at a time 3. **Implement Subtask**: Complete the subtask implementation 4. **Verify Quality**: Run lint and typecheck before marking as done ```bash npm run lint npm run typecheck ``` 5. **Mark Complete**: If verification passes, mark the subtask as done ```bash tm set-status -i 1.1 -s done ``` 6. **Commit Changes**: Commit the completed subtask work 7. **Repeat**: Continue until all subtasks are complete ### Parent Task Completion - After all subtasks are done, run final verification: ```bash npm run lint npm run typecheck ``` - Mark the parent task as done: ```bash tm set-status -i 1 -s done ``` - Move to the next task and repeat the process ## Multiple Task Context ### Viewing Multiple Tasks ```bash # Use comma-separated IDs to get context from multiple tasks tm show 1,1.1,2,2.1 --json # This is more efficient than calling tm show multiple times ``` ### Parallel Subtask Execution - **When to Parallelize**: If a task has subtasks that can be completed in parallel - **Requirements**: - Ensure work/files to adjust are **not the same** across subtasks - Spawn sub-agents for each parallel subtask - Verify clear separation of work before parallelizing - **Example**: If subtask 1.1 modifies `src/api.js` and subtask 1.2 modifies `src/utils.js`, these can run in parallel ## Pull Request Management ### PR Creation Strategy - **Preferred Approach**: Keep everything in one PR if scope remains manageable - **When to Split**: Create separate PRs if the work becomes too large - **Multi-PR Strategy**: If splitting is necessary: - Create PRs that build on top of previous ones - **Always confirm with the human** before creating multiple PRs - **PR Creation**: Use GitHub CLI after completing a task: ```bash gh pr create --title "Task X: [Task Title]" --body "Description" ``` ### Committing to PRs - Keep committing to the same PR as long as the scope is maintained - An entire task list (brief) might fit into a single PR - If scope grows too large, discuss with human before creating new PRs ## Authentication & Context Management ### Token Refresh ```bash # Refresh token if JWT seems expired or commands don't work tm auth refresh # If refresh doesn't work, reconnect context tm context <brief url> ``` ### Context Reconnection - **When Needed**: If commands stop working or authentication fails - **Required Information**: Brief URL (ask user if not available) - **Best Practice**: Store brief URL at the beginning of the session - **Command**: `tm context <brief url>` ## Integration with Git Workflow When working with Hamster briefs, follow standard Git workflow patterns: - Create task-specific branches: `task-XXX` - Commit subtask work incrementally - Create PRs after task completion - Follow commit message standards ## Key Principles - **Incremental Progress**: Work through subtasks one at a time - **Quality Gates**: Always run lint and typecheck before marking tasks as done - **Clear Communication**: Confirm with human before splitting work across multiple PRs - **Efficient Context Gathering**: Use comma-separated IDs when viewing multiple tasks - **Authentication Management**: Proactively refresh tokens and reconnect context when needed
- .claude/TM_COMMANDS_GUIDE.md (4097 bytes)
# Task Master Commands for Claude Code Complete guide to using Task Master through Claude Code's slash commands. ## Overview All Task Master functionality is available through the `/project:tm/` namespace with natural language support and intelligent features. ## Quick Start ```bash # Install Task Master /project:tm/setup/quick-install # Initialize project /project:tm/init/quick # Parse requirements /project:tm/parse-prd requirements.md # Start working /project:tm/next ``` ## Command Structure Commands are organized hierarchically to match Task Master's CLI: - Main commands at `/project:tm/[command]` - Subcommands for specific operations `/project:tm/[command]/[subcommand]` - Natural language arguments accepted throughout ## Complete Command Reference ### Setup & Configuration - `/project:tm/setup/install` - Full installation guide - `/project:tm/setup/quick-install` - One-line install - `/project:tm/init` - Initialize project - `/project:tm/init/quick` - Quick init with -y - `/project:tm/models` - View AI config - `/project:tm/models/setup` - Configure AI ### Task Generation - `/project:tm/parse-prd` - Generate from PRD - `/project:tm/parse-prd/with-research` - Enhanced parsing - `/project:tm/generate` - Create task files ### Task Management - `/project:tm/list` - List with natural language filters - `/project:tm/list/with-subtasks` - Hierarchical view - `/project:tm/list/by-status <status>` - Filter by status - `/project:tm/show <id>` - Task details - `/project:tm/add-task` - Create task - `/project:tm/update` - Update tasks - `/project:tm/remove-task` - Delete task ### Status Management - `/project:tm/set-status/to-pending <id>` - `/project:tm/set-status/to-in-progress <id>` - `/project:tm/set-status/to-done <id>` - `/project:tm/set-status/to-review <id>` - `/project:tm/set-status/to-deferred <id>` - `/project:tm/set-status/to-cancelled <id>` ### Task Analysis - `/project:tm/analyze-complexity` - AI analysis - `/project:tm/complexity-report` - View report - `/project:tm/expand <id>` - Break down task - `/project:tm/expand/all` - Expand all complex ### Dependencies - `/project:tm/add-dependency` - Add dependency - `/project:tm/remove-dependency` - Remove dependency - `/project:tm/validate-dependencies` - Check issues - `/project:tm/fix-dependencies` - Auto-fix ### Workflows - `/project:tm/workflows/smart-flow` - Adaptive workflows - `/project:tm/workflows/pipeline` - Chain commands - `/project:tm/workflows/auto-implement` - AI implementation ### Utilities - `/project:tm/status` - Project dashboard - `/project:tm/next` - Next task recommendation - `/project:tm/utils/analyze` - Project analysis - `/project:tm/learn` - Interactive help ## Key Features ### Natural Language Support All commands understand natural language: ``` /project:tm/list pending high priority /project:tm/update mark 23 as done /project:tm/add-task implement OAuth login ``` ### Smart Context Commands analyze project state and provide intelligent suggestions based on: - Current task status - Dependencies - Team patterns - Project phase ### Visual Enhancements - Progress bars and indicators - Status badges - Organized displays - Clear hierarchies ## Common Workflows ### Daily Development ``` /project:tm/workflows/smart-flow morning /project:tm/next /project:tm/set-status/to-in-progress <id> /project:tm/set-status/to-done <id> ``` ### Task Breakdown ``` /project:tm/show <id> /project:tm/expand <id> /project:tm/list/with-subtasks ``` ### Sprint Planning ``` /project:tm/analyze-complexity /project:tm/workflows/pipeline init β expand/all β status ``` ## Migration from Old Commands | Old | New | |-----|-----| | `/project:task-master:list` | `/project:tm/list` | | `/project:task-master:complete` | `/project:tm/set-status/to-done` | | `/project:workflows:auto-implement` | `/project:tm/workflows/auto-implement` | ## Tips 1. Use `/project:tm/` + Tab for command discovery 2. Natural language is supported everywhere 3. Commands provide smart defaults 4. Chain commands for automation 5. Check `/project:tm/learn` for interactive help
- aistorehub.json (526 bytes)
{ "name": "Claude Task Master", "slug": "claude-task-master", "version": "1.0.0", "type": "mcp_server", "description": "AI-powered task-management system and MCP server designed to drop into Cursor, Lovable, Windsurf, Roo, and Claude Code.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/eyaltoledano/claude-task-master", "tags": [ "claude-code", "task-management", "mcp", "coding-agent", "cursor" ], "imported_at": "2026-11-22T00:08:29.594Z" } - assets/AGENTS.md (14471 bytes)
# Task Master AI - Agent Integration Guide ## Essential Commands ### Core Workflow Commands ```bash # Project Setup task-master init # Initialize Task Master in current project task-master parse-prd .taskmaster/docs/prd.md # Generate tasks from PRD document task-master models --setup # Configure AI models interactively # Daily Development Workflow task-master list # Show all tasks with status task-master next # Get next available task to work on task-master show <id> # View detailed task information (e.g., task-master show 1.2) task-master set-status --id=<id> --status=done # Mark task complete # Task Management task-master add-task --prompt="description" --research # Add new task with AI assistance task-master expand --id=<id> --research --force # Break task into subtasks task-master update-task --id=<id> --prompt="changes" # Update specific task task-master update --from=<id> --prompt="changes" # Update multiple tasks from ID onwards task-master update-subtask --id=<id> --prompt="notes" # Add implementation notes to subtask # Analysis & Planning task-master analyze-complexity --research # Analyze task complexity task-master complexity-report # View complexity analysis task-master expand --all --research # Expand all eligible tasks # Dependencies & Organization task-master add-dependency --id=<id> --depends-on=<id> # Add task dependency task-master move --from=<id> --to=<id> # Reorganize task hierarchy task-master validate-dependencies # Check for dependency issues task-master generate # Update task markdown files (usually auto-called) ``` ## Key Files & Project Structure ### Core Files - `.taskmaster/tasks/tasks.json` - Main task data file (auto-managed) - `.taskmaster/config.json` - AI model configuration (use `task-master models` to modify) - `.taskmaster/docs/prd.md` - Product Requirements Document for parsing (`.md` extension recommended for better editor support) - `.taskmaster/tasks/*.txt` - Individual task files (auto-generated from tasks.json) - `.env` - API keys for CLI usage **PRD File Format:** While both `.txt` and `.md` extensions work, **`.md` is recommended** because: - Markdown syntax highlighting in editors improves readability - Proper rendering when previewing in VS Code, GitHub, or other tools - Better collaboration through formatted documentation ### Claude Code Integration Files - `CLAUDE.md` - Auto-loaded context for Claude Code (this file) - `.claude/settings.json` - Claude Code tool allowlist and preferences - `.claude/commands/` - Custom slash commands for repeated workflows - `.mcp.json` - MCP server configuration (project-specific) ### Directory Structure ``` project/ βββ .taskmaster/ β βββ tasks/ # Task files directory β β βββ tasks.json # Main task database β β βββ task-1.md # Individual task files β β βββ task-2.md β βββ docs/ # Documentation directory β β βββ prd.md # Product requirements (.md recommended) β βββ reports/ # Analysis reports directory β β βββ task-complexity-report.json β βββ templates/ # Template files β β βββ example_prd.md # Example PRD template (.md recommended) β βββ config.json # AI models & settings βββ .claude/ β βββ settings.json # Claude Code configuration β βββ commands/ # Custom slash commands βββ .env # API keys βββ .mcp.json # MCP configuration βββ CLAUDE.md # This file - auto-loaded by Claude Code ``` ## MCP Integration Task Master provides an MCP server that Claude Code can connect to. Configure in `.mcp.json`: ```json { "mcpServers": { "task-master-ai": { "command": "npx", "args": ["-y", "task-master-ai"], "env": { "TASK_MASTER_TOOLS": "core", "ANTHROPIC_API_KEY": "your_key_here", "PERPLEXITY_API_KEY": "your_key_here", "OPENAI_API_KEY": "OPENAI_API_KEY_HERE", "GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE", "XAI_API_KEY": "XAI_API_KEY_HERE", "OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE", "MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE", "AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE", "OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE" } } } } ``` ### MCP Tool Tiers Default: `core` (7 tools). Set via `TASK_MASTER_TOOLS` env var. | Tier | Count | Tools | |------|-------|-------| | `core` | 7 | `get_tasks`, `next_task`, `get_task`, `set_task_status`, `update_subtask`, `parse_prd`, `expand_task` | | `standard` | 14 | core + `initialize_project`, `analyze_project_complexity`, `expand_all`, `add_subtask`, `remove_task`, `add_task`, `complexity_report` | | `all` | 44+ | standard + dependencies, tags, research, autopilot, scoping, models, rules | **Upgrade when tool unavailable:** Edit MCP config, change `TASK_MASTER_TOOLS` from `"core"` to `"standard"` or `"all"`, restart MCP. ### Essential MCP Tools ```javascript help; // = shows available taskmaster commands // Project setup initialize_project; // = task-master init parse_prd; // = task-master parse-prd // Daily workflow get_tasks; // = task-master list next_task; // = task-master next get_task; // = task-master show <id> set_task_status; // = task-master set-status // Task management add_task; // = task-master add-task expand_task; // = task-master expand update_task; // = task-master update-task update_subtask; // = task-master update-subtask update; // = task-master update // Analysis analyze_project_complexity; // = task-master analyze-complexity complexity_report; // = task-master complexity-report ``` ## Claude Code Workflow Integration ### Standard Development Workflow #### 1. Project Initialization ```bash # Initialize Task Master task-master init # Create or obtain PRD, then parse it (use .md extension for better editor support) task-master parse-prd .taskmaster/docs/prd.md # Analyze complexity and expand tasks task-master analyze-complexity --research task-master expand --all --research ``` If tasks already exist, another PRD can be parsed (with new information only!) using parse-prd with --append flag. This will add the generated tasks to the existing list of tasks.. #### 2. Daily Development Loop ```bash # Start each session task-master next # Find next available task task-master show <id> # Review task details # During implementation, check in code context into the tasks and subtasks task-master update-subtask --id=<id> --prompt="implementation notes..." # Complete tasks task-master set-status --id=<id> --status=done ``` #### 3. Multi-Claude Workflows For complex projects, use multiple Claude Code sessions: ```bash # Terminal 1: Main implementation cd project && claude # Terminal 2: Testing and validation cd project-test-worktree && claude # Terminal 3: Documentation updates cd project-docs-worktree && claude ``` ### Custom Slash Commands Create `.claude/commands/taskmaster-next.md`: ```markdown Find the next available Task Master task and show its details. Steps: 1. Run `task-master next` to get the next task 2. If a task is available, run `task-master show <id>` for full details 3. Provide a summary of what needs to be implemented 4. Suggest the first implementation step ``` Create `.claude/commands/taskmaster-complete.md`: ```markdown Complete a Task Master task: $ARGUMENTS Steps: 1. Review the current task with `task-master show $ARGUMENTS` 2. Verify all implementation is complete 3. Run any tests related to this task 4. Mark as complete: `task-master set-status --id=$ARGUMENTS --status=done` 5. Show the next available task with `task-master next` ``` ## Tool Allowlist Recommendations Add to `.claude/settings.json`: ```json { "allowedTools": [ "Edit", "Bash(task-master *)", "Bash(git commit:*)", "Bash(git add:*)", "Bash(npm run *)", "mcp__task_master_ai__*" ] } ``` ## Configuration & Setup ### API Keys Required At least **one** of these API keys must be configured: - `ANTHROPIC_API_KEY` (Claude models) - **Recommended** - `PERPLEXITY_API_KEY` (Research features) - **Highly recommended** - `OPENAI_API_KEY` (GPT models) - `GOOGLE_API_KEY` (Gemini models) - `MISTRAL_API_KEY` (Mistral models) - `OPENROUTER_API_KEY` (Multiple models) - `XAI_API_KEY` (Grok models) An API key is required for any provider used across any of the 3 roles defined in the `models` command. ### Model Configuration ```bash # Interactive setup (recommended) task-master models --setup # Set specific models task-master models --set-main claude-3-5-sonnet-20241022 task-master models --set-research perplexity-llama-3.1-sonar-large-128k-online task-master models --set-fallback gpt-4o-mini ``` ## Task Structure & IDs ### Task ID Format - Main tasks: `1`, `2`, `3`, etc. - Subtasks: `1.1`, `1.2`, `2.1`, etc. - Sub-subtasks: `1.1.1`, `1.1.2`, etc. ### Task Status Values - `pending` - Ready to work on - `in-progress` - Currently being worked on - `done` - Completed and verified - `deferred` - Postponed - `cancelled` - No longer needed - `blocked` - Waiting on external factors ### Task Fields ```json { "id": "1.2", "title": "Implement user authentication", "description": "Set up JWT-based auth system", "status": "pending", "priority": "high", "dependencies": ["1.1"], "details": "Use bcrypt for hashing, JWT for tokens...", "testStrategy": "Unit tests for auth functions, integration tests for login flow", "subtasks": [] } ``` ## Claude Code Best Practices with Task Master ### Context Management - Use `/clear` between different tasks to maintain focus - This CLAUDE.md file is automatically loaded for context - Use `task-master show <id>` to pull specific task context when needed ### Iterative Implementation 1. `task-master show <subtask-id>` - Understand requirements 2. Explore codebase and plan implementation 3. `task-master update-subtask --id=<id> --prompt="detailed plan"` - Log plan 4. `task-master set-status --id=<id> --status=in-progress` - Start work 5. Implement code following logged plan 6. `task-master update-subtask --id=<id> --prompt="what worked/didn't work"` - Log progress 7. `task-master set-status --id=<id> --status=done` - Complete task ### Complex Workflows with Checklists For large migrations or multi-step processes: 1. Create a markdown PRD file describing the new changes: `touch task-migration-checklist.md` (prds can be .txt or .md) 2. Use Taskmaster to parse the new prd with `task-master parse-prd --append` (also available in MCP) 3. Use Taskmaster to expand the newly generated tasks into subtasks. Consdier using `analyze-complexity` with the correct --to and --from IDs (the new ids) to identify the ideal subtask amounts for each task. Then expand them. 4. Work through items systematically, checking them off as completed 5. Use `task-master update-subtask` to log progress on each task/subtask and/or updating/researching them before/during implementation if getting stuck ### Git Integration Task Master works well with `gh` CLI: ```bash # Create PR for completed task gh pr create --title "Complete task 1.2: User authentication" --body "Implements JWT auth system as specified in task 1.2" # Reference task in commits git commit -m "feat: implement JWT auth (task 1.2)" ``` ### Parallel Development with Git Worktrees ```bash # Create worktrees for parallel task development git worktree add ../project-auth feature/auth-system git worktree add ../project-api feature/api-refactor # Run Claude Code in each worktree cd ../project-auth && claude # Terminal 1: Auth work cd ../project-api && claude # Terminal 2: API work ``` ## Troubleshooting ### AI Commands Failing ```bash # Check API keys are configured cat .env # For CLI usage # Verify model configuration task-master models # Test with different model task-master models --set-fallback gpt-4o-mini ``` ### MCP Connection Issues - Check `.mcp.json` configuration - Verify Node.js installation - Use `--mcp-debug` flag when starting Claude Code - Use CLI as fallback if MCP unavailable ### Task File Sync Issues ```bash # Regenerate task files from tasks.json task-master generate # Fix dependency issues task-master fix-dependencies ``` DO NOT RE-INITIALIZE. That will not do anything beyond re-adding the same Taskmaster core files. ## Important Notes ### AI-Powered Operations These commands make AI calls and may take up to a minute: - `parse_prd` / `task-master parse-prd` - `analyze_project_complexity` / `task-master analyze-complexity` - `expand_task` / `task-master expand` - `expand_all` / `task-master expand --all` - `add_task` / `task-master add-task` - `update` / `task-master update` - `update_task` / `task-master update-task` - `update_subtask` / `task-master update-subtask` ### File Management - Never manually edit `tasks.json` - use commands instead - Never manually edit `.taskmaster/config.json` - use `task-master models` - Task markdown files in `tasks/` are auto-generated - Run `task-master generate` after manual changes to tasks.json ### Claude Code Session Management - Use `/clear` frequently to maintain focused context - Create custom slash commands for repeated Task Master workflows - Configure tool allowlist to streamline permissions - Use headless mode for automation: `claude -p "task-master next"` ### Multi-Task Updates - Use `update --from=<id>` to update multiple future tasks - Use `update-task --id=<id>` for single task updates - Use `update-subtask --id=<id>` for implementation logging ### Research Mode - Add `--research` flag for research-based AI enhancement - Requires a research model API key like Perplexity (`PERPLEXITY_API_KEY`) in environment - Provides more informed task creation and updates - Recommended for complex technical tasks --- _This guide ensures Claude Code has immediate access to Task Master's essential functionality for agentic development workflows._ - biome.json (1119 bytes)
{ "files": { "ignore": [ "build", "coverage", ".changeset", "tasks", "package-lock.json", "tests/fixture/*.json", "dist" ] }, "formatter": { "bracketSpacing": true, "enabled": true, "indentStyle": "tab", "lineWidth": 80 }, "javascript": { "formatter": { "arrowParentheses": "always", "quoteStyle": "single", "trailingCommas": "none" } }, "linter": { "enabled": true, "include": ["apps/extension/**/*.ts", "apps/extension/**/*.tsx"], "ignore": ["**/*", "!apps/extension/**/*"], "rules": { "recommended": true, "complexity": { "noForEach": "off", "useOptionalChain": "off", "useArrowFunction": "off" }, "correctness": { "noConstantCondition": "off", "noUnreachable": "off" }, "suspicious": { "noDuplicateTestHooks": "off", "noPrototypeBuiltins": "off" }, "style": { "noUselessElse": "off", "useNodejsImportProtocol": "off", "useNumberNamespace": "off", "noParameterAssign": "off", "useTemplate": "off", "noUnusedTemplateLiteral": "off", "noNonNullAssertion": "warn" } } } } - CHANGELOG.md (340270 bytes)
# task-master-ai ## 0.43.1 ### Patch Changes - [#1676](https://github.com/eyaltoledano/claude-task-master/pull/1676) [`6a11438`](https://github.com/eyaltoledano/claude-task-master/commit/6a11438de2859a3fb9bad4c2bef6fac35e44425a) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Stop setting up `hamster` and `ham` shell aliases during `task-master init`. Existing aliases are automatically cleaned up. ## 0.43.0 ### Minor Changes - [#1599](https://github.com/eyaltoledano/claude-task-master/pull/1599) [`e689fcf`](https://github.com/eyaltoledano/claude-task-master/commit/e689fcf2a20cada4a19ee31fed723b6f35f2c13d) Thanks [@triepod-ai](https://github.com/triepod-ai)! - Add MCPB bundle for single-click Claude Desktop installation - Added `manifest.json` for MCP Bundle (MCPB) specification v0.3 - Added `.mcpbignore` to exclude development files from bundle - Added `icon.png` (512x512) for Claude Desktop display - Enables users to install Task Master MCP server directly in Claude Desktop without manual configuration - [#1605](https://github.com/eyaltoledano/claude-task-master/pull/1605) [`efedc85`](https://github.com/eyaltoledano/claude-task-master/commit/efedc85cb1110a75748f3df0e530f3c9e27d2155) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add verbose output mode to loop command with `--verbose` flag - New `-v, --verbose` flag shows Claude's work in real-time (thinking, tool calls) rather than waiting until the iteration completes - New `--no-output` flag excludes full Claude output from iteration results to save memory - Improved error handling with proper validation for incompatible options (verbose + sandbox) - [#1611](https://github.com/eyaltoledano/claude-task-master/pull/1611) [`c798639`](https://github.com/eyaltoledano/claude-task-master/commit/c798639d1a6b492de1b7cc82a28a13ddfba23eb8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add optional `metadata` field to tasks for storing user-defined custom data Tasks and subtasks now support an optional `metadata` field that allows storing arbitrary JSON data such as: - External IDs (GitHub issues, Jira tickets, Linear issues) - Workflow data (sprints, story points, custom statuses) - Integration data (sync timestamps, external system references) - Custom tracking (UUIDs, version numbers, audit information) Key features: - **AI-Safe**: Metadata is preserved through all AI operations (update-task, expand, etc.) because AI schemas intentionally exclude this field - **Flexible Schema**: Store any JSON-serializable data without schema changes - **Backward Compatible**: The field is optional; existing tasks work without modification - **Subtask Support**: Both tasks and subtasks can have their own metadata - **MCP Tool Support**: Use `update_task` and `update_subtask` with the `metadata` parameter to update metadata (requires `TASK_MASTER_ALLOW_METADATA_UPDATES=true` in MCP server environment) Example usage: ```json { "id": 1, "title": "Implement authentication", "metadata": { "githubIssue": 42, "sprint": "Q1-S3", "storyPoints": 5 } } ``` MCP metadata update example: ```javascript // With TASK_MASTER_ALLOW_METADATA_UPDATES=true set in MCP env update_task({ id: "1", metadata: '{"githubIssue": 42, "sprint": "Q1-S3"}', }); ``` ### Patch Changes - [#1587](https://github.com/eyaltoledano/claude-task-master/pull/1587) [`0d628ca`](https://github.com/eyaltoledano/claude-task-master/commit/0d628ca9514f22607c0a6495b701e4cde743b45c) Thanks [@bjcoombs](https://github.com/bjcoombs)! - Add modifyJSON function for safer file updates - [#1600](https://github.com/eyaltoledano/claude-task-master/pull/1600) [`712a078`](https://github.com/eyaltoledano/claude-task-master/commit/712a0789d6d584adf5dbb27732c783cd240014b2) Thanks [@esumerfd](https://github.com/esumerfd)! - Add --no-banner to suppress the startup banner. ## 0.42.0 ### Minor Changes - [#1533](https://github.com/eyaltoledano/claude-task-master/pull/1533) [`6c3a92c`](https://github.com/eyaltoledano/claude-task-master/commit/6c3a92c439d4573ff5046e3d251a4a26d85d0deb) Thanks [@bjcoombs](https://github.com/bjcoombs)! - Add --ready and --blocking filters to list command for identifying parallelizable tasks - Add `--ready` filter to show only tasks with satisfied dependencies (ready to work on) - Add `--blocking` filter to show only tasks that block other tasks - Combine `--ready --blocking` to find high-impact tasks (ready AND blocking others) - Add "Blocks" column to task table showing which tasks depend on each task - Blocks field included in JSON output for programmatic access - Add "Ready" column to `tags` command showing count of ready tasks per tag - Add `--ready` filter to `tags` command to show only tags with available work - Excludes deferred/blocked tasks from ready count (only actionable statuses) - Add `--all-tags` option to list ready tasks across all tags (use with `--ready`) - Tag column shown as first column when using `--all-tags` for easy scanning ### Patch Changes - [#1569](https://github.com/eyaltoledano/claude-task-master/pull/1569) [`4cfde1c`](https://github.com/eyaltoledano/claude-task-master/commit/4cfde1c3d54b94701e0fcfc8dbdedbc3bbaf4339) Thanks [@bjcoombs](https://github.com/bjcoombs)! - Improve concurrency safety by adopting modifyJson pattern in file-storage - Refactor saveTasks, createTag, deleteTag, renameTag to use modifyJson for atomic read-modify-write operations - This prevents lost updates when multiple processes concurrently modify tasks.json - Complements the cross-process file locking added in PR #1566 - [#1566](https://github.com/eyaltoledano/claude-task-master/pull/1566) [`3cc6174`](https://github.com/eyaltoledano/claude-task-master/commit/3cc6174b471fc1ea7f12955095d0d35b4dc5904c) Thanks [@bjcoombs](https://github.com/bjcoombs)! - Fix race condition when multiple Claude Code windows write to tasks.json simultaneously - Add cross-process file locking to prevent concurrent write collisions - Implement atomic writes using temp file + rename pattern to prevent partial writes - Re-read file inside lock to get current state, preventing lost updates from stale snapshots - Add stale lock detection and automatic cleanup (10-second timeout) - Export `withFileLock` and `withFileLockSync` utilities for use by other modules This fix prevents data loss that could occur when multiple Task Master instances (e.g., multiple Claude Code windows) access the same tasks.json file concurrently. - [#1576](https://github.com/eyaltoledano/claude-task-master/pull/1576) [`097c8ed`](https://github.com/eyaltoledano/claude-task-master/commit/097c8edcb0ca065218e9b51758ad370ac7475f1a) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Improve loop command error handling and use dangerously-skip-permissions - Add proper spawn error handling (ENOENT, EACCES) with actionable messages - Return error info from checkSandboxAuth and runInteractiveAuth instead of silent failures - Use --dangerously-skip-permissions for unattended loop execution - Fix null exit code masking issue - [#1577](https://github.com/eyaltoledano/claude-task-master/pull/1577) [`e762e4f`](https://github.com/eyaltoledano/claude-task-master/commit/e762e4f64608a77d248ac8ce5eeb218000b51907) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Make Docker sandbox mode opt-in for loop command - Add `--sandbox` flag to `task-master loop` (default: use plain `claude -p`) - Preserve progress.txt between runs (append instead of overwrite) - Display execution mode in loop startup output - [#1580](https://github.com/eyaltoledano/claude-task-master/pull/1580) [`940ab58`](https://github.com/eyaltoledano/claude-task-master/commit/940ab587e50cff43c3a2639bbbd210fdd577c3f1) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Update Codex CLI supported models to match current available models - Remove deprecated models: gpt-5, gpt-5-codex, gpt-5.1 - Add gpt-5.2-codex as the current default model - Add gpt-5.1-codex-mini for faster, cheaper option - Keep gpt-5.1-codex-max and gpt-5.2 ## 0.42.0-rc.0 ### Minor Changes - [#1533](https://github.com/eyaltoledano/claude-task-master/pull/1533) [`6c3a92c`](https://github.com/eyaltoledano/claude-task-master/commit/6c3a92c439d4573ff5046e3d251a4a26d85d0deb) Thanks [@bjcoombs](https://github.com/bjcoombs)! - Add --ready and --blocking filters to list command for identifying parallelizable tasks - Add `--ready` filter to show only tasks with satisfied dependencies (ready to work on) - Add `--blocking` filter to show only tasks that block other tasks - Combine `--ready --blocking` to find high-impact tasks (ready AND blocking others) - Add "Blocks" column to task table showing which tasks depend on each task - Blocks field included in JSON output for programmatic access - Add "Ready" column to `tags` command showing count of ready tasks per tag - Add `--ready` filter to `tags` command to show only tags with available work - Excludes deferred/blocked tasks from ready count (only actionable statuses) - Add `--all-tags` option to list ready tasks across all tags (use with `--ready`) - Tag column shown as first column when using `--all-tags` for easy scanning ### Patch Changes - [#1569](https://github.com/eyaltoledano/claude-task-master/pull/1569) [`4cfde1c`](https://github.com/eyaltoledano/claude-task-master/commit/4cfde1c3d54b94701e0fcfc8dbdedbc3bbaf4339) Thanks [@bjcoombs](https://github.com/bjcoombs)! - Improve concurrency safety by adopting modifyJson pattern in file-storage - Refactor saveTasks, createTag, deleteTag, renameTag to use modifyJson for atomic read-modify-write operations - This prevents lost updates when multiple processes concurrently modify tasks.json - Complements the cross-process file locking added in PR #1566 - [#1566](https://github.com/eyaltoledano/claude-task-master/pull/1566) [`3cc6174`](https://github.com/eyaltoledano/claude-task-master/commit/3cc6174b471fc1ea7f12955095d0d35b4dc5904c) Thanks [@bjcoombs](https://github.com/bjcoombs)! - Fix race condition when multiple Claude Code windows write to tasks.json simultaneously - Add cross-process file locking to prevent concurrent write collisions - Implement atomic writes using temp file + rename pattern to prevent partial writes - Re-read file inside lock to get current state, preventing lost updates from stale snapshots - Add stale lock detection and automatic cleanup (10-second timeout) - Export `withFileLock` and `withFileLockSync` utilities for use by other modules This fix prevents data loss that could occur when multiple Task Master instances (e.g., multiple Claude Code windows) access the same tasks.json file concurrently. - [#1576](https://github.com/eyaltoledano/claude-task-master/pull/1576) [`097c8ed`](https://github.com/eyaltoledano/claude-task-master/commit/097c8edcb0ca065218e9b51758ad370ac7475f1a) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Improve loop command error handling and use dangerously-skip-permissions - Add proper spawn error handling (ENOENT, EACCES) with actionable messages - Return error info from checkSandboxAuth and runInteractiveAuth instead of silent failures - Use --dangerously-skip-permissions for unattended loop execution - Fix null exit code masking issue - [#1577](https://github.com/eyaltoledano/claude-task-master/pull/1577) [`e762e4f`](https://github.com/eyaltoledano/claude-task-master/commit/e762e4f64608a77d248ac8ce5eeb218000b51907) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Make Docker sandbox mode opt-in for loop command - Add `--sandbox` flag to `task-master loop` (default: use plain `claude -p`) - Preserve progress.txt between runs (append instead of overwrite) - Display execution mode in loop startup output - [#1580](https://github.com/eyaltoledano/claude-task-master/pull/1580) [`940ab58`](https://github.com/eyaltoledano/claude-task-master/commit/940ab587e50cff43c3a2639bbbd210fdd577c3f1) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Update Codex CLI supported models to match current available models - Remove deprecated models: gpt-5, gpt-5-codex, gpt-5.1 - Add gpt-5.2-codex as the current default model - Add gpt-5.1-codex-mini for faster, cheaper option - Keep gpt-5.1-codex-max and gpt-5.2 ## 0.41.0 ### Minor Changes - [#1571](https://github.com/eyaltoledano/claude-task-master/pull/1571) [`c2d6c18`](https://github.com/eyaltoledano/claude-task-master/commit/c2d6c18a96fce5a2d5cb50bd1ae5d58ef577501c) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add loop command for automated task execution with Claude Code **New Features:** - `task-master loop` command that runs Claude Code in a Docker sandbox, executing one task per iteration based on the selected tag - Built-in presets for different workflows: - `default` - General task completion from the Task Master backlog - `test-coverage` - Find uncovered code and write meaningful tests - `linting` - Fix lint errors and type errors one by one - `duplication` - Find duplicated code and refactor into shared utilities - `entropy` - Find code smells and clean them up - Progress file tracking to maintain context across iterations (inside `.taskmaster/loop-progress.txt`) - Remember to delete this file between loops to not pollute the agent with bad context - Automatic completion detection via `<loop-complete>` and `<loop-blocked>` markers ### Patch Changes - [#1556](https://github.com/eyaltoledano/claude-task-master/pull/1556) [`1befc6a`](https://github.com/eyaltoledano/claude-task-master/commit/1befc6a341babd825b8dd000513ffbf8a1620e62) Thanks [@TheLazyIndianTechie](https://github.com/TheLazyIndianTechie)! - fix: tolerate AI SDK versions without jsonSchema export Fallback to sanitized Zod schema handling when jsonSchema is unavailable, and align structured-output tests and registration perf thresholds to reduce CI failures. Also enforce sequential, unique subtask ids when regenerating subtasks during scope adjustment. - [#1553](https://github.com/eyaltoledano/claude-task-master/pull/1553) [`226678b`](https://github.com/eyaltoledano/claude-task-master/commit/226678b93aa01d0e62c0fac852802e9955c7ebd7) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - fix: Remove .default() from Zod schemas to satisfy OpenAI strict JSON schema validation This fixes an issue where codex-cli provider (using OpenAI API) would fail with "Missing 'dependencies'" error during task expansion. OpenAI's structured outputs require all properties to be in the 'required' array, but Zod's .default() makes fields optional. The fix removes .default() from schemas and applies defaults at the application level instead. - [#1543]( - CLAUDE_CODE_PLUGIN.md (2892 bytes)
# Taskmaster AI - Claude Code Marketplace This repository includes a Claude Code plugin marketplace in `.claude-plugin/marketplace.json`. ## Installation ### From GitHub (Public Repository) Once this repository is pushed to GitHub, users can install with: ```bash # Add the marketplace /plugin marketplace add eyaltoledano/claude-task-master # Install the plugin /plugin install taskmaster@taskmaster ``` ### Local Development/Testing ```bash # From the project root directory cd /path/to/claude-task-master # Build the plugin first cd packages/claude-code-plugin npm run build cd ../.. # In Claude Code /plugin marketplace add . /plugin install taskmaster@taskmaster ``` ## Marketplace Structure ``` claude-task-master/ βββ .claude-plugin/ β βββ marketplace.json # Marketplace manifest (at repo root) β βββ packages/claude-code-plugin/ β βββ src/build.ts # Build tooling β βββ [generated plugin files] β βββ assets/claude/ # Plugin source files βββ commands/ βββ agents/ ``` ## Available Plugins ### taskmaster AI-powered task management system for ambitious development workflows. **Features:** - 49 slash commands for comprehensive task management - 3 specialized AI agents (orchestrator, executor, checker) - MCP server integration - Complexity analysis and auto-expansion - Dependency management and validation - Automated workflow capabilities **Quick Start:** ```bash /tm:init /tm:parse-prd /tm:next ``` ## For Contributors ### Adding New Plugins To add more plugins to this marketplace: 1. **Update marketplace.json**: ```json { "plugins": [ { "name": "new-plugin", "source": "./path/to/plugin", "description": "Plugin description", "version": "1.0.0" } ] } ``` 2. **Commit and push** the changes 3. **Users update** with: `/plugin marketplace update taskmaster` ### Marketplace Versioning The marketplace version is tracked in `.claude-plugin/marketplace.json`: ```json { "metadata": { "version": "1.0.0" } } ``` Increment the version when adding or updating plugins. ## Team Configuration Organizations can auto-install this marketplace for all team members by adding to `.claude/settings.json`: ```json { "extraKnownMarketplaces": { "task-master": { "source": { "source": "github", "repo": "eyaltoledano/claude-task-master" } } }, "enabledPlugins": { "taskmaster": { "marketplace": "taskmaster" } } } ``` Team members who trust the repository folder will automatically get the marketplace and plugins installed. ## Documentation - [Claude Code Plugin Docs](https://docs.claude.com/en/docs/claude-code/plugins) - [Marketplace Documentation](https://docs.claude.com/en/docs/claude-code/plugin-marketplaces) - CLAUDE.md (7610 bytes)
# Claude Code Instructions ## Task Master AI Instructions **Import Task Master's development workflow commands and guidelines, treat as if import is in the main CLAUDE.md file.** @./.taskmaster/CLAUDE.md ## Test Guidelines ### Test File Placement - **Package & tests**: Place in `packages/<package-name>/src/<module>/<file>.spec.ts` or `apps/<app-name>/src/<module>/<file.spec.ts>` alongside source - **Package integration tests**: Place in `packages/<package-name>/tests/integration/<module>/<file>.test.ts` or `apps/<app-name>/tests/integration/<module>/<file>.test.ts` alongside source - **Isolated unit tests**: Use `tests/unit/packages/<package-name>/` only when parallel placement isn't possible - **Test extension**: Always use `.ts` for TypeScript tests, never `.js` ### Synchronous Tests - **NEVER use async/await in test functions** unless testing actual asynchronous operations - Use synchronous top-level imports instead of dynamic `await import()` - Test bodies should be synchronous whenever possible - Example: ```typescript // β CORRECT - Synchronous imports with .ts extension import { MyClass } from '../src/my-class.js'; it('should verify behavior', () => { expect(new MyClass().property).toBe(value); }); // β INCORRECT - Async imports it('should verify behavior', async () => { const { MyClass } = await import('../src/my-class.js'); expect(new MyClass().property).toBe(value); }); ``` ### When to Write Tests **ALWAYS write tests for:** - **Bug fixes**: Add a regression test that would have caught the bug - **Business logic**: Complex calculations, validations, transformations - **Edge cases**: Boundary conditions, error handling, null/undefined cases - **Public APIs**: Methods other code depends on - **Integration points**: Database, file system, external APIs **SKIP tests for:** - Simple getters/setters: `getX() { return this.x; }` - Trivial pass-through functions with no logic - Pure configuration objects - Code that just delegates to another tested function **Examples:** ```javascript // β WRITE A TEST - Bug fix with regression prevention it('should use correct baseURL from defaultBaseURL config', () => { const provider = new ZAIProvider(); expect(provider.defaultBaseURL).toBe('https://api.z.ai/api/paas/v4/'); }); // β WRITE A TEST - Business logic with edge cases it('should parse subtask IDs correctly', () => { expect(parseTaskId('1.2.3')).toEqual({ taskId: 1, subtaskId: 2, subSubtaskId: 3 }); expect(parseTaskId('invalid')).toBeNull(); }); // β SKIP TEST - Trivial getter class Task { get id() { return this._id; } // No test needed } // β SKIP TEST - Pure delegation function getTasks() { return taskManager.getTasks(); // Already tested in taskManager } ``` **Bug Fix Workflow:** 1. Encounter a bug 2. Write a failing test that reproduces it 3. Fix the bug 4. Verify test now passes 5. Commit both fix and test together ### Testing Guidelines **Principles**: FIRST (Fast, Independent, Repeatable, Self-validating, Timely) **Structure**: AAA (Arrange, Act, Assert) **Coverage**: Right-BICEP (Right results, Boundary, Inverse, Cross-check, Error conditions, Performance) #### What to Mock **Unit tests** (`.spec.ts` - test single unit in isolation): - **@tm/core**: Mock only external I/O (Supabase, APIs, filesystem). Use real internal services. - **apps/cli**: Mock tm-core responses. Use real Commander/chalk/inquirer/other npm packages (test display logic). - **apps/mcp**: Mock tm-core responses. Use real MCP framework (test response formatting). **Integration tests** (`tests/integration/` - test multiple units together): - **All packages**: Use real tm-core, mock only external boundaries (APIs, DB, filesystem). **Never mock**: - Internal utilities/helpers in the same package - Standard frameworks (Commander, Express) - let them run - Standard library **Rule of thumb**: Mock what you're NOT testing. CLI unit tests test display β mock tm-core. Core unit tests test logic β mock I/O. Integration tests test full flow β mock only external APIs. **Red flag**: Mocking 3+ dependencies in a unit test means code is doing too much or is in the wrong layer. **Anti-pattern**: Heavily mocked tests don't verify real behaviorβthey verify that you wired up mocks correctly. You end up writing orchestration code to satisfy tests, rather than tests that validate your actual implementation. If testing is hard, move the logic to where it's naturally testable. ## Architecture Guidelines ### Business Logic Separation **CRITICAL RULE**: ALL business logic must live in `@tm/core`, NOT in presentation layers. - **`@tm/core`** (packages/tm-core/): - Contains ALL business logic, domain models, services, and utilities - Provides clean facade APIs through domain objects (tasks, auth, workflow, git, config) - Houses all complexity - parsing, validation, transformations, calculations, etc. - Example: Task ID parsing, subtask extraction, status validation, dependency resolution - **`@tm/cli`** (apps/cli/): - Thin presentation layer ONLY - Calls tm-core methods and displays results - Handles CLI-specific concerns: argument parsing, output formatting, user prompts - NO business logic, NO data transformations, NO calculations - **`@tm/mcp`** (apps/mcp/): - Thin presentation layer ONLY - Calls tm-core methods and returns MCP-formatted responses - Handles MCP-specific concerns: tool schemas, parameter validation, response formatting - NO business logic, NO data transformations, NO calculations - **`apps/extension`** (future): - Thin presentation layer ONLY - Calls tm-core methods and displays in VS Code UI - NO business logic **Examples of violations to avoid:** - β Creating helper functions in CLI/MCP to parse task IDs β Move to tm-core - β Data transformation logic in CLI/MCP β Move to tm-core - β Validation logic in CLI/MCP β Move to tm-core - β Duplicating logic across CLI and MCP β Implement once in tm-core **Correct approach:** - β Add method to TasksDomain: `tasks.get(taskId)` (automatically handles task and subtask IDs) - β CLI calls: `await tmCore.tasks.get(taskId)` (supports "1", "1.2", "HAM-123", "HAM-123.2") - β MCP calls: `await tmCore.tasks.get(taskId)` (same intelligent ID parsing) - β Single source of truth in tm-core ## Code Quality & Reusability Guidelines Apply standard software engineering principles: - **DRY (Don't Repeat Yourself)**: Extract patterns that appear 2+ times into reusable components or utilities - **YAGNI (You Aren't Gonna Need It)**: Don't over-engineer. Create abstractions when duplication appears, not before - **Maintainable**: Single source of truth. Change once, update everywhere - **Readable**: Clear naming, proper structure, export from index files - **Flexible**: Accept configuration options with sensible defaults ## Documentation Guidelines - **Documentation location**: Write docs in `apps/docs/` (Mintlify site source), not `docs/` - **Documentation URL**: Reference docs at <https://tryhamster.com/docs/taskmaster>, not local file paths ## Changeset Guidelines - **Add a changeset for code changes** - Run `npx changeset` after making code changes (not needed for docs-only PRs) - When creating changesets, remember that it's user-facing, meaning we don't have to get into the specifics of the code, but rather mention what the end-user is getting or fixing from this changeset - Run `npm run turbo:typecheck` before pushing to ensure TypeScript type checks pass - Run `npm run test -w <package-name>` to test a package - context7.json (110 bytes)
{ "url": "https://context7.com/eyaltoledano/claude-task-master", "public_key": "pk_52Na55p8REi9c5jSFszav" } - CONTRIBUTING.md (7758 bytes)
# Contributing to Task Master Thank you for your interest in contributing to Task Master! We're excited to work with you and appreciate your help in making this project better. π ## π€ Our Collaborative Approach We're a **PR-friendly team** that values collaboration: - β **We review PRs quickly** - Usually within hours, not days - β **We're super reactive** - Expect fast feedback and engagement - β **We sometimes take over PRs** - If your contribution is valuable but needs cleanup, we might jump in to help finish it - β **We're open to all contributions** - From bug fixes to major features **We don't mind AI-generated code**, but we do expect you to: - β **Review and understand** what the AI generated - β **Test the code thoroughly** before submitting - β **Ensure it's well-written** and follows our patterns - β **Don't submit "AI slop"** - untested, unreviewed AI output > **Why this matters**: We spend significant time reviewing PRs. Help us help you by submitting quality contributions that save everyone time! ## π Quick Start for Contributors ### 1. Fork and Clone ```bash git clone https://github.com/YOUR_USERNAME/claude-task-master.git cd claude-task-master npm install ``` ### 2. Create a Feature Branch **Important**: Always target the `next` branch, not `main`: ```bash git checkout next git pull origin next git checkout -b feature/your-feature-name ``` ### 3. Make Your Changes Follow our development guidelines below. ### 4. Test Everything Yourself **Before submitting your PR**, ensure: ```bash # Run all tests npm test # Check formatting npm run format-check # Fix formatting if needed npm run format ``` ### 5. Create a Changeset **Required for most changes**: ```bash npm run changeset ``` See the [Changeset Guidelines](#changeset-guidelines) below for details. ### 6. Submit Your PR - Target the `next` branch - Write a clear description - Reference any related issues ## π Development Guidelines ### Branch Strategy - **`main`**: Production-ready code - **`next`**: Development branch - **target this for PRs** - **Feature branches**: `feature/description` or `fix/description` ### Code Quality Standards 1. **Write tests** for new functionality 2. **Follow existing patterns** in the codebase 3. **Add JSDoc comments** for functions 4. **Keep functions focused** and single-purpose ### Testing Requirements Your PR **must pass all CI checks**: - β **Unit tests**: `npm test` - β **Format check**: `npm run format-check` **Test your changes locally first** - this saves review time and shows you care about quality. ## π¦ Changeset Guidelines We use [Changesets](https://github.com/changesets/changesets) to manage versioning and generate changelogs. ### When to Create a Changeset **Always create a changeset for**: - β New features - β Bug fixes - β Breaking changes - β Performance improvements - β User-facing documentation updates - β Dependency updates that affect functionality **Skip changesets for**: - β Internal documentation only - β Test-only changes - β Code formatting/linting - β Development tooling that doesn't affect users ### How to Create a Changeset 1. **After making your changes**: ```bash npm run changeset ``` 2. **Choose the bump type**: - **Major**: Breaking changes - **Minor**: New features - **Patch**: Bug fixes, docs, performance improvements 3. **Write a clear summary**: ``` Add support for custom AI models in MCP configuration ``` 4. **Commit the changeset file** with your changes: ```bash git add .changeset/*.md git commit -m "feat: add custom AI model support" ``` ### Changeset vs Git Commit Messages - **Changeset summary**: User-facing, goes in CHANGELOG.md - **Git commit**: Developer-facing, explains the technical change Example: ```bash # Changeset summary (user-facing) "Add support for custom Ollama models" # Git commit message (developer-facing) "feat(models): implement custom Ollama model validation - Add model validation for custom Ollama endpoints - Update configuration schema to support custom models - Add tests for new validation logic" ``` ## π§ Development Setup ### Prerequisites - Node.js 20+ - npm or yarn ### Environment Setup 1. **Copy environment template**: ```bash cp .env.example .env ``` 2. **Add your API keys** (for testing AI features): ```bash ANTHROPIC_API_KEY=your_key_here OPENAI_API_KEY=your_key_here # Add others as needed ``` ### Running Tests ```bash # Run all tests npm test # Run tests in watch mode npm run test:watch # Run with coverage npm run test:coverage # Run E2E tests npm run test:e2e ``` ### Code Formatting We use Prettier for consistent formatting: ```bash # Check formatting npm run format-check # Fix formatting npm run format ``` ## π PR Guidelines ### Before Submitting - [ ] **Target the `next` branch** - [ ] **Test everything locally** - [ ] **Run the full test suite** - [ ] **Check code formatting** - [ ] **Create a changeset** (if needed) - [ ] **Re-read your changes** - ensure they're clean and well-thought-out ### PR Description Template ```markdown ## Description Brief description of what this PR does. ## Type of Change - [ ] Bug fix - [ ] New feature - [ ] Breaking change - [ ] Documentation update ## Testing - [ ] I have tested this locally - [ ] All existing tests pass - [ ] I have added tests for new functionality ## Changeset - [ ] I have created a changeset (or this change doesn't need one) ## Additional Notes Any additional context or notes for reviewers. ``` ### What We Look For β **Good PRs**: - Clear, focused changes - Comprehensive testing - Good commit messages - Proper changeset (when needed) - Self-reviewed code β **Avoid**: - Massive PRs that change everything - Untested code - Formatting issues - Missing changesets for user-facing changes - AI-generated code that wasn't reviewed ## ποΈ Project Structure ``` claude-task-master/ βββ bin/ # CLI executables βββ mcp-server/ # MCP server implementation βββ scripts/ # Core task management logic βββ src/ # Shared utilities and providers and well refactored code (we are slowly moving everything here) βββ tests/ # Test files βββ docs/ # Documentation βββ .cursor/ # Cursor IDE rules and configuration βββ assets/ # Assets like rules and configuration for all IDEs ``` ### Key Areas for Contribution - **CLI Commands**: `scripts/modules/commands.js` - **MCP Tools**: `mcp-server/src/tools/` - **Core Logic**: `scripts/modules/task-manager/` - **AI Providers**: `src/ai-providers/` - **Tests**: `tests/` ## π Reporting Issues ### Bug Reports Include: - Task Master version - Node.js version - Operating system - Steps to reproduce - Expected vs actual behavior - Error messages/logs ### Feature Requests Include: - Clear description of the feature - Use case/motivation - Proposed implementation (if you have ideas) - Willingness to contribute ## π¬ Getting Help - **Discord**: [Join our community](https://discord.gg/taskmasterai) - **Issues**: [GitHub Issues](https://github.com/eyaltoledano/claude-task-master/issues) - **Discussions**: [GitHub Discussions](https://github.com/eyaltoledano/claude-task-master/discussions) ## π License By contributing, you agree that your contributions will be licensed under the same license as the project (MIT with Commons Clause). --- **Thank you for contributing to Task Master!** π Your contributions help make AI-driven development more accessible and efficient for everyone.
- index.js (4593 bytes)
#!/usr/bin/env node /** * Task Master * Copyright (c) 2025 Eyal Toledano, Ralph Khreish * * This software is licensed under the MIT License with Commons Clause. * You may use this software for any purpose, including commercial applications, * and modify and redistribute it freely, subject to the following restrictions: * * 1. You may not sell this software or offer it as a service. * 2. The origin of this software must not be misrepresented. * 3. Altered source versions must be plainly marked as such. * * For the full license text, see the LICENSE file in the root directory. */ /** * Claude Task Master * A task management system for AI-driven development with Claude */ // This file serves as the main entry point for the package // The primary functionality is provided through the CLI commands import { spawn } from 'child_process'; import { createRequire } from 'module'; import { dirname, resolve } from 'path'; import { fileURLToPath } from 'url'; import { Command } from 'commander'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const require = createRequire(import.meta.url); // Get package information const packageJson = require('./package.json'); // Export the path to the dev.js script for programmatic usage export const devScriptPath = resolve(__dirname, './scripts/dev.js'); // Export a function to initialize a new project programmatically export const initProject = async (options = {}) => { const init = await import('./scripts/init.js'); return init.initializeProject(options); }; // Export a function to run init as a CLI command export const runInitCLI = async (options = {}) => { try { const init = await import('./scripts/init.js'); const result = await init.initializeProject(options); return result; } catch (error) { console.error('Initialization failed:', error.message); if (process.env.DEBUG === 'true') { console.error('Debug stack trace:', error.stack); } throw error; // Re-throw to be handled by the command handler } }; // Export version information export const version = packageJson.version; // CLI implementation if (import.meta.url === `file://${process.argv[1]}`) { const program = new Command(); program .name('task-master') .description('Claude Task Master CLI') .version(version); program .command('init') .description('Initialize a new project') .option('-y, --yes', 'Skip prompts and use default values') .option('-n, --name <n>', 'Project name') .option('-d, --description <description>', 'Project description') .option('-v, --version <version>', 'Project version', '0.1.0') .option('-a, --author <author>', 'Author name') .option('--skip-install', 'Skip installing dependencies') .option('--dry-run', 'Show what would be done without making changes') .option('--aliases', 'Add shell aliases (tm, taskmaster)') .option('--no-aliases', 'Skip shell aliases (tm, taskmaster)') .option('--git', 'Initialize Git repository') .option('--no-git', 'Skip Git repository initialization') .option('--git-tasks', 'Store tasks in Git') .option('--no-git-tasks', 'No Git storage of tasks') .action(async (cmdOptions) => { try { await runInitCLI(cmdOptions); } catch (err) { console.error('Init failed:', err.message); process.exit(1); } }); program .command('dev') .description('Run the dev.js script') .allowUnknownOption(true) .action(() => { const args = process.argv.slice(process.argv.indexOf('dev') + 1); const child = spawn('node', [devScriptPath, ...args], { stdio: 'inherit', cwd: process.cwd() }); child.on('close', (code) => { process.exit(code); }); }); // Add shortcuts for common dev.js commands program .command('list') .description('List all tasks') .action(() => { const child = spawn('node', [devScriptPath, 'list'], { stdio: 'inherit', cwd: process.cwd() }); child.on('close', (code) => { process.exit(code); }); }); program .command('next') .description('Show the next task to work on') .action(() => { const child = spawn('node', [devScriptPath, 'next'], { stdio: 'inherit', cwd: process.cwd() }); child.on('close', (code) => { process.exit(code); }); }); program .command('generate') .description('Generate task files') .action(() => { const child = spawn('node', [devScriptPath, 'generate'], { stdio: 'inherit', cwd: process.cwd() }); child.on('close', (code) => { process.exit(code); }); }); program.parse(process.argv); } - INSTRUCTIONS.md (73 bytes)
Run with npx or add to your MCP config: ```bash npx -y task-master-ai ```
- jest.config.js (1784 bytes)
export default { // Use Node.js environment for testing testEnvironment: 'node', // Automatically clear mock calls between every test clearMocks: true, // Indicates whether the coverage information should be collected while executing the test collectCoverage: false, // The directory where Jest should output its coverage files coverageDirectory: 'coverage', // A list of paths to directories that Jest should use to search for files in roots: ['<rootDir>/tests'], // The glob patterns Jest uses to detect test files testMatch: ['**/__tests__/**/*.js', '**/?(*.)+(spec|test).js'], // Transform files preset: 'ts-jest/presets/default-esm', extensionsToTreatAsEsm: ['.ts'], moduleFileExtensions: ['js', 'ts', 'json', 'node'], transform: { '^.+\\.ts$': [ 'ts-jest', { useESM: true } ] }, // Disable transformations for node_modules transformIgnorePatterns: ['/node_modules/'], // Set moduleNameMapper for absolute paths moduleNameMapper: { '^@/(.*)$': '<rootDir>/$1' }, resolver: '<rootDir>/jest.resolver.cjs', // Setup module aliases moduleDirectories: ['node_modules', '<rootDir>'], // Configure test coverage thresholds // Note: ts-jest reports coverage against .ts files, not .js coverageThreshold: { global: { branches: 80, functions: 80, lines: 80, statements: 80 }, // Critical code requires higher coverage './src/utils/**/*.ts': { branches: 70, functions: 90, lines: 90, statements: 90 }, './src/middleware/**/*.ts': { branches: 70, functions: 85, lines: 85, statements: 85 } }, // Generate coverage report in these formats coverageReporters: ['text', 'lcov'], // Verbose output verbose: true, // Setup file setupFilesAfterEnv: ['<rootDir>/tests/setup.js'] }; - jest.resolver.cjs (486 bytes)
const { defaultResolver } = require('jest-resolve'); module.exports = function customResolver(request, options) { const resolve = options.defaultResolver || defaultResolver; try { return resolve(request, options); } catch (error) { if (request.startsWith('.') && request.endsWith('.js')) { try { return resolve(request.replace(/\.js$/, '.ts'), options); } catch (tsError) { tsError.cause = tsError.cause ?? error; throw tsError; } } throw error; } }; - LICENSE (2191 bytes)
Task Master License MIT License Copyright (c) 2025 β Eyal Toledano, Ralph Khreish Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "Commons Clause" License Condition v1.0 The Software is provided to you by the Licensor under the License (defined below), subject to the following condition: Without limiting other conditions in the License, the grant of rights under the License will not include, and the License does not grant to you, the right to Sell the Software. For purposes of the foregoing, "Sell" means practicing any or all of the rights granted to you under the License to provide the Software to third parties, for a fee or other consideration (including without limitation fees for hosting or consulting/support services related to the Software), as part of a product or service whose value derives, entirely or substantially, from the functionality of the Software. Any license notice or attribution required by the License must also include this Commons Clause License Condition notice. Software: All Task Master associated files (including all files in the GitHub repository "claude-task-master" and in the npm package "task-master-ai"). License: MIT Licensor: Eyal Toledano, Ralph Khreish
- llms-install.md (4852 bytes)
# Taskmaster AI Installation Guide This guide helps AI assistants install and configure Taskmaster for users in their development projects. ## What is Taskmaster? Taskmaster is an AI-driven task management system designed for development workflows. It helps break down projects into manageable tasks, track dependencies, and maintain development momentum through structured, AI-enhanced planning. ## Installation Steps ### Step 1: Add MCP Configuration Add the following configuration to the user's MCP settings file (`.cursor/mcp.json` for Cursor, or equivalent for other editors): ```json { "mcpServers": { "taskmaster-ai": { "command": "npx", "args": ["-y", "task-master-ai"], "env": { "ANTHROPIC_API_KEY": "user_will_add_their_key_here", "PERPLEXITY_API_KEY": "user_will_add_their_key_here", "OPENAI_API_KEY": "user_will_add_their_key_here", "GOOGLE_API_KEY": "user_will_add_their_key_here", "MISTRAL_API_KEY": "user_will_add_their_key_here", "OPENROUTER_API_KEY": "user_will_add_their_key_here", "XAI_API_KEY": "user_will_add_their_key_here" } } } } ``` ### Step 2: API Key Requirements Inform the user they need **at least one** API key from the following providers: - **Anthropic** (for Claude models) - Recommended - **OpenAI** (for GPT models) - **Google** (for Gemini models) - **Perplexity** (for research features) - Highly recommended - **Mistral** (for Mistral models) - **OpenRouter** (access to multiple models) - **xAI** (for Grok models) The user will be able to define 3 separate roles (can be the same provider or separate providers) for main AI operations, research operations (research providers/models only), and a fallback model in case of errors. ### Step 3: Initialize Project Once the MCP server is configured and API keys are added, initialize Taskmaster in the user's project: > Can you initialize Task Master in my project? This will run the `initialize_project` tool to set up the basic file structure. ### Step 4: Create Initial Tasks Users have two options for creating initial tasks: **Option A: Parse a PRD (Recommended)** If they have a Product Requirements Document: > Can you parse my PRD file at [path/to/prd.txt] to generate initial tasks? If the user does not have a PRD, the AI agent can help them create one and store it in scripts/prd.txt for parsing. **Option B: Start from scratch** > Can you help me add my first task: [describe the task] ## Common Usage Patterns ### Daily Workflow > What's the next task I should work on? > Can you show me the details for task [ID]? > Can you mark task [ID] as done? ### Task Management > Can you break down task [ID] into subtasks? > Can you add a new task: [description] > Can you analyze the complexity of my tasks? ### Project Organization > Can you show me all my pending tasks? > Can you move task [ID] to become a subtask of [parent ID]? > Can you update task [ID] with this new information: [details] ## Verification Steps After installation, verify everything is working: 1. **Check MCP Connection**: The AI should be able to access Task Master tools 2. **Test Basic Commands**: Try `get_tasks` to list current tasks 3. **Verify API Keys**: Ensure AI-powered commands work (like `add_task`) Note: An API key fallback exists that allows the MCP server to read API keys from `.env` instead of the MCP JSON config. It is recommended to have keys in both places in case the MCP server is unable to read keys from its environment for whatever reason. When adding keys to `.env` only, the `models` tool will explain that the keys are not OK for MCP. Despite this, the fallback should kick in and the API keys will be read from the `.env` file. ## Troubleshooting **If MCP server doesn't start:** - Verify the JSON configuration is valid - Check that Node.js is installed - Ensure API keys are properly formatted **If AI commands fail:** - Verify at least one API key is configured - Check API key permissions and quotas - Try using a different model via the `models` tool ## CLI Fallback Taskmaster is also available via CLI commands, by installing with `npm install task-master-ai@latest` in a terminal. Running `task-master help` will show all available commands, which offer a 1:1 experience with the MCP server. As the AI agent, you should refer to the system prompts and rules provided to you to identify Taskmaster-specific rules that help you understand how and when to use it. ## Next Steps Once installed, users can: - Create new tasks with `add-task` or parse a PRD (scripts/prd.txt) into tasks with `parse-prd` - Set up model preferences with `models` tool - Expand tasks into subtasks with `expand-all` and `expand-task` - Explore advanced features like research mode and complexity analysis For detailed documentation, refer to the Task Master docs directory.`` - manifest.json (2479 bytes)
{ "manifest_version": "0.3", "name": "Claude Task Master", "version": "0.43.1", "description": "AI-powered task management for structured development workflows. Parse PRDs, generate tasks with AI, track dependencies, and manage complexity.", "author": { "name": "Eyal Toledano", "url": "https://github.com/eyaltoledano" }, "repository": { "type": "git", "url": "https://github.com/eyaltoledano/claude-task-master" }, "icon": "icon.png", "server": { "type": "node", "entry_point": "dist/mcp-server.js", "mcp_config": { "command": "npx", "args": ["-y", "task-master-ai"], "env": { "ANTHROPIC_API_KEY": "${user_config.anthropic_api_key}", "PERPLEXITY_API_KEY": "${user_config.perplexity_api_key}", "OPENAI_API_KEY": "${user_config.openai_api_key}", "TASK_MASTER_TOOLS": "${user_config.task_master_tools}" } } }, "user_config": { "anthropic_api_key": { "type": "string", "title": "Anthropic API Key", "description": "API key for Claude models - get from console.anthropic.com (recommended)", "required": false, "sensitive": true }, "perplexity_api_key": { "type": "string", "title": "Perplexity API Key", "description": "API key for research features - get from perplexity.ai (optional)", "required": false, "sensitive": true }, "openai_api_key": { "type": "string", "title": "OpenAI API Key", "description": "API key for GPT models - get from platform.openai.com (optional)", "required": false, "sensitive": true }, "task_master_tools": { "type": "string", "title": "Tool Set", "description": "Which tools to enable: core (7 tools), standard (15 tools), or all (44 tools)", "required": false, "default": "core" } }, "tools": [ { "name": "get_tasks", "description": "Get all tasks with optional status filter" }, { "name": "next_task", "description": "Get the next recommended task to work on" }, { "name": "get_task", "description": "Get details for a specific task by ID" }, { "name": "set_task_status", "description": "Set the status of one or more tasks or subtasks" }, { "name": "update_subtask", "description": "Update a subtask with implementation details" }, { "name": "parse_prd", "description": "Parse a Product Requirements Document to generate initial tasks" }, { "name": "expand_task", "description": "Expand a task into subtasks for detailed implementation" } ] } - mcp-test.js (1951 bytes)
#!/usr/bin/env node import fs from 'fs'; import path from 'path'; import { Config } from 'fastmcp'; // Log the current directory console.error(`Current working directory: ${process.cwd()}`); try { console.error('Attempting to load FastMCP Config...'); // Check if .cursor/mcp.json exists const mcpPath = path.join(process.cwd(), '.cursor', 'mcp.json'); console.error(`Checking if mcp.json exists at: ${mcpPath}`); if (fs.existsSync(mcpPath)) { console.error('mcp.json file found'); console.error( `File content: ${JSON.stringify(JSON.parse(fs.readFileSync(mcpPath, 'utf8')), null, 2)}` ); } else { console.error('mcp.json file not found'); } // Try to create Config const config = new Config(); console.error('Config created successfully'); // Check if env property exists if (config.env) { console.error( `Config.env exists with keys: ${Object.keys(config.env).join(', ')}` ); // Print each env var value (careful with sensitive values) for (const [key, value] of Object.entries(config.env)) { if (key.includes('KEY')) { console.error(`${key}: [value hidden]`); } else { console.error(`${key}: ${value}`); } } } else { console.error('Config.env does not exist'); } } catch (error) { console.error(`Error loading Config: ${error.message}`); console.error(`Stack trace: ${error.stack}`); } // Log process.env to see if values from mcp.json were loaded automatically console.error('\nChecking if process.env already has values from mcp.json:'); const envVars = [ 'ANTHROPIC_API_KEY', 'PERPLEXITY_API_KEY', 'MODEL', 'PERPLEXITY_MODEL', 'MAX_TOKENS', 'TEMPERATURE', 'DEFAULT_SUBTASKS', 'DEFAULT_PRIORITY' ]; for (const varName of envVars) { if (process.env[varName]) { if (varName.includes('KEY')) { console.error(`${varName}: [value hidden]`); } else { console.error(`${varName}: ${process.env[varName]}`); } } else { console.error(`${varName}: not set`); } } - output.json (52 bytes)
{ "key": "value", "nested": { "prop": true } } - package.json (5710 bytes)
{ "name": "task-master-ai", "version": "0.43.1", "description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.", "main": "index.js", "type": "module", "bin": { "task-master": "dist/task-master.js", "task-master-mcp": "dist/mcp-server.js", "task-master-ai": "dist/mcp-server.js" }, "publishConfig": { "provenance": true, "access": "public" }, "workspaces": ["apps/*", "packages/*", "."], "scripts": { "build": "npm run build:build-config && cross-env NODE_ENV=production tsdown", "dev": "tsdown --watch", "turbo:dev": "turbo dev", "turbo:build": "turbo build", "turbo:typecheck": "turbo typecheck", "turbo:test": "turbo test", "turbo:test:unit": "turbo test:unit", "turbo:test:integration": "turbo test:integration", "build:build-config": "npm run build -w @tm/build-config", "test": "cross-env NODE_ENV=test node --experimental-vm-modules node_modules/.bin/jest", "test:unit": "node --experimental-vm-modules node_modules/.bin/jest --testPathPattern=unit", "test:integration": "node --experimental-vm-modules node_modules/.bin/jest --testPathPattern=integration", "test:fails": "node --experimental-vm-modules node_modules/.bin/jest --onlyFailures", "test:watch": "node --experimental-vm-modules node_modules/.bin/jest --watch", "test:coverage": "node --experimental-vm-modules node_modules/.bin/jest --coverage", "test:ci": "node --experimental-vm-modules node_modules/.bin/jest --coverage --ci", "test:e2e": "./tests/e2e/run_e2e.sh", "test:e2e-report": "./tests/e2e/run_e2e.sh --analyze-log", "postpack": "chmod +x dist/task-master.js dist/mcp-server.js", "changeset": "changeset", "changeset:validate": "node .github/scripts/validate-changesets.mjs", "version": "changeset version && node ./.github/scripts/sync-manifest-version.mjs && npm i --package-lock-only", "release": "node ./.github/scripts/release.mjs", "publish-packages": "turbo run build lint test && changeset version && changeset publish", "inspector": "npx @modelcontextprotocol/inspector node dist/mcp-server.js", "mcp-server": "node dist/mcp-server.js", "format-check": "biome format .", "format": "biome format . --write", "deps:check": "manypkg check || echo 'Note: Workspace package version warnings are expected for internal @tm/* packages'", "deps:fix": "manypkg fix" }, "keywords": [ "claude", "task", "management", "ai", "development", "cursor", "anthropic", "llm", "mcp", "context" ], "author": "Eyal Toledano", "license": "MIT WITH Commons-Clause", "dependencies": { "@ai-sdk/amazon-bedrock": "^3.0.23", "@ai-sdk/anthropic": "^2.0.18", "@ai-sdk/azure": "^2.0.89", "@ai-sdk/google": "^2.0.16", "@ai-sdk/google-vertex": "^3.0.86", "@ai-sdk/groq": "^2.0.21", "@ai-sdk/mistral": "^2.0.16", "@ai-sdk/openai": "^2.0.34", "@ai-sdk/openai-compatible": "^1.0.25", "@ai-sdk/perplexity": "^2.0.10", "@ai-sdk/provider": "^2.0.0", "@ai-sdk/provider-utils": "^3.0.10", "@ai-sdk/xai": "^2.0.22", "@aws-sdk/credential-providers": "^3.895.0", "@inquirer/search": "^3.0.15", "@openrouter/ai-sdk-provider": "^1.2.0", "@sentry/node": "^10.27.0", "@streamparser/json": "^0.0.22", "@supabase/supabase-js": "^2.57.4", "@types/turndown": "^5.0.6", "ai": "^5.0.51", "ai-sdk-provider-claude-code": "^2.2.4", "ai-sdk-provider-codex-cli": "^0.7.0", "ai-sdk-provider-gemini-cli": "^1.4.0", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "boxen": "^8.0.1", "chalk": "5.6.2", "cli-highlight": "^2.1.11", "cli-progress": "^3.12.0", "cli-table3": "^0.6.5", "commander": "^12.1.0", "cors": "^2.8.5", "date-fns": "^4.1.0", "dotenv": "^16.6.1", "express": "^4.21.2", "fastmcp": "^3.23.1", "figlet": "^1.8.0", "fs-extra": "^11.3.0", "fuse.js": "^7.1.0", "gpt-tokens": "^1.3.14", "gradient-string": "^3.0.0", "helmet": "^8.1.0", "inquirer": "^12.5.0", "jsonc-parser": "^3.3.1", "jsonrepair": "^3.13.0", "jsonwebtoken": "^9.0.2", "lru-cache": "^10.2.0", "marked": "^15.0.12", "marked-terminal": "^7.3.0", "ollama-ai-provider-v2": "^1.3.1", "open": "^10.2.0", "ora": "^8.2.0", "proper-lockfile": "^4.1.2", "simple-git": "^3.28.0", "steno": "^4.0.2", "terminal-link": "^5.0.0", "turndown": "^7.2.2", "undici": "^7.16.0", "uuid": "^11.1.0", "zod": "^4.1.12" }, "optionalDependencies": { "@anthropic-ai/claude-code": "^2.0.59", "@biomejs/cli-linux-x64": "^1.9.4" }, "engines": { "node": ">=20.0.0" }, "packageManager": "[email protected]", "repository": { "type": "git", "url": "git+https://github.com/eyaltoledano/claude-task-master.git" }, "homepage": "https://github.com/eyaltoledano/claude-task-master#readme", "bugs": { "url": "https://github.com/eyaltoledano/claude-task-master/issues" }, "files": [ "dist/**", "README-task-master.md", "README.md", "LICENSE", "CHANGELOG.md" ], "overrides": { "node-fetch": "^2.6.12", "whatwg-url": "^11.0.0" }, "devDependencies": { "@anthropic-ai/mcpb": "^2.1.2", "@biomejs/biome": "^1.9.4", "@changesets/changelog-github": "^0.5.1", "@changesets/cli": "^2.28.1", "@manypkg/cli": "^0.25.1", "@tm/ai-sdk-provider-grok-cli": "*", "@tm/cli": "*", "@types/fs-extra": "^11.0.4", "@types/jest": "^29.5.14", "@types/marked-terminal": "^6.1.1", "@vitest/coverage-v8": "^4.0.10", "concurrently": "^9.2.1", "cross-env": "^10.0.0", "execa": "^8.0.1", "jest": "^29.7.0", "jest-environment-node": "^29.7.0", "mock-fs": "^5.5.0", "prettier": "^3.5.3", "supertest": "^7.1.0", "ts-jest": "^29.4.2", "tsdown": "^0.15.2", "tsx": "^4.20.4", "turbo": "2.5.6", "typescript": "^5.9.2" } } - packages/claude-code-plugin/agents/task-checker.md (5849 bytes)
--- name: task-checker description: Use this agent to verify that tasks marked as 'review' have been properly implemented according to their specifications. This agent performs quality assurance by checking implementations against requirements, running tests, and ensuring best practices are followed. <example>Context: A task has been marked as 'review' after implementation. user: 'Check if task 118 was properly implemented' assistant: 'I'll use the task-checker agent to verify the implementation meets all requirements.' <commentary>Tasks in 'review' status need verification before being marked as 'done'.</commentary></example> <example>Context: Multiple tasks are in review status. user: 'Verify all tasks that are ready for review' assistant: 'I'll deploy the task-checker to verify all tasks in review status.' <commentary>The checker ensures quality before tasks are marked complete.</commentary></example> model: sonnet color: yellow --- You are a Quality Assurance specialist that rigorously verifies task implementations against their specifications. Your role is to ensure that tasks marked as 'review' meet all requirements before they can be marked as 'done'. ## Core Responsibilities 1. **Task Specification Review** - Retrieve task details using MCP tool `mcp__task-master-ai__get_task` - Understand the requirements, test strategy, and success criteria - Review any subtasks and their individual requirements 2. **Implementation Verification** - Use `Read` tool to examine all created/modified files - Use `Bash` tool to run compilation and build commands - Use `Grep` tool to search for required patterns and implementations - Verify file structure matches specifications - Check that all required methods/functions are implemented 3. **Test Execution** - Run tests specified in the task's testStrategy - Execute build commands (npm run build, tsc --noEmit, etc.) - Verify no compilation errors or warnings - Check for runtime errors where applicable - Test edge cases mentioned in requirements 4. **Code Quality Assessment** - Verify code follows project conventions - Check for proper error handling - Ensure TypeScript typing is strict (no 'any' unless justified) - Verify documentation/comments where required - Check for security best practices 5. **Dependency Validation** - Verify all task dependencies were actually completed - Check integration points with dependent tasks - Ensure no breaking changes to existing functionality ## Verification Workflow 1. **Retrieve Task Information** ``` Use mcp__task-master-ai__get_task to get full task details Note the implementation requirements and test strategy ``` 2. **Check File Existence** ```bash # Verify all required files exist ls -la [expected directories] # Read key files to verify content ``` 3. **Verify Implementation** - Read each created/modified file - Check against requirements checklist - Verify all subtasks are complete 4. **Run Tests** ```bash # TypeScript compilation cd [project directory] && npx tsc --noEmit # Run specified tests npm test [specific test files] # Build verification npm run build ``` 5. **Generate Verification Report** ## Output Format ```yaml verification_report: task_id: [ID] status: PASS | FAIL | PARTIAL score: [1-10] requirements_met: - β [Requirement that was satisfied] - β [Another satisfied requirement] issues_found: - β [Issue description] - β οΈ [Warning or minor issue] files_verified: - path: [file path] status: [created/modified/verified] issues: [any problems found] tests_run: - command: [test command] result: [pass/fail] output: [relevant output] recommendations: - [Specific fix needed] - [Improvement suggestion] verdict: | [Clear statement on whether task should be marked 'done' or sent back to 'pending'] [If FAIL: Specific list of what must be fixed] [If PASS: Confirmation that all requirements are met] ``` ## Decision Criteria **Mark as PASS (ready for 'done'):** - All required files exist and contain expected content - All tests pass successfully - No compilation or build errors - All subtasks are complete - Core requirements are met - Code quality is acceptable **Mark as PARTIAL (may proceed with warnings):** - Core functionality is implemented - Minor issues that don't block functionality - Missing nice-to-have features - Documentation could be improved - Tests pass but coverage could be better **Mark as FAIL (must return to 'pending'):** - Required files are missing - Compilation or build errors - Tests fail - Core requirements not met - Security vulnerabilities detected - Breaking changes to existing code ## Important Guidelines - **BE THOROUGH**: Check every requirement systematically - **BE SPECIFIC**: Provide exact file paths and line numbers for issues - **BE FAIR**: Distinguish between critical issues and minor improvements - **BE CONSTRUCTIVE**: Provide clear guidance on how to fix issues - **BE EFFICIENT**: Focus on requirements, not perfection ## Tools You MUST Use - `Read`: Examine implementation files (READ-ONLY) - `Bash`: Run tests and verification commands - `Grep`: Search for patterns in code - `mcp__task-master-ai__get_task`: Get task details - **NEVER use Write/Edit** - you only verify, not fix ## Integration with Workflow You are the quality gate between 'review' and 'done' status: 1. Task-executor implements and marks as 'review' 2. You verify and report PASS/FAIL 3. Claude either marks as 'done' (PASS) or 'pending' (FAIL) 4. If FAIL, task-executor re-implements based on your report Your verification ensures high quality and prevents accumulation of technical debt. - packages/claude-code-plugin/agents/task-executor.md (4655 bytes)
--- name: task-executor description: Use this agent when you need to implement, complete, or work on a specific task that has been identified by the task-orchestrator or when explicitly asked to execute a particular task. This agent focuses on the actual implementation and completion of individual tasks rather than planning or orchestration. Examples: <example>Context: The task-orchestrator has identified that task 2.3 'Implement user authentication' needs to be worked on next. user: 'Let's work on the authentication task' assistant: 'I'll use the task-executor agent to implement the user authentication task that was identified.' <commentary>Since we need to actually implement a specific task rather than plan or identify tasks, use the task-executor agent.</commentary></example> <example>Context: User wants to complete a specific subtask. user: 'Please implement the JWT token validation for task 2.3.1' assistant: 'I'll launch the task-executor agent to implement the JWT token validation subtask.' <commentary>The user is asking for specific implementation work on a known task, so the task-executor is appropriate.</commentary></example> <example>Context: After reviewing the task list, implementation is needed. user: 'Now let's actually build the API endpoint for user registration' assistant: 'I'll use the task-executor agent to implement the user registration API endpoint.' <commentary>Moving from planning to execution phase requires the task-executor agent.</commentary></example> model: sonnet color: blue --- You are an elite implementation specialist focused on executing and completing specific tasks with precision and thoroughness. Your role is to take identified tasks and transform them into working implementations, following best practices and project standards. **Core Responsibilities:** 1. **Task Analysis**: When given a task, first retrieve its full details using `task-master show <id>` to understand requirements, dependencies, and acceptance criteria. 2. **Implementation Planning**: Before coding, briefly outline your implementation approach: - Identify files that need to be created or modified - Note any dependencies or prerequisites - Consider the testing strategy defined in the task 3. **Focused Execution**: - Implement one subtask at a time for clarity and traceability - Follow the project's coding standards from CLAUDE.md if available - Prefer editing existing files over creating new ones - Only create files that are essential for the task completion 4. **Progress Documentation**: - Use `task-master update-subtask --id=<id> --prompt="implementation notes"` to log your approach and any important decisions - Update task status to 'in-progress' when starting: `task-master set-status --id=<id> --status=in-progress` - Mark as 'done' only after verification: `task-master set-status --id=<id> --status=done` 5. **Quality Assurance**: - Implement the testing strategy specified in the task - Verify that all acceptance criteria are met - Check for any dependency conflicts or integration issues - Run relevant tests before marking task as complete 6. **Dependency Management**: - Check task dependencies before starting implementation - If blocked by incomplete dependencies, clearly communicate this - Use `task-master validate-dependencies` when needed **Implementation Workflow:** 1. Retrieve task details and understand requirements 2. Check dependencies and prerequisites 3. Plan implementation approach 4. Update task status to in-progress 5. Implement the solution incrementally 6. Log progress and decisions in subtask updates 7. Test and verify the implementation 8. Mark task as done when complete 9. Suggest next task if appropriate **Key Principles:** - Focus on completing one task thoroughly before moving to the next - Maintain clear communication about what you're implementing and why - Follow existing code patterns and project conventions - Prioritize working code over extensive documentation unless docs are the task - Ask for clarification if task requirements are ambiguous - Consider edge cases and error handling in your implementations **Integration with Task Master:** You work in tandem with the task-orchestrator agent. While the orchestrator identifies and plans tasks, you execute them. Always use Task Master commands to: - Track your progress - Update task information - Maintain project state - Coordinate with the broader development workflow When you complete a task, briefly summarize what was implemented and suggest whether to continue with the next task or if review/testing is needed first.
- packages/claude-code-plugin/agents/task-orchestrator.md (7093 bytes)
--- name: task-orchestrator description: Use this agent when you need to coordinate and manage the execution of Task Master tasks, especially when dealing with complex task dependencies and parallel execution opportunities. This agent should be invoked at the beginning of a work session to analyze the task queue, identify parallelizable work, and orchestrate the deployment of task-executor agents. It should also be used when tasks complete to reassess the dependency graph and deploy new executors as needed.\n\n<example>\nContext: User wants to start working on their project tasks using Task Master\nuser: "Let's work on the next available tasks in the project"\nassistant: "I'll use the task-orchestrator agent to analyze the task queue and coordinate execution"\n<commentary>\nThe user wants to work on tasks, so the task-orchestrator should be deployed to analyze dependencies and coordinate execution.\n</commentary>\n</example>\n\n<example>\nContext: Multiple independent tasks are available in the queue\nuser: "Can we work on multiple tasks at once?"\nassistant: "Let me deploy the task-orchestrator to analyze task dependencies and parallelize the work"\n<commentary>\nWhen parallelization is mentioned or multiple tasks could be worked on, the orchestrator should coordinate the effort.\n</commentary>\n</example>\n\n<example>\nContext: A complex feature with many subtasks needs implementation\nuser: "Implement the authentication system tasks"\nassistant: "I'll use the task-orchestrator to break down the authentication tasks and coordinate their execution"\n<commentary>\nFor complex multi-task features, the orchestrator manages the overall execution strategy.\n</commentary>\n</example> model: opus color: green --- You are the Task Orchestrator, an elite coordination agent specialized in managing Task Master workflows for maximum efficiency and parallelization. You excel at analyzing task dependency graphs, identifying opportunities for concurrent execution, and deploying specialized task-executor agents to complete work efficiently. ## Core Responsibilities 1. **Task Queue Analysis**: You continuously monitor and analyze the task queue using Task Master MCP tools to understand the current state of work, dependencies, and priorities. 2. **Dependency Graph Management**: You build and maintain a mental model of task dependencies, identifying which tasks can be executed in parallel and which must wait for prerequisites. 3. **Executor Deployment**: You strategically deploy task-executor agents for individual tasks or task groups, ensuring each executor has the necessary context and clear success criteria. 4. **Progress Coordination**: You track the progress of deployed executors, handle task completion notifications, and reassess the execution strategy as tasks complete. ## Operational Workflow ### Initial Assessment Phase 1. Use `get_tasks` or `task-master list` to retrieve all available tasks 2. Analyze task statuses, priorities, and dependencies 3. Identify tasks with status 'pending' that have no blocking dependencies 4. Group related tasks that could benefit from specialized executors 5. Create an execution plan that maximizes parallelization ### Executor Deployment Phase 1. For each independent task or task group: - Deploy a task-executor agent with specific instructions - Provide the executor with task ID, requirements, and context - Set clear completion criteria and reporting expectations 2. Maintain a registry of active executors and their assigned tasks 3. Establish communication protocols for progress updates ### Coordination Phase 1. Monitor executor progress through task status updates 2. When a task completes: - Verify completion with `get_task` or `task-master show <id>` - Update task status if needed using `set_task_status` - Reassess dependency graph for newly unblocked tasks - Deploy new executors for available work 3. Handle executor failures or blocks: - Reassign tasks to new executors if needed - Escalate complex issues to the user - Update task status to 'blocked' when appropriate ### Optimization Strategies **Parallel Execution Rules**: - Never assign dependent tasks to different executors simultaneously - Prioritize high-priority tasks when resources are limited - Group small, related subtasks for single executor efficiency - Balance executor load to prevent bottlenecks **Context Management**: - Provide executors with minimal but sufficient context - Share relevant completed task information when it aids execution - Maintain a shared knowledge base of project-specific patterns **Quality Assurance**: - Verify task completion before marking as done - Ensure test strategies are followed when specified - Coordinate cross-task integration testing when needed ## Communication Protocols When deploying executors, provide them with: ``` TASK ASSIGNMENT: - Task ID: [specific ID] - Objective: [clear goal] - Dependencies: [list any completed prerequisites] - Success Criteria: [specific completion requirements] - Context: [relevant project information] - Reporting: [when and how to report back] ``` When receiving executor updates: 1. Acknowledge completion or issues 2. Update task status in Task Master 3. Reassess execution strategy 4. Deploy new executors as appropriate ## Decision Framework **When to parallelize**: - Multiple pending tasks with no interdependencies - Sufficient context available for independent execution - Tasks are well-defined with clear success criteria **When to serialize**: - Strong dependencies between tasks - Limited context or unclear requirements - Integration points requiring careful coordination **When to escalate**: - Circular dependencies detected - Critical blockers affecting multiple tasks - Ambiguous requirements needing clarification - Resource conflicts between executors ## Error Handling 1. **Executor Failure**: Reassign task to new executor with additional context about the failure 2. **Dependency Conflicts**: Halt affected executors, resolve conflict, then resume 3. **Task Ambiguity**: Request clarification from user before proceeding 4. **System Errors**: Implement graceful degradation, falling back to serial execution if needed ## Performance Metrics Track and optimize for: - Task completion rate - Parallel execution efficiency - Executor success rate - Time to completion for task groups - Dependency resolution speed ## Integration with Task Master Leverage these Task Master MCP tools effectively: - `get_tasks` - Continuous queue monitoring - `get_task` - Detailed task analysis - `set_task_status` - Progress tracking - `next_task` - Fallback for serial execution - `analyze_project_complexity` - Strategic planning - `complexity_report` - Resource allocation You are the strategic mind coordinating the entire task execution effort. Your success is measured by the efficient completion of all tasks while maintaining quality and respecting dependencies. Think systematically, act decisively, and continuously optimize the execution strategy based on real-time progress.
- README-task-master.md (18401 bytes)
# Task Master ### by [@eyaltoledano](https://x.com/eyaltoledano) A task management system for AI-driven development with Claude, designed to work seamlessly with Cursor AI. ## Requirements - Node.js 14.0.0 or higher - Anthropic API key (Claude API) - Anthropic SDK version 0.39.0 or higher - OpenAI SDK (for Perplexity API integration, optional) ## Configuration Taskmaster uses two primary configuration methods: 1. **`.taskmasterconfig` File (Project Root)** - Stores most settings: AI model selections (main, research, fallback), parameters (max tokens, temperature), logging level, default priority/subtasks, project name. - **Created and managed using `task-master models --setup` CLI command or the `models` MCP tool.** - Do not edit manually unless you know what you are doing. 2. **Environment Variables (`.env` file or MCP `env` block)** - Used **only** for sensitive **API Keys** (e.g., `ANTHROPIC_API_KEY`, `PERPLEXITY_API_KEY`, etc.) and specific endpoints (like `OLLAMA_BASE_URL`). - **For CLI:** Place keys in a `.env` file in your project root. - **For MCP/Cursor:** Place keys in the `env` section of your `.cursor/mcp.json` (or other MCP config according to the AI IDE or client you use) file under the `taskmaster-ai` server definition. **Important:** Settings like model choices, max tokens, temperature, and log level are **no longer configured via environment variables.** Use the `task-master models` command or tool. See the [Configuration Guide](docs/configuration.md) for full details. ## Installation ```bash # Install globally npm install -g task-master-ai # OR install locally within your project npm install task-master-ai ``` ### Initialize a new project ```bash # If installed globally task-master init # If installed locally npx task-master init ``` This will prompt you for project details and set up a new project with the necessary files and structure. ### Important Notes 1. **ES Modules Configuration:** - This project uses ES Modules (ESM) instead of CommonJS. - This is set via `"type": "module"` in your package.json. - Use `import/export` syntax instead of `require()`. - Files should use `.js` or `.mjs` extensions. - To use a CommonJS module, either: - Rename it with `.cjs` extension - Use `await import()` for dynamic imports - If you need CommonJS throughout your project, remove `"type": "module"` from package.json, but Task Master scripts expect ESM. 2. The Anthropic SDK version should be 0.39.0 or higher. ## Quick Start with Global Commands After installing the package globally, you can use these CLI commands from any directory: ```bash # Initialize a new project task-master init # Parse a PRD and generate tasks task-master parse-prd your-prd.txt # List all tasks task-master list # Show the next task to work on task-master next # Generate task files task-master generate ``` ## Troubleshooting ### If `task-master init` doesn't respond: Try running it with Node directly: ```bash node node_modules/claude-task-master/scripts/init.js ``` Or clone the repository and run: ```bash git clone https://github.com/eyaltoledano/claude-task-master.git cd claude-task-master node scripts/init.js ``` ## Task Structure Tasks in tasks.json have the following structure: - `id`: Unique identifier for the task (Example: `1`) - `title`: Brief, descriptive title of the task (Example: `"Initialize Repo"`) - `description`: Concise description of what the task involves (Example: `"Create a new repository, set up initial structure."`) - `status`: Current state of the task (Example: `"pending"`, `"done"`, `"deferred"`) - `dependencies`: IDs of tasks that must be completed before this task (Example: `[1, 2]`) - Dependencies are displayed with status indicators (β for completed, β±οΈ for pending) - This helps quickly identify which prerequisite tasks are blocking work - `priority`: Importance level of the task (Example: `"high"`, `"medium"`, `"low"`) - `details`: In-depth implementation instructions (Example: `"Use GitHub client ID/secret, handle callback, set session token."`) - `testStrategy`: Verification approach (Example: `"Deploy and call endpoint to confirm 'Hello World' response."`) - `subtasks`: List of smaller, more specific tasks that make up the main task (Example: `[{"id": 1, "title": "Configure OAuth", ...}]`) ## Integrating with Cursor AI Claude Task Master is designed to work seamlessly with [Cursor AI](https://www.cursor.so/), providing a structured workflow for AI-driven development. ### Setup with Cursor 1. After initializing your project, open it in Cursor 2. The `.cursor/rules/dev_workflow.mdc` file is automatically loaded by Cursor, providing the AI with knowledge about the task management system 3. Place your PRD document in the `scripts/` directory (e.g., `scripts/prd.txt`) 4. Open Cursor's AI chat and switch to Agent mode ### Setting up MCP in Cursor To enable enhanced task management capabilities directly within Cursor using the Model Control Protocol (MCP): 1. Go to Cursor settings 2. Navigate to the MCP section 3. Click on "Add New MCP Server" 4. Configure with the following details: - Name: "Task Master" - Type: "Command" - Command: "npx -y task-master-ai" 5. Save the settings Once configured, you can interact with Task Master's task management commands directly through Cursor's interface, providing a more integrated experience. ### Initial Task Generation In Cursor's AI chat, instruct the agent to generate tasks from your PRD: ``` Please use the task-master parse-prd command to generate tasks from my PRD. The PRD is located at scripts/prd.txt. ``` The agent will execute: ```bash task-master parse-prd scripts/prd.txt ``` This will: - Parse your PRD document - Generate a structured `tasks.json` file with tasks, dependencies, priorities, and test strategies - The agent will understand this process due to the Cursor rules ### Generate Individual Task Files Next, ask the agent to generate individual task files: ``` Please generate individual task files from tasks.json ``` The agent will execute: ```bash task-master generate ``` This creates individual task files in the `tasks/` directory (e.g., `task_001.txt`, `task_002.txt`), making it easier to reference specific tasks. ## AI-Driven Development Workflow The Cursor agent is pre-configured (via the rules file) to follow this workflow: ### 1. Task Discovery and Selection Ask the agent to list available tasks: ``` What tasks are available to work on next? ``` The agent will: - Run `task-master list` to see all tasks - Run `task-master next` to determine the next task to work on - Analyze dependencies to determine which tasks are ready to be worked on - Prioritize tasks based on priority level and ID order - Suggest the next task(s) to implement ### 2. Task Implementation When implementing a task, the agent will: - Reference the task's details section for implementation specifics - Consider dependencies on previous tasks - Follow the project's coding standards - Create appropriate tests based on the task's testStrategy You can ask: ``` Let's implement task 3. What does it involve? ``` ### 3. Task Verification Before marking a task as complete, verify it according to: - The task's specified testStrategy - Any automated tests in the codebase - Manual verification if required ### 4. Task Completion When a task is completed, tell the agent: ``` Task 3 is now complete. Please update its status. ``` The agent will execute: ```bash task-master set-status --id=3 --status=done ``` ### 5. Handling Implementation Drift If during implementation, you discover that: - The current approach differs significantly from what was planned - Future tasks need to be modified due to current implementation choices - New dependencies or requirements have emerged Tell the agent: ``` We've changed our approach. We're now using Express instead of Fastify. Please update all future tasks to reflect this change. ``` The agent will execute: ```bash task-master update --from=4 --prompt="Now we are using Express instead of Fastify." ``` This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work. ### 6. Breaking Down Complex Tasks For complex tasks that need more granularity: ``` Task 5 seems complex. Can you break it down into subtasks? ``` The agent will execute: ```bash task-master expand --id=5 --num=3 ``` You can provide additional context: ``` Please break down task 5 with a focus on security considerations. ``` The agent will execute: ```bash task-master expand --id=5 --prompt="Focus on security aspects" ``` You can also expand all pending tasks: ``` Please break down all pending tasks into subtasks. ``` The agent will execute: ```bash task-master expand --all ``` For research-backed subtask generation using Perplexity AI: ``` Please break down task 5 using research-backed generation. ``` The agent will execute: ```bash task-master expand --id=5 --research ``` ## Command Reference Here's a comprehensive reference of all available commands: ### Parse PRD ```bash # Parse a PRD file and generate tasks task-master parse-prd <prd-file.txt> # Limit the number of tasks generated (default is 10) task-master parse-prd <prd-file.txt> --num-tasks=5 # Allow task master to determine the number of tasks based on complexity task-master parse-prd <prd-file.txt> --num-tasks=0 ``` ### List Tasks ```bash # List all tasks task-master list # List tasks with a specific status task-master list --status=<status> # List tasks with subtasks task-master list --with-subtasks # List tasks with a specific status and include subtasks task-master list --status=<status> --with-subtasks ``` ### Show Next Task ```bash # Show the next task to work on based on dependencies and status task-master next ``` ### Show Specific Task ```bash # Show details of a specific task task-master show <id> # or task-master show --id=<id> # View a specific subtask (e.g., subtask 2 of task 1) task-master show 1.2 ``` ### Update Tasks ```bash # Update tasks from a specific ID and provide context task-master update --from=<id> --prompt="<prompt>" ``` ### Generate Task Files ```bash # Generate individual task files from tasks.json task-master generate ``` ### Set Task Status ```bash # Set status of a single task task-master set-status --id=<id> --status=<status> # Set status for multiple tasks task-master set-status --id=1,2,3 --status=<status> # Set status for subtasks task-master set-status --id=1.1,1.2 --status=<status> ``` When marking a task as "done", all of its subtasks will automatically be marked as "done" as well. ### Expand Tasks ```bash # Expand a specific task with subtasks task-master expand --id=<id> --num=<number> # Expand a task with a dynamic number of subtasks (ignoring complexity report) task-master expand --id=<id> --num=0 # Expand with additional context task-master expand --id=<id> --prompt="<context>" # Expand all pending tasks task-master expand --all # Force regeneration of subtasks for tasks that already have them task-master expand --all --force # Research-backed subtask generation for a specific task task-master expand --id=<id> --research # Research-backed generation for all tasks task-master expand --all --research ``` ### Clear Subtasks ```bash # Clear subtasks from a specific task task-master clear-subtasks --id=<id> # Clear subtasks from multiple tasks task-master clear-subtasks --id=1,2,3 # Clear subtasks from all tasks task-master clear-subtasks --all ``` ### Analyze Task Complexity ```bash # Analyze complexity of all tasks task-master analyze-complexity # Save report to a custom location task-master analyze-complexity --output=my-report.json # Use a specific LLM model task-master analyze-complexity --model=claude-3-opus-20240229 # Set a custom complexity threshold (1-10) task-master analyze-complexity --threshold=6 # Use an alternative tasks file task-master analyze-complexity --file=custom-tasks.json # Use Perplexity AI for research-backed complexity analysis task-master analyze-complexity --research ``` ### View Complexity Report ```bash # Display the task complexity analysis report task-master complexity-report # View a report at a custom location task-master complexity-report --file=my-report.json ``` ### Managing Task Dependencies ```bash # Add a dependency to a task task-master add-dependency --id=<id> --depends-on=<id> # Remove a dependency from a task task-master remove-dependency --id=<id> --depends-on=<id> # Validate dependencies without fixing them task-master validate-dependencies # Find and fix invalid dependencies automatically task-master fix-dependencies ``` ### Add a New Task ```bash # Add a new task using AI task-master add-task --prompt="Description of the new task" # Add a task with dependencies task-master add-task --prompt="Description" --dependencies=1,2,3 # Add a task with priority task-master add-task --prompt="Description" --priority=high ``` ## Feature Details ### Analyzing Task Complexity The `analyze-complexity` command: - Analyzes each task using AI to assess its complexity on a scale of 1-10 - Recommends optimal number of subtasks based on configured DEFAULT_SUBTASKS - Generates tailored prompts for expanding each task - Creates a comprehensive JSON report with ready-to-use commands - Saves the report to scripts/task-complexity-report.json by default The generated report contains: - Complexity analysis for each task (scored 1-10) - Recommended number of subtasks based on complexity - AI-generated expansion prompts customized for each task - Ready-to-run expansion commands directly within each task analysis ### Viewing Complexity Report The `complexity-report` command: - Displays a formatted, easy-to-read version of the complexity analysis report - Shows tasks organized by complexity score (highest to lowest) - Provides complexity distribution statistics (low, medium, high) - Highlights tasks recommended for expansion based on threshold score - Includes ready-to-use expansion commands for each complex task - If no report exists, offers to generate one on the spot ### Smart Task Expansion The `expand` command automatically checks for and uses the complexity report: When a complexity report exists: - Tasks are automatically expanded using the recommended subtask count and prompts - When expanding all tasks, they're processed in order of complexity (highest first) - Research-backed generation is preserved from the complexity analysis - You can still override recommendations with explicit command-line options Example workflow: ```bash # Generate the complexity analysis report with research capabilities task-master analyze-complexity --research # Review the report in a readable format task-master complexity-report # Expand tasks using the optimized recommendations task-master expand --id=8 # or expand all tasks task-m - README.md (17421 bytes)
<a name="readme-top"></a> <div align='center'> <a href="https://trendshift.io/repositories/13971" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13971" alt="eyaltoledano%2Fclaude-task-master | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a> </div> <p align="center"> <a href="https://tryhamster.com/product/taskmaster"><img src="./images/logo.png?raw=true" alt="Taskmaster logo"></a> </p> <p align="center"> <b>Taskmaster</b>: A task management system for AI-driven development, designed to work seamlessly with any AI chat. </p> <p align="center"> <a href="https://discord.gg/taskmasterai" target="_blank"><img src="https://dcbadge.limes.pink/api/server/https://discord.gg/taskmasterai?style=flat" alt="Discord"></a> | <a href="https://tryhamster.com/docs/taskmaster" target="_blank">Docs</a> </p> <p align="center"> <a href="https://github.com/eyaltoledano/claude-task-master/actions/workflows/ci.yml"><img src="https://github.com/eyaltoledano/claude-task-master/actions/workflows/ci.yml/badge.svg" alt="CI"></a> <a href="https://github.com/eyaltoledano/claude-task-master/stargazers"><img src="https://img.shields.io/github/stars/eyaltoledano/claude-task-master?style=social" alt="GitHub stars"></a> <a href="https://badge.fury.io/js/task-master-ai"><img src="https://badge.fury.io/js/task-master-ai.svg" alt="npm version"></a> <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT%20with%20Commons%20Clause-blue.svg" alt="License"></a> </p> <p align="center"> <a href="https://www.npmjs.com/package/task-master-ai"><img src="https://img.shields.io/npm/d18m/task-master-ai?style=flat" alt="NPM Downloads"></a> <a href="https://www.npmjs.com/package/task-master-ai"><img src="https://img.shields.io/npm/dm/task-master-ai?style=flat" alt="NPM Downloads"></a> <a href="https://www.npmjs.com/package/task-master-ai"><img src="https://img.shields.io/npm/dw/task-master-ai?style=flat" alt="NPM Downloads"></a> </p> ## By [@eyaltoledano](https://x.com/eyaltoledano) & [@RalphEcom](https://x.com/RalphEcom) [](https://x.com/eyaltoledano) [](https://x.com/RalphEcom) A task management system for AI-driven development with Claude, designed to work seamlessly with Cursor AI. ## Documentation π **[View Full Documentation](https://tryhamster.com/docs/taskmaster)** ### Quick Links - [Quick Start Guide](https://tryhamster.com/docs/taskmaster/getting-started/quick-start/quick-start) - [Installation](https://tryhamster.com/docs/taskmaster/getting-started/quick-start/installation) - [API Keys & Providers](https://tryhamster.com/docs/taskmaster/getting-started/api-keys) - [Supported Editors](https://tryhamster.com/docs/taskmaster/ide-setup/supported-editors) - [MCP Tools Reference](https://tryhamster.com/docs/taskmaster/capabilities/mcp) - [CLI Commands Reference](https://tryhamster.com/docs/taskmaster/capabilities/cli-root-commands) - [Task Structure](https://tryhamster.com/docs/taskmaster/capabilities/task-structure) - [Task Dependencies](https://tryhamster.com/docs/taskmaster/task-workflow/dependencies) - [Tags & Workstreams](https://tryhamster.com/docs/taskmaster/task-workflow/tags) - [Research Command](https://tryhamster.com/docs/taskmaster/task-workflow/research) - [Loop Command](https://tryhamster.com/docs/taskmaster/automation/loop) - [AI Providers Overview](https://tryhamster.com/docs/taskmaster/ai-providers/overview) - [Team Collaboration](https://tryhamster.com/docs/taskmaster/team/overview) - [Best Practices](https://tryhamster.com/docs/taskmaster/best-practices/index) - [FAQ](https://tryhamster.com/docs/taskmaster/getting-started/faq) - [Changelog](CHANGELOG.md) ### More from Hamster - [Hamster Studio](https://tryhamster.com/product/studio) - [Product & Engineering Methods](https://tryhamster.com/methods) - [Product & Engineering Skills](https://tryhamster.com/skills) - [Hamster Pricing](https://tryhamster.com/pricing) #### Quick Install for Cursor 1.0+ (One-Click) [](https://cursor.com/en/install-mcp?name=task-master-ai&config=eyJjb21tYW5kIjoibnB4IC15IC0tcGFja2FnZT10YXNrLW1hc3Rlci1haSB0YXNrLW1hc3Rlci1haSIsImVudiI6eyJBTlRIUk9QSUNfQVBJX0tFWSI6IllPVVJfQU5USFJPUElDX0FQSV9LRVlfSEVSRSIsIlBFUlBMRVhJVFlfQVBJX0tFWSI6IllPVVJfUEVSUExFWElUWV9BUElfS0VZX0hFUkUiLCJPUEVOQUlfQVBJX0tFWSI6IllPVVJfT1BFTkFJX0tFWV9IRVJFIiwiR09PR0xFX0FQSV9LRVkiOiJZT1VSX0dPT0dMRV9LRVlfSEVSRSIsIk1JU1RSQUxfQVBJX0tFWSI6IllPVVJfTUlTVFJBTF9LRVlfSEVSRSIsIkdST1FfQVBJX0tFWSI6IllPVVJfR1JPUV9LRVlfSEVSRSIsIk9QRU5ST1VURVJfQVBJX0tFWSI6IllPVVJfT1BFTlJPVVRFUl9LRVlfSEVSRSIsIlhBSV9BUElfS0VZIjoiWU9VUl9YQUlfS0VZX0hFUkUiLCJBWlVSRV9PUEVOQUlfQVBJX0tFWSI6IllPVVJfQVpVUkVfS0VZX0hFUkUiLCJPTExBTUFfQVBJX0tFWSI6IllPVVJfT0xMQU1BX0FQSV9LRVlfSEVSRSJ9fQ%3D%3D) > **Note:** After clicking the link, you'll still need to add your API keys to the configuration. The link installs the MCP server with placeholder keys that you'll need to replace with your actual API keys. #### Claude Code Quick Install For Claude Code users: ```bash claude mcp add taskmaster-ai -- npx -y task-master-ai ``` Don't forget to add your API keys to the configuration: - in the root .env of your Project - in the "env" section of your mcp config for taskmaster-ai ## Requirements Taskmaster utilizes AI across several commands, and those require a separate API key. You can use a variety of models from different AI providers provided you add your API keys. For example, if you want to use Claude 3.7, you'll need an Anthropic API key. You can define 3 types of models to be used: the main model, the research model, and the fallback model (in case either the main or research fail). Whatever model you use, its provider API key must be present in either mcp.json or .env. At least one (1) of the following is required: - Anthropic API key (Claude API) - OpenAI API key - Google Gemini API key - Perplexity API key (for research model) - xAI API Key (for research or main model) - OpenRouter API Key (for research or main model) - Claude Code (no API key required - requires Claude Code CLI) - Codex CLI (OAuth via ChatGPT subscription - requires Codex CLI) Using the research model is optional but highly recommended. You will need at least ONE API key (unless using Claude Code or Codex CLI with OAuth). Adding all API keys enables you to seamlessly switch between model providers at will. ## Quick Start ### Option 1: MCP (Recommended) MCP (Model Control Protocol) lets you run Task Master directly from your editor. #### 1. Add your MCP config at the following path depending on your editor | Editor | Scope | Linux/macOS Path | Windows Path | Key | | ------------ | ------- | ------------------------------------- | ------------------------------------------------- | ------------ | | **Cursor** | Global | `~/.cursor/mcp.json` | `%USERPROFILE%\.cursor\mcp.json` | `mcpServers` | | | Project | `<project_folder>/.cursor/mcp.json` | `<project_folder>\.cursor\mcp.json` | `mcpServers` | | **Windsurf** | Global | `~/.codeium/windsurf/mcp_config.json` | `%USERPROFILE%\.codeium\windsurf\mcp_config.json` | `mcpServers` | | **VS Code** | Project | `<project_folder>/.vscode/mcp.json` | `<project_folder>\.vscode\mcp.json` | `servers` | | **Q CLI** | Global | `~/.aws/amazonq/mcp.json` | | `mcpServers` | ##### Manual Configuration ###### Cursor & Windsurf & Q Developer CLI (`mcpServers`) ```json { "mcpServers": { "task-master-ai": { "command": "npx", "args": ["-y", "task-master-ai"], "env": { // "TASK_MASTER_TOOLS": "all", // Options: "all", "standard", "core", or comma-separated list of tools "ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE", "PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE", "OPENAI_API_KEY": "YOUR_OPENAI_KEY_HERE", "GOOGLE_API_KEY": "YOUR_GOOGLE_KEY_HERE", "MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE", "GROQ_API_KEY": "YOUR_GROQ_KEY_HERE", "OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE", "XAI_API_KEY": "YOUR_XAI_KEY_HERE", "AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE", "OLLAMA_API_KEY": "YOUR_OLLAMA_API_KEY_HERE" } } } } ``` > π Replace `YOUR_β¦_KEY_HERE` with your real API keys. You can remove keys you don't use. > **Note**: If you see `0 tools enabled` in the MCP settings, restart your editor and check that your API keys are correctly configured. ###### VSβ―Code (`servers` + `type`) ```json { "servers": { "task-master-ai": { "command": "npx", "args": ["-y", "task-master-ai"], "env": { // "TASK_MASTER_TOOLS": "all", // Options: "all", "standard", "core", or comma-separated list of tools "ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_API_KEY_HERE", "PERPLEXITY_API_KEY": "YOUR_PERPLEXITY_API_KEY_HERE", "OPENAI_API_KEY": "YOUR_OPENAI_KEY_HERE", "GOOGLE_API_KEY": "YOUR_GOOGLE_KEY_HERE", "MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE", "GROQ_API_KEY": "YOUR_GROQ_KEY_HERE", "OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE", "XAI_API_KEY": "YOUR_XAI_KEY_HERE", "AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE", "OLLAMA_API_KEY": "YOUR_OLLAMA_API_KEY_HERE" }, "type": "stdio" } } } ``` > π Replace `YOUR_β¦_KEY_HERE` with your real API keys. You can remove keys you don't use. #### 2. (Cursor-only) Enable Taskmaster MCP Open Cursor Settings (Ctrl+Shift+J) β‘ Click on MCP tab on the left β‘ Enable task-master-ai with the toggle #### 3. (Optional) Configure the models you want to use In your editor's AI chat pane, say: ```txt Change the main, research and fallback models to <model_name>, <model_name> and <model_name> respectively. ``` For example, to use Claude Code (no API key required): ```txt Change the main model to claude-code/sonnet ``` [Table of available models](docs/models.md) | [Claude Code setup](docs/examples/claude-code-usage.md) #### 4. Initialize Task Master In your editor's AI chat pane, say: ```txt Initialize taskmaster-ai in my project ``` #### 5. Make sure you have a PRD (Recommended) For **new projects**: Create your PRD at `.taskmaster/docs/prd.txt`. For **existing projects**: You can use `scripts/prd.txt` or migrate with `task-master migrate` An example PRD template is available after initialization in `.taskmaster/templates/example_prd.txt`. > [!NOTE] > While a PRD is recommended for complex projects, you can always create individual tasks by asking "Can you help me implement [description of what you want to do]?" in chat. **Always start with a detailed PRD.** The more detailed your PRD, the better the generated tasks will be. #### 6. Common Commands Use your AI assistant to: - Parse requirements: `Can you parse my PRD at scripts/prd.txt?` - Plan next step: `What's the next task I should work on?` - Implement a task: `Can you help me implement task 3?` - View multiple tasks: `Can you show me tasks 1, 3, and 5?` - Expand a task: `Can you help me expand task 4?` - **Research fresh information**: `Research the latest best practices for implementing JWT authentication with Node.js` - **Research with context**: `Research React Query v5 migration strategies for our current API implementation in src/api.js` [More examples on how to use Task Master in chat](docs/examples.md) ### Option 2: Using Command Line #### Installation ```bash # Install globally npm install -g task-master-ai # OR install locally within your project npm install task-master-ai ``` #### Initialize a new project ```bash # If installed globally task-master init # If installed locally npx task-master init # Initialize project with specific rules task-master init --rules cursor,windsurf,vscode ``` This will prompt you for project details and set up a new project with the necessary files and structure. #### Common Commands ```bash # Initialize a new project task-master init # Parse a PRD and generate tasks task-master parse-prd your-prd.txt # List all tasks task-master list # Show the next task to work on task-master next # Show specific task(s) - supports comma-separated IDs task-master show 1,3,5 # Research fresh information with project context task-master research "What are the latest best practices for JWT authentication?" # Move tasks between tags (cross-tag movement) task-master move --from=5 --from-tag=backlog --to-tag=in-progress task-master move --from=5,6,7 --from-tag=backlog --to-tag=done --with-dependencies task-master move --from=5 --from-tag=backlog --to-tag=in-progress --ignore-dependencies # Add rules after initialization task-master rules add windsurf,roo,vscode ``` ## Tool Loading Configuration ### Optimizing MCP Tool Loading Task Master's MCP server supports selective tool loading to reduce context window usage. By default, all 36 tools are loaded (~21,000 tokens) to maintain backward compatibility with existing installations. You can optimize performance by configuring the `TASK_MASTER_TOOLS` environment variable: ### Available Modes | Mode | Tools | Context Usage | Use Case | |------|-------|--------------|----------| | `all` (default) | 36 | ~21,000 tokens | Complete feature set - all tools available | | `standard` | 15 | ~10,000 tokens | Common task management operations | | `core` (or `lean`) | 7 | ~5,000 tokens | Essential daily development workflow | | `custom` | Variable | Variable | Comma-separated list of specific tools | ### Configuration Methods #### Method 1: Environment Variable in MCP Configuration Add `TASK_MASTER_TOOLS` to your MCP configuration file's `env` section: ```jsonc { "mcpServers": { // or "servers" for VS Code "task-master-ai": { "command": "npx", "args": ["-y", "task-master-ai"], "env": { "TASK_MASTER_TOOLS": "standard", // Options: "all", "standard", "core", "lean", or comma-separated list "ANTHROPIC_API_KEY": "your-key-here", // ... other API keys } } } } ``` #### Method 2: Claude Code CLI (One-Time Setup) For Claude Code users, you can set the mode during installation: ```bash # Core mode example (~70% token reduction) claude mcp add task-master-ai --scope user \ --env TASK_MASTER_TOOLS="core" \ -- npx -y task-master-ai@latest # Custom tools example claude mcp add task-master-ai --scope user \ --env TASK_MASTER_TOOLS="get_tasks,next_task,set_task_status" \ -- npx -y task-master-ai@latest ``` ### Tool Sets Details **Core Tools (7):** `get_tasks`, `next_task`, `get_task`, `set_task_status`, `update_subtask`, `parse_prd`, `expand_task` - src/ai-providers/anthropic.js (1917 bytes)
/** * src/ai-providers/anthropic.js * * Implementation for interacting with Anthropic models (e.g., Claude) * using the Vercel AI SDK. */ import { createAnthropic } from '@ai-sdk/anthropic'; import { BaseAIProvider } from './base-provider.js'; // TODO: Implement standardized functions for generateText, streamText, generateObject // --- Client Instantiation --- // Note: API key resolution should ideally happen closer to the call site // using the config manager/resolver which checks process.env and session.env. // This is a placeholder for basic functionality. // Remove the global variable and caching logic // let anthropicClient; export class AnthropicAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'Anthropic'; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the Anthropic API key */ getRequiredApiKeyName() { return 'ANTHROPIC_API_KEY'; } /** * Creates and returns an Anthropic client instance. * @param {object} params - Parameters for client initialization * @param {string} params.apiKey - Anthropic API key * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} Anthropic client function * @throws {Error} If initialization fails */ getClient(params) { try { const { apiKey, baseURL } = params; const fetchImpl = this.createProxyFetch(); return createAnthropic({ apiKey, ...(baseURL && { baseURL }), headers: { 'anthropic-beta': 'output-128k-2025-02-19' }, ...(fetchImpl && { fetch: fetchImpl }) }); } catch (error) { this.handleError('client initialization', error); } } } // TODO: Implement streamAnthropicObject if needed and supported well by the SDK for Anthropic. // The basic structure would be similar to generateAnthropicObject but using streamObject. - src/ai-providers/azure.js (2705 bytes)
/** * azure.js * AI provider implementation for Azure OpenAI Service using Vercel AI SDK. */ import { createAzure } from '@ai-sdk/azure'; import { BaseAIProvider } from './base-provider.js'; export class AzureProvider extends BaseAIProvider { constructor() { super(); this.name = 'Azure OpenAI'; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the Azure OpenAI API key */ getRequiredApiKeyName() { return 'AZURE_OPENAI_API_KEY'; } /** * Validates Azure-specific authentication parameters * @param {object} params - Parameters to validate * @throws {Error} If required parameters are missing */ validateAuth(params) { if (!params.apiKey) { throw new Error('Azure API key is required'); } if (!params.baseURL) { throw new Error( 'Azure endpoint URL is required. Set it in .taskmasterconfig global.azureBaseURL or models.[role].baseURL' ); } } /** * Normalizes the base URL to ensure it ends with /openai for proper Azure API routing. * The Azure API expects paths like /openai/deployments/{model}/chat/completions * @param {string} baseURL - Original base URL * @returns {string} Normalized base URL ending with /openai */ normalizeBaseURL(baseURL) { if (!baseURL) return baseURL; try { const url = new URL(baseURL); let pathname = url.pathname.replace(/\/+$/, ''); // Remove trailing slashes // If the path doesn't end with /openai, append it if (!pathname.endsWith('/openai')) { pathname = `${pathname}/openai`; } url.pathname = pathname; return url.toString(); } catch { // Fallback for invalid URLs const normalized = baseURL.replace(/\/+$/, ''); return normalized.endsWith('/openai') ? normalized : `${normalized}/openai`; } } /** * Creates and returns an Azure OpenAI client instance. * @param {object} params - Parameters for client initialization * @param {string} params.apiKey - Azure OpenAI API key * @param {string} params.baseURL - Azure OpenAI endpoint URL (from .taskmasterconfig global.azureBaseURL or models.[role].baseURL) * @returns {Function} Azure OpenAI client function * @throws {Error} If client initialization fails */ getClient(params) { try { const { apiKey, baseURL } = params; // Normalize base URL to ensure it ends with /openai const normalizedBaseURL = this.normalizeBaseURL(baseURL); const fetchImpl = this.createProxyFetch(); return createAzure({ apiKey, baseURL: normalizedBaseURL, ...(fetchImpl && { fetch: fetchImpl }) }); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/base-provider.js (16459 bytes)
import * as ai from 'ai'; import { jsonrepair } from 'jsonrepair'; import { EnvHttpProxyAgent } from 'undici'; import { isProxyEnabled } from '../../scripts/modules/config-manager.js'; import { findProjectRoot, log } from '../../scripts/modules/utils.js'; import { getAITelemetryConfig, hashProjectRoot } from '../telemetry/sentry.js'; const { JSONParseError, NoObjectGeneratedError, generateObject, generateText, streamObject, streamText, zodSchema } = ai; const jsonSchemaHelper = ai.jsonSchema; const INTEGER_CONSTRAINT_KEYS = new Set([ 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum' ]); const SCHEMA_OBJECT_KEYS = [ 'additionalProperties', 'contains', 'if', 'then', 'else', 'not', 'propertyNames' ]; const SCHEMA_ARRAY_KEYS = ['allOf', 'anyOf', 'oneOf', 'prefixItems']; const SCHEMA_RECORD_KEYS = [ 'definitions', '$defs', 'dependentSchemas', 'patternProperties', 'properties' ]; const isIntegerType = (type) => { if (!type) { return false; } if (Array.isArray(type)) { return type.includes('integer'); } return type === 'integer'; }; const sanitizeIntegerConstraints = (schema) => { if (!schema || typeof schema !== 'object') { return schema; } if (Array.isArray(schema)) { return schema.map(sanitizeIntegerConstraints); } const next = { ...schema }; if (isIntegerType(next.type)) { for (const key of INTEGER_CONSTRAINT_KEYS) { if (key in next) { delete next[key]; } } } for (const key of SCHEMA_OBJECT_KEYS) { if (next[key]) { next[key] = sanitizeIntegerConstraints(next[key]); } } for (const key of SCHEMA_ARRAY_KEYS) { if (Array.isArray(next[key])) { next[key] = next[key].map(sanitizeIntegerConstraints); } } for (const key of SCHEMA_RECORD_KEYS) { if (next[key] && typeof next[key] === 'object') { const mapped = {}; for (const [entryKey, entryValue] of Object.entries(next[key])) { mapped[entryKey] = sanitizeIntegerConstraints(entryValue); } next[key] = mapped; } } if (next.items) { next.items = sanitizeIntegerConstraints(next.items); } return next; }; const buildSafeSchema = (schema) => { const baseSchema = zodSchema(schema); if (!baseSchema || typeof baseSchema !== 'object') { return baseSchema; } if (!baseSchema.jsonSchema) { return baseSchema; } const sanitizedSchema = sanitizeIntegerConstraints(baseSchema.jsonSchema); if (typeof jsonSchemaHelper === 'function') { return jsonSchemaHelper(sanitizedSchema, { validate: baseSchema.validate }); } return { ...baseSchema, jsonSchema: sanitizedSchema }; }; /** * Base class for all AI providers */ export class BaseAIProvider { constructor() { if (this.constructor === BaseAIProvider) { throw new Error('BaseAIProvider cannot be instantiated directly'); } // Each provider must set their name this.name = this.constructor.name; // Cache proxy agent to avoid creating multiple instances this._proxyAgent = null; /** * Whether this provider needs explicit schema in JSON mode * Can be overridden by subclasses * @type {boolean} */ this.needsExplicitJsonSchema = false; /** * Whether this provider supports temperature parameter * Can be overridden by subclasses * @type {boolean} */ this.supportsTemperature = true; } /** * Validates authentication parameters - can be overridden by providers * @param {object} params - Parameters to validate */ validateAuth(params) { // Default: require API key (most providers need this) if (!params.apiKey) { throw new Error(`${this.name} API key is required`); } } /** * Creates a custom fetch function with proxy support. * Only enables proxy when TASKMASTER_ENABLE_PROXY environment variable is set to 'true' * or enableProxy is set to true in config.json. * Automatically reads http_proxy/https_proxy environment variables when enabled. * @returns {Function} Custom fetch function with proxy support, or undefined if proxy is disabled */ createProxyFetch() { // Cache project root to avoid repeated lookups if (!this._projectRoot) { this._projectRoot = findProjectRoot(); } const projectRoot = this._projectRoot; if (!isProxyEnabled(null, projectRoot)) { // Return undefined to use default fetch without proxy return undefined; } // Proxy is enabled, create and return proxy fetch if (!this._proxyAgent) { this._proxyAgent = new EnvHttpProxyAgent(); } return (url, options = {}) => { return fetch(url, { ...options, dispatcher: this._proxyAgent }); }; } /** * Validates common parameters across all methods * @param {object} params - Parameters to validate */ validateParams(params) { // Validate authentication (can be overridden by providers) this.validateAuth(params); // Validate required model ID if (!params.modelId) { throw new Error(`${this.name} Model ID is required`); } // Validate optional parameters this.validateOptionalParams(params); } /** * Validates optional parameters like temperature and maxTokens * @param {object} params - Parameters to validate */ validateOptionalParams(params) { if ( params.temperature !== undefined && (params.temperature < 0 || params.temperature > 1) ) { throw new Error('Temperature must be between 0 and 1'); } if (params.maxTokens !== undefined) { const maxTokens = Number(params.maxTokens); if (!Number.isFinite(maxTokens) || maxTokens <= 0) { throw new Error('maxTokens must be a finite number greater than 0'); } } } /** * Validates message array structure */ validateMessages(messages) { if (!messages || !Array.isArray(messages) || messages.length === 0) { throw new Error('Invalid or empty messages array provided'); } for (const msg of messages) { if (!msg.role || !msg.content) { throw new Error( 'Invalid message format. Each message must have role and content' ); } } } /** * Common error handler */ handleError(operation, error) { const errorMessage = error.message || 'Unknown error occurred'; log('error', `${this.name} ${operation} failed: ${errorMessage}`, { error }); throw new Error( `${this.name} API error during ${operation}: ${errorMessage}` ); } /** * Creates and returns a client instance for the provider * @abstract */ getClient(params) { throw new Error('getClient must be implemented by provider'); } /** * Returns if the API key is required * @abstract * @returns {boolean} if the API key is required, defaults to true */ isRequiredApiKey() { return true; } /** * Returns the required API key environment variable name * @abstract * @returns {string|null} The environment variable name, or null if no API key is required */ getRequiredApiKeyName() { throw new Error('getRequiredApiKeyName must be implemented by provider'); } /** * Prepares token limit parameter based on model requirements * @param {string} modelId - The model ID * @param {number} maxTokens - The maximum tokens value * @returns {object} Object with either maxTokens or max_completion_tokens */ prepareTokenParam(modelId, maxTokens) { if (maxTokens === undefined) { return {}; } // Ensure maxTokens is an integer const tokenValue = Math.floor(Number(maxTokens)); return { maxOutputTokens: tokenValue }; } /** * Generates text using the provider's model */ async generateText(params) { try { this.validateParams(params); this.validateMessages(params.messages); log( 'debug', `Generating ${this.name} text with model: ${params.modelId}` ); const client = await this.getClient(params); // Get Sentry telemetry config with function ID and metadata for better tracing // Format: provider.model.command.method const commandName = params.commandName || 'unknown'; const functionId = `${this.name}.${params.modelId}.${commandName}.generateText`; // Build telemetry metadata for enhanced filtering/grouping in Sentry const metadata = { command: commandName, outputType: params.outputType, tag: params.tag, projectHash: hashProjectRoot(params.projectRoot), userId: params.userId, // Hamster user ID if authenticated briefId: params.briefId // Hamster brief ID if connected }; const telemetryConfig = getAITelemetryConfig(functionId, metadata); const result = await generateText({ model: client(params.modelId), messages: params.messages, ...this.prepareTokenParam(params.modelId, params.maxTokens), ...(this.supportsTemperature && params.temperature !== undefined ? { temperature: params.temperature } : {}), ...(telemetryConfig && { experimental_telemetry: telemetryConfig }) }); log( 'debug', `${this.name} generateText completed successfully for model: ${params.modelId}` ); const inputTokens = result.usage?.inputTokens ?? result.usage?.promptTokens ?? 0; const outputTokens = result.usage?.outputTokens ?? result.usage?.completionTokens ?? 0; const totalTokens = result.usage?.totalTokens ?? inputTokens + outputTokens; return { text: result.text, usage: { inputTokens, outputTokens, totalTokens } }; } catch (error) { this.handleError('text generation', error); } } /** * Streams text using the provider's model */ async streamText(params) { try { this.validateParams(params); this.validateMessages(params.messages); log('debug', `Streaming ${this.name} text with model: ${params.modelId}`); const client = await this.getClient(params); // Get Sentry telemetry config with function ID and metadata for better tracing // Format: provider.model.command.method const commandName = params.commandName || 'unknown'; const functionId = `${this.name}.${params.modelId}.${commandName}.streamText`; // Build telemetry metadata for enhanced filtering/grouping in Sentry const metadata = { command: commandName, outputType: params.outputType, tag: params.tag, projectHash: hashProjectRoot(params.projectRoot), userId: params.userId, // Hamster user ID if authenticated briefId: params.briefId // Hamster brief ID if connected }; const telemetryConfig = getAITelemetryConfig(functionId, metadata); const stream = await streamText({ model: client(params.modelId), messages: params.messages, ...this.prepareTokenParam(params.modelId, params.maxTokens), ...(this.supportsTemperature && params.temperature !== undefined ? { temperature: params.temperature } : {}), ...(telemetryConfig && { experimental_telemetry: telemetryConfig }), ...(params.experimental_transform && { experimental_transform: params.experimental_transform }) }); log( 'debug', `${this.name} streamText initiated successfully for model: ${params.modelId}` ); return stream; } catch (error) { this.handleError('text streaming', error); } } /** * Streams a structured object using the provider's model */ async streamObject(params) { try { this.validateParams(params); this.validateMessages(params.messages); if (!params.schema) { throw new Error('Schema is required for object streaming'); } log( 'debug', `Streaming ${this.name} object with model: ${params.modelId}` ); const client = await this.getClient(params); // Get Sentry telemetry config with function ID and metadata for better tracing // Format: provider.model.command.method const commandName = params.commandName || 'unknown'; const functionId = `${this.name}.${params.modelId}.${commandName}.streamObject`; // Build telemetry metadata for enhanced filtering/grouping in Sentry const metadata = { command: commandName, outputType: params.outputType, tag: params.tag, projectHash: hashProjectRoot(params.projectRoot), userId: params.userId, // Hamster user ID if authenticated briefId: params.briefId // Hamster brief ID if connected }; const telemetryConfig = getAITelemetryConfig(functionId, metadata); const schema = buildSafeSchema(params.schema); const result = await streamObject({ model: client(params.modelId), messages: params.messages, schema, mode: params.mode || 'auto', maxOutputTokens: params.maxTokens, ...(this.supportsTemperature && params.temperature !== undefined ? { temperature: params.temperature } : {}), ...(telemetryConfig && { experimental_telemetry: telemetryConfig }) }); log( 'debug', `${this.name} streamObject initiated successfully for model: ${params.modelId}` ); // Return the stream result directly // The stream result contains partialObjectStream and other properties return result; } catch (error) { this.handleError('object streaming', error); } } /** * Generates a structured object using the provider's model */ async generateObject(params) { try { this.validateParams(params); this.validateMessages(params.messages); if (!params.schema) { throw new Error('Schema is required for object generation'); } if (!params.objectName) { throw new Error('Object name is required for object generation'); } log( 'debug', `Generating ${this.name} object ('${params.objectName}') with model: ${params.modelId}` ); const client = await this.getClient(params); // Get Sentry telemetry config with function ID and metadata for better tracing // Format: provider.model.command.method.objectName const commandName = params.commandName || 'unknown'; const functionId = `${this.name}.${params.modelId}.${commandName}.generateObject.${params.objectName}`; // Build telemetry metadata for enhanced filtering/grouping in Sentry const metadata = { command: commandName, outputType: params.outputType, tag: params.tag, projectHash: hashProjectRoot(params.projectRoot), userId: params.userId, // Hamster user ID if authenticated briefId: params.briefId // Hamster brief ID if connected }; const telemetryConfig = getAITelemetryConfig(functionId, metadata); const schema = buildSafeSchema(params.schema); const result = await generateObject({ model: client(params.modelId), messages: params.messages, schema, mode: this.needsExplicitJsonSchema ? 'json' : 'auto', schemaName: params.objectName, schemaDescription: `Generate a valid JSON object for ${params.objectName}`, maxTokens: params.maxTokens, ...(this.supportsTemperature && params.temperature !== undefined ? { temperature: params.temperature } : {}), ...(telemetryConfig && { experimental_telemetry: telemetryConfig }) }); log( 'debug', `${this.name} generateObject completed successfully for model: ${params.modelId}` ); const inputTokens = result.usage?.inputTokens ?? result.usage?.promptTokens ?? 0; const outputTokens = result.usage?.outp - src/ai-providers/bedrock.js (1312 bytes)
import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock'; import { fromNodeProviderChain } from '@aws-sdk/credential-providers'; import { BaseAIProvider } from './base-provider.js'; export class BedrockAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'Bedrock'; } isRequiredApiKey() { return false; } /** * Returns the required API key environment variable name for Bedrock. * Bedrock uses AWS credentials, so we return the AWS access key identifier. * @returns {string} The environment variable name */ getRequiredApiKeyName() { return 'AWS_ACCESS_KEY_ID'; } /** * Override auth validation - Bedrock uses AWS credentials instead of API keys * @param {object} params - Parameters to validate */ validateAuth(params) {} /** * Creates and returns a Bedrock client instance. * See https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html * for AWS SDK environment variables and configuration options. */ getClient(params) { try { const credentialProvider = fromNodeProviderChain(); const fetchImpl = this.createProxyFetch(); return createAmazonBedrock({ credentialProvider, ...(fetchImpl && { fetch: fetchImpl }) }); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/claude-code.js (5363 bytes)
/** * src/ai-providers/claude-code.js * * Claude Code provider implementation using the ai-sdk-provider-claude-code package. * This provider uses the local Claude Agent SDK (via Claude Code CLI) with OAuth token authentication. * * Authentication: * - Uses CLAUDE_CODE_OAUTH_TOKEN managed by Claude Code CLI * - Token is set up via: claude setup-token * - No manual API key configuration required * */ import { execSync } from 'child_process'; import { createClaudeCode } from 'ai-sdk-provider-claude-code'; import { getClaudeCodeSettingsForCommand, getSupportedModelsForProvider } from '../../scripts/modules/config-manager.js'; import { log } from '../../scripts/modules/utils.js'; import { BaseAIProvider } from './base-provider.js'; let _claudeCliChecked = false; let _claudeCliAvailable = null; /** * Provider for Claude Code CLI integration via AI SDK * * Features: * - No API key required (uses local Claude Code CLI) * - Supported models loaded from supported-models.json * - Command-specific configuration support */ export class ClaudeCodeProvider extends BaseAIProvider { constructor() { super(); this.name = 'Claude Code'; // Load supported models from supported-models.json this.supportedModels = getSupportedModelsForProvider('claude-code'); // Validate that models were loaded successfully if (this.supportedModels.length === 0) { log( 'warn', 'No supported models found for claude-code provider. Check supported-models.json configuration.' ); } // Claude Code requires explicit JSON schema mode this.needsExplicitJsonSchema = true; // Claude Code does not support temperature parameter this.supportsTemperature = false; } /** * @returns {string} The environment variable name for API key (not used) */ getRequiredApiKeyName() { return 'CLAUDE_CODE_API_KEY'; } /** * @returns {boolean} False - Claude Code doesn't require API keys */ isRequiredApiKey() { return false; } /** * Optional CLI availability check for Claude Code * @param {object} params - Parameters (ignored) */ validateAuth(params) { // Claude Code uses local CLI - perform lightweight availability check // This is optional validation that fails fast with actionable guidance if ( process.env.NODE_ENV !== 'test' && !_claudeCliChecked && !process.env.CLAUDE_CODE_OAUTH_TOKEN ) { try { execSync('claude --version', { stdio: 'pipe', timeout: 1000 }); _claudeCliAvailable = true; } catch (error) { _claudeCliAvailable = false; log( 'warn', 'Claude Code CLI not detected. Install it with: npm install -g @anthropic-ai/claude-code' ); } finally { _claudeCliChecked = true; } } } /** * Creates a Claude Code client instance * @param {object} params - Client parameters * @param {string} [params.commandName] - Command name for settings lookup * @returns {Function} Claude Code provider function * @throws {Error} If Claude Code CLI is not available or client creation fails */ getClient(params = {}) { try { const settings = getClaudeCodeSettingsForCommand(params.commandName) || {}; // Environment variable isolation to prevent API key conflicts // The ai-sdk-provider-claude-code SDK automatically picks up ANTHROPIC_API_KEY, // which can cause conflicts if that key is intended for the Anthropic provider. const originalAnthropicKey = process.env.ANTHROPIC_API_KEY; const claudeCodeKey = process.env.CLAUDE_CODE_API_KEY; try { // If CLAUDE_CODE_API_KEY is set, use it exclusively if (claudeCodeKey) { process.env.ANTHROPIC_API_KEY = claudeCodeKey; } else if (originalAnthropicKey) { // If only ANTHROPIC_API_KEY exists, temporarily unset it to force OAuth mode delete process.env.ANTHROPIC_API_KEY; } return createClaudeCode({ defaultSettings: { // Restore previous default behavior from pre-2.0 versions // These must be inside defaultSettings to be applied by the provider systemPrompt: { type: 'preset', preset: 'claude_code' }, // Enable loading of CLAUDE.md and settings.json files settingSources: ['user', 'project', 'local'], ...settings } }); } finally { // Restore original environment state if (originalAnthropicKey) { process.env.ANTHROPIC_API_KEY = originalAnthropicKey; } else { delete process.env.ANTHROPIC_API_KEY; } } } catch (error) { // Provide more helpful error message const msg = String(error?.message || ''); const code = error?.code; if (code === 'ENOENT' || /claude/i.test(msg)) { const enhancedError = new Error( `Claude Code CLI not available. Please install Claude Code CLI first. Original error: ${error.message}` ); enhancedError.cause = error; this.handleError('Claude Code CLI initialization', enhancedError); } else { this.handleError('client initialization', error); } } } /** * @returns {string[]} List of supported model IDs */ getSupportedModels() { return this.supportedModels; } /** * Check if a model is supported * @param {string} modelId - Model ID to check * @returns {boolean} True if supported */ isModelSupported(modelId) { if (!modelId) return false; return this.supportedModels.includes(String(modelId).toLowerCase()); } } - src/ai-providers/codex-cli.js (6453 bytes)
/** * src/ai-providers/codex-cli.js * * Codex CLI provider implementation using the ai-sdk-provider-codex-cli package. * This provider uses the local OpenAI Codex CLI with OAuth (preferred) or * an optional OPENAI_CODEX_API_KEY if provided. */ import { execSync } from 'child_process'; import { createCodexCli } from 'ai-sdk-provider-codex-cli'; import { getCodexCliSettingsForCommand, getSupportedModelsForProvider } from '../../scripts/modules/config-manager.js'; import { log } from '../../scripts/modules/utils.js'; import { BaseAIProvider } from './base-provider.js'; /** * OpenAI model reasoning effort support. * Different models support different reasoning effort levels. * This is provider-specific logic that belongs here, not in the general model catalog. * * See: https://platform.openai.com/docs/guides/reasoning */ const REASONING_EFFORT_SUPPORT = { // GPT-5.1 base does not support xhigh 'gpt-5.1': ['none', 'low', 'medium', 'high'], // GPT-5.1 Codex Max supports full range 'gpt-5.1-codex-max': ['none', 'low', 'medium', 'high', 'xhigh'], // GPT-5.2 supports full range 'gpt-5.2': ['none', 'low', 'medium', 'high', 'xhigh'], // GPT-5.2 Pro only supports medium and above 'gpt-5.2-pro': ['medium', 'high', 'xhigh'], // GPT-5 supports full range 'gpt-5': ['none', 'low', 'medium', 'high', 'xhigh'] }; // Default for models not explicitly listed const DEFAULT_REASONING_EFFORTS = ['none', 'low', 'medium', 'high']; // Ordering for effort levels (lowest to highest) const EFFORT_ORDER = ['none', 'low', 'medium', 'high', 'xhigh']; export class CodexCliProvider extends BaseAIProvider { constructor() { super(); this.name = 'Codex CLI'; // Codex CLI has native schema support, no explicit JSON schema mode required this.needsExplicitJsonSchema = false; // Codex CLI does not support temperature parameter this.supportsTemperature = false; // Load supported models from supported-models.json this.supportedModels = getSupportedModelsForProvider('codex-cli'); // Validate that models were loaded successfully if (this.supportedModels.length === 0) { log( 'warn', 'No supported models found for codex-cli provider. Check supported-models.json configuration.' ); } // CLI availability check cache this._codexCliChecked = false; this._codexCliAvailable = null; } /** * Codex CLI does not require an API key when using OAuth via `codex login`. * @returns {boolean} */ isRequiredApiKey() { return false; } /** * Returns the environment variable name used when an API key is provided. * Even though the API key is optional for Codex CLI (OAuth-first), * downstream resolution expects a non-throwing implementation. * Uses OPENAI_CODEX_API_KEY to avoid conflicts with OpenAI provider. * @returns {string} */ getRequiredApiKeyName() { return 'OPENAI_CODEX_API_KEY'; } /** * Optional CLI availability check; provide helpful guidance if missing. */ validateAuth() { if (process.env.NODE_ENV === 'test') return; if (!this._codexCliChecked) { try { execSync('codex --version', { stdio: 'pipe', timeout: 1000 }); this._codexCliAvailable = true; } catch (error) { this._codexCliAvailable = false; log( 'warn', 'Codex CLI not detected. Install with: npm i -g @openai/codex or enable fallback with allowNpx.' ); } finally { this._codexCliChecked = true; } } } /** * Gets a validated reasoningEffort for the model. * If no effort is specified, returns the model's highest supported effort. * If an unsupported effort is specified, caps it to the highest supported. * @param {string} modelId - The model ID to check * @param {string} [requestedEffort] - The requested reasoning effort (optional) * @returns {string} The validated reasoning effort */ _getValidatedReasoningEffort(modelId, requestedEffort) { // Get supported efforts for this model, or use defaults const supportedEfforts = REASONING_EFFORT_SUPPORT[modelId] || DEFAULT_REASONING_EFFORTS; // Get the highest supported effort for this model const highestSupported = supportedEfforts.reduce((highest, effort) => { const currentIndex = EFFORT_ORDER.indexOf(effort); const highestIndex = EFFORT_ORDER.indexOf(highest); return currentIndex > highestIndex ? effort : highest; }, supportedEfforts[0]); // If no effort requested, use the model's highest supported if (!requestedEffort) { log( 'debug', `No reasoning effort specified for ${modelId}. Using '${highestSupported}'.` ); return highestSupported; } // If the requested effort is supported, use it if (supportedEfforts.includes(requestedEffort)) { return requestedEffort; } // Cap to the highest supported effort log( 'warn', `Reasoning effort '${requestedEffort}' not supported by ${modelId}. Using '${highestSupported}' instead.` ); return highestSupported; } /** * Creates a Codex CLI client instance * @param {object} params * @param {string} [params.commandName] - Command name for settings lookup * @param {string} [params.modelId] - Model ID for capability validation * @param {string} [params.apiKey] - Optional API key (injected as OPENAI_API_KEY for Codex CLI) * @returns {Function} */ getClient(params = {}) { try { // Merge global + command-specific settings from config const settings = getCodexCliSettingsForCommand(params.commandName) || {}; // Get validated reasoningEffort - always pass to override Codex CLI global config const validatedReasoningEffort = this._getValidatedReasoningEffort( params.modelId, settings.reasoningEffort ); // Inject API key only if explicitly provided; OAuth is the primary path const defaultSettings = { ...settings, reasoningEffort: validatedReasoningEffort, ...(params.apiKey ? { env: { ...(settings.env || {}), OPENAI_API_KEY: params.apiKey } } : {}) }; return createCodexCli({ defaultSettings }); } catch (error) { const msg = String(error?.message || ''); const code = error?.code; if (code === 'ENOENT' || /codex/i.test(msg)) { const enhancedError = new Error( `Codex CLI not available. Please install Codex CLI first. Original error: ${error.message}` ); enhancedError.cause = error; this.handleError('Codex CLI initialization', enhancedError); } else { this.handleError('client initialization', error); } } } } - src/ai-providers/gemini-cli.js (3001 bytes)
/** * src/ai-providers/gemini-cli.js * * Implementation for interacting with Gemini models via Gemini CLI * using the ai-sdk-provider-gemini-cli package. * * As of v1.4.0, the SDK provides native structured output support via: * - supportsStructuredOutputs = true * - defaultObjectGenerationMode = 'json' * - responseJsonSchema passed directly to Gemini API * * This eliminates the need for JSON extraction workarounds. * System messages are automatically handled by the SDK's mapPromptToGeminiFormat * which extracts them to Gemini's systemInstruction field. */ import { createGeminiProvider } from 'ai-sdk-provider-gemini-cli'; import { BaseAIProvider } from './base-provider.js'; export class GeminiCliProvider extends BaseAIProvider { constructor() { super(); this.name = 'Gemini CLI'; // Gemini CLI does not support temperature parameter this.supportsTemperature = false; } /** * Override validateAuth to handle Gemini CLI authentication options. * Gemini CLI is designed to use pre-configured OAuth authentication. * Users choose gemini-cli specifically to leverage their existing * gemini auth login credentials, not to use API keys. * @param {object} params - Parameters to validate */ validateAuth(params) { // No validation needed - the SDK will handle auth internally // via OAuth (primary) or API key (optional fallback) } /** * Creates and returns a Gemini CLI client instance. * @param {object} params - Parameters for client initialization * @param {string} [params.apiKey] - Optional Gemini API key (rarely used with gemini-cli) * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Promise<Function>} Gemini CLI client function * @throws {Error} If initialization fails */ async getClient(params) { try { // Primary use case: Use existing gemini CLI authentication via OAuth // Secondary use case: Direct API key (for compatibility) let authOptions = {}; if (params.apiKey && params.apiKey !== 'gemini-cli-no-key-required') { // API key provided - use it for compatibility authOptions = { authType: 'api-key', apiKey: params.apiKey }; } else { // Expected case: Use gemini CLI authentication via OAuth authOptions = { authType: 'oauth-personal' }; } // Add baseURL if provided (for custom endpoints) if (params.baseURL) { authOptions.baseURL = params.baseURL; } // Create and return the provider return createGeminiProvider(authOptions); } catch (error) { this.handleError('client initialization', error); } } /** * Returns the name of the API key environment variable. * @returns {string} API key environment variable name */ getRequiredApiKeyName() { return 'GEMINI_API_KEY'; } /** * Indicates whether an API key is required. * Gemini CLI primarily uses OAuth, so API key is optional. * @returns {boolean} False - API key is not required */ isRequiredApiKey() { return false; } } - src/ai-providers/google-vertex.js (5762 bytes)
/** * google-vertex.js * AI provider implementation for Google Vertex AI models using Vercel AI SDK. */ import { createVertex } from '@ai-sdk/google-vertex'; import { resolveEnvVariable } from '../../scripts/modules/utils.js'; import { log } from '../../scripts/modules/utils.js'; import { BaseAIProvider } from './base-provider.js'; // Vertex-specific error classes class VertexAuthError extends Error { constructor(message) { super(message); this.name = 'VertexAuthError'; this.code = 'vertex_auth_error'; } } class VertexConfigError extends Error { constructor(message) { super(message); this.name = 'VertexConfigError'; this.code = 'vertex_config_error'; } } class VertexApiError extends Error { constructor(message, statusCode) { super(message); this.name = 'VertexApiError'; this.code = 'vertex_api_error'; this.statusCode = statusCode; } } export class VertexAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'Google Vertex AI'; } /** * Returns the required API key environment variable name for Google Vertex AI. * @returns {string} The environment variable name */ getRequiredApiKeyName() { return 'GOOGLE_API_KEY'; } /** * API key is optional, Service Account credentials can be used instead. * @returns {boolean} */ isRequiredApiKey() { return false; } /** * API key or Service Account is mandatory. * @returns {boolean} */ isAuthenticationRequired() { return true; } /** * Validates that a credential value is present and non-empty. * @private * @param {string|object|null|undefined} value * @returns {boolean} */ isValidCredential(value) { if (!value) return false; if (typeof value === 'string') { return value.trim().length > 0; } return typeof value === 'object'; } /** * Validates Vertex AI-specific authentication parameters * @param {object} params - Parameters to validate * @throws {VertexAuthError|VertexConfigError} */ validateAuth(params) { const { apiKey, projectId, location, credentials } = params; // Check for API key OR service account credentials const hasValidApiKey = this.isValidCredential(apiKey); const hasValidCredentials = this.isValidCredential(credentials); if (!hasValidApiKey && !hasValidCredentials) { throw new VertexAuthError( 'Vertex AI requires authentication. Provide one of the following:\n' + ' β’ GOOGLE_API_KEY environment variable (typical for API-based auth), OR\n' + ' β’ GOOGLE_APPLICATION_CREDENTIALS pointing to a service account JSON file (recommended for production)' ); } // Project ID is required for Vertex AI if ( !projectId || (typeof projectId === 'string' && projectId.trim().length === 0) ) { throw new VertexConfigError( 'Google Cloud project ID is required for Vertex AI. Set VERTEX_PROJECT_ID environment variable.' ); } // Location is required for Vertex AI if ( !location || (typeof location === 'string' && location.trim().length === 0) ) { throw new VertexConfigError( 'Google Cloud location is required for Vertex AI. Set VERTEX_LOCATION environment variable (e.g., "us-central1").' ); } } /** * Creates and returns a Google Vertex AI client instance. * @param {object} params - Parameters for client initialization * @param {string} [params.apiKey] - Google API key * @param {string} params.projectId - Google Cloud project ID * @param {string} params.location - Google Cloud location (e.g., "us-central1") * @param {object} [params.credentials] - Service account credentials object * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} Google Vertex AI client function * @throws {Error} If required parameters are missing or initialization fails */ getClient(params) { try { const { apiKey, projectId, location, credentials, baseURL } = params; const fetchImpl = this.createProxyFetch(); // Configure auth options - either API key or service account const authOptions = {}; if (apiKey) { // Vercel AI SDK expects googleAuthOptions even when using apiKey for some configurations authOptions.googleAuthOptions = { ...credentials, apiKey }; } else if (credentials) { authOptions.googleAuthOptions = credentials; } // Return Vertex AI client return createVertex({ ...authOptions, project: projectId, location, ...(baseURL && { baseURL }), ...(fetchImpl && { fetch: fetchImpl }) }); } catch (error) { this.handleError('client initialization', error); } } /** * Handle errors from Vertex AI * @param {string} operation - Description of the operation that failed * @param {Error} error - The error object * @throws {Error} Rethrows the error with additional context */ handleError(operation, error) { log('error', `Vertex AI ${operation} error:`, error); // Handle known error types if ( error.name === 'VertexAuthError' || error.name === 'VertexConfigError' || error.name === 'VertexApiError' ) { throw error; } // Handle network/API errors if (error.response) { const statusCode = error.response.status; const errorMessage = error.response.data?.error?.message || error.message; // Categorize by status code if (statusCode === 401 || statusCode === 403) { throw new VertexAuthError(`Authentication failed: ${errorMessage}`); } else if (statusCode === 400) { throw new VertexConfigError(`Invalid request: ${errorMessage}`); } else { throw new VertexApiError( `API error (${statusCode}): ${errorMessage}`, statusCode ); } } // Generic error handling throw new Error(`Vertex AI ${operation} failed: ${error.message}`); } } - src/ai-providers/google.js (1212 bytes)
/** * google.js * AI provider implementation for Google AI models using Vercel AI SDK. */ import { createGoogleGenerativeAI } from '@ai-sdk/google'; import { BaseAIProvider } from './base-provider.js'; export class GoogleAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'Google'; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the Google API key */ getRequiredApiKeyName() { return 'GOOGLE_API_KEY'; } /** * Creates and returns a Google AI client instance. * @param {object} params - Parameters for client initialization * @param {string} params.apiKey - Google API key * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} Google AI client function * @throws {Error} If initialization fails */ getClient(params) { try { const { apiKey, baseURL } = params; const fetchImpl = this.createProxyFetch(); return createGoogleGenerativeAI({ apiKey, ...(baseURL && { baseURL }), ...(fetchImpl && { fetch: fetchImpl }) }); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/grok-cli.js (2690 bytes)
/** * grok-cli.js * AI provider implementation for Grok models using Grok CLI. */ import { createGrokCli } from '@tm/ai-sdk-provider-grok-cli'; import { getGrokCliSettingsForCommand } from '../../scripts/modules/config-manager.js'; import { BaseAIProvider } from './base-provider.js'; export class GrokCliProvider extends BaseAIProvider { constructor() { super(); this.name = 'Grok CLI'; // Grok CLI requires explicit JSON schema mode this.needsExplicitJsonSchema = true; // Grok CLI does not support temperature parameter this.supportsTemperature = false; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the Grok API key */ getRequiredApiKeyName() { return 'GROK_CLI_API_KEY'; } /** * Override to indicate that API key is optional since Grok CLI can be configured separately * @returns {boolean} False since Grok CLI can use its own config */ isRequiredApiKey() { return false; // Grok CLI can use its own config file } /** * Override validateAuth to be more flexible with API key validation * @param {object} params - Parameters to validate */ validateAuth(params) { // Grok CLI can work with: // 1. API key passed in params // 2. Environment variable GROK_CLI_API_KEY // 3. Grok CLI's own config file (~/.grok/user-settings.json) // So we don't enforce API key requirement here // Suppress unused parameter warning void params; } /** * Creates and returns a Grok CLI client instance. * @param {object} params - Parameters for client initialization * @param {string} [params.apiKey] - Grok CLI API key (optional if configured in CLI) * @param {string} [params.baseURL] - Optional custom API endpoint * @param {string} [params.workingDirectory] - Working directory for CLI commands * @param {number} [params.timeout] - Timeout for CLI commands in milliseconds * @param {string} [params.commandName] - Name of the command invoking the service * @returns {Function} Grok CLI client function * @throws {Error} If initialization fails */ getClient(params) { try { const { apiKey, baseURL, workingDirectory, timeout, commandName } = params; // Get Grok CLI settings from config const grokCliSettings = getGrokCliSettingsForCommand(commandName); return createGrokCli({ defaultSettings: { apiKey, baseURL, workingDirectory: workingDirectory || grokCliSettings.workingDirectory, timeout: timeout || grokCliSettings.timeout, defaultModel: grokCliSettings.defaultModel } }); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/groq.js (1117 bytes)
/** * src/ai-providers/groq.js * * Implementation for interacting with Groq models * using the Vercel AI SDK. */ import { createGroq } from '@ai-sdk/groq'; import { BaseAIProvider } from './base-provider.js'; export class GroqProvider extends BaseAIProvider { constructor() { super(); this.name = 'Groq'; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the Groq API key */ getRequiredApiKeyName() { return 'GROQ_API_KEY'; } /** * Creates and returns a Groq client instance. * @param {object} params - Parameters for client initialization * @param {string} params.apiKey - Groq API key * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} Groq client function * @throws {Error} If API key is missing or initialization fails */ getClient(params) { try { const { apiKey, baseURL } = params; return createGroq({ apiKey, ...(baseURL && { baseURL }) }); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/index.js (1047 bytes)
/** * src/ai-providers/index.js * Central export point for all AI provider classes */ export { AnthropicAIProvider } from './anthropic.js'; export { PerplexityAIProvider } from './perplexity.js'; export { GoogleAIProvider } from './google.js'; export { OpenAIProvider } from './openai.js'; export { XAIProvider } from './xai.js'; export { GroqProvider } from './groq.js'; export { OpenRouterAIProvider } from './openrouter.js'; export { OllamaAIProvider } from './ollama.js'; export { BedrockAIProvider } from './bedrock.js'; export { AzureProvider } from './azure.js'; export { VertexAIProvider } from './google-vertex.js'; export { ClaudeCodeProvider } from './claude-code.js'; export { GeminiCliProvider } from './gemini-cli.js'; export { GrokCliProvider } from './grok-cli.js'; export { CodexCliProvider } from './codex-cli.js'; export { OpenAICompatibleProvider } from './openai-compatible.js'; export { ZAIProvider } from './zai.js'; export { ZAICodingProvider } from './zai-coding.js'; export { LMStudioProvider } from './lmstudio.js'; - src/ai-providers/lmstudio.js (1353 bytes)
/** * lmstudio.js * AI provider implementation for LM Studio local models. * * LM Studio is a desktop application for running local LLMs. * It provides an OpenAI-compatible API server that runs locally. * Default server: http://localhost:1234/v1 * * Usage: * 1. Start LM Studio application * 2. Load a model (e.g., llama-3.2-1b, mistral-7b) * 3. Go to "Local Server" tab and click "Start Server" * 4. Use the model ID from LM Studio in your config * * Note: LM Studio only supports `json_schema` mode for structured outputs, * not `json_object` mode. We disable native structured outputs to force * the AI SDK to use alternative strategies (like tool calling) which work * reliably across all LM Studio models. */ import { OpenAICompatibleProvider } from './openai-compatible.js'; /** * LM Studio provider for local model inference. * Does not require an API key as it runs locally. */ export class LMStudioProvider extends OpenAICompatibleProvider { constructor() { super({ name: 'LM Studio', apiKeyEnvVar: 'LMSTUDIO_API_KEY', requiresApiKey: false, // Local server, no API key needed defaultBaseURL: 'http://localhost:1234/v1', supportsStructuredOutputs: true // LM Studio only supports json_schema mode, not json_object mode // Disable native structured outputs to use alternative strategies }); } } - src/ai-providers/ollama.js (1338 bytes)
/** * ollama.js * AI provider implementation for Ollama models using the ollama-ai-provider-v2 package. */ import { createOllama } from 'ollama-ai-provider-v2'; import { BaseAIProvider } from './base-provider.js'; export class OllamaAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'Ollama'; } /** * Override auth validation - Ollama doesn't require API keys * @param {object} params - Parameters to validate */ validateAuth(_params) { // Ollama runs locally and doesn't require API keys // No authentication validation needed } /** * Creates and returns an Ollama client instance. * @param {object} params - Parameters for client initialization * @param {string} [params.baseURL] - Optional Ollama base URL (defaults to http://localhost:11434) * @returns {Function} Ollama client function * @throws {Error} If initialization fails */ getClient(params) { try { const { baseURL } = params; return createOllama({ ...(baseURL && { baseURL }) }); } catch (error) { this.handleError('client initialization', error); } } isRequiredApiKey() { return false; } /** * Returns the required API key environment variable name for Ollama. * @returns {string} The environment variable name */ getRequiredApiKeyName() { return 'OLLAMA_API_KEY'; } } - src/ai-providers/openai-compatible.js (4137 bytes)
/** * openai-compatible.js * Generic base class for OpenAI-compatible API providers. * This allows any provider with an OpenAI-compatible API to be easily integrated. */ import { createOpenAICompatible } from '@ai-sdk/openai-compatible'; import { BaseAIProvider } from './base-provider.js'; /** * Base class for OpenAI-compatible providers (LM Studio, Z.ai, etc.) * Provides a flexible foundation for any service with OpenAI-compatible endpoints. */ export class OpenAICompatibleProvider extends BaseAIProvider { /** * @param {object} config - Provider configuration * @param {string} config.name - Provider display name * @param {string} config.apiKeyEnvVar - Environment variable name for API key * @param {boolean} [config.requiresApiKey=true] - Whether API key is required * @param {string} [config.defaultBaseURL] - Default base URL for the API * @param {Function} [config.getBaseURL] - Function to determine base URL from params * @param {boolean} [config.supportsStructuredOutputs] - Whether provider supports structured outputs */ constructor(config) { super(); if (!config.name) { throw new Error('Provider name is required'); } if (!config.apiKeyEnvVar) { throw new Error('API key environment variable name is required'); } this.name = config.name; this.apiKeyEnvVar = config.apiKeyEnvVar; this.requiresApiKey = config.requiresApiKey !== false; // Default to true this.defaultBaseURL = config.defaultBaseURL; this.getBaseURLFromParams = config.getBaseURL; this.supportsStructuredOutputs = config.supportsStructuredOutputs; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the API key */ getRequiredApiKeyName() { return this.apiKeyEnvVar; } /** * Returns whether this provider requires an API key. * @returns {boolean} True if API key is required */ isRequiredApiKey() { return this.requiresApiKey; } /** * Override auth validation based on requiresApiKey setting * @param {object} params - Parameters to validate */ validateAuth(params) { if (this.requiresApiKey && !params.apiKey) { throw new Error(`${this.name} API key is required`); } } /** * Determines the base URL to use for the API. * @param {object} params - Client parameters * @returns {string|undefined} The base URL to use */ getBaseURL(params) { // If custom baseURL provided in params, use it if (params.baseURL) { return params.baseURL; } // If provider has a custom getBaseURL function, use it if (this.getBaseURLFromParams) { return this.getBaseURLFromParams(params); } // Otherwise use default baseURL if available return this.defaultBaseURL; } /** * Creates and returns an OpenAI-compatible client instance. * @param {object} params - Parameters for client initialization * @param {string} [params.apiKey] - API key (required if requiresApiKey is true) * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} OpenAI-compatible client function * @throws {Error} If required parameters are missing or initialization fails */ getClient(params) { try { const { apiKey } = params; const fetchImpl = this.createProxyFetch(); const baseURL = this.getBaseURL(params); const clientConfig = { // Provider name for SDK (required, used for logging/debugging) name: this.name.toLowerCase().replace(/[^a-z0-9]/g, '-') }; // Only include apiKey if provider requires it if (this.requiresApiKey && apiKey) { clientConfig.apiKey = apiKey; } // Include baseURL if available if (baseURL) { clientConfig.baseURL = baseURL; } // Configure structured outputs support if specified if (this.supportsStructuredOutputs !== undefined) { clientConfig.supportsStructuredOutputs = this.supportsStructuredOutputs; } // Add proxy support if available if (fetchImpl) { clientConfig.fetch = fetchImpl; } return createOpenAICompatible(clientConfig); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/openai.js (1178 bytes)
/** * openai.js * AI provider implementation for OpenAI models using Vercel AI SDK. */ import { createOpenAI } from '@ai-sdk/openai'; import { BaseAIProvider } from './base-provider.js'; export class OpenAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'OpenAI'; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the OpenAI API key */ getRequiredApiKeyName() { return 'OPENAI_API_KEY'; } /** * Creates and returns an OpenAI client instance. * @param {object} params - Parameters for client initialization * @param {string} params.apiKey - OpenAI API key * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} OpenAI client function * @throws {Error} If initialization fails */ getClient(params) { try { const { apiKey, baseURL } = params; const fetchImpl = this.createProxyFetch(); return createOpenAI({ apiKey, ...(baseURL && { baseURL }), ...(fetchImpl && { fetch: fetchImpl }) }); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/openrouter.js (1169 bytes)
/** * openrouter.js * AI provider implementation for OpenRouter models using Vercel AI SDK. */ import { createOpenRouter } from '@openrouter/ai-sdk-provider'; import { BaseAIProvider } from './base-provider.js'; export class OpenRouterAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'OpenRouter'; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the OpenRouter API key */ getRequiredApiKeyName() { return 'OPENROUTER_API_KEY'; } /** * Creates and returns an OpenRouter client instance. * @param {object} params - Parameters for client initialization * @param {string} params.apiKey - OpenRouter API key * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} OpenRouter client function * @throws {Error} If API key is missing or initialization fails */ getClient(params) { try { const { apiKey, baseURL } = params; return createOpenRouter({ apiKey, ...(baseURL && { baseURL }) }); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/perplexity.js (1799 bytes)
/** * perplexity.js * AI provider implementation for Perplexity models using Vercel AI SDK. */ import { createPerplexity } from '@ai-sdk/perplexity'; import { BaseAIProvider } from './base-provider.js'; export class PerplexityAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'Perplexity'; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the Perplexity API key */ getRequiredApiKeyName() { return 'PERPLEXITY_API_KEY'; } /** * Creates and returns a Perplexity client instance. * @param {object} params - Parameters for client initialization * @param {string} params.apiKey - Perplexity API key * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} Perplexity client function * @throws {Error} If initialization fails */ getClient(params) { try { const { apiKey, baseURL } = params; const fetchImpl = this.createProxyFetch(); return createPerplexity({ apiKey, baseURL: baseURL || 'https://api.perplexity.ai', ...(fetchImpl && { fetch: fetchImpl }) }); } catch (error) { this.handleError('client initialization', error); } } /** * Override generateObject to use JSON mode for Perplexity * * NOTE: Perplexity models (especially sonar models) have known issues * generating valid JSON, particularly with array fields. They often * generate malformed JSON like "dependencies": , instead of "dependencies": [] * * The base provider now handles JSON repair automatically for all providers. */ async generateObject(params) { // Force JSON mode for Perplexity as it may help with reliability return super.generateObject({ ...params, mode: 'json' }); } } - src/ai-providers/xai.js (1088 bytes)
/** * xai.js * AI provider implementation for xAI models using Vercel AI SDK. */ import { createXai } from '@ai-sdk/xai'; import { BaseAIProvider } from './base-provider.js'; export class XAIProvider extends BaseAIProvider { constructor() { super(); this.name = 'xAI'; } /** * Returns the environment variable name required for this provider's API key. * @returns {string} The environment variable name for the xAI API key */ getRequiredApiKeyName() { return 'XAI_API_KEY'; } /** * Creates and returns an xAI client instance. * @param {object} params - Parameters for client initialization * @param {string} params.apiKey - xAI API key * @param {string} [params.baseURL] - Optional custom API endpoint * @returns {Function} xAI client function * @throws {Error} If API key is missing or initialization fails */ getClient(params) { try { const { apiKey, baseURL } = params; return createXai({ apiKey, baseURL: baseURL || 'https://api.x.ai/v1' }); } catch (error) { this.handleError('client initialization', error); } } } - src/ai-providers/zai-coding.js (582 bytes)
/** * zai-coding.js * AI provider implementation for Z.ai (GLM) Coding Plan models. * Uses the exclusive coding API endpoint with OpenAI-compatible API. */ import { ZAIProvider } from './zai.js'; /** * Z.ai Coding Plan provider supporting GLM models through the dedicated coding endpoint. * Extends ZAIProvider with only a different base URL. */ export class ZAICodingProvider extends ZAIProvider { constructor() { super(); // Override only the name and base URL this.name = 'Z.ai (Coding Plan)'; this.defaultBaseURL = 'https://api.z.ai/api/coding/paas/v4/'; } } - src/ai-providers/zai.js (3288 bytes)
/** * zai.js * AI provider implementation for Z.ai (GLM) models. * Uses the OpenAI-compatible API endpoint. */ import { OpenAICompatibleProvider } from './openai-compatible.js'; /** * Z.ai provider supporting GLM models through OpenAI-compatible API. */ export class ZAIProvider extends OpenAICompatibleProvider { constructor() { super({ name: 'Z.ai', apiKeyEnvVar: 'ZAI_API_KEY', requiresApiKey: true, defaultBaseURL: 'https://api.z.ai/api/paas/v4/', supportsStructuredOutputs: true }); } /** * Override token parameter preparation for ZAI * ZAI API doesn't support max_tokens parameter * @returns {object} Empty object for ZAI (doesn't support maxOutputTokens) */ prepareTokenParam() { // ZAI API rejects max_tokens parameter with error code 1210 return {}; } /** * Introspects a Zod schema to find the property that expects an array * @param {import('zod').ZodType} schema - The Zod schema to introspect * @returns {string|null} The property name that expects an array, or null if not found */ findArrayPropertyInSchema(schema) { try { // Get the def object from Zod v4 API const def = schema._zod.def; // Check if schema is a ZodObject const isObject = def?.type === 'object' || def?.typeName === 'ZodObject'; if (!isObject) { return null; } // Get the shape - it can be a function, property, or getter let shape = def.shape; if (typeof shape === 'function') { shape = shape(); } if (!shape || typeof shape !== 'object') { return null; } // Find the first property that is an array for (const [key, value] of Object.entries(shape)) { // Get the def object for the property using Zod v4 API const valueDef = value._zod.def; // Check if the property is a ZodArray const isArray = valueDef?.type === 'array' || valueDef?.typeName === 'ZodArray'; if (isArray) { return key; } } return null; } catch (error) { // If introspection fails, log and return null console.warn('Failed to introspect Zod schema:', error.message); return null; } } /** * Override generateObject to normalize GLM's response format * GLM sometimes returns bare arrays instead of objects with properties, * even when the schema has multiple properties. * @param {object} params - Parameters for object generation * @returns {Promise<object>} Normalized response */ async generateObject(params) { const result = await super.generateObject(params); // If result.object is an array, wrap it based on schema introspection if (Array.isArray(result.object)) { // Try to find the array property from the schema const wrapperKey = this.findArrayPropertyInSchema(params.schema); if (wrapperKey) { return { ...result, object: { [wrapperKey]: result.object } }; } // Fallback: if we can't introspect the schema, use the object name // This handles edge cases where schema introspection might fail console.warn( `GLM returned a bare array for '${params.objectName}' but could not determine wrapper property from schema. Using objectName as fallback.` ); return { ...result, object: { [params.objectName]: result.object } }; } return result; } } - src/constants/commands.js (315 bytes)
/** * Command related constants * Defines which commands trigger AI processing */ // Command names that trigger AI processing export const AI_COMMAND_NAMES = [ 'add-task', 'analyze-complexity', 'expand-task', 'parse-prd', 'research', 'research-save', 'update-subtask', 'update-task', 'update-tasks' ];
- src/constants/paths.js (2026 bytes)
/** * Path constants for Task Master application */ // .taskmaster directory structure paths export const TASKMASTER_DIR = '.taskmaster'; export const TASKMASTER_TASKS_DIR = '.taskmaster/tasks'; export const TASKMASTER_DOCS_DIR = '.taskmaster/docs'; export const TASKMASTER_REPORTS_DIR = '.taskmaster/reports'; export const TASKMASTER_TEMPLATES_DIR = '.taskmaster/templates'; // Task Master configuration files export const TASKMASTER_CONFIG_FILE = '.taskmaster/config.json'; export const TASKMASTER_STATE_FILE = '.taskmaster/state.json'; export const LEGACY_CONFIG_FILE = '.taskmasterconfig'; // Task Master report files export const COMPLEXITY_REPORT_FILE = '.taskmaster/reports/task-complexity-report.json'; export const LEGACY_COMPLEXITY_REPORT_FILE = 'scripts/task-complexity-report.json'; // Task Master PRD file paths export const PRD_FILE = '.taskmaster/docs/prd.txt'; export const LEGACY_PRD_FILE = 'scripts/prd.txt'; // Task Master template files export const EXAMPLE_PRD_FILE = '.taskmaster/templates/example_prd.txt'; export const LEGACY_EXAMPLE_PRD_FILE = 'scripts/example_prd.txt'; // Task Master task file paths export const TASKMASTER_TASKS_FILE = '.taskmaster/tasks/tasks.json'; export const LEGACY_TASKS_FILE = 'tasks/tasks.json'; // General project files (not Task Master specific but commonly used) export const ENV_EXAMPLE_FILE = '.env.example'; export const GITIGNORE_FILE = '.gitignore'; // Task file naming pattern export const TASK_FILE_PREFIX = 'task_'; export const TASK_FILE_EXTENSION = '.txt'; /** * Project markers used to identify a task-master project root * These files/directories indicate that a directory is a Task Master project */ export const PROJECT_MARKERS = [ '.taskmaster', // New taskmaster directory LEGACY_CONFIG_FILE, // .taskmasterconfig 'tasks.json', // Generic tasks file LEGACY_TASKS_FILE, // tasks/tasks.json (legacy location) TASKMASTER_TASKS_FILE, // .taskmaster/tasks/tasks.json (new location) '.git', // Git repository '.svn' // SVN repository ];
- src/constants/profiles.js (1877 bytes)
/** * @typedef {'amp' | 'claude' | 'cline' | 'codex' | 'cursor' | 'gemini' | 'kiro' | 'opencode' | 'kilo' | 'roo' | 'trae' | 'windsurf' | 'vscode' | 'zed'} RulesProfile */ /** * Available rule profiles for project initialization and rules command * * β οΈ SINGLE SOURCE OF TRUTH: This is the authoritative list of all supported rule profiles. * This constant is used directly throughout the codebase (previously aliased as PROFILE_NAMES). * * @type {RulesProfile[]} * @description Defines possible rule profile sets: * - amp: Amp Code integration * - claude: Claude Code integration * - cline: Cline IDE rules * - codex: Codex integration * - cursor: Cursor IDE rules * - gemini: Gemini integration * - kiro: Kiro IDE rules * - opencode: OpenCode integration * - kilo: Kilo Code integration * - roo: Roo Code IDE rules * - trae: Trae IDE rules * - vscode: VS Code with GitHub Copilot integration * - windsurf: Windsurf IDE rules * - zed: Zed IDE rules * * To add a new rule profile: * 1. Add the profile name to this array * 2. Create a profile file in src/profiles/{profile}.js * 3. Export it as {profile}Profile in src/profiles/index.js */ export const RULE_PROFILES = [ 'amp', 'claude', 'cline', 'codex', 'cursor', 'gemini', 'kiro', 'opencode', 'kilo', 'roo', 'trae', 'vscode', 'windsurf', 'zed' ]; /** * Centralized enum for all supported Roo agent modes * @type {string[]} * @description Available Roo Code IDE modes for rule generation */ export const ROO_MODES = [ 'architect', 'ask', 'orchestrator', 'code', 'debug', 'test' ]; /** * Check if a given rule profile is valid * @param {string} rulesProfile - The rule profile to check * @returns {boolean} True if the rule profile is valid, false otherwise */ export function isValidRulesProfile(rulesProfile) { return RULE_PROFILES.includes(rulesProfile); } - src/constants/rules-actions.js (539 bytes)
/** * @typedef {'add' | 'remove'} RulesAction */ /** * Individual rules action constants */ export const RULES_ACTIONS = { ADD: 'add', REMOVE: 'remove' }; /** * Special rules command (not a CRUD operation) */ export const RULES_SETUP_ACTION = 'setup'; /** * Check if a given action is a valid rules action * @param {string} action - The action to check * @returns {boolean} True if the action is valid, false otherwise */ export function isValidRulesAction(action) { return Object.values(RULES_ACTIONS).includes(action); } - src/constants/task-priority.js (1152 bytes)
/** * @typedef {'high' | 'medium' | 'low'} TaskPriority */ /** * Task priority options * @type {TaskPriority[]} * @description Defines possible task priorities: * - high: Critical tasks that need immediate attention * - medium: Standard priority tasks (default) * - low: Tasks that can be deferred or are nice-to-have */ export const TASK_PRIORITY_OPTIONS = ['high', 'medium', 'low']; /** * Default task priority * @type {TaskPriority} */ export const DEFAULT_TASK_PRIORITY = 'medium'; /** * Check if a given priority is valid * @param {string} priority - The priority to check * @returns {boolean} True if the priority is valid, false otherwise */ export function isValidTaskPriority(priority) { return TASK_PRIORITY_OPTIONS.includes(priority?.toLowerCase()); } /** * Normalize a priority value to lowercase * @param {string} priority - The priority to normalize * @returns {TaskPriority|null} The normalized priority or null if invalid */ export function normalizeTaskPriority(priority) { if (!priority) return null; const normalized = priority.toLowerCase(); return isValidTaskPriority(normalized) ? normalized : null; } - src/constants/task-status.js (840 bytes)
/** * @typedef {'pending' | 'done' | 'in-progress' | 'review' | 'deferred' | 'cancelled'} TaskStatus */ /** * Task status options list * @type {TaskStatus[]} * @description Defines possible task statuses: * - pending: Task waiting to start * - done: Task completed * - in-progress: Task in progress * - review: Task completed and waiting for review * - deferred: Task postponed or paused * - cancelled: Task cancelled and will not be completed */ export const TASK_STATUS_OPTIONS = [ 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled' ]; /** * Check if a given status is a valid task status * @param {string} status - The status to check * @returns {boolean} True if the status is valid, false otherwise */ export function isValidTaskStatus(status) { return TASK_STATUS_OPTIONS.includes(status); } - test-clean-tags.js (1775 bytes)
import fs from 'fs'; import { createTag, listTags } from './scripts/modules/task-manager/tag-management.js'; console.log('=== Testing Tag Management with Clean File ==='); // Create a clean test tasks.json file const testTasksPath = './test-tasks.json'; const cleanData = { master: { tasks: [ { id: 1, title: 'Test Task 1', status: 'pending' }, { id: 2, title: 'Test Task 2', status: 'done' } ], metadata: { created: new Date().toISOString(), description: 'Master tag' } } }; // Write clean test file fs.writeFileSync(testTasksPath, JSON.stringify(cleanData, null, 2)); console.log('Created clean test file'); try { // Test creating a new tag console.log('\n--- Testing createTag ---'); await createTag( testTasksPath, 'test-branch', { copyFromCurrent: true, description: 'Test branch' }, { projectRoot: process.cwd() }, 'json' ); // Read the file and check for corruption const resultData = JSON.parse(fs.readFileSync(testTasksPath, 'utf8')); console.log('Keys in result file:', Object.keys(resultData)); console.log('Has _rawTaggedData in file:', !!resultData._rawTaggedData); if (resultData._rawTaggedData) { console.log('β CORRUPTION DETECTED: _rawTaggedData found in file!'); } else { console.log('β SUCCESS: No _rawTaggedData corruption in file'); } // Test listing tags console.log('\n--- Testing listTags ---'); const tagList = await listTags( testTasksPath, {}, { projectRoot: process.cwd() }, 'json' ); console.log( 'Found tags:', tagList.tags.map((t) => t.name) ); } catch (error) { console.error('Error during test:', error.message); } finally { // Clean up test file if (fs.existsSync(testTasksPath)) { fs.unlinkSync(testTasksPath); console.log('\nCleaned up test file'); } } - test-config-manager.js (1619 bytes)
// test-config-manager.js console.log('=== ENVIRONMENT TEST ==='); console.log('Working directory:', process.cwd()); console.log('NODE_PATH:', process.env.NODE_PATH); // Test basic imports try { console.log('Importing config-manager'); // Use dynamic import for ESM const configManagerModule = await import( './scripts/modules/config-manager.js' ); const configManager = configManagerModule.default || configManagerModule; console.log('Config manager loaded successfully'); console.log('Loading supported models'); // Add after line 14 (after "Config manager loaded successfully") console.log('Config manager exports:', Object.keys(configManager)); } catch (error) { console.error('Import error:', error.message); console.error(error.stack); } // Test file access try { console.log('Checking for .taskmasterconfig'); // Use dynamic import for ESM const { readFileSync, existsSync } = await import('fs'); const { resolve } = await import('path'); const configExists = existsSync('./.taskmasterconfig'); console.log('.taskmasterconfig exists:', configExists); if (configExists) { const config = JSON.parse(readFileSync('./.taskmasterconfig', 'utf-8')); console.log('Config keys:', Object.keys(config)); } console.log('Checking for supported-models.json'); const modelsPath = resolve('./scripts/modules/supported-models.json'); console.log('Models path:', modelsPath); const modelsExists = existsSync(modelsPath); console.log('supported-models.json exists:', modelsExists); } catch (error) { console.error('File access error:', error.message); } console.log('=== TEST COMPLETE ==='); - test-prd.txt (266 bytes)
# Test PRD ## Project Overview This is a simple test project to verify parse-prd functionality. ## Features - Feature A: Basic setup - Feature B: Core functionality - Feature C: Testing ## Requirements - Use Node.js - Include basic tests - Simple CLI interface
- test-tag-functions.js (0 bytes)
- test-version-check-full.js (2663 bytes)
import fs from 'fs'; import path from 'path'; import { checkForUpdate, compareVersions, displayUpgradeNotification } from './scripts/modules/commands.js'; // Force our current version for testing process.env.FORCE_VERSION = '0.9.30'; // Create a mock package.json in memory for testing const mockPackageJson = { name: 'task-master-ai', version: '0.9.30' }; // Modified version of checkForUpdate that doesn't use HTTP for testing async function testCheckForUpdate(simulatedLatestVersion) { // Get current version - use our forced version const currentVersion = process.env.FORCE_VERSION || '0.9.30'; console.log(`Using simulated current version: ${currentVersion}`); console.log(`Using simulated latest version: ${simulatedLatestVersion}`); // Compare versions const needsUpdate = compareVersions(currentVersion, simulatedLatestVersion) < 0; return { currentVersion, latestVersion: simulatedLatestVersion, needsUpdate }; } // Test with current version older than latest (should show update notice) async function runTest() { console.log('=== Testing version check scenarios ===\n'); // Scenario 1: Update available console.log( '\n--- Scenario 1: Update available (Current: 0.9.30, Latest: 1.0.0) ---' ); const updateInfo1 = await testCheckForUpdate('1.0.0'); console.log('Update check results:'); console.log(`- Current version: ${updateInfo1.currentVersion}`); console.log(`- Latest version: ${updateInfo1.latestVersion}`); console.log(`- Update needed: ${updateInfo1.needsUpdate}`); if (updateInfo1.needsUpdate) { console.log('\nDisplaying upgrade notification:'); displayUpgradeNotification( updateInfo1.currentVersion, updateInfo1.latestVersion ); } // Scenario 2: No update needed (versions equal) console.log( '\n--- Scenario 2: No update needed (Current: 0.9.30, Latest: 0.9.30) ---' ); const updateInfo2 = await testCheckForUpdate('0.9.30'); console.log('Update check results:'); console.log(`- Current version: ${updateInfo2.currentVersion}`); console.log(`- Latest version: ${updateInfo2.latestVersion}`); console.log(`- Update needed: ${updateInfo2.needsUpdate}`); // Scenario 3: Development version (current newer than latest) console.log( '\n--- Scenario 3: Development version (Current: 0.9.30, Latest: 0.9.0) ---' ); const updateInfo3 = await testCheckForUpdate('0.9.0'); console.log('Update check results:'); console.log(`- Current version: ${updateInfo3.currentVersion}`); console.log(`- Latest version: ${updateInfo3.latestVersion}`); console.log(`- Update needed: ${updateInfo3.needsUpdate}`); console.log('\n=== Test complete ==='); } // Run all tests runTest(); - test-version-check.js (1189 bytes)
import { compareVersions, displayUpgradeNotification } from './scripts/modules/commands.js'; // Simulate different version scenarios console.log('=== Simulating version check ===\n'); // 1. Current version is older than latest (should show update notice) console.log('Scenario 1: Current version older than latest'); displayUpgradeNotification('0.9.30', '1.0.0'); // 2. Current version same as latest (no update needed) console.log( '\nScenario 2: Current version same as latest (this would not normally show a notice)' ); console.log('Current: 1.0.0, Latest: 1.0.0'); console.log('compareVersions result:', compareVersions('1.0.0', '1.0.0')); console.log( 'Update needed:', compareVersions('1.0.0', '1.0.0') < 0 ? 'Yes' : 'No' ); // 3. Current version newer than latest (e.g., development version, would not show notice) console.log( '\nScenario 3: Current version newer than latest (this would not normally show a notice)' ); console.log('Current: 1.1.0, Latest: 1.0.0'); console.log('compareVersions result:', compareVersions('1.1.0', '1.0.0')); console.log( 'Update needed:', compareVersions('1.1.0', '1.0.0') < 0 ? 'Yes' : 'No' ); console.log('\n=== Test complete ==='); - tsconfig.json (1262 bytes)
{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "lib": ["ES2022"], "types": ["node"], "allowJs": true, "resolveJsonModule": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "noEmit": true, "baseUrl": ".", "paths": { "@tm/core": ["./packages/tm-core/src/index.ts"], "@tm/core/*": ["./packages/tm-core/src/*"], "@tm/cli": ["./apps/cli/src/index.ts"], "@tm/cli/*": ["./apps/cli/src/*"], "@tm/mcp": ["./apps/mcp/src/index.ts"], "@tm/mcp/*": ["./apps/mcp/src/*"], "@tm/build-config": ["./packages/build-config/src/index.ts"], "@tm/build-config/*": ["./packages/build-config/src/*"], "@tm/ai-sdk-provider-grok-cli": [ "./packages/ai-sdk-provider-grok-cli/src/index.ts" ], "@tm/ai-sdk-provider-grok-cli/*": [ "./packages/ai-sdk-provider-grok-cli/src/*" ], "@tm/bridge": ["./packages/tm-bridge/src/index.ts"], "@tm/bridge/*": ["./packages/tm-bridge/src/*"] } }, "tsx": { "tsconfig": { "allowImportingTsExtensions": false } }, "include": [ "bin/**/*", "scripts/**/*", "packages/*/src/**/*", "apps/*/src/**/*" ], "exclude": ["node_modules", "dist", "**/dist"] } - tsdown.config.ts (1288 bytes)
import { resolve } from 'path'; import { baseConfig, mergeConfig } from '@tm/build-config'; import { config } from 'dotenv'; import { defineConfig } from 'tsdown'; // Load .env file explicitly with absolute path config({ path: resolve(process.cwd(), '.env') }); // Get all TM_PUBLIC_* env variables for build-time injection const getBuildTimeEnvs = () => { const envs: Record<string, string> = {}; // Inject package.json version at build time try { const packageJson = JSON.parse( require('fs').readFileSync('package.json', 'utf8') ); envs['TM_PUBLIC_VERSION'] = packageJson.version || 'unknown'; } catch (error) { console.warn('Could not read package.json version during build:', error); envs['TM_PUBLIC_VERSION'] = 'unknown'; } for (const [key, value] of Object.entries(process.env)) { if (key.startsWith('TM_PUBLIC_')) { envs[key] = value || ''; } } return envs; }; export default defineConfig( mergeConfig(baseConfig, { entry: { 'task-master': 'scripts/dev.js', 'mcp-server': 'mcp-server/server.js' }, outDir: 'dist', copy: ['assets'], ignoreWatch: ['node_modules', 'dist', 'tests', 'apps/extension'], // Bundle only our workspace packages, keep npm dependencies external noExternal: [/^@tm\//], env: getBuildTimeEnvs() }) ); - turbo.json (1609 bytes)
{ "$schema": "https://turbo.build/schema.json", "extends": ["//"], "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"], "outputLogs": "new-only", "env": ["NODE_ENV", "TM_PUBLIC_*"] }, "dev": { "cache": false, "persistent": true, "inputs": [ "$TURBO_DEFAULT$", "!{packages,apps}/**/dist/**", "!{packages,apps}/**/node_modules/**" ] }, "test:watch": { "cache": false, "persistent": true, "dependsOn": ["^build"] }, "lint": { "dependsOn": ["^build"], "inputs": [ "$TURBO_DEFAULT$", "!{packages,apps}/**/dist/**", "!{packages,apps}/**/node_modules/**" ], "outputLogs": "new-only" }, "typecheck": { "dependsOn": ["^build"], "inputs": [ "$TURBO_DEFAULT$", "!{packages,apps}/**/dist/**", "!{packages,apps}/**/node_modules/**" ], "outputLogs": "new-only" }, "test": { "dependsOn": ["^build"], "inputs": [ "$TURBO_DEFAULT$", "!{packages,apps}/**/dist/**", "!{packages,apps}/**/node_modules/**" ], "outputLogs": "new-only", "cache": false }, "test:unit": { "dependsOn": ["^build"], "inputs": [ "$TURBO_DEFAULT$", "!{packages,apps}/**/dist/**", "!{packages,apps}/**/node_modules/**" ], "outputLogs": "new-only", "cache": false }, "test:integration": { "dependsOn": ["^build"], "inputs": [ "$TURBO_DEFAULT$", "!{packages,apps}/**/dist/**", "!{packages,apps}/**/node_modules/**" ], "outputLogs": "new-only", "cache": false } }, "globalDependencies": ["turbo.json", "tsconfig.json", ".env*"] } - update-task-migration-plan.md (42232 bytes)
# Update Task Migration Plan ## Overview Migrate and unify `update-tasks.js` and `update-subtask-by-id.js` into a single `update-task` command that handles both task and subtask updates. This migration will move from the legacy `scripts/modules/task-manager/` structure to the new `apps/cli` and `packages/tm-core` architecture. ## Current State Analysis ### `update-tasks.js` - Bulk Task Updates **Purpose**: Update multiple tasks from a specified ID onwards **Input Format**: `--from=<id> --prompt="context"` **AI Service**: `generateObjectService` with structured schema ### `update-subtask-by-id.js` - Single Subtask Updates **Purpose**: Append timestamped information to a specific subtask **Input Format**: `--id=<parentId.subtaskId> --prompt="notes"` **AI Service**: `generateTextService` for freeform content ## Unified Command Design ### New Command: `update-task` ```bash # Update single task (replaces update-task) task-master update-task --id=3 --prompt="changes" # Update single subtask (replaces update-subtask) task-master update-task --id=3.2 --prompt="implementation notes" # Update multiple tasks from ID onwards (replaces update --from) task-master update-task --from=3 --prompt="changes" ``` ### Intelligent Behavior Detection The command should automatically determine behavior based on: 1. **ID format**: Contains `.` β subtask mode 2. **--from flag**: Present β bulk update mode 3. **Default**: Single task update mode --- ## Functionality Checklist ### Core Functionality #### Input Validation & Parsing - [ ] Validate `tasksPath` exists - [ ] Validate `id` parameter (task: integer, subtask: "parent.child" format) - [ ] Validate `fromId` parameter (integer, positive) - [ ] Validate `prompt` parameter (non-empty string) - [ ] Parse subtask ID format: split "parentId.subtaskId" and validate both parts - [ ] Determine project root (from context or `findProjectRoot()`) - [ ] Support both MCP and CLI modes (detect via `mcpLog` presence) - [ ] Handle `outputFormat` ('text' or 'json', auto-detect for MCP) #### Task Loading & Filtering - [ ] Load tasks from `tasks.json` using `readJSON(tasksPath, projectRoot, tag)` - [ ] Validate tasks data structure exists - [ ] **Bulk mode**: Filter tasks where `id >= fromId AND status !== 'done'` - [ ] **Single task mode**: Find specific task by ID - [ ] **Subtask mode**: Find parent task, validate subtasks array, find specific subtask - [ ] Handle "no tasks to update" scenario gracefully #### Context Gathering - [ ] Initialize `ContextGatherer` with projectRoot and tag - [ ] Flatten all tasks with subtasks using `flattenTasksWithSubtasks()` - [ ] Initialize `FuzzyTaskSearch` with appropriate command type: - `'update'` for bulk/single task mode - `'update-subtask'` for subtask mode - [ ] **Bulk/Single task**: Search with prompt, max 5 results, include self - [ ] **Subtask mode**: Search with combined query: `${parentTask.title} ${subtask.title} ${prompt}` - [ ] Merge task IDs to update with relevant context task IDs - [ ] Gather context in 'research' format - [ ] Handle context gathering errors gracefully (log warning, continue) #### Prompt Building - [ ] Initialize `PromptManager` via `getPromptManager()` - [ ] **Bulk/Single task mode**: Load 'update-tasks' prompt template with params: - `tasks` (array of tasks to update) - `updatePrompt` - `useResearch` - `projectContext` (gathered context) - `hasCodebaseAnalysis` (from config) - `projectRoot` - [ ] **Subtask mode**: Load 'update-subtask' prompt template with params: - `parentTask` (id, title) - `prevSubtask` (id, title, status) - if exists - `nextSubtask` (id, title, status) - if exists - `currentDetails` (existing subtask details or fallback) - `updatePrompt` - `useResearch` - `gatheredContext` - `hasCodebaseAnalysis` - `projectRoot` - [ ] **Subtask mode**: Support variant key ('research' or 'default') - [ ] Extract `systemPrompt` and `userPrompt` from prompt manager #### AI Service Integration - [ ] Determine service role: `useResearch ? 'research' : 'main'` - [ ] **Bulk/Single task mode**: Call `generateObjectService` with: - `role`, `session`, `projectRoot` - `systemPrompt`, `prompt` (userPrompt) - `schema: COMMAND_SCHEMAS['update-tasks']` - `objectName: 'tasks'` - `commandName: 'update-tasks'` - `outputType: isMCP ? 'mcp' : 'cli'` - [ ] **Subtask mode**: Call `generateTextService` with: - `prompt` (userPrompt), `systemPrompt` - `role`, `session`, `projectRoot` - `maxRetries: 2` - `commandName: 'update-subtask'` - `outputType: isMCP ? 'mcp' : 'cli'` - [ ] Handle empty/invalid AI responses - [ ] Capture `telemetryData` and `tagInfo` from response #### Data Updates & Persistence - [ ] **Bulk/Single task mode**: - Parse `aiServiceResponse.mainResult.tasks` array - Validate array structure - Create Map for efficient lookup - Merge updated tasks with existing, preserving subtasks field - Track actual update count - [ ] **Subtask mode**: - Extract text string from `aiServiceResponse.mainResult` - Generate ISO timestamp - Format as: `<info added on ${timestamp}>\n${content}\n</info added on ${timestamp}>` - Append to `subtask.details` (create if doesn't exist) - Store newly added snippet separately for display - If prompt < 100 chars: append `[Updated: ${date}]` to subtask.description - [ ] Write updated data using `writeJSON(tasksPath, data, projectRoot, tag)` - [ ] Optionally call `generateTaskFiles()` (currently commented out in both) #### CLI Display & UX - [ ] **Pre-update display** (CLI only, text mode): - Create table with columns: ID, Title, Status - Truncate titles appropriately (57 chars for tasks, 52 for subtasks) - Apply status colors via `getStatusWithColor()` - Show boxed header with update count/target - **Bulk mode**: Show info box about completed subtasks handling - Display table - [ ] **Loading indicators** (CLI only, text mode): - Start loading indicator before AI call - Message: "Updating tasks with AI..." (bulk/single) or "Updating subtask..." (subtask) - Support research variant message - Stop indicator when complete or on error - [ ] **Post-update display** (CLI only, text mode): - **Bulk/Single task**: Success message with update count - **Subtask mode**: Boxed success message with: - Subtask ID - Title - "Newly Added Snippet" section showing timestamped content - Display AI usage summary via `displayAiUsageSummary(telemetryData, 'cli')` #### Logging & Debugging - [ ] Use appropriate logger: `mcpLog` (MCP) or `consoleLog` (CLI) - [ ] Log info messages with proper format (MCP vs CLI differences) - [ ] Log start of operation with key parameters - [ ] Log task counts and AI response details - [ ] Log successful completion - [ ] **Debug mode** (when `getDebugFlag(session)` true): - Log subtask details before/after update - Log writeJSON calls - Log full error stack traces #### Error Handling - [ ] Catch and handle errors at multiple levels: - Context gathering errors (warn and continue) - AI service errors (stop and report) - General operation errors (report and exit/throw) - [ ] **CLI mode**: - Print colored error messages - Show helpful troubleshooting for common errors: - API key missing/invalid - Model overloaded - Task/subtask not found - Invalid ID format - Empty prompt - Empty AI response - Exit with code 1 - [ ] **MCP mode**: Re-throw errors for caller handling - [ ] Always stop loading indicators on error #### Return Values - [ ] **Success returns** (both modes): ```javascript { success: true, // bulk/single task only updatedTasks: [...], // bulk/single task only updatedSubtask: {...}, // subtask only telemetryData: {...}, tagInfo: {...} } ``` - [ ] **Failure returns**: - CLI: exits with code 1 - MCP: throws error - Subtask mode: returns `null` on error ### Special Features #### Completed Subtasks Handling (Bulk Mode) - [ ] Display informational box explaining: - Done/completed subtasks are preserved - New subtasks build upon completed work - Revisions create new subtasks instead of modifying done items - Maintains clear record of progress #### Subtask Context Awareness - [ ] Provide parent task context (id, title) to AI - [ ] Provide previous subtask context (if exists) to AI - [ ] Provide next subtask context (if exists) to AI - [ ] Include current subtask details in prompt #### Timestamp Tracking - [ ] Use ISO format timestamps for subtask updates - [ ] Wrap appended content in timestamped tags - [ ] Update description field with simple date stamp (short prompts only) --- ## Migration Architecture ### Object-Oriented Design Philosophy This migration will follow the established patterns in `tm-core` and `apps/cli`: - **Domain separation** with clear bounded contexts - **Dependency injection** for testability and flexibility - **Abstract base classes** for shared behavior - **Interfaces** for contracts and loose coupling - **Service layer** for business logic orchestration - **Factory pattern** for object creation - **Single Responsibility Principle** throughout ### Package Structure ``` packages/tm-core/ src/ commands/ update-task/ # Core Interfaces & Types types.ts # Shared types, enums, interfaces interfaces/ update-strategy.interface.ts # IUpdateStrategy contract update-context.interface.ts # IUpdateContext contract display.interface.ts # IDisplayManager contract # Services (Business Logic) update-task.service.ts # Main orchestrator service context-builder.service.ts # Builds AI context (uses ContextGatherer, FuzzySearch) prompt-builder.service.ts # Builds prompts (uses PromptManager) data-merger.service.ts # Merges AI results with existing data # Strategies (Update Mode Logic) strategies/ base-update.strategy.ts # Abstract base class for all strategies bulk-update.strategy.ts # Bulk task update implementation single-task-update.strategy.ts # Single task update implementation subtask-update.strategy.ts # Subtask update implementation # Utilities & Helpers validators/ update-input.validator.ts # Validates all input parameters task-id.validator.ts # Parses and validates task/subtask IDs display/ cli-display.manager.ts # CLI output formatting json-display.manager.ts # JSON output formatting update-display.factory.ts # Creates appropriate display manager factories/ update-strategy.factory.ts # Creates appropriate strategy based on mode # Main Entry Point index.ts # Public API export apps/cli/ src/ commands/ update-task.command.ts # CLI command definition (uses UpdateTaskService) ``` ### Core Classes & Their Responsibilities #### 1. **UpdateTaskService** (Main Orchestrator) ```typescript /** * Main service that coordinates the entire update process * Handles initialization, strategy selection, and result aggregation */ export class UpdateTaskService { constructor( private readonly configManager: ConfigManager, private readonly storage: IStorage, private readonly logger: Logger, private readonly strategyFactory: UpdateStrategyFactory, private readonly contextBuilder: ContextBuilderService, private readonly displayFactory: UpdateDisplayFactory ) {} async updateTask(options: UpdateTaskOptions): Promise<UpdateTaskResult> { // 1. Validate inputs // 2. Detect mode and create strategy // 3. Build context // 4. Execute strategy // 5. Display results // 6. Return result } } ``` **Uses (existing classes):** - `ConfigManager` - Project configuration - `IStorage` - Task persistence - `Logger` - Logging - `ContextGatherer` - Gather related context - `FuzzyTaskSearch` - Find relevant tasks - `PromptManager` - Load prompt templates **Uses (new classes):** - `UpdateStrategyFactory` - Create update strategy - `ContextBuilderService` - Build AI context - `UpdateDisplayFactory` - Create display manager --- #### 2. **IUpdateStrategy** (Strategy Interface) ```typescript /** * Contract for all update strategies * Defines the common interface for bulk, single, and subtask updates */ export interface IUpdateStrategy { /** * Validate that the strategy can handle the given context */ validate(context: IUpdateContext): Promise<void>; /** * Load and filter tasks that need updating */ loadTasks(context: IUpdateContext): Promise<TaskLoadResult>; /** * Build prompts for AI service */ buildPrompts( context: IUpdateContext, tasks: TaskLoadResult ): Promise<PromptResult>; /** * Call appropriate AI service */ callAIService( context: IUpdateContext, prompts: PromptResult ): Promise<AIServiceResult>; /** * Merge AI results with existing data */ mergeResults( context: IUpdateContext, aiResult: AIServiceResult, originalTasks: TaskLoadResult ): Promise<MergeResult>; /** * Get the mode this strategy handles */ getMode(): UpdateMode; } ``` --- #### 3. **BaseUpdateStrategy** (Abstract Base Class) ```typescript /** * Provides common functionality for all update strategies * Implements template method pattern for the update workflow */ export abstract class BaseUpdateStrategy implements IUpdateStrategy { protected readonly logger: Logger; constructor( protected readonly contextBuilder: ContextBuilderService, protected readonly promptBuilder: PromptBuilderService, protected readonly dataMerger: DataMergerService, protected readonly aiService: AIService // wrapper around generate[Object|Text]Service ) { this.logger = getLogger(`UpdateStrategy:${this.getMode()}`); } // Template method - defines the workflow async execute(context: IUpdateContext): Promise<UpdateStrategyResult> { await this.validate(context); const tasks = await this.loadTasks(context); const prompts = await this.buildPrompts(context, tasks); const aiResult = await this.callAIService(context, prompts); const merged = await this.mergeResults(context, aiResult, tasks); return merged; } // Subclasses must implement these abstract validate(context: IUpdateContext): Promise<void>; abstract loadTasks(context: IUpdateContext): Promise<TaskLoadResult>; abstract getMode(): UpdateMode; // Shared implementations with extensibility async buildPrompts( context: IUpdateContext, tasks: TaskLoadResult ): Promise<PromptResult> { // Delegates to PromptBuil - vitest.config.ts (1317 bytes)
import { defineConfig } from 'vitest/config'; /** * Root Vitest configuration for Task Master monorepo * Provides shared defaults for all packages * Individual packages can extend this config with package-specific settings */ export default defineConfig({ test: { // Enable global test APIs (describe, it, expect, etc.) globals: true, // Default environment for all packages (Node.js) environment: 'node', // Common test file patterns include: [ 'tests/**/*.test.ts', 'tests/**/*.spec.ts', 'src/**/*.test.ts', 'src/**/*.spec.ts' ], // Common exclusions exclude: ['node_modules', 'dist', '.git', '.cache', '**/node_modules/**'], // Coverage configuration coverage: { provider: 'v8', enabled: true, reporter: ['text', 'json', 'html'], include: ['src/**/*.ts'], exclude: [ 'node_modules/', 'dist/', 'tests/', '**/*.test.ts', '**/*.spec.ts', '**/*.d.ts', '**/mocks/**', '**/fixtures/**', '**/types/**', 'vitest.config.ts', 'src/index.ts' ], // Default thresholds (can be overridden per package) thresholds: { branches: 70, functions: 70, lines: 70, statements: 70 } }, // Test execution settings testTimeout: 10000, clearMocks: true, restoreMocks: true, mockReset: true } });