Compare commits

...

95 Commits

Author SHA1 Message Date
Ralph Khreish
9c3b3497a4 chore: add contributing.md 2025-05-27 18:58:56 -04:00
github-actions[bot]
682b54e103 docs: Auto-update and format models.md 2025-05-27 22:42:42 +00:00
Ralph Khreish
6a8a68e1a3 Feat/add.azure.and.other.providers (#607)
* fix: claude-4 not having the right max_tokens

* feat: add bedrock support

* chore: fix package-lock.json

* fix: rename baseUrl to baseURL

* feat: add azure support

* fix: final touches of azure integration

* feat: add google vertex provider

* chore: fix tests and refactor task-manager.test.js

* chore: move task 92 to 94
2025-05-28 00:42:31 +02:00
Ralph Khreish
80735f9e60 feat(config): Implement TASK_MASTER_PROJECT_ROOT support for project root resolution (#604)
* feat(config): Implement TASK_MASTER_PROJECT_ROOT support for project root resolution

- Added support for the TASK_MASTER_PROJECT_ROOT environment variable in MCP configuration, establishing a clear precedence order for project root resolution.
- Updated utility functions to prioritize the environment variable, followed by args.projectRoot and session-based resolution.
- Enhanced error handling and logging for project root determination.
- Introduced new tasks for comprehensive testing and documentation updates related to the new configuration options.

* chore: fix CI issues
2025-05-28 00:32:34 +02:00
github-actions[bot]
48732d5423 docs: Auto-update and format models.md 2025-05-25 22:13:23 -04:00
Eyal Toledano
2d520de269 fix(add-task): removes stdout in add-task which will crash MCP server (#593)
* fix(add-task): fixes an isse in which stdout leaks out of add-task causing the mcp server to crash if used.

* chore: add changeset

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-05-25 22:13:23 -04:00
celgost
b60e1cf835 revamping readme (#522) 2025-05-24 17:21:15 +02:00
Ralph Khreish
d1e45ff50e Merge pull request #589 from eyaltoledano/changeset-release/main
Version Packages
2025-05-24 16:25:26 +02:00
github-actions[bot]
1513858da4 Version Packages 2025-05-24 14:07:53 +00:00
Ralph Khreish
59dcf4bd64 Release 0.15.0
Release 0.15.0
2025-05-24 16:07:24 +02:00
github-actions[bot]
a09ba021c5 chore: rc version bump 2025-05-24 00:44:47 +00:00
Eyal Toledano
e906166141 Merge pull request #567 from eyaltoledano/parse-prd-research
v0.15 improvements & new features
2025-05-23 20:42:41 -04:00
Eyal Toledano
231e569e84 Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7 2025-05-23 20:33:45 -04:00
Eyal Toledano
09add37423 feat(models): Add comprehensive Ollama model validation and interactive setup - Add 'Custom Ollama model' option to interactive setup (--setup) - Implement live validation against local Ollama instance via /api/tags - Support configurable Ollama endpoints from .taskmasterconfig - Add robust error handling for server connectivity and model existence - Enhance user experience with clear validation feedback - Support both MCP server and CLI interfaces 2025-05-23 20:20:39 -04:00
Eyal Toledano
91fc779714 chore: adjusts changesets and an import. 2025-05-23 17:41:25 -04:00
Eyal Toledano
8c69c0aafd Task management, research, improvements for 24, 41 and 51 2025-05-23 17:30:25 -04:00
Eyal Toledano
43ad75c7fa chore: formatting 2025-05-23 14:44:53 -04:00
Eyal Toledano
a59dd037cf chore: changeset for Claude Code rules. depends on us adding it as an init option from the other PR. 2025-05-23 13:23:26 -04:00
Eyal Toledano
3293c7858b feat: adds AGENTS.md to the assets/ folder so we can add it into the project if the user selects Claude Code as the IDE of choice in the init sequence (to be done in another PR) 2025-05-23 13:17:45 -04:00
Eyal Toledano
b371808524 fix(models): Adjusts the Claude 4 models and introduces the llms-install.md file to enable AI agents to install the Taskmaster MCP server programmatically. 2025-05-23 12:59:14 -04:00
Shrey Paharia
86d8f00af8 Add next task to set status for mcp server (#558) 2025-05-22 11:09:36 +02:00
Eyal Toledano
0c55ce0165 chore: linting and prettier 2025-05-22 04:17:06 -04:00
Eyal Toledano
5a91941913 removes changeset for set/mark which i didnt add in the end 2025-05-22 04:15:10 -04:00
Eyal Toledano
04af16de27 feat(move-tasks): Implement move command for tasks and subtasks
Adds a new CLI command and MCP tool to reorganize tasks and subtasks within the hierarchy. Features include:
- Moving tasks between different positions in the task list
- Converting tasks to subtasks and vice versa
- Moving subtasks between parents
- Moving multiple tasks at once with comma-separated IDs
- Creating placeholder tasks when moving to new IDs
- Validation to prevent accidental data loss

This is particularly useful for resolving merge conflicts when multiple team members create tasks on different branches.
2025-05-22 04:14:22 -04:00
Eyal Toledano
edf0f23005 update changesets 2025-05-22 03:03:25 -04:00
Eyal Toledano
e0e1155260 fix(parse-prd): Fix parameter naming inconsistency in CLI parse-prd command 2025-05-22 02:59:32 -04:00
Eyal Toledano
70f4054f26 feat(parse-prd): Add research flag to parse-prd command for enhanced PRD analysis. Significantly improves parse PRD system prompt when used with research. 2025-05-22 02:57:51 -04:00
Eyal Toledano
34c769bcd0 feat(analyze): add task ID filtering to analyze-complexity command
Enhance analyze-complexity to support analyzing specific tasks by ID or range:
- Add --id option for comma-separated task IDs
- Add --from/--to options for analyzing tasks within a range
- Implement intelligent merging with existing reports
- Update CLI, MCP tools, and direct functions for consistent support
- Add changeset documenting the feature
2025-05-22 01:49:41 -04:00
Eyal Toledano
34df2c8bbd feat: automatically create tasks.json when missing (Task #68)
This commit implements automatic tasks.json file creation when it doesn't exist:

- When tasks.json is missing or invalid, create a new one with { tasks: [] }
- Allows adding tasks immediately after initializing a project without parsing a PRD
- Replaces error with informative feedback about file creation
- Enables smoother workflow for new projects or directories

This change improves user experience by removing the requirement to parse a PRD
before adding the first task to a newly initialized project. Closes #494
2025-05-22 01:18:27 -04:00
Eyal Toledano
5e9bc28abe feat(add-task): enhance dependency detection with semantic search
This commit significantly improves the  functionality by implementing
fuzzy semantic search to find contextually relevant dependencies:

- Add Fuse.js for powerful fuzzy search capability with weighted multi-field matching
- Implement score-based relevance ranking with high/medium relevance tiers
- Enhance context generation to include detailed information about similar tasks
- Fix context shadowing issue that prevented detailed task information from
  reaching the AI model
- Add informative CLI output showing semantic search results and dependency patterns
- Improve formatting of dependency information in prompts with task titles

The result is that newly created tasks are automatically placed within the correct
dependency structure without manual intervention, with the AI having much better
context about which tasks are most relevant to the new one being created.

This significantly improves the user experience by reducing the need to manually
update task dependencies after creation, all without increasing token usage or costs.
2025-05-22 01:09:40 -04:00
Eyal Toledano
d2e64318e2 fix(ai-services): add logic for API key checking in fallback sequence 2025-05-21 22:49:25 -04:00
Eyal Toledano
4c835264ac task management 2025-05-21 21:23:39 -04:00
github-actions[bot]
c882f89a8c Version Packages 2025-05-20 18:40:38 +02:00
Ralph Khreish
20e1b72a17 Merge pull request #549 from eyaltoledano/changeset-release/main
Version Packages
2025-05-20 00:34:13 +02:00
github-actions[bot]
db631f43a5 Version Packages 2025-05-19 22:31:08 +00:00
Ralph Khreish
3b9402f1f8 Merge Release 0.14.0 #529
Release 0.14.0
2025-05-20 00:30:46 +02:00
Ralph Khreish
c8c0fc2a57 fix: improve ollama object to telemetry structure (#546) 2025-05-19 23:05:45 +02:00
HR
60b8e97a1c fix: roomodes typo (#544) 2025-05-19 17:00:06 +02:00
github-actions[bot]
3a6d6dd671 chore: rc version bump 2025-05-18 08:08:54 +00:00
Ralph Khreish
f4a83ec047 feat: add ollama support (#536) 2025-05-18 10:07:31 +02:00
Eyal Toledano
0699f64299 Merge pull request #442 from eyaltoledano/telemetry
feat(telemetry): Implement AI usage telemetry pattern and apply to ad…
2025-05-17 22:34:01 -04:00
Eyal Toledano
60b8f5faa3 fix(expand-task): Ensure advanced parsing logic works and trimmed AI response properly if any jsonToParse modifications need to be made on initial parse of response. 2025-05-17 22:26:37 -04:00
Eyal Toledano
cd6e42249e fix(parse-prd): simplifies append and force variable names across the chain to avoid confusion. parse-prd append tested on MCP and the fix is good to go. Also adjusts e2e test to properly capture costs. 2025-05-17 20:10:53 -04:00
Eyal Toledano
fcd80623b6 linting 2025-05-17 18:43:15 -04:00
Eyal Toledano
026815353f fix(ai): Correctly imports generateText in openai.js, adds specific cause and reason for OpenRouter failures in the openrouter.js catch, performs complexity analysis on all tm tasks, adds new tasks to further improve the maxTokens to take input and output maximum into account. Adjusts default fallback max tokens so 3.5 does not fail. 2025-05-17 18:42:57 -04:00
Eyal Toledano
8a3b611fc2 fix(telemetry): renames _aggregateTelemetry to aggregateTelemetry to avoid confusion about it being a private function (it's not) 2025-05-17 17:48:45 -04:00
Eyal Toledano
6ba42b53dc fix: dupe export 2025-05-16 18:17:33 -04:00
Eyal Toledano
3e304232ab Solves merge conflicts with origin/next. 2025-05-16 18:15:11 -04:00
Eyal Toledano
70fa5b0031 fix(config): adjusts getUserId to optionally create/fill in the (currently hardcoded) userId to the telemetry object if it is not found. This prevents the telemetry call from landing as null for users who may have a taskmasterconfig but no userId in the globals. 2025-05-16 17:41:48 -04:00
github-actions[bot]
314c0de8c4 chore: rc version bump 2025-05-16 21:37:00 +00:00
Ralph Khreish
58b417a8ce Add complexity score to task (#528)
* feat: added complexity score handling to list tasks

* feat: added handling for complexity score in find task by id

* test: remove console dir

* chore: add changeset

* format: fixed formatting issues

* ref: reorder imports

* feat: updated handling for findTaskById to take complexityReport as input

* test: fix findTaskById complexity report testcases

* fix: added handling for complexity report path

* chore: add changeset

* fix: moved complexity report handling to list tasks rather than list tasks direct

* fix: add complexity handling to next task in list command

* fix: added handling for show cli

* fix: fixed next cli command handling

* fix: fixed handling for complexity report path in mcp

* feat: added handling to get-task

* feat: added handling for next-task in mcp

* feat: add handling for report path override

* chore: remove unecessary changeset

* ref: remove unecessary comments

* feat: update list and find next task

* fix: fixed running tests

* fix: fixed findTaskById

* fix: fixed findTaskById and tests

* fix: fixed addComplexityToTask util

* fix: fixed mcp server project root input

* chore: cleanup

---------

Co-authored-by: Shrey Paharia <shreypaharia@gmail.com>
2025-05-16 23:24:25 +02:00
Ralph Khreish
a8dabf4485 fix: remove cache from list-tasks and next-task mcp calls (#527)
* fix: remove cache from list-tasks and next-task mcp calls

* chore: remove cached function

* chore: add changeset
2025-05-16 22:54:03 +02:00
Ralph Khreish
bc19bc7927 Merge remote-tracking branch 'origin/next' into telemetry 2025-05-16 18:16:58 +02:00
Ralph Khreish
da317f2607 fix: error handling of task status settings (#523)
* fix: error handling of task status settings

* fix: update import path

---------

Co-authored-by: shenysun <shenysun@163.com>
2025-05-16 15:47:01 +02:00
Ralph Khreish
ed17cb0e0a feat: implement baseUrls on all ai providers(#521) 2025-05-16 15:34:29 +02:00
Ralph Khreish
e96734a6cc fix: updateTask enableSilentMode is not defined (#517)
- Closes #412
2025-05-15 22:56:52 +02:00
Ralph Khreish
17294ff259 Fix: Correct version resolution for banner and update check (#511)
* Fix: Correct version resolution for banner and update check

Resolves issues where the tool's version was displayed as 'unknown'.

- Modified 'displayBanner' in 'ui.js' and 'checkForUpdate' in 'commands.js' to read package.json relative to their own script locations using import.meta.url.
- This ensures the correct local version is identified for both the main banner display and the update notification mechanism.
- Restored a missing closing brace in 'ui.js' to fix a SyntaxError.

* fix: refactor and cleanup

* fix: chores and cleanup and testing

* chore: cleanup

* fix: add changeset

---------

Co-authored-by: Christer Soederlund <christer.soderlund@gmail.com>
2025-05-15 22:41:16 +02:00
Lars Bell
a96215a359 Update .taskmasterconfig (#435)
* Update .taskmasterconfig

Max tokens in 3.5 is lower.  With the current number get this error:

Service call failed for role fallback (Provider: anthropic, Model: claude-3-5-sonnet-20240620): max_tokens: 120000 > 8192, which is the maximum allowed number of output tokens for claude-3-5-sonnet-20240620

* Fix fallback model ID format and update maxTokens in Taskmaster configuration

---------

Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com>
2025-05-15 13:01:21 +02:00
Ralph Khreish
0a611843b5 fix: Inline comments in .env.example conflicting with env variable values (#501)
* fix: Update API key format in env.example to use quotes for consistency

* chore: add changelog
2025-05-15 01:32:49 +02:00
Kayvan Sylvan
a1f8d52474 chore: rename log level environment variable to TASKMASTER_LOG_LEVEL (#417)
* chore: rename log level environment variable to `TASKMASTER_LOG_LEVEL`

### CHANGES
- Update environment variable from `LOG_LEVEL` to `TASKMASTER_LOG_LEVEL`.
- Reflect change in documentation for clarity.
- Adjust variable name in script and test files.
- Maintain default log level as `info`.

* fix: add changeset

* chore: rename `LOG_LEVEL` to `TASKMASTER_LOG_LEVEL` for consistency

### CHANGES
- Update environment variable name to `TASKMASTER_LOG_LEVEL` in documentation.
- Reflect rename in configuration rules for clarity.
- Maintain consistency across project configuration settings.
2025-05-15 01:09:41 +02:00
Eyal Toledano
da636f6681 fix(e2e): further improves the end to end script to take into account the changes made for each AI provider as it now responds with an obejct not just the result straight up. 2025-05-14 19:04:47 -04:00
Eyal Toledano
ca5ec03cd8 fix(ai,tasks): Enhance AI provider robustness and task processing
This commit introduces several improvements to AI interactions and
task management functionalities:

- AI Provider Enhancements (for Telemetry & Robustness):
    - :
        - Added a check in  to ensure
          is a string, throwing an error if not. This prevents downstream
           errors (e.g., in ).
    - , , :
        - Standardized return structures for their respective
          and  functions to consistently include /
          and  fields. This aligns them with other providers (like
          Anthropic, Google, Perplexity) for consistent telemetry data
          collection, as part of implementing subtask 77.14 and similar work.

- Task Expansion ():
    - Updated  to be more explicit
      about using an empty array  for empty  to
      better guide AI output.
    - Implemented a pre-emptive cleanup step in
      to replace malformed  with
      before JSON parsing. This improves resilience to AI output quirks,
      particularly observed with Perplexity.

- Adjusts issue in commands.js where successfulRemovals would be undefined. It's properly invoked from the result variable now.

- Updates supported models for Gemini
These changes address issues observed during E2E tests, enhance the
reliability of AI-driven task analysis and expansion, and promote
consistent telemetry data across multiple AI providers.
2025-05-14 19:04:03 -04:00
Ralph Khreish
c47deeb869 Merge remote-tracking branch 'origin/main' into next 2025-05-15 00:29:54 +02:00
github-actions[bot]
dd90c9cb5d Version Packages 2025-05-15 00:29:11 +02:00
Ralph Khreish
c7042845d6 chore: improve CI to better accomodate pre-releases for testing (#507) 2025-05-15 00:28:06 +02:00
Eyal Toledano
79a41543d5 fix(ai): Align Perplexity provider with standard telemetry response structure
This commit updates the Perplexity AI provider () to ensure its functions return data in a structure consistent with other providers and the expectations of the unified AI service layer ().

Specifically:
-  now returns an object  instead of only the text string.
-  now returns an object  instead of only the result object.

These changes ensure that  can correctly extract both the primary AI-generated content and the token usage data for telemetry purposes when Perplexity models are used. This resolves issues encountered during E2E testing where complexity analysis (which can use Perplexity for its research role) failed due to unexpected response formats.

The  function was already compliant.
2025-05-14 11:46:35 -04:00
Joe Danziger
efce37469b Fix duplicate output on CLI help screen (#496)
* remove duplication

* add changeset

* fix formatting
2025-05-14 13:12:15 +02:00
Joe Danziger
4117f71c18 Fix CLI --force flag on parse-prd command 2025-05-13 22:06:09 +02:00
Eyal Toledano
9f4bac8d6a fix(ai): Improve AI object response handling in parse-prd
This commit updates  to more robustly handle responses from .

Previously, the module strictly expected the AI-generated object to be nested under . This change ensures that it now first checks if  itself contains the expected task data object, and then falls back to checking .

This enhancement increases compatibility with varying AI provider response structures, similar to the improvements recently made in .
2025-05-13 13:21:51 -04:00
Eyal Toledano
e53d5e1577 feat(ai): Enhance Google provider telemetry and AI object response handling
This commit introduces two key improvements:

1.  **Google Provider Telemetry:**
    - Updated  to include token usage data (, ) in the responses from  and .
    - This aligns the Google provider with others for consistent AI usage telemetry.

2.  **Robust AI Object Response Handling:**
    - Modified  to more flexibly handle responses from .
    - The add-task module now check for the AI-generated object in both  and , improving compatibility with different AI provider response structures (e.g., Gemini).

These changes enhance the reliability of AI interactions, particularly with the Google provider, and ensure accurate telemetry collection.
2025-05-13 12:13:35 -04:00
Eyal Toledano
59230c4d91 chore: task management and formatting. 2025-05-09 14:12:21 -04:00
Eyal Toledano
04b6a3cb21 feat(telemetry): Integrate AI usage telemetry into analyze-complexity
This commit applies the standard telemetry pattern to the analyze-task-complexity command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/analyze-task-complexity.js):
    -   The call to generateTextService now includes commandName: 'analyze-complexity' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for parsing the complexity report JSON.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { report: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/analyze-task-complexity.js):
    -   The call to the core analyzeTaskComplexity function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 19:34:00 -04:00
Eyal Toledano
37178ff1b9 feat(telemetry): Integrate AI usage telemetry into update-subtask
This commit applies the standard telemetry pattern to the update-subtask command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/update-subtask-by-id.js):
    -   The call to generateTextService now includes commandName: 'update-subtask' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for the appended content.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { updatedSubtask: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/update-subtask-by-id.js):
    -   The call to the core updateSubtaskById function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 19:04:25 -04:00
Eyal Toledano
bbc8b9cc1f feat(telemetry): Integrate AI usage telemetry into update-tasks
This commit applies the standard telemetry pattern to the update-tasks command and its corresponding MCP tool.

Key Changes:

1.  Core Logic (scripts/modules/task-manager/update-tasks.js):
    -   The call to generateTextService now includes commandName: 'update-tasks' and outputType.
    -   The full response { mainResult, telemetryData } is captured.
    -   mainResult (the AI-generated text) is used for parsing the updated task JSON.
    -   If running in CLI mode (outputFormat === 'text'), displayAiUsageSummary is called with the telemetryData.
    -   The function now returns { success: true, updatedTasks: ..., telemetryData: ... }.

2.  Direct Function (mcp-server/src/core/direct-functions/update-tasks.js):
    -   The call to the core updateTasks function now passes the necessary context for telemetry (commandName, outputType).
    -   The successful response object now correctly extracts coreResult.telemetryData and includes it in the data.telemetryData field returned to the MCP client.
2025-05-08 18:51:29 -04:00
Eyal Toledano
c955431753 feat(telemetry): Integrate AI usage telemetry into update-tasks
This commit applies the standard telemetry pattern to the  command and its corresponding MCP tool.

Key Changes:

1.  **Core Logic ():**
    -   The call to  now includes  and .
    -   The full response  is captured.
    -    (the AI-generated text) is used for parsing the updated task JSON.
    -   If running in CLI mode (),  is called with the .
    -   The function now returns .

2.  **Direct Function ():**
    -   The call to the core  function now passes the necessary context for telemetry (, ).
    -   The successful response object now correctly extracts  and includes it in the  field returned to the MCP client.
2025-05-08 18:37:41 -04:00
Eyal Toledano
21c3cb8cda feat(telemetry): Integrate telemetry for expand-all, aggregate results
This commit implements AI usage telemetry for the `expand-all-tasks` command/tool and refactors its CLI output for clarity and consistency.

Key Changes:

1.  **Telemetry Integration for `expand-all-tasks` (Subtask 77.8):**\n    -   The `expandAllTasks` core logic (`scripts/modules/task-manager/expand-all-tasks.js`) now calls the `expandTask` function for each eligible task and collects the individual `telemetryData` returned.\n    -   A new helper function `_aggregateTelemetry` (in `utils.js`) is used to sum up token counts and costs from all individual expansions into a single `telemetryData` object for the entire `expand-all` operation.\n    -   The `expandAllTasksDirect` wrapper (`mcp-server/src/core/direct-functions/expand-all-tasks.js`) now receives and passes this aggregated `telemetryData` in the MCP response.\n    -   For CLI usage, `displayAiUsageSummary` is called once with the aggregated telemetry.

2.  **Improved CLI Output for `expand-all`:**\n    -   The `expandAllTasks` core function now handles displaying a final "Expansion Summary" box (showing Attempted, Expanded, Skipped, Failed counts) directly after the aggregated telemetry summary.\n    -   This consolidates all summary output within the core function for better flow and removes redundant logging from the command action in `scripts/modules/commands.js`.\n    -   The summary box border is green for success and red if any expansions failed.

3.  **Code Refinements:**\n    -   Ensured `chalk` and `boxen` are imported in `expand-all-tasks.js` for the new summary box.\n    -   Minor adjustments to logging messages for clarity.
2025-05-08 18:22:00 -04:00
Eyal Toledano
ab84afd036 feat(telemetry): Integrate usage telemetry for expand-task, fix return types
This commit integrates AI usage telemetry for the `expand-task` command/tool and resolves issues related to incorrect return type handling and logging.

Key Changes:

1.  **Telemetry Integration for `expand-task` (Subtask 77.7):**\n    -   Applied the standard telemetry pattern to the `expandTask` core logic (`scripts/modules/task-manager/expand-task.js`) and the `expandTaskDirect` wrapper (`mcp-server/src/core/direct-functions/expand-task.js`).\n    -   AI service calls now pass `commandName` and `outputType`.\n    -   Core function returns `{ task, telemetryData }`.\n    -   Direct function correctly extracts `task` and passes `telemetryData` in the MCP response `data` field.\n    -   Telemetry summary is now displayed in the CLI output for the `expand` command.

2.  **Fix AI Service Return Type Handling (`ai-services-unified.js`):**\n    -   Corrected the `_unifiedServiceRunner` function to properly handle the return objects from provider-specific functions (`generateText`, `generateObject`).\n    -   It now correctly extracts `providerResponse.text` or `providerResponse.object` into the `mainResult` field based on `serviceType`, resolving the "text.trim is not a function" error encountered during `expand-task`.

3.  **Log Cleanup:**\n    -   Removed various redundant or excessive `console.log` statements across multiple files (as indicated by recent changes) to reduce noise and improve clarity, particularly for MCP interactions.
2025-05-08 16:02:23 -04:00
Eyal Toledano
f89d2aacc0 feat(telemetry): Integrate AI usage telemetry into parse-prd
Implements AI usage telemetry capture and propagation for the  command and MCP tool, following the established telemetry pattern.

Key changes:

-   **Core ():**
    -   Modified the  call to include  and .
    -   Updated to receive  from .
    -   Adjusted to return an object .
    -   Added a call to  to show telemetry data in the CLI output when not in MCP mode.

-   **Direct Function ():**
    -   Updated the call to the core  function to pass , , and .
    -   Modified to correctly handle the new return structure from the core function.
    -   Ensures  received from the core function is included in the  field of the successful MCP response.

-   **MCP Tool ():**
    -   No changes required; existing  correctly passes through the  object containing .

-   **CLI Command ():**
    -   The  command's action now relies on the core  function to handle CLI success messages and telemetry display.

This ensures that AI usage for the  functionality is tracked and can be displayed or logged as appropriate for both CLI and MCP interactions.
2025-05-07 14:22:42 -04:00
Eyal Toledano
0288311965 fix(parse-prd): resolves issue preventing --append flag from properly working in the CLI context. Adds changeset. 2025-05-07 14:17:41 -04:00
Eyal Toledano
8ae772086d fix(next): adjusts CLI output for next when the result is a subtask. previously incorrect suggested creating subtasks for the subtask. 2025-05-07 14:07:50 -04:00
Eyal Toledano
2b3ae8bf89 tests: adjusts the tests to properly pass. 2025-05-07 13:54:01 -04:00
Eyal Toledano
245c3cb398 feat(telemetry): Implement AI usage telemetry pattern and apply to add-task
This commit introduces a standardized pattern for capturing and propagating AI usage telemetry (cost, tokens, model used) across the Task Master stack and applies it to the 'add-task' functionality.

Key changes include:

- **Telemetry Pattern Definition:**
  - Added  defining the integration pattern for core logic, direct functions, MCP tools, and CLI commands.
  - Updated related rules (, ,
 Usage: mcp [OPTIONS] COMMAND [ARGS]...

 MCP development tools

╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --help          Show this message and exit.                                                                                                │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Commands ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ version   Show the MCP version.                                                                                                            │
│ dev       Run a MCP server with the MCP Inspector.                                                                                         │
│ run       Run a MCP server.                                                                                                                │
│ install   Install a MCP server in the Claude desktop app.                                                                                  │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯, , ) to reference the new telemetry rule.

- **Core Telemetry Implementation ():**
  - Refactored the unified AI service to generate and return a  object alongside the main AI result.
  - Fixed an MCP server startup crash by removing redundant local loading of  and instead using the  imported from  for cost calculations.
  - Added  to the  object.

- ** Integration:**
  - Modified  (core) to receive  from the AI service, return it, and call the new UI display function for CLI output.
  - Updated  to receive  from the core function and include it in the  payload of its response.
  - Ensured  (MCP tool) correctly passes the  through via .
  - Updated  to correctly pass context (, ) to the core  function and rely on it for CLI telemetry display.

- **UI Enhancement:**
  - Added  function to  to show telemetry details in the CLI.

- **Project Management:**
  - Added subtasks 77.6 through 77.12 to track the rollout of this telemetry pattern to other AI-powered commands (, , , , , , ).

This establishes the foundation for tracking AI usage across the application.
2025-05-07 13:41:25 -04:00
Ralph Khreish
09d839fff5 Merge pull request #405 from eyaltoledano/changeset-release/main
Version Packages
2025-05-03 20:46:10 +02:00
github-actions[bot]
90068348d3 Version Packages 2025-05-03 18:13:24 +00:00
Ralph Khreish
02e347d2d7 Merge pull request #404 from eyaltoledano/next
Release 0.13.2
2025-05-03 20:13:05 +02:00
Ralph Khreish
0527c363e3 Merge remote-tracking branch 'origin/main' into next 2025-05-03 19:32:07 +02:00
Ralph Khreish
735135efe9 chore: allow github actions to commit 2025-05-03 19:24:00 +02:00
Ralph Khreish
4fee667a05 chore: improve pre-release workflow 2025-05-03 19:07:42 +02:00
Ralph Khreish
01963af2cb Fix: issues with 0.13.0 not working (#402)
* Exit prerelease mode and version packages

* hotfix: move production package to "dependencies"

* Enter prerelease mode and version packages

* Enter prerelease mode and version packages

* chore: cleanup

* chore: improve pre.json and add pre-release workflow

* chore: fix package.json

* chore: cleanup
2025-05-03 18:55:18 +02:00
Ralph Khreish
0633895f3b Version Packages (#401)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-05-03 17:02:05 +02:00
github-actions[bot]
10442c1119 Version Packages 2025-05-03 14:56:40 +00:00
Ralph Khreish
734a4fdcfc hotfix: move production package to "dependencies" (#399) 2025-05-03 16:56:17 +02:00
Ralph Khreish
8dace2186c Merge pull request #390 from eyaltoledano/changeset-release/main
Version Packages
2025-05-03 10:17:11 +02:00
github-actions[bot]
095e373843 Version Packages 2025-05-03 08:14:02 +00:00
Ralph Khreish
0bc9bac392 Merge pull request #369 from eyaltoledano/next
Release 0.13.0
2025-05-03 10:13:43 +02:00
191 changed files with 28154 additions and 6583 deletions

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
- Add support for Google Gemini models via Vercel AI SDK integration.

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Add xAI provider and Grok models support

View File

@@ -1,8 +0,0 @@
---
'task-master-ai': minor
---
feat(expand): Enhance `expand` and `expand-all` commands
- Integrate `task-complexity-report.json` to automatically determine the number of subtasks and use tailored prompts for expansion based on prior analysis. You no longer need to try copy-pasting the recommended prompt. If it exists, it will use it for you. You can just run `task-master update --id=[id of task] --research` and it will use that prompt automatically. No extra prompt needed.
- Change default behavior to *append* new subtasks to existing ones. Use the `--force` flag to clear existing subtasks before expanding. This is helpful if you need to add more subtasks to a task but you want to do it by the batch from a given prompt. Use force if you want to start fresh with a task's subtasks.

View File

@@ -1,9 +0,0 @@
---
'task-master-ai': patch
---
Better support for file paths on Windows, Linux & WSL.
- Standardizes handling of different path formats (URI encoded, Windows, Linux, WSL).
- Ensures tools receive a clean, absolute path suitable for the server OS.
- Simplifies tool implementation by centralizing normalization logic.

View File

@@ -1,7 +0,0 @@
---
'task-master-ai': minor
---
Adds support for the OpenRouter AI provider. Users can now configure models available through OpenRouter (requiring an `OPENROUTER_API_KEY`) via the `task-master models` command, granting access to a wide range of additional LLMs.
- IMPORTANT FYI ABOUT OPENROUTER: Taskmaster relies on AI SDK, which itself relies on tool use. It looks like **free** models sometimes do not include tool use. For example, Gemini 2.5 pro (free) failed via OpenRouter (no tool use) but worked fine on the paid version of the model. Custom model support for Open Router is considered experimental and likely will not be further improved for some time.

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Add integration for Roo Code

View File

@@ -1,8 +0,0 @@
---
'task-master-ai': patch
---
Improved update-subtask
- Now it has context about the parent task details
- It also has context about the subtask before it and the subtask after it (if they exist)
- Not passing all subtasks to stay token efficient

View File

@@ -1,13 +0,0 @@
---
'task-master-ai': patch
---
Improve and adjust `init` command for robustness and updated dependencies.
- **Update Initialization Dependencies:** Ensure newly initialized projects (`task-master init`) include all required AI SDK dependencies (`@ai-sdk/*`, `ai`, provider wrappers) in their `package.json` for out-of-the-box AI feature compatibility. Remove unnecessary dependencies (e.g., `uuid`) from the init template.
- **Silence `npm install` during `init`:** Prevent `npm install` output from interfering with non-interactive/MCP initialization by suppressing its stdio in silent mode.
- **Improve Conditional Model Setup:** Reliably skip interactive `models --setup` during non-interactive `init` runs (e.g., `init -y` or MCP) by checking `isSilentMode()` instead of passing flags.
- **Refactor `init.js`:** Remove internal `isInteractive` flag logic.
- **Update `init` Instructions:** Tweak the "Getting Started" text displayed after `init`.
- **Fix MCP Server Launch:** Update `.cursor/mcp.json` template to use `node ./mcp-server/server.js` instead of `npx task-master-mcp`.
- **Update Default Model:** Change the default main model in the `.taskmasterconfig` template.

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Fixes an issue with add-task which did not use the manually defined properties and still needlessly hit the AI endpoint.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Add AWS bedrock support

View File

@@ -0,0 +1,13 @@
---
'task-master-ai': minor
---
# Add Google Vertex AI Provider Integration
- Implemented `VertexAIProvider` class extending BaseAIProvider
- Added authentication and configuration handling for Vertex AI
- Updated configuration manager with Vertex-specific getters
- Modified AI services unified system to integrate the provider
- Added documentation for Vertex AI setup and configuration
- Updated environment variable examples for Vertex AI support
- Implemented specialized error handling for Vertex-specific issues

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Add support for Azure

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': minor
---
Adds model management and new configuration file .taskmasterconfig which houses the models used for main, research and fallback. Adds models command and setter flags. Adds a --setup flag with an interactive setup. We should be calling this during init. Shows a table of active and available models when models is called without flags. Includes SWE scores and token costs, which are manually entered into the supported_models.json, the new place where models are defined for support. Config-manager.js is the core module responsible for managing the new config."

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Fixes an issue that prevented remove-subtask with comma separated tasks/subtasks from being deleted (only the first ID was being deleted). Closes #140

View File

@@ -1,10 +0,0 @@
---
'task-master-ai': patch
---
Improves next command to be subtask-aware
- The logic for determining the "next task" (findNextTask function, used by task-master next and the next_task MCP tool) has been significantly improved. Previously, it only considered top-level tasks, making its recommendation less useful when a parent task containing subtasks was already marked 'in-progress'.
- The updated logic now prioritizes finding the next available subtask within any 'in-progress' parent task, considering subtask dependencies and priority.
- If no suitable subtask is found within active parent tasks, it falls back to recommending the next eligible top-level task based on the original criteria (status, dependencies, priority).
This change makes the next command much more relevant and helpful during the implementation phase of complex tasks.

View File

@@ -1,11 +0,0 @@
---
'task-master-ai': minor
---
Adds custom model ID support for Ollama and OpenRouter providers.
- Adds the `--ollama` and `--openrouter` flags to `task-master models --set-<role>` command to set models for those providers outside of the support models list.
- Updated `task-master models --setup` interactive mode with options to explicitly enter custom Ollama or OpenRouter model IDs.
- Implemented live validation against OpenRouter API (`/api/v1/models`) when setting a custom OpenRouter model ID (via flag or setup).
- Refined logic to prioritize explicit provider flags/choices over internal model list lookups in case of ID conflicts.
- Added warnings when setting custom/unvalidated models.
- We obviously don't recommend going with a custom, unproven model. If you do and find performance is good, please let us know so we can add it to the list of supported models.

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Add `--status` flag to `show` command to filter displayed subtasks.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': minor
---
Renamed baseUrl to baseURL

View File

@@ -1,7 +0,0 @@
---
'task-master-ai': minor
---
Integrate OpenAI as a new AI provider.
- Enhance `models` command/tool to display API key status.
- Implement model-specific `maxTokens` override based on `supported-models.json` to save you if you use an incorrect max token value.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fix max_tokens error when trying to use claude-sonnet-4 and claude-opus-4

View File

@@ -0,0 +1,7 @@
---
'task-master-ai': minor
---
Add TASK_MASTER_PROJECT_ROOT env variable supported in mcp.json and .env for project root resolution
- Some users were having issues where the MCP wasn't able to detect the location of their project root, you can now set the `TASK_MASTER_PROJECT_ROOT` environment variable to the root of your project.

View File

@@ -0,0 +1,5 @@
---
'task-master-ai': patch
---
Fix add-task MCP command causing an error

View File

@@ -1,9 +0,0 @@
---
'task-master-ai': minor
---
Tweaks Perplexity AI calls for research mode to max out input tokens and get day-fresh information
- Forces temp at 0.1 for highly deterministic output, no variations
- Adds a system prompt to further improve the output
- Correctly uses the maximum input tokens (8,719, used 8,700) for perplexity
- Specificies to use a high degree of research across the web
- Specifies to use information that is as fresh as today; this support stuff like capturing brand new announcements like new GPT models and being able to query for those in research. 🔥

View File

@@ -1,5 +0,0 @@
---
'task-master-ai': patch
---
Fix --task to --num-tasks in ui + related tests - issue #324

View File

@@ -1,9 +0,0 @@
---
'task-master-ai': patch
---
Adds a 'models' CLI and MCP command to get the current model configuration, available models, and gives the ability to set main/research/fallback models."
- In the CLI, `task-master models` shows the current models config. Using the `--setup` flag launches an interactive set up that allows you to easily select the models you want to use for each of the three roles. Use `q` during the interactive setup to cancel the setup.
- In the MCP, responses are simplified in RESTful format (instead of the full CLI output). The agent can use the `models` tool with different arguments, including `listAvailableModels` to get available models. Run without arguments, it will return the current configuration. Arguments are available to set the model for each of the three roles. This allows you to manage Taskmaster AI providers and models directly from either the CLI or MCP or both.
- Updated the CLI help menu when you run `task-master` to include missing commands and .taskmasterconfig information.
- Adds `--research` flag to `add-task` so you can hit up Perplexity right from the add-task flow, rather than having to add a task and then update it.

View File

@@ -25,6 +25,7 @@ This document outlines the architecture and usage patterns for interacting with
* Implements **retry logic** for specific API errors (`_attemptProviderCallWithRetries`).
* Resolves API keys automatically via `_resolveApiKey` (using `resolveEnvVariable`).
* Maps requests to the correct provider implementation (in `src/ai-providers/`) via `PROVIDER_FUNCTIONS`.
* Returns a structured object containing the primary AI result (`mainResult`) and telemetry data (`telemetryData`). See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for details on how this telemetry data is propagated and handled.
* **Provider Implementations (`src/ai-providers/*.js`):**
* Contain provider-specific wrappers around Vercel AI SDK functions (`generateText`, `generateObject`).

View File

@@ -42,6 +42,7 @@ alwaysApply: false
- Resolves API keys (from `.env` or `session.env`).
- Implements fallback and retry logic.
- Orchestrates calls to provider-specific implementations (`src/ai-providers/`).
- Telemetry data generated by the AI service layer is propagated upwards through core logic, direct functions, and MCP tools. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the detailed integration pattern.
- **[`src/ai-providers/*.js`](mdc:src/ai-providers/): Provider-Specific Implementations**
- **Purpose**: Provider-specific wrappers for Vercel AI SDK functions.

View File

@@ -49,6 +49,7 @@ Task Master offers two primary ways to interact:
- Maintain valid dependency structure with `add_dependency`/`remove_dependency` tools or `task-master add-dependency`/`remove-dependency` commands, `validate_dependencies` / `task-master validate-dependencies`, and `fix_dependencies` / `task-master fix-dependencies` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) when needed
- Respect dependency chains and task priorities when selecting work
- Report progress regularly using `get_tasks` / `task-master list`
- Reorganize tasks as needed using `move_task` / `task-master move --from=<id> --to=<id>` (see [`taskmaster.mdc`](mdc:.cursor/rules/taskmaster.mdc)) to change task hierarchy or ordering
## Task Complexity Analysis
@@ -116,7 +117,7 @@ Taskmaster configuration is managed through two main mechanisms:
* For MCP/Cursor integration, configure these keys in the `env` section of `.cursor/mcp.json`.
* Available keys/variables: See `assets/env.example` or the Configuration section in the command reference (previously linked to `taskmaster.mdc`).
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
**Important:** Non-API key settings (like model selections, `MAX_TOKENS`, `TASKMASTER_LOG_LEVEL`) are **no longer configured via environment variables**. Use the `task-master models` command (or `--setup` for interactive configuration) or the `models` MCP tool.
**If AI commands FAIL in MCP** verify that the API key for the selected provider is present in the `env` section of `.cursor/mcp.json`.
**If AI commands FAIL in CLI** verify that the API key for the selected provider is present in the `.env` file in the root of the project.
@@ -154,6 +155,25 @@ Taskmaster configuration is managed through two main mechanisms:
- Task files are automatically regenerated after dependency changes
- Dependencies are visualized with status indicators in task listings and files
## Task Reorganization
- Use `move_task` / `task-master move --from=<id> --to=<id>` to move tasks or subtasks within the hierarchy
- This command supports several use cases:
- Moving a standalone task to become a subtask (e.g., `--from=5 --to=7`)
- Moving a subtask to become a standalone task (e.g., `--from=5.2 --to=7`)
- Moving a subtask to a different parent (e.g., `--from=5.2 --to=7.3`)
- Reordering subtasks within the same parent (e.g., `--from=5.2 --to=5.4`)
- Moving a task to a new, non-existent ID position (e.g., `--from=5 --to=25`)
- Moving multiple tasks at once using comma-separated IDs (e.g., `--from=10,11,12 --to=16,17,18`)
- The system includes validation to prevent data loss:
- Allows moving to non-existent IDs by creating placeholder tasks
- Prevents moving to existing task IDs that have content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- The system maintains proper parent-child relationships and dependency integrity
- Task files are automatically regenerated after the move operation
- This provides greater flexibility in organizing and refining your task structure as project understanding evolves
- This is especially useful when dealing with potential merge conflicts arising from teams creating tasks on separate branches. Solve these conflicts very easily by moving your tasks and keeping theirs.
## Iterative Subtask Implementation
Once a task has been broken down into subtasks using `expand_task` or similar methods, follow this iterative process for implementation:

View File

@@ -3,7 +3,6 @@ description: Glossary of other Cursor rules
globs: **/*
alwaysApply: true
---
# Glossary of Task Master Cursor Rules
This file provides a quick reference to the purpose of each rule file located in the `.cursor/rules` directory.
@@ -23,4 +22,5 @@ This file provides a quick reference to the purpose of each rule file located in
- **[`tests.mdc`](mdc:.cursor/rules/tests.mdc)**: Guidelines for implementing and maintaining tests for Task Master CLI.
- **[`ui.mdc`](mdc:.cursor/rules/ui.mdc)**: Guidelines for implementing and maintaining user interface components.
- **[`utilities.mdc`](mdc:.cursor/rules/utilities.mdc)**: Guidelines for implementing utility functions.
- **[`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc)**: Guidelines for integrating AI usage telemetry across Task Master.

View File

@@ -522,3 +522,8 @@ Follow these steps to add MCP support for an existing Task Master command (see [
// Add more functions as implemented
};
```
## Telemetry Integration
- Direct functions calling core logic that involves AI should receive and pass through `telemetryData` within their successful `data` payload. See [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc) for the standard pattern.
- MCP tools use `handleApiResult`, which ensures the `data` object (potentially including `telemetryData`) from the direct function is correctly included in the final response.

View File

@@ -3,7 +3,6 @@ description: Guidelines for integrating new features into the Task Master CLI
globs: scripts/modules/*.js
alwaysApply: false
---
# Task Master Feature Integration Guidelines
## Feature Placement Decision Process
@@ -196,6 +195,8 @@ The standard pattern for adding a feature follows this workflow:
- ✅ **DO**: If an MCP tool fails with vague errors (e.g., JSON parsing issues like `Unexpected token ... is not valid JSON`), **try running the equivalent CLI command directly in the terminal** (e.g., `task-master expand --all`). CLI output often provides much more specific error messages (like missing function definitions or stack traces from the core logic) that pinpoint the root cause.
- ❌ **DON'T**: Rely solely on MCP logs if the error is unclear; use the CLI as a complementary debugging tool for core logic issues.
- **Telemetry Integration**: Ensure AI calls correctly handle and propagate `telemetryData` as described in [`telemetry.mdc`](mdc:.cursor/rules/telemetry.mdc).
```javascript
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
/**

View File

@@ -269,11 +269,36 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Delete unnecessary subtasks or promote a subtask to a top-level task.
### 17. Move Task (`move_task`)
* **MCP Tool:** `move_task`
* **CLI Command:** `task-master move [options]`
* **Description:** `Move a task or subtask to a new position within the task hierarchy.`
* **Key Parameters/Options:**
* `from`: `Required. ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated for multiple tasks.` (CLI: `--from <id>`)
* `to`: `Required. ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated.` (CLI: `--to <id>`)
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Reorganize tasks by moving them within the hierarchy. Supports various scenarios like:
* Moving a task to become a subtask
* Moving a subtask to become a standalone task
* Moving a subtask to a different parent
* Reordering subtasks within the same parent
* Moving a task to a new, non-existent ID (automatically creates placeholders)
* Moving multiple tasks at once with comma-separated IDs
* **Validation Features:**
* Allows moving tasks to non-existent destination IDs (creates placeholder tasks)
* Prevents moving to existing task IDs that already have content (to avoid overwriting)
* Validates that source tasks exist before attempting to move them
* Maintains proper parent-child relationships
* **Example CLI:** `task-master move --from=5.2 --to=7.3` to move subtask 5.2 to become subtask 7.3.
* **Example Multi-Move:** `task-master move --from=10,11,12 --to=16,17,18` to move multiple tasks to new positions.
* **Common Use:** Resolving merge conflicts in tasks.json when multiple team members create tasks on different branches.
---
## Dependency Management
### 17. Add Dependency (`add_dependency`)
### 18. Add Dependency (`add_dependency`)
* **MCP Tool:** `add_dependency`
* **CLI Command:** `task-master add-dependency [options]`
@@ -284,7 +309,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <path>`)
* **Usage:** Establish the correct order of execution between tasks.
### 18. Remove Dependency (`remove_dependency`)
### 19. Remove Dependency (`remove_dependency`)
* **MCP Tool:** `remove_dependency`
* **CLI Command:** `task-master remove-dependency [options]`
@@ -295,7 +320,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Update task relationships when the order of execution changes.
### 19. Validate Dependencies (`validate_dependencies`)
### 20. Validate Dependencies (`validate_dependencies`)
* **MCP Tool:** `validate_dependencies`
* **CLI Command:** `task-master validate-dependencies [options]`
@@ -304,7 +329,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* `file`: `Path to your Taskmaster 'tasks.json' file. Default relies on auto-detection.` (CLI: `-f, --file <file>`)
* **Usage:** Audit the integrity of your task dependencies.
### 20. Fix Dependencies (`fix_dependencies`)
### 21. Fix Dependencies (`fix_dependencies`)
* **MCP Tool:** `fix_dependencies`
* **CLI Command:** `task-master fix-dependencies [options]`
@@ -317,7 +342,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
## Analysis & Reporting
### 21. Analyze Project Complexity (`analyze_project_complexity`)
### 22. Analyze Project Complexity (`analyze_project_complexity`)
* **MCP Tool:** `analyze_project_complexity`
* **CLI Command:** `task-master analyze-complexity [options]`
@@ -330,7 +355,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
* **Usage:** Used before breaking down tasks to identify which ones need the most attention.
* **Important:** This MCP tool makes AI calls and can take up to a minute to complete. Please inform users to hang tight while the operation is in progress.
### 22. View Complexity Report (`complexity_report`)
### 23. View Complexity Report (`complexity_report`)
* **MCP Tool:** `complexity_report`
* **CLI Command:** `task-master complexity-report [options]`
@@ -343,7 +368,7 @@ This document provides a detailed reference for interacting with Taskmaster, cov
## File Management
### 23. Generate Task Files (`generate`)
### 24. Generate Task Files (`generate`)
* **MCP Tool:** `generate`
* **CLI Command:** `task-master generate [options]`

228
.cursor/rules/telemetry.mdc Normal file
View File

@@ -0,0 +1,228 @@
---
description: Guidelines for integrating AI usage telemetry across Task Master.
globs: scripts/modules/**/*.js,mcp-server/src/**/*.js
alwaysApply: true
---
# AI Usage Telemetry Integration
This document outlines the standard pattern for capturing, propagating, and handling AI usage telemetry data (cost, tokens, model, etc.) across the Task Master stack. This ensures consistent telemetry for both CLI and MCP interactions.
## Overview
Telemetry data is generated within the unified AI service layer ([`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)) and then passed upwards through the calling functions.
- **Data Source**: [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js) (specifically its `generateTextService`, `generateObjectService`, etc.) returns an object like `{ mainResult: AI_CALL_OUTPUT, telemetryData: TELEMETRY_OBJECT }`.
- **`telemetryData` Object Structure**:
```json
{
"timestamp": "ISO_STRING_DATE",
"userId": "USER_ID_FROM_CONFIG",
"commandName": "invoking_command_or_tool_name",
"modelUsed": "ai_model_id",
"providerName": "ai_provider_name",
"inputTokens": NUMBER,
"outputTokens": NUMBER,
"totalTokens": NUMBER,
"totalCost": NUMBER, // e.g., 0.012414
"currency": "USD" // e.g., "USD"
}
```
## Integration Pattern by Layer
The key principle is that each layer receives telemetry data from the layer below it (if applicable) and passes it to the layer above it, or handles it for display in the case of the CLI.
### 1. Core Logic Functions (e.g., in `scripts/modules/task-manager/`)
Functions in this layer that invoke AI services are responsible for handling the `telemetryData` they receive from [`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js).
- **Actions**:
1. Call the appropriate AI service function (e.g., `generateObjectService`).
- Pass `commandName` (e.g., `add-task`, `expand-task`) and `outputType` (e.g., `cli` or `mcp`) in the `params` object to the AI service. The `outputType` can be derived from context (e.g., presence of `mcpLog`).
2. The AI service returns an object, e.g., `aiServiceResponse = { mainResult: {/*AI output*/}, telemetryData: {/*telemetry data*/} }`.
3. Extract `aiServiceResponse.mainResult` for the core processing.
4. **Must return an object that includes `aiServiceResponse.telemetryData`**.
Example: `return { operationSpecificData: /*...*/, telemetryData: aiServiceResponse.telemetryData };`
- **CLI Output Handling (If Applicable)**:
- If the core function also handles CLI output (e.g., it has an `outputFormat` parameter that can be `'text'` or `'cli'`):
1. Check if `outputFormat === 'text'` (or `'cli'`).
2. If so, and if `aiServiceResponse.telemetryData` is available, call `displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli')` from [`scripts/modules/ui.js`](mdc:scripts/modules/ui.js).
- This ensures telemetry is displayed directly to CLI users after the main command output.
- **Example Snippet (Core Logic in `scripts/modules/task-manager/someAiAction.js`)**:
```javascript
import { generateObjectService } from '../ai-services-unified.js';
import { displayAiUsageSummary } from '../ui.js';
async function performAiRelatedAction(params, context, outputFormat = 'text') {
const { commandNameFromContext, /* other context vars */ } = context;
let aiServiceResponse = null;
try {
aiServiceResponse = await generateObjectService({
// ... other parameters for AI service ...
commandName: commandNameFromContext || 'default-action-name',
outputType: context.mcpLog ? 'mcp' : 'cli' // Derive outputType
});
const usefulAiOutput = aiServiceResponse.mainResult.object;
// ... do work with usefulAiOutput ...
if (outputFormat === 'text' && aiServiceResponse.telemetryData) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
return {
actionData: /* results of processing */,
telemetryData: aiServiceResponse.telemetryData
};
} catch (error) {
// ... handle error ...
throw error;
}
}
```
### 2. Direct Function Wrappers (in `mcp-server/src/core/direct-functions/`)
These functions adapt core logic for the MCP server, ensuring structured responses.
- **Actions**:
1. Call the corresponding core logic function.
- Pass necessary context (e.g., `session`, `mcpLog`, `projectRoot`).
- Provide the `commandName` (typically derived from the MCP tool name) and `outputType: 'mcp'` in the context object passed to the core function.
- If the core function supports an `outputFormat` parameter, pass `'json'` to suppress CLI-specific UI.
2. The core logic function returns an object (e.g., `coreResult = { actionData: ..., telemetryData: ... }`).
3. Include `coreResult.telemetryData` as a field within the `data` object of the successful response returned by the direct function.
- **Example Snippet (Direct Function `someAiActionDirect.js`)**:
```javascript
import { performAiRelatedAction } from '../../../../scripts/modules/task-manager/someAiAction.js'; // Core function
import { createLogWrapper } from '../../tools/utils.js'; // MCP Log wrapper
export async function someAiActionDirect(args, log, context = {}) {
const { session } = context;
// ... prepare arguments for core function from args, including args.projectRoot ...
try {
const coreResult = await performAiRelatedAction(
{ /* parameters for core function */ },
{ // Context for core function
session,
mcpLog: createLogWrapper(log),
projectRoot: args.projectRoot,
commandNameFromContext: 'mcp_tool_some_ai_action', // Example command name
outputType: 'mcp'
},
'json' // Request 'json' output format from core function
);
return {
success: true,
data: {
operationSpecificData: coreResult.actionData,
telemetryData: coreResult.telemetryData // Pass telemetry through
}
};
} catch (error) {
// ... error handling, return { success: false, error: ... } ...
}
}
```
### 3. MCP Tools (in `mcp-server/src/tools/`)
These are the exposed endpoints for MCP clients.
- **Actions**:
1. Call the corresponding direct function wrapper.
2. The direct function returns an object structured like `{ success: true, data: { operationSpecificData: ..., telemetryData: ... } }` (or an error object).
3. Pass this entire result object to `handleApiResult(result, log)` from [`mcp-server/src/tools/utils.js`](mdc:mcp-server/src/tools/utils.js).
4. `handleApiResult` ensures that the `data` field from the direct function's response (which correctly includes `telemetryData`) is part of the final MCP response.
- **Example Snippet (MCP Tool `some_ai_action.js`)**:
```javascript
import { someAiActionDirect } from '../core/task-master-core.js';
import { handleApiResult, withNormalizedProjectRoot } from './utils.js';
// ... zod for parameters ...
export function registerSomeAiActionTool(server) {
server.addTool({
name: "some_ai_action",
// ... description, parameters ...
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
const resultFromDirectFunction = await someAiActionDirect(
{ /* args including projectRoot */ },
log,
{ session }
);
return handleApiResult(resultFromDirectFunction, log); // This passes the nested telemetryData through
} catch (error) {
// ... error handling ...
}
})
});
}
```
### 4. CLI Commands (`scripts/modules/commands.js`)
These define the command-line interface.
- **Actions**:
1. Call the appropriate core logic function.
2. Pass `outputFormat: 'text'` (or ensure the core function defaults to text-based output for CLI).
3. The core logic function (as per Section 1) is responsible for calling `displayAiUsageSummary` if telemetry data is available and it's in CLI mode.
4. The command action itself **should not** call `displayAiUsageSummary` if the core logic function already handles this. This avoids duplicate display.
- **Example Snippet (CLI Command in `commands.js`)**:
```javascript
// In scripts/modules/commands.js
import { performAiRelatedAction } from './task-manager/someAiAction.js'; // Core function
programInstance
.command('some-cli-ai-action')
// ... .option() ...
.action(async (options) => {
try {
const projectRoot = findProjectRoot() || '.'; // Example root finding
// ... prepare parameters for core function from command options ...
await performAiRelatedAction(
{ /* parameters for core function */ },
{ // Context for core function
projectRoot,
commandNameFromContext: 'some-cli-ai-action',
outputType: 'cli'
},
'text' // Explicitly request text output format for CLI
);
// Core function handles displayAiUsageSummary internally for 'text' outputFormat
} catch (error) {
// ... error handling ...
}
});
```
## Summary Flow
The telemetry data flows as follows:
1. **[`ai-services-unified.js`](mdc:scripts/modules/ai-services-unified.js)**: Generates `telemetryData` and returns `{ mainResult, telemetryData }`.
2. **Core Logic Function**:
* Receives `{ mainResult, telemetryData }`.
* Uses `mainResult`.
* If CLI (`outputFormat: 'text'`), calls `displayAiUsageSummary(telemetryData)`.
* Returns `{ operationSpecificData, telemetryData }`.
3. **Direct Function Wrapper**:
* Receives `{ operationSpecificData, telemetryData }` from core logic.
* Returns `{ success: true, data: { operationSpecificData, telemetryData } }`.
4. **MCP Tool**:
* Receives direct function response.
* `handleApiResult` ensures the final MCP response to the client is `{ success: true, data: { operationSpecificData, telemetryData } }`.
5. **CLI Command**:
* Calls core logic with `outputFormat: 'text'`. Display is handled by core logic.
This pattern ensures telemetry is captured and appropriately handled/exposed across all interaction modes.

View File

@@ -7,3 +7,9 @@ MISTRAL_API_KEY=YOUR_MISTRAL_KEY_HERE
OPENROUTER_API_KEY=YOUR_OPENROUTER_KEY_HERE
XAI_API_KEY=YOUR_XAI_KEY_HERE
AZURE_OPENAI_API_KEY=YOUR_AZURE_KEY_HERE
# Google Vertex AI Configuration
VERTEX_PROJECT_ID=your-gcp-project-id
VERTEX_LOCATION=us-central1
# Optional: Path to service account credentials JSON file (alternative to API key)
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json

62
.github/workflows/pre-release.yml vendored Normal file
View File

@@ -0,0 +1,62 @@
name: Pre-Release (RC)
on:
workflow_dispatch: # Allows manual triggering from GitHub UI/API
concurrency: pre-release-${{ github.ref }}
jobs:
rc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Cache node_modules
uses: actions/cache@v4
with:
path: |
node_modules
*/*/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install dependencies
run: npm ci
timeout-minutes: 2
- name: Enter RC mode
run: |
npx changeset pre exit || true
npx changeset pre enter rc
- name: Version RC packages
run: npx changeset version
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create Release Candidate Pull Request or Publish Release Candidate to npm
uses: changesets/action@v1
with:
publish: npm run release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Exit RC mode
run: npx changeset pre exit
- name: Commit & Push changes
uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref }}
message: 'chore: rc version bump'

View File

@@ -33,6 +33,9 @@ jobs:
run: npm ci
timeout-minutes: 2
- name: Exit pre-release mode (safety check)
run: npx changeset pre exit || true
- name: Create Release Pull Request or Publish to npm
uses: changesets/action@v1
with:

40
.github/workflows/update-models-md.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: Update models.md from supported-models.json
on:
push:
branches:
- main
- next
paths:
- 'scripts/modules/supported-models.json'
- 'docs/scripts/models-json-to-markdown.js'
jobs:
update_markdown:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Run transformation script
run: node docs/scripts/models-json-to-markdown.js
- name: Format Markdown with Prettier
run: npx prettier --write docs/models.md
- name: Stage docs/models.md
run: git add docs/models.md
- name: Commit & Push docs/models.md
uses: actions-js/push@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref_name }}
message: 'docs: Auto-update and format models.md'
author_name: 'github-actions[bot]'
author_email: 'github-actions[bot]@users.noreply.github.com'

3
.gitignore vendored
View File

@@ -61,3 +61,6 @@ dist
*.debug
init-debug.log
dev-debug.log
# NPMRC
.npmrc

View File

@@ -2,8 +2,8 @@
"models": {
"main": {
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 100000,
"modelId": "claude-sonnet-4-20250514",
"maxTokens": 50000,
"temperature": 0.2
},
"research": {
@@ -15,7 +15,7 @@
"fallback": {
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 120000,
"maxTokens": 128000,
"temperature": 0.2
}
},
@@ -25,7 +25,8 @@
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Taskmaster",
"ollamaBaseUrl": "http://localhost:11434/api",
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
"ollamaBaseURL": "http://localhost:11434/api",
"userId": "1234567890",
"azureBaseURL": "https://your-endpoint.azure.com/"
}
}

View File

@@ -1,5 +1,371 @@
# task-master-ai
## 0.15.0
### Minor Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
- **Robust Error Handling**:
- Detects when Ollama server is not running and provides clear error messages
- Validates model existence and lists available alternatives when model not found
- Graceful fallback behavior for connection issues
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
- Added Mistral models: Devstral Small, Mistral Nemo
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
- Updated Gemini model to latest 2.5 Flash preview version
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
- Research current technologies and best practices relevant to the project
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
- Include specific library recommendations with version numbers
- Provide more detailed implementation guidance based on industry standards
- Create more accurate dependency relationships between tasks
This results in higher quality, more actionable tasks with minimal additional effort.
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
Status: DONE
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
**Usage:**
- CLI command: `task-master move --from=<id> --to=<id>`
- MCP tool: `move_task` with parameters:
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
- `to`: ID of destination (e.g., "7" or "7.3")
- `file` (optional): Custom path to tasks.json
**Example scenarios:**
- Move task to become subtask: `--from="5" --to="7"`
- Move subtask to standalone task: `--from="5.2" --to="7"`
- Move subtask to different parent: `--from="5.2" --to="7.3"`
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
**Multiple Task Support:**
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
**Validation Features:**
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- Ensures proper parent-child relationships are maintained
### Patch Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
## 0.15.0-rc.0
### Minor Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`09add37`](https://github.com/eyaltoledano/claude-task-master/commit/09add37423d70b809d5c28f3cde9fccd5a7e64e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Added comprehensive Ollama model validation and interactive setup support
- **Interactive Setup Enhancement**: Added "Custom Ollama model" option to `task-master models --setup`, matching the existing OpenRouter functionality
- **Live Model Validation**: When setting Ollama models, Taskmaster now validates against the local Ollama instance by querying `/api/tags` endpoint
- **Configurable Endpoints**: Uses the `ollamaBaseUrl` from `.taskmasterconfig` (with role-specific `baseUrl` overrides supported)
- **Robust Error Handling**:
- Detects when Ollama server is not running and provides clear error messages
- Validates model existence and lists available alternatives when model not found
- Graceful fallback behavior for connection issues
- **Full Platform Support**: Both MCP server tools and CLI commands support the new validation
- **Improved User Experience**: Clear feedback during model validation with informative success/error messages
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`4c83526`](https://github.com/eyaltoledano/claude-task-master/commit/4c835264ac6c1f74896cddabc3b3c69a5c435417) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds and updates supported AI models with costs:
- Added new OpenRouter models: GPT-4.1 series, O3, Codex Mini, Llama 4 Maverick, Llama 4 Scout, Qwen3-235b
- Added Mistral models: Devstral Small, Mistral Nemo
- Updated Ollama models with latest variants: Devstral, Qwen3, Mistral-small3.1, Llama3.3
- Updated Gemini model to latest 2.5 Flash preview version
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`70f4054`](https://github.com/eyaltoledano/claude-task-master/commit/70f4054f268f9f8257870e64c24070263d4e2966) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--research` flag to parse-prd command, enabling enhanced task generation from PRD files. When used, Taskmaster leverages the research model to:
- Research current technologies and best practices relevant to the project
- Identify technical challenges and security concerns not explicitly mentioned in the PRD
- Include specific library recommendations with version numbers
- Provide more detailed implementation guidance based on industry standards
- Create more accurate dependency relationships between tasks
This results in higher quality, more actionable tasks with minimal additional effort.
_NOTE_ That this is an experimental feature. Research models don't typically do great at structured output. You may find some failures when using research mode, so please share your feedback so we can improve this.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`5e9bc28`](https://github.com/eyaltoledano/claude-task-master/commit/5e9bc28abea36ec7cd25489af7fcc6cbea51038b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - This change significantly enhances the `add-task` command's intelligence. When you add a new task, Taskmaster now automatically: - Analyzes your existing tasks to find those most relevant to your new task's description. - Provides the AI with detailed context from these relevant tasks.
This results in newly created tasks being more accurately placed within your project's dependency structure, saving you time and any need to update tasks just for dependencies, all without significantly increasing AI costs. You'll get smarter, more connected tasks right from the start.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34c769b`](https://github.com/eyaltoledano/claude-task-master/commit/34c769bcd0faf65ddec3b95de2ba152a8be3ec5c) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Enhance analyze-complexity to support analyzing specific task IDs. - You can now analyze individual tasks or selected task groups by using the new `--id` option with comma-separated IDs, or `--from` and `--to` options to specify a range of tasks. - The feature intelligently merges analysis results with existing reports, allowing incremental analysis while preserving previous results.
- [#558](https://github.com/eyaltoledano/claude-task-master/pull/558) [`86d8f00`](https://github.com/eyaltoledano/claude-task-master/commit/86d8f00af809887ee0ba0ba7157cc555e0d07c38) Thanks [@ShreyPaharia](https://github.com/ShreyPaharia)! - Add next task to set task status response
Status: DONE
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`04af16d`](https://github.com/eyaltoledano/claude-task-master/commit/04af16de27295452e134b17b3c7d0f44bbb84c29) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add move command to enable moving tasks and subtasks within the task hierarchy. This new command supports moving standalone tasks to become subtasks, subtasks to become standalone tasks, and moving subtasks between different parents. The implementation handles circular dependencies, validation, and proper updating of parent-child relationships.
**Usage:**
- CLI command: `task-master move --from=<id> --to=<id>`
- MCP tool: `move_task` with parameters:
- `from`: ID of task/subtask to move (e.g., "5" or "5.2")
- `to`: ID of destination (e.g., "7" or "7.3")
- `file` (optional): Custom path to tasks.json
**Example scenarios:**
- Move task to become subtask: `--from="5" --to="7"`
- Move subtask to standalone task: `--from="5.2" --to="7"`
- Move subtask to different parent: `--from="5.2" --to="7.3"`
- Reorder subtask within same parent: `--from="5.2" --to="5.4"`
- Move multiple tasks at once: `--from="10,11,12" --to="16,17,18"`
- Move task to new ID: `--from="5" --to="25"` (creates a new task with ID 25)
**Multiple Task Support:**
The command supports moving multiple tasks simultaneously by providing comma-separated lists for both `--from` and `--to` parameters. The number of source and destination IDs must match. This is particularly useful for resolving merge conflicts in task files when multiple team members have created tasks on different branches.
**Validation Features:**
- Allows moving tasks to new, non-existent IDs (automatically creates placeholders)
- Prevents moving to existing task IDs that already contain content (to avoid overwriting)
- Validates source tasks exist before attempting to move them
- Ensures proper parent-child relationships are maintained
### Patch Changes
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`231e569`](https://github.com/eyaltoledano/claude-task-master/commit/231e569e84804a2e5ba1f9da1a985d0851b7e949) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adjusts default main model model to Claude Sonnet 4. Adjusts default fallback to Claude Sonney 3.7"
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`b371808`](https://github.com/eyaltoledano/claude-task-master/commit/b371808524f2c2986f4940d78fcef32c125d01f2) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds llms-install.md to the root to enable AI agents to programmatically install the Taskmaster MCP server. This is specifically being introduced for the Cline MCP marketplace and will be adjusted over time for other MCP clients as needed.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`a59dd03`](https://github.com/eyaltoledano/claude-task-master/commit/a59dd037cfebb46d38bc44dd216c7c23933be641) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds AGENTS.md to power Claude Code integration more natively based on Anthropic's best practice and Claude-specific MCP client behaviours. Also adds in advanced workflows that tie Taskmaster commands together into one Claude workflow."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`e0e1155`](https://github.com/eyaltoledano/claude-task-master/commit/e0e115526089bf41d5d60929956edf5601ff3e23) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes issue with force/append flag combinations for parse-prd.
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`34df2c8`](https://github.com/eyaltoledano/claude-task-master/commit/34df2c8bbddc0e157c981d32502bbe6b9468202e) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - You can now add tasks to a newly initialized project without having to parse a prd. This will automatically create the missing tasks.json file and create the first task. Lets you vibe if you want to vibe."
- [#567](https://github.com/eyaltoledano/claude-task-master/pull/567) [`d2e6431`](https://github.com/eyaltoledano/claude-task-master/commit/d2e64318e2f4bfc3457792e310cc4ff9210bba30) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue where the research fallback would attempt to make API calls without checking for a valid API key first. This ensures proper error handling when the main task generation and first fallback both fail. Closes #421 #519.
## 0.14.0
### Minor Changes
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
- You can now add it by running `task-master models --setup` and selecting it.
- Ollama is a local model provider, so no API key is required.
- Ollama models are available at `http://localhost:11434/api` by default.
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
### Patch Changes
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Resolve all issues related to MCP
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
- Fixes #477
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
- [#402](https://github.com/eyaltoledano/claude-task-master/pull/402) [`01963af`](https://github.com/eyaltoledano/claude-task-master/commit/01963af2cb6f77f43b2ad8a6e4a838ec205412bc) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add src directory to exports
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
- Fixes issues users where having where they were getting stale data
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
- Closes #419
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
- Ensures a clean, branded help experience with no repeated content.
- Fixes #339
## 0.14.0-rc.1
### Minor Changes
- [#536](https://github.com/eyaltoledano/claude-task-master/pull/536) [`f4a83ec`](https://github.com/eyaltoledano/claude-task-master/commit/f4a83ec047b057196833e3a9b861d4bceaec805d) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Add Ollama as a supported AI provider.
- You can now add it by running `task-master models --setup` and selecting it.
- Ollama is a local model provider, so no API key is required.
- Ollama models are available at `http://localhost:11434/api` by default.
- You can change the default URL by setting the `OLLAMA_BASE_URL` environment variable or by adding a `baseUrl` property to the `ollama` model role in `.taskmasterconfig`.
- If you want to use a custom API key, you can set it in the `OLLAMA_API_KEY` environment variable.
### Patch Changes
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`2b3ae8b`](https://github.com/eyaltoledano/claude-task-master/commit/2b3ae8bf89dc471c4ce92f3a12ded57f61faa449) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds costs information to AI commands using input/output tokens and model costs.
- [#442](https://github.com/eyaltoledano/claude-task-master/pull/442) [`0288311`](https://github.com/eyaltoledano/claude-task-master/commit/0288311965ae2a343ebee4a0c710dde94d2ae7e7) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Small fixes - `next` command no longer incorrectly suggests that subtasks be broken down into subtasks in the CLI - fixes the `append` flag so it properly works in the CLI
## 0.14.0-rc.0
### Minor Changes
- [#521](https://github.com/eyaltoledano/claude-task-master/pull/521) [`ed17cb0`](https://github.com/eyaltoledano/claude-task-master/commit/ed17cb0e0a04dedde6c616f68f24f3660f68dd04) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - .taskmasterconfig now supports a baseUrl field per model role (main, research, fallback), allowing endpoint overrides for any provider.
- [#528](https://github.com/eyaltoledano/claude-task-master/pull/528) [`58b417a`](https://github.com/eyaltoledano/claude-task-master/commit/58b417a8ce697e655f749ca4d759b1c20014c523) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Display task complexity scores in task lists, next task, and task details views.
### Patch Changes
- [#478](https://github.com/eyaltoledano/claude-task-master/pull/478) [`4117f71`](https://github.com/eyaltoledano/claude-task-master/commit/4117f71c18ee4d321a9c91308d00d5d69bfac61e) Thanks [@joedanz](https://github.com/joedanz)! - Fix CLI --force flag for parse-prd command
Previously, the --force flag was not respected when running `parse-prd`, causing the command to prompt for confirmation or fail even when --force was provided. This patch ensures that the flag is correctly passed and handled, allowing users to overwrite existing tasks.json files as intended.
- Fixes #477
- [#511](https://github.com/eyaltoledano/claude-task-master/pull/511) [`17294ff`](https://github.com/eyaltoledano/claude-task-master/commit/17294ff25918d64278674e558698a1a9ad785098) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Task Master no longer tells you to update when you're already up to date
- [#523](https://github.com/eyaltoledano/claude-task-master/pull/523) [`da317f2`](https://github.com/eyaltoledano/claude-task-master/commit/da317f2607ca34db1be78c19954996f634c40923) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix the error handling of task status settings
- [#527](https://github.com/eyaltoledano/claude-task-master/pull/527) [`a8dabf4`](https://github.com/eyaltoledano/claude-task-master/commit/a8dabf44856713f488960224ee838761716bba26) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Remove caching layer from MCP direct functions for task listing, next task, and complexity report
- Fixes issues users where having where they were getting stale data
- [#417](https://github.com/eyaltoledano/claude-task-master/pull/417) [`a1f8d52`](https://github.com/eyaltoledano/claude-task-master/commit/a1f8d52474fdbdf48e17a63e3f567a6d63010d9f) Thanks [@ksylvan](https://github.com/ksylvan)! - Fix for issue #409 LOG_LEVEL Pydantic validation error
- [#501](https://github.com/eyaltoledano/claude-task-master/pull/501) [`0a61184`](https://github.com/eyaltoledano/claude-task-master/commit/0a611843b56a856ef0a479dc34078326e05ac3a8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix initial .env.example to work out of the box
- Closes #419
- [#435](https://github.com/eyaltoledano/claude-task-master/pull/435) [`a96215a`](https://github.com/eyaltoledano/claude-task-master/commit/a96215a359b25061fd3b3f3c7b10e8ac0390c062) Thanks [@lebsral](https://github.com/lebsral)! - Fix default fallback model and maxTokens in Taskmaster initialization
- [#517](https://github.com/eyaltoledano/claude-task-master/pull/517) [`e96734a`](https://github.com/eyaltoledano/claude-task-master/commit/e96734a6cc6fec7731de72eb46b182a6e3743d02) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix bug when updating tasks on the MCP server (#412)
- [#496](https://github.com/eyaltoledano/claude-task-master/pull/496) [`efce374`](https://github.com/eyaltoledano/claude-task-master/commit/efce37469bc58eceef46763ba32df1ed45242211) Thanks [@joedanz](https://github.com/joedanz)! - Fix duplicate output on CLI help screen
- Prevent the Task Master CLI from printing the help screen more than once when using `-h` or `--help`.
- Removed redundant manual event handlers and guards for help output; now only the Commander `.helpInformation` override is used for custom help.
- Simplified logic so that help is only shown once for both "no arguments" and help flag flows.
- Ensures a clean, branded help experience with no repeated content.
- Fixes #339
## 0.13.1
### Patch Changes
- [#399](https://github.com/eyaltoledano/claude-task-master/pull/399) [`734a4fd`](https://github.com/eyaltoledano/claude-task-master/commit/734a4fdcfc89c2e089255618cf940561ad13a3c8) Thanks [@Crunchyman-ralph](https://github.com/Crunchyman-ralph)! - Fix ERR_MODULE_NOT_FOUND when trying to run MCP Server
## 0.13.0
### Minor Changes
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ef782ff`](https://github.com/eyaltoledano/claude-task-master/commit/ef782ff5bd4ceb3ed0dc9ea82087aae5f79ac933) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - feat(expand): Enhance `expand` and `expand-all` commands
- Integrate `task-complexity-report.json` to automatically determine the number of subtasks and use tailored prompts for expansion based on prior analysis. You no longer need to try copy-pasting the recommended prompt. If it exists, it will use it for you. You can just run `task-master update --id=[id of task] --research` and it will use that prompt automatically. No extra prompt needed.
- Change default behavior to _append_ new subtasks to existing ones. Use the `--force` flag to clear existing subtasks before expanding. This is helpful if you need to add more subtasks to a task but you want to do it by the batch from a given prompt. Use force if you want to start fresh with a task's subtasks.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`87d97bb`](https://github.com/eyaltoledano/claude-task-master/commit/87d97bba00d84e905756d46ef96b2d5b984e0f38) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds support for the OpenRouter AI provider. Users can now configure models available through OpenRouter (requiring an `OPENROUTER_API_KEY`) via the `task-master models` command, granting access to a wide range of additional LLMs. - IMPORTANT FYI ABOUT OPENROUTER: Taskmaster relies on AI SDK, which itself relies on tool use. It looks like **free** models sometimes do not include tool use. For example, Gemini 2.5 pro (free) failed via OpenRouter (no tool use) but worked fine on the paid version of the model. Custom model support for Open Router is considered experimental and likely will not be further improved for some time.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`1ab836f`](https://github.com/eyaltoledano/claude-task-master/commit/1ab836f191cb8969153593a9a0bd47fc9aa4a831) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds model management and new configuration file .taskmasterconfig which houses the models used for main, research and fallback. Adds models command and setter flags. Adds a --setup flag with an interactive setup. We should be calling this during init. Shows a table of active and available models when models is called without flags. Includes SWE scores and token costs, which are manually entered into the supported_models.json, the new place where models are defined for support. Config-manager.js is the core module responsible for managing the new config."
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`c8722b0`](https://github.com/eyaltoledano/claude-task-master/commit/c8722b0a7a443a73b95d1bcd4a0b68e0fce2a1cd) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds custom model ID support for Ollama and OpenRouter providers.
- Adds the `--ollama` and `--openrouter` flags to `task-master models --set-<role>` command to set models for those providers outside of the support models list.
- Updated `task-master models --setup` interactive mode with options to explicitly enter custom Ollama or OpenRouter model IDs.
- Implemented live validation against OpenRouter API (`/api/v1/models`) when setting a custom OpenRouter model ID (via flag or setup).
- Refined logic to prioritize explicit provider flags/choices over internal model list lookups in case of ID conflicts.
- Added warnings when setting custom/unvalidated models.
- We obviously don't recommend going with a custom, unproven model. If you do and find performance is good, please let us know so we can add it to the list of supported models.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`2517bc1`](https://github.com/eyaltoledano/claude-task-master/commit/2517bc112c9a497110f3286ca4bfb4130c9addcb) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Integrate OpenAI as a new AI provider. - Enhance `models` command/tool to display API key status. - Implement model-specific `maxTokens` override based on `supported-models.json` to save you if you use an incorrect max token value.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`9a48278`](https://github.com/eyaltoledano/claude-task-master/commit/9a482789f7894f57f655fb8d30ba68542bd0df63) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Tweaks Perplexity AI calls for research mode to max out input tokens and get day-fresh information - Forces temp at 0.1 for highly deterministic output, no variations - Adds a system prompt to further improve the output - Correctly uses the maximum input tokens (8,719, used 8,700) for perplexity - Specificies to use a high degree of research across the web - Specifies to use information that is as fresh as today; this support stuff like capturing brand new announcements like new GPT models and being able to query for those in research. 🔥
### Patch Changes
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`842eaf7`](https://github.com/eyaltoledano/claude-task-master/commit/842eaf722498ddf7307800b4cdcef4ac4fd7e5b0) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - - Add support for Google Gemini models via Vercel AI SDK integration.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ed79d4f`](https://github.com/eyaltoledano/claude-task-master/commit/ed79d4f4735dfab4124fa189214c0bd5e23a6860) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add xAI provider and Grok models support
- [#378](https://github.com/eyaltoledano/claude-task-master/pull/378) [`ad89253`](https://github.com/eyaltoledano/claude-task-master/commit/ad89253e313a395637aa48b9f92cc39b1ef94ad8) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Better support for file paths on Windows, Linux & WSL.
- Standardizes handling of different path formats (URI encoded, Windows, Linux, WSL).
- Ensures tools receive a clean, absolute path suitable for the server OS.
- Simplifies tool implementation by centralizing normalization logic.
- [#285](https://github.com/eyaltoledano/claude-task-master/pull/285) [`2acba94`](https://github.com/eyaltoledano/claude-task-master/commit/2acba945c0afee9460d8af18814c87e80f747e9f) Thanks [@neno-is-ooo](https://github.com/neno-is-ooo)! - Add integration for Roo Code
- [#378](https://github.com/eyaltoledano/claude-task-master/pull/378) [`d63964a`](https://github.com/eyaltoledano/claude-task-master/commit/d63964a10eed9be17856757661ff817ad6bacfdc) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improved update-subtask - Now it has context about the parent task details - It also has context about the subtask before it and the subtask after it (if they exist) - Not passing all subtasks to stay token efficient
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`5f504fa`](https://github.com/eyaltoledano/claude-task-master/commit/5f504fafb8bdaa0043c2d20dee8bbb8ec2040d85) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improve and adjust `init` command for robustness and updated dependencies.
- **Update Initialization Dependencies:** Ensure newly initialized projects (`task-master init`) include all required AI SDK dependencies (`@ai-sdk/*`, `ai`, provider wrappers) in their `package.json` for out-of-the-box AI feature compatibility. Remove unnecessary dependencies (e.g., `uuid`) from the init template.
- **Silence `npm install` during `init`:** Prevent `npm install` output from interfering with non-interactive/MCP initialization by suppressing its stdio in silent mode.
- **Improve Conditional Model Setup:** Reliably skip interactive `models --setup` during non-interactive `init` runs (e.g., `init -y` or MCP) by checking `isSilentMode()` instead of passing flags.
- **Refactor `init.js`:** Remove internal `isInteractive` flag logic.
- **Update `init` Instructions:** Tweak the "Getting Started" text displayed after `init`.
- **Fix MCP Server Launch:** Update `.cursor/mcp.json` template to use `node ./mcp-server/server.js` instead of `npx task-master-mcp`.
- **Update Default Model:** Change the default main model in the `.taskmasterconfig` template.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`96aeeff`](https://github.com/eyaltoledano/claude-task-master/commit/96aeeffc195372722c6a07370540e235bfe0e4d8) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue with add-task which did not use the manually defined properties and still needlessly hit the AI endpoint.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`5aea93d`](https://github.com/eyaltoledano/claude-task-master/commit/5aea93d4c0490c242d7d7042a210611977848e0a) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Fixes an issue that prevented remove-subtask with comma separated tasks/subtasks from being deleted (only the first ID was being deleted). Closes #140
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`66ac9ab`](https://github.com/eyaltoledano/claude-task-master/commit/66ac9ab9f66d006da518d6e8a3244e708af2764d) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Improves next command to be subtask-aware - The logic for determining the "next task" (findNextTask function, used by task-master next and the next_task MCP tool) has been significantly improved. Previously, it only considered top-level tasks, making its recommendation less useful when a parent task containing subtasks was already marked 'in-progress'. - The updated logic now prioritizes finding the next available subtask within any 'in-progress' parent task, considering subtask dependencies and priority. - If no suitable subtask is found within active parent tasks, it falls back to recommending the next eligible top-level task based on the original criteria (status, dependencies, priority).
This change makes the next command much more relevant and helpful during the implementation phase of complex tasks.
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`ca7b045`](https://github.com/eyaltoledano/claude-task-master/commit/ca7b0457f1dc65fd9484e92527d9fd6d69db758d) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Add `--status` flag to `show` command to filter displayed subtasks.
- [#328](https://github.com/eyaltoledano/claude-task-master/pull/328) [`5a2371b`](https://github.com/eyaltoledano/claude-task-master/commit/5a2371b7cc0c76f5e95d43921c1e8cc8081bf14e) Thanks [@knoxgraeme](https://github.com/knoxgraeme)! - Fix --task to --num-tasks in ui + related tests - issue #324
- [#240](https://github.com/eyaltoledano/claude-task-master/pull/240) [`6cb213e`](https://github.com/eyaltoledano/claude-task-master/commit/6cb213ebbd51116ae0688e35b575d09443d17c3b) Thanks [@eyaltoledano](https://github.com/eyaltoledano)! - Adds a 'models' CLI and MCP command to get the current model configuration, available models, and gives the ability to set main/research/fallback models." - In the CLI, `task-master models` shows the current models config. Using the `--setup` flag launches an interactive set up that allows you to easily select the models you want to use for each of the three roles. Use `q` during the interactive setup to cancel the setup. - In the MCP, responses are simplified in RESTful format (instead of the full CLI output). The agent can use the `models` tool with different arguments, including `listAvailableModels` to get available models. Run without arguments, it will return the current configuration. Arguments are available to set the model for each of the three roles. This allows you to manage Taskmaster AI providers and models directly from either the CLI or MCP or both. - Updated the CLI help menu when you run `task-master` to include missing commands and .taskmasterconfig information. - Adds `--research` flag to `add-task` so you can hit up Perplexity right from the add-task flow, rather than having to add a task and then update it.
## 0.12.1
### Patch Changes

335
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,335 @@
# 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 14+
- 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.

104
README.md
View File

@@ -11,18 +11,39 @@ A task management system for AI-driven development with Claude, designed to work
## Requirements
Taskmaster utilizes AI across several commands, and those require a separate API key. You can use a variety of models from different AI providers provided you add your API keys. For example, if you want to use Claude 3.7, you'll need an Anthropic API key.
You can define 3 types of models to be used: the main model, the research model, and the fallback model (in case either the main or research fail). Whatever model you use, its provider API key must be present in either mcp.json or .env.
At least one (1) of the following is required:
- Anthropic API key (Claude API)
- OpenAI SDK (for Perplexity API integration, optional)
- OpenAI API key
- Google Gemini API key
- Perplexity API key (for research model)
- xAI API Key (for research or main model)
- OpenRouter API Key (for research or main model)
Using the research model is optional but highly recommended. You will need at least ONE API key. Adding all API keys enables you to seamlessly switch between model providers at will.
## Quick Start
### Option 1 | MCP (Recommended):
### Option 1: MCP (Recommended)
MCP (Model Control Protocol) provides the easiest way to get started with Task Master directly in your editor.
MCP (Model Control Protocol) lets you run Task Master directly from your editor.
1. **Add the MCP config to your editor** (Cursor recommended, but it works with other text editors):
#### 1. Add your MCP config at the following path depending on your editor
```json
| 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` |
| **VSCode** | Project | `<project_folder>/.vscode/mcp.json` | `<project_folder>\.vscode\mcp.json` | `servers` |
##### Cursor & Windsurf (`mcpServers`)
```jsonc
{
"mcpServers": {
"taskmaster-ai": {
@@ -36,30 +57,83 @@ MCP (Model Control Protocol) provides the easiest way to get started with Task M
"MISTRAL_API_KEY": "YOUR_MISTRAL_KEY_HERE",
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE"
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE",
"OLLAMA_API_KEY": "YOUR_OLLAMA_API_KEY_HERE"
}
}
}
}
```
2. **Enable the MCP** in your editor
> 🔑 Replace `YOUR_…_KEY_HERE` with your real API keys. You can remove keys you don't use.
3. **Prompt the AI** to initialize Task Master:
##### VSCode (`servers` + `type`)
```
Can you please initialize taskmaster-ai into my project?
```jsonc
{
"servers": {
"taskmaster-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"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",
"OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY_HERE",
"XAI_API_KEY": "YOUR_XAI_KEY_HERE",
"AZURE_OPENAI_API_KEY": "YOUR_AZURE_KEY_HERE"
},
"type": "stdio"
}
}
}
```
4. **Use common commands** directly through your AI assistant:
> 🔑 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 editors AI chat pane, say:
```txt
Can you parse my PRD at scripts/prd.txt?
What's the next task I should work on?
Can you help me implement task 3?
Can you help me expand task 4?
Change the main, research and fallback models to <model_name>, <model_name> and <model_name> respectively.
```
[Table of available models](docs/models.md)
#### 4. Initialize Task Master
In your editors AI chat pane, say:
```txt
Initialize taskmaster-ai in my project
```
#### 5. Make sure you have a PRD in `<project_folder>/scripts/prd.txt`
An example of a PRD is located into `<project_folder>/scripts/example_prd.txt`.
**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: `Whats the next task I should work on?`
- Implement a task: `Can you help me implement task 3?`
- Expand a task: `Can you help me expand task 4?`
[More examples on how to use Task Master in chat](docs/examples.md)
### Option 2: Using Command Line
#### Installation

View File

@@ -14,8 +14,8 @@
},
"fallback": {
"provider": "anthropic",
"modelId": "claude-3.5-sonnet-20240620",
"maxTokens": 120000,
"modelId": "claude-3-5-sonnet-20240620",
"maxTokens": 8192,
"temperature": 0.1
}
},
@@ -25,7 +25,7 @@
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Taskmaster",
"ollamaBaseUrl": "http://localhost:11434/api",
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
"ollamaBaseURL": "http://localhost:11434/api",
"azureOpenaiBaseURL": "https://your-endpoint.openai.azure.com/"
}
}

View File

@@ -198,7 +198,7 @@ alwaysApply: true
- **MAX_TOKENS** (Default: `"4000"`): Maximum tokens for responses (Example: `MAX_TOKENS=8000`)
- **TEMPERATURE** (Default: `"0.7"`): Temperature for model responses (Example: `TEMPERATURE=0.5`)
- **DEBUG** (Default: `"false"`): Enable debug logging (Example: `DEBUG=true`)
- **LOG_LEVEL** (Default: `"info"`): Console output level (Example: `LOG_LEVEL=debug`)
- **TASKMASTER_LOG_LEVEL** (Default: `"info"`): Console output level (Example: `TASKMASTER_LOG_LEVEL=debug`)
- **DEFAULT_SUBTASKS** (Default: `"3"`): Default subtask count (Example: `DEFAULT_SUBTASKS=5`)
- **DEFAULT_PRIORITY** (Default: `"medium"`): Default priority (Example: `DEFAULT_PRIORITY=high`)
- **PROJECT_NAME** (Default: `"MCP SaaS MVP"`): Project name in metadata (Example: `PROJECT_NAME=My Awesome Project`)

413
assets/AGENTS.md Normal file
View File

@@ -0,0 +1,413 @@
# Task Master AI - Claude Code Integration Guide
## Essential Commands
### Core Workflow Commands
```bash
# Project Setup
task-master init # Initialize Task Master in current project
task-master parse-prd scripts/prd.txt # Generate tasks from PRD document
task-master models --setup # Configure AI models interactively
# Daily Development Workflow
task-master list # Show all tasks with status
task-master next # Get next available task to work on
task-master show <id> # View detailed task information (e.g., task-master show 1.2)
task-master set-status --id=<id> --status=done # Mark task complete
# Task Management
task-master add-task --prompt="description" --research # Add new task with AI assistance
task-master expand --id=<id> --research --force # Break task into subtasks
task-master update-task --id=<id> --prompt="changes" # Update specific task
task-master update --from=<id> --prompt="changes" # Update multiple tasks from ID onwards
task-master update-subtask --id=<id> --prompt="notes" # Add implementation notes to subtask
# Analysis & Planning
task-master analyze-complexity --research # Analyze task complexity
task-master complexity-report # View complexity analysis
task-master expand --all --research # Expand all eligible tasks
# Dependencies & Organization
task-master add-dependency --id=<id> --depends-on=<id> # Add task dependency
task-master move --from=<id> --to=<id> # Reorganize task hierarchy
task-master validate-dependencies # Check for dependency issues
task-master generate # Update task markdown files (usually auto-called)
```
## Key Files & Project Structure
### Core Files
- `tasks/tasks.json` - Main task data file (auto-managed)
- `.taskmasterconfig` - AI model configuration (use `task-master models` to modify)
- `scripts/prd.txt` - Product Requirements Document for parsing
- `tasks/*.txt` - Individual task files (auto-generated from tasks.json)
- `.env` - API keys for CLI usage
### Claude Code Integration Files
- `CLAUDE.md` - Auto-loaded context for Claude Code (this file)
- `.claude/settings.json` - Claude Code tool allowlist and preferences
- `.claude/commands/` - Custom slash commands for repeated workflows
- `.mcp.json` - MCP server configuration (project-specific)
### Directory Structure
```
project/
├── tasks/
│ ├── tasks.json # Main task database
│ ├── task-1.md # Individual task files
│ └── task-2.md
├── scripts/
│ ├── prd.txt # Product requirements
│ └── task-complexity-report.json
├── .claude/
│ ├── settings.json # Claude Code configuration
│ └── commands/ # Custom slash commands
├── .taskmasterconfig # AI models & settings
├── .env # API keys
├── .mcp.json # MCP configuration
└── CLAUDE.md # This file - auto-loaded by Claude Code
```
## MCP Integration
Task Master provides an MCP server that Claude Code can connect to. Configure in `.mcp.json`:
```json
{
"mcpServers": {
"task-master-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "your_key_here",
"PERPLEXITY_API_KEY": "your_key_here",
"OPENAI_API_KEY": "OPENAI_API_KEY_HERE",
"GOOGLE_API_KEY": "GOOGLE_API_KEY_HERE",
"XAI_API_KEY": "XAI_API_KEY_HERE",
"OPENROUTER_API_KEY": "OPENROUTER_API_KEY_HERE",
"MISTRAL_API_KEY": "MISTRAL_API_KEY_HERE",
"AZURE_OPENAI_API_KEY": "AZURE_OPENAI_API_KEY_HERE",
"OLLAMA_API_KEY": "OLLAMA_API_KEY_HERE"
}
}
}
}
```
### Essential MCP Tools
```javascript
help; // = shows available taskmaster commands
// Project setup
initialize_project; // = task-master init
parse_prd; // = task-master parse-prd
// Daily workflow
get_tasks; // = task-master list
next_task; // = task-master next
get_task; // = task-master show <id>
set_task_status; // = task-master set-status
// Task management
add_task; // = task-master add-task
expand_task; // = task-master expand
update_task; // = task-master update-task
update_subtask; // = task-master update-subtask
update; // = task-master update
// Analysis
analyze_project_complexity; // = task-master analyze-complexity
complexity_report; // = task-master complexity-report
```
## Claude Code Workflow Integration
### Standard Development Workflow
#### 1. Project Initialization
```bash
# Initialize Task Master
task-master init
# Create or obtain PRD, then parse it
task-master parse-prd scripts/prd.txt
# Analyze complexity and expand tasks
task-master analyze-complexity --research
task-master expand --all --research
```
If tasks already exist, another PRD can be parsed (with new information only!) using parse-prd with --append flag. This will add the generated tasks to the existing list of tasks..
#### 2. Daily Development Loop
```bash
# Start each session
task-master next # Find next available task
task-master show <id> # Review task details
# During implementation, check in code context into the tasks and subtasks
task-master update-subtask --id=<id> --prompt="implementation notes..."
# Complete tasks
task-master set-status --id=<id> --status=done
```
#### 3. Multi-Claude Workflows
For complex projects, use multiple Claude Code sessions:
```bash
# Terminal 1: Main implementation
cd project && claude
# Terminal 2: Testing and validation
cd project-test-worktree && claude
# Terminal 3: Documentation updates
cd project-docs-worktree && claude
```
### Custom Slash Commands
Create `.claude/commands/taskmaster-next.md`:
```markdown
Find the next available Task Master task and show its details.
Steps:
1. Run `task-master next` to get the next task
2. If a task is available, run `task-master show <id>` for full details
3. Provide a summary of what needs to be implemented
4. Suggest the first implementation step
```
Create `.claude/commands/taskmaster-complete.md`:
```markdown
Complete a Task Master task: $ARGUMENTS
Steps:
1. Review the current task with `task-master show $ARGUMENTS`
2. Verify all implementation is complete
3. Run any tests related to this task
4. Mark as complete: `task-master set-status --id=$ARGUMENTS --status=done`
5. Show the next available task with `task-master next`
```
## Tool Allowlist Recommendations
Add to `.claude/settings.json`:
```json
{
"allowedTools": [
"Edit",
"Bash(task-master *)",
"Bash(git commit:*)",
"Bash(git add:*)",
"Bash(npm run *)",
"mcp__task_master_ai__*"
]
}
```
## Configuration & Setup
### API Keys Required
At least **one** of these API keys must be configured:
- `ANTHROPIC_API_KEY` (Claude models) - **Recommended**
- `PERPLEXITY_API_KEY` (Research features) - **Highly recommended**
- `OPENAI_API_KEY` (GPT models)
- `GOOGLE_API_KEY` (Gemini models)
- `MISTRAL_API_KEY` (Mistral models)
- `OPENROUTER_API_KEY` (Multiple models)
- `XAI_API_KEY` (Grok models)
An API key is required for any provider used across any of the 3 roles defined in the `models` command.
### Model Configuration
```bash
# Interactive setup (recommended)
task-master models --setup
# Set specific models
task-master models --set-main claude-3-5-sonnet-20241022
task-master models --set-research perplexity-llama-3.1-sonar-large-128k-online
task-master models --set-fallback gpt-4o-mini
```
## Task Structure & IDs
### Task ID Format
- Main tasks: `1`, `2`, `3`, etc.
- Subtasks: `1.1`, `1.2`, `2.1`, etc.
- Sub-subtasks: `1.1.1`, `1.1.2`, etc.
### Task Status Values
- `pending` - Ready to work on
- `in-progress` - Currently being worked on
- `done` - Completed and verified
- `deferred` - Postponed
- `cancelled` - No longer needed
- `blocked` - Waiting on external factors
### Task Fields
```json
{
"id": "1.2",
"title": "Implement user authentication",
"description": "Set up JWT-based auth system",
"status": "pending",
"priority": "high",
"dependencies": ["1.1"],
"details": "Use bcrypt for hashing, JWT for tokens...",
"testStrategy": "Unit tests for auth functions, integration tests for login flow",
"subtasks": []
}
```
## Claude Code Best Practices with Task Master
### Context Management
- Use `/clear` between different tasks to maintain focus
- This CLAUDE.md file is automatically loaded for context
- Use `task-master show <id>` to pull specific task context when needed
### Iterative Implementation
1. `task-master show <subtask-id>` - Understand requirements
2. Explore codebase and plan implementation
3. `task-master update-subtask --id=<id> --prompt="detailed plan"` - Log plan
4. `task-master set-status --id=<id> --status=in-progress` - Start work
5. Implement code following logged plan
6. `task-master update-subtask --id=<id> --prompt="what worked/didn't work"` - Log progress
7. `task-master set-status --id=<id> --status=done` - Complete task
### Complex Workflows with Checklists
For large migrations or multi-step processes:
1. Create a markdown PRD file describing the new changes: `touch task-migration-checklist.md` (prds can be .txt or .md)
2. Use Taskmaster to parse the new prd with `task-master parse-prd --append` (also available in MCP)
3. Use Taskmaster to expand the newly generated tasks into subtasks. Consdier using `analyze-complexity` with the correct --to and --from IDs (the new ids) to identify the ideal subtask amounts for each task. Then expand them.
4. Work through items systematically, checking them off as completed
5. Use `task-master update-subtask` to log progress on each task/subtask and/or updating/researching them before/during implementation if getting stuck
### Git Integration
Task Master works well with `gh` CLI:
```bash
# Create PR for completed task
gh pr create --title "Complete task 1.2: User authentication" --body "Implements JWT auth system as specified in task 1.2"
# Reference task in commits
git commit -m "feat: implement JWT auth (task 1.2)"
```
### Parallel Development with Git Worktrees
```bash
# Create worktrees for parallel task development
git worktree add ../project-auth feature/auth-system
git worktree add ../project-api feature/api-refactor
# Run Claude Code in each worktree
cd ../project-auth && claude # Terminal 1: Auth work
cd ../project-api && claude # Terminal 2: API work
```
## Troubleshooting
### AI Commands Failing
```bash
# Check API keys are configured
cat .env # For CLI usage
# Verify model configuration
task-master models
# Test with different model
task-master models --set-fallback gpt-4o-mini
```
### MCP Connection Issues
- Check `.mcp.json` configuration
- Verify Node.js installation
- Use `--mcp-debug` flag when starting Claude Code
- Use CLI as fallback if MCP unavailable
### Task File Sync Issues
```bash
# Regenerate task files from tasks.json
task-master generate
# Fix dependency issues
task-master fix-dependencies
```
DO NOT RE-INITIALIZE. That will not do anything beyond re-adding the same Taskmaster core files.
## Important Notes
### AI-Powered Operations
These commands make AI calls and may take up to a minute:
- `parse_prd` / `task-master parse-prd`
- `analyze_project_complexity` / `task-master analyze-complexity`
- `expand_task` / `task-master expand`
- `expand_all` / `task-master expand --all`
- `add_task` / `task-master add-task`
- `update` / `task-master update`
- `update_task` / `task-master update-task`
- `update_subtask` / `task-master update-subtask`
### File Management
- Never manually edit `tasks.json` - use commands instead
- Never manually edit `.taskmasterconfig` - use `task-master models`
- Task markdown files in `tasks/` are auto-generated
- Run `task-master generate` after manual changes to tasks.json
### Claude Code Session Management
- Use `/clear` frequently to maintain focused context
- Create custom slash commands for repeated Task Master workflows
- Configure tool allowlist to streamline permissions
- Use headless mode for automation: `claude -p "task-master next"`
### Multi-Task Updates
- Use `update --from=<id>` to update multiple future tasks
- Use `update-task --id=<id>` for single task updates
- Use `update-subtask --id=<id>` for implementation logging
### Research Mode
- Add `--research` flag for research-based AI enhancement
- Requires a research model API key like Perplexity (`PERPLEXITY_API_KEY`) in environment
- Provides more informed task creation and updates
- Recommended for complex technical tasks
---
_This guide ensures Claude Code has immediate access to Task Master's essential functionality for agentic development workflows._

View File

@@ -1,8 +1,9 @@
# API Keys (Required to enable respective provider)
ANTHROPIC_API_KEY=your_anthropic_api_key_here # Required: Format: sk-ant-api03-...
PERPLEXITY_API_KEY=your_perplexity_api_key_here # Optional: Format: pplx-...
OPENAI_API_KEY=your_openai_api_key_here # Optional, for OpenAI/OpenRouter models. Format: sk-proj-...
GOOGLE_API_KEY=your_google_api_key_here # Optional, for Google Gemini models.
MISTRAL_API_KEY=your_mistral_key_here # Optional, for Mistral AI models.
XAI_API_KEY=YOUR_XAI_KEY_HERE # Optional, for xAI AI models.
AZURE_OPENAI_API_KEY=your_azure_key_here # Optional, for Azure OpenAI models (requires endpoint in .taskmasterconfig).
ANTHROPIC_API_KEY="your_anthropic_api_key_here" # Required: Format: sk-ant-api03-...
PERPLEXITY_API_KEY="your_perplexity_api_key_here" # Optional: Format: pplx-...
OPENAI_API_KEY="your_openai_api_key_here" # Optional, for OpenAI/OpenRouter models. Format: sk-proj-...
GOOGLE_API_KEY="your_google_api_key_here" # Optional, for Google Gemini models.
MISTRAL_API_KEY="your_mistral_key_here" # Optional, for Mistral AI models.
XAI_API_KEY="YOUR_XAI_KEY_HERE" # Optional, for xAI AI models.
AZURE_OPENAI_API_KEY="your_azure_key_here" # Optional, for Azure OpenAI models (requires endpoint in .taskmasterconfig).
OLLAMA_API_KEY="your_ollama_api_key_here" # Optional: For remote Ollama servers that require authentication.

View File

@@ -39,7 +39,7 @@
{
"slug": "debug",
"name": "Debug",
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mdode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
"roleDefinition": "You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution. When activated by another mode, your task is to meticulously analyze the provided debugging request (potentially referencing Taskmaster tasks, logs, or metrics), use diagnostic tools as instructed to investigate the issue, identify the root cause, and report your findings and recommended next steps back via `attempt_completion`. You focus solely on diagnostics within the scope defined by the delegated task.",
"customInstructions": "Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.",
"groups": [
"read",

View File

@@ -31,7 +31,7 @@ Task Master configuration is now managed through two primary methods:
- Create a `.env` file in your project root for CLI usage.
- See `assets/env.example` for required key names.
**Important:** Settings like `MODEL`, `MAX_TOKENS`, `TEMPERATURE`, `LOG_LEVEL`, etc., are **no longer set via `.env`**. Use `task-master models --setup` instead.
**Important:** Settings like `MODEL`, `MAX_TOKENS`, `TEMPERATURE`, `TASKMASTER_LOG_LEVEL`, etc., are **no longer set via `.env`**. Use `task-master models --setup` instead.
## How It Works
@@ -200,7 +200,7 @@ Notes:
## Logging
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
The script supports different logging levels controlled by the `TASKMASTER_LOG_LEVEL` environment variable:
- `debug`: Detailed information, typically useful for troubleshooting
- `info`: Confirmation that things are working as expected (default)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,368 @@
We want to refine how Task Master handles AI model token limits to be more precise, by:
1. Distinguishing between `maxInputTokens` and `maxOutputTokens` in the configuration.
2. Dynamically adjusting the `maxOutputTokens` for an API call based on the actual prompt length to stay within the model's total context window (or respecting separate input/output limits if the API and model support that).
3. Ensuring that `ai-services-unified.js` uses these more granular limits.
This is a good improvement for both cost control and preventing errors.
Here's a plan:
**Phase 1: Configuration and Core Logic Updates**
1. **Update `.taskmasterconfig` Structure:**
- I'll modify the `models` section in your `.taskmasterconfig`. For each role (`main`, `research`, `fallback`), `maxTokens` will be replaced with `maxInputTokens` and `maxOutputTokens`.
- We'll need to decide on reasonable default values for these new fields. We can look at the current `maxTokens` and the model's known limits to make an initial guess.
2. **Update `MODEL_MAP` in `ai-services-unified.js`:**
- This array already stores cost data. We need to ensure it also stores the _absolute_ maximum input and output tokens for each model listed (e.g., `model_max_input_tokens`, `model_max_output_tokens`). If these fields are not present, they will need to be added. The values in `.taskmasterconfig` will then represent user-defined operational limits, which should ideally be validated against these absolute maximums.
3. **Update `config-manager.js`:**
- Getter functions like `getParametersForRole` will be updated to fetch `maxInputTokens` and `maxOutputTokens` instead of the singular `maxTokens`.
- New getters might be needed if we want to access the model's absolute limits directly from `MODEL_MAP` via `config-manager.js`.
4. **Update `ai-services-unified.js` (`_unifiedServiceRunner`):**
- **Token Counting:** This is a crucial step. Before an API call, we need to estimate the token count of the combined `systemPrompt` and `userPrompt`.
- The Vercel AI SDK or the individual provider SDKs might offer utilities for this. For example, some SDKs expose a `tokenizer` or a way to count tokens for a given string.
- If a direct utility isn't available through the Vercel SDK for the specific provider, we might need to use a library like `tiktoken` for OpenAI/Anthropic models or investigate provider-specific tokenization. This could be complex as tokenization varies between models.
- For now, let's assume we can get a reasonable estimate.
- **Dynamic Output Token Calculation & Validation:**
- Retrieve `configured_max_input_tokens` and `configured_max_output_tokens` from `config-manager.js` for the current role.
- Retrieve `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
- Let `prompt_tokens = countTokens(systemPrompt + userPrompt)`.
- **Input Validation:** If `prompt_tokens > configured_max_input_tokens` OR `prompt_tokens > model_absolute_max_input_tokens`, throw an error. (We might also consider auto-truncation strategies in the future, but an error is safer to start).
- **Output Calculation:** The `max_tokens` parameter sent to the API (which typically refers to the _max number of tokens to generate_) should be `configured_max_output_tokens`. We also need to ensure this doesn't violate the model's absolute output limit.
- Some models have a _total_ context window (input + output). If this is the case for a model, the `max_tokens` parameter for the API call might need to be `min(configured_max_output_tokens, model_absolute_total_tokens - prompt_tokens)`. However, many modern APIs handle separate input and output limits, simplifying this. We'll aim to pass `configured_max_output_tokens` as the API's `max_tokens` parameter, assuming the input validation has passed.
- **API Call Parameter:** Update the `callParams` to use the correctly determined `max_tokens` for generation (which will be our `configured_max_output_tokens`).
**Phase 2: Error Handling and Refinements**
1. **Enhanced Error Handling:** Provide clear error messages if prompt tokens exceed input limits, or if API calls fail due to token issues despite our calculations.
2. **Validation:** Add validation (perhaps in `config-manager.js` or when `task-master models --setup` is run) to ensure `configured_max_input_tokens` and `configured_max_output_tokens` in `.taskmasterconfig` do not exceed the `model_absolute_max_input_tokens` and `model_absolute_max_output_tokens` from `MODEL_MAP`.
Let's start by inspecting `scripts/modules/config-manager.js` to see how parameters and `MODEL_MAP` are currently handled. This will inform the changes needed for `.taskmasterconfig` and `ai-services-unified.js`.
I will now read `scripts/modules/config-manager.js`.
Okay, I've reviewed `scripts/modules/config-manager.js`. Here's what I've gathered and how it impacts the plan:
- **`MODEL_MAP` Source:** `MODEL_MAP` is loaded from `supported-models.json`. This is excellent, as it means we can update the model capabilities (including new token limits) in a structured JSON file.
- **Configuration Loading:** `_loadAndValidateConfig` handles loading `.taskmasterconfig` and merging it with `DEFAULTS`.
- **Getters:** There are specific getters for `maxTokens` for each role (e.g., `getMainMaxTokens`). We will need to update these.
- **`getParametersForRole`:** This function already exists and is a good candidate for returning the new `maxInputTokens` and `maxOutputTokens`.
Here's the refined plan:
**Phase 1: Configuration and Data Structures**
1. **Update `supported-models.json`:**
- For each model entry in `supported-models.json`, we need to add `maxInputTokens` and `maxOutputTokens` fields. These should reflect the _absolute maximums_ for that specific model.
- Example entry change:
```json
// Before
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"context_window": 200000, // This might be total context
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"maxInputTokens": 190000, // Example
"maxOutputTokens": 8192, // Example, often smaller for generation
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
```
- I will need to find the official input/output token limits for the models currently in your `MODEL_MAP`. If you have this information handy, it would speed things up. Otherwise, I can make educated guesses or search for them.
2. **Update `.taskmasterconfig` (Defaults and User File):**
- In `scripts/modules/config-manager.js`, modify the `DEFAULTS` object. For each role (`main`, `research`, `fallback`), replace `maxTokens` with:
- `maxInputTokens`: A sensible default (e.g., a large portion of the model's capability, but user-configurable).
- `maxOutputTokens`: A sensible default for generation (e.g., 4096 or 8192).
- You will then need to manually update your existing `.taskmasterconfig` file to reflect this new structure. I can provide the snippet for you to paste.
3. **Update `config-manager.js`:**
- Modify `getParametersForRole(role, explicitRoot = null)`:
- It currently fetches `maxTokens` and `temperature`.
- Update it to fetch `maxInputTokens`, `maxOutputTokens`, and `temperature` from the loaded config for the given role.
- Remove the role-specific `getMaxTokens` functions (e.g., `getMainMaxTokens`, `getResearchMaxTokens`, `getFallbackMaxTokens`). The `getParametersForRole` will be the central way to get these.
- (Optional, for later validation) Consider adding a new function `getModelCapabilities(providerName, modelId)` that reads from `MODEL_MAP` to return the absolute `maxInputTokens` and `maxOutputTokens` for a given model. This would be useful for validating the user's settings in `.taskmasterconfig`.
**Phase 2: Core Logic in `ai-services-unified.js`**
1. **Token Counting (`_unifiedServiceRunner`):**
- This is the most complex part. We need a reliable way to count tokens for the prompts.
- **Strategy 1 (Ideal):** Leverage Vercel AI SDK. The SDK might provide a way to get a tokenizer for the active model or a utility function. We'll need to investigate its capabilities.
- **Strategy 2 (Fallback):** Use a library like `tiktoken` for models compatible with OpenAI's tokenization (many are, including some Anthropic models). For other models, we might need provider-specific tokenizers or make estimations (less ideal).
- **Initial Approach:** Let's try to find a Vercel AI SDK utility first. If not, we'll start with `tiktoken` as a common case and acknowledge that other models might need specific handling later.
- The function `_unifiedServiceRunner` will call this token counting utility:
```javascript
// Placeholder for token counting
function countTokens(text, modelId /* or providerName */) {
// ... implementation using SDK or library ...
// This is a simplification; actual tokenization is model-specific.
// For now, a rough estimate might be (text.length / 4) as a placeholder
// if a proper tokenizer isn't immediately available.
if (!text) return 0;
return Math.ceil(text.length / 3.5); // Very rough general estimate
}
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
```
2. **Dynamic Output Token Calculation & Validation (`_unifiedServiceRunner`):**
- Fetch parameters using the updated `getParametersForRole` from `config-manager.js`:
```javascript
const roleParams = getParametersForRole(
currentRole,
effectiveProjectRoot
);
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
```
- Fetch model's absolute limits from `MODEL_MAP` (we'll need a helper in `config-manager.js` or do it directly in `ai-services-unified.js` for now):
```javascript
// Simplified; ideally use a robust getter from config-manager
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
(m) => m.id === modelId
);
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
const modelAbsoluteMaxOutput =
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
```
- **Input Validation:**
```javascript
if (promptTokens > roleParams.maxInputTokens) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
);
}
if (promptTokens > modelAbsoluteMaxInput) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
);
}
```
- **API Call Parameter (`max_tokens` for generation):**
The `max_tokens` parameter passed to the provider's API call should be `roleParams.maxOutputTokens`. We must also ensure this doesn't exceed the model's absolute output capability.
```javascript
const apiMaxOutputTokens = Math.min(
roleParams.maxOutputTokens,
modelAbsoluteMaxOutput
);
const callParams = {
apiKey,
modelId,
// Use apiMaxOutputTokens for the actual API call
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
temperature: roleParams.temperature,
messages,
baseUrl,
...(serviceType === 'generateObject' && { schema, objectName }),
...restApiParams
};
```
3. **Update `logAiUsage`:**
- The cost calculation in `logAiUsage` seems correct as it already uses `inputCost` and `outputCost` per 1M tokens. This part should remain compatible.
**Next Steps:**
1. **Modify `supported-models.json`:** I need the content of this file to propose the new `maxInputTokens` and `maxOutputTokens` fields. Please provide it.
2. **Decide on Tokenizer Strategy:** What are your thoughts on the token counting? Are you aware of any utilities within Vercel AI SDK for this, or should we plan to integrate `tiktoken` initially?
Once I have the content of `supported-models.json`, I can draft the changes for it and then proceed to `config-manager.js` and `.taskmasterconfig`.
```json
// Before
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"context_window": 200000, // This might be total context
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
// After (assuming 200k is total, and we make a reasonable split or find official numbers)
{
"id": "claude-3-7-sonnet-20250219",
"name": "Claude 3.7 Sonnet (Preview)",
"maxInputTokens": 190000, // Example
"maxOutputTokens": 8192, // Example, often smaller for generation
"cost_per_1m_tokens": { "input": 3, "output": 15, "currency": "USD" }
}
```
```javascript
// Placeholder for token counting
function countTokens(text, modelId /* or providerName */) {
// ... implementation using SDK or library ...
// This is a simplification; actual tokenization is model-specific.
// For now, a rough estimate might be (text.length / 4) as a placeholder
// if a proper tokenizer isn't immediately available.
if (!text) return 0;
return Math.ceil(text.length / 3.5); // Very rough general estimate
}
const promptTokens = countTokens(systemPrompt) + countTokens(prompt);
```
```javascript
const roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
// roleParams will now contain { maxInputTokens, maxOutputTokens, temperature }
```
```javascript
// Simplified; ideally use a robust getter from config-manager
const modelInfo = MODEL_MAP[providerName?.toLowerCase()]?.find(
(m) => m.id === modelId
);
const modelAbsoluteMaxInput = modelInfo?.maxInputTokens || Infinity;
const modelAbsoluteMaxOutput =
modelInfo?.maxOutputTokens || roleParams.maxOutputTokens; // Fallback to configured if not in map
```
```javascript
if (promptTokens > roleParams.maxInputTokens) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds configured max input tokens (${roleParams.maxInputTokens}) for role '${currentRole}'.`
);
}
if (promptTokens > modelAbsoluteMaxInput) {
throw new Error(
`Prompt (${promptTokens} tokens) exceeds model's absolute max input tokens (${modelAbsoluteMaxInput}) for ${modelId}.`
);
}
```
```javascript
const apiMaxOutputTokens = Math.min(
roleParams.maxOutputTokens,
modelAbsoluteMaxOutput
);
const callParams = {
apiKey,
modelId,
// Use apiMaxOutputTokens for the actual API call
maxTokens: apiMaxOutputTokens, // This usually means max tokens to GENERATE
temperature: roleParams.temperature,
messages,
baseUrl,
...(serviceType === 'generateObject' && { schema, objectName }),
...restApiParams
};
```
Okay, I have the contents of `supported-models.json`.
It seems many models have a `max_tokens` field, which I assume is the _total context window_. Some don't have it, and for others (like OpenAI `gpt-4o`), the listed `max_tokens` (16384) is known to be its _output_ token limit when using the Chat Completions API, while the context window is much larger (128k). This highlights the complexity: `max_tokens` in `supported-models.json` is used inconsistently.
**Revised Plan for `supported-models.json` and Token Definitions:**
To bring clarity, we'll introduce two new fields and ensure their meaning is consistent:
- `contextWindowTokens`: The total number of tokens the model can process (input + output). This would replace the current ambiguous `max_tokens`.
- `maxOutputTokens`: The maximum number of tokens the model can _generate_ in a single response. This is often smaller than the total context window, especially for larger models.
If a model _only_ specifies a total context window, we'll have to make a reasonable assumption for `maxOutputTokens` (e.g., 4096 or 8192, or a fraction of the total context window). If it only specifies an output token limit (like some OpenAI models in certain API modes), we'll need to find its total context window.
**Updated `supported-models.json` Structure (Example):**
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```
I will proceed to generate the updated `supported-models.json` content. This will be a significant change. I will make my best effort to find the correct `contextWindowTokens` and `maxOutputTokens` for each model. If official numbers are ambiguous or not readily available, I'll use sensible defaults and add a comment.
**Regarding Tokenizer Strategy:**
- **Vercel AI SDK:** The `ai` package (Vercel AI SDK) itself is a lightweight wrapper. Tokenization is usually handled by the underlying provider-specific SDKs (e.g., `@anthropic-ai/sdk`, `openai`). The Vercel SDK doesn't provide a universal tokenizer.
- **Provider SDKs:**
- `@anthropic-ai/sdk`: Does not expose a public tokenizer directly. Anthropic recommends counting based on their guidelines (roughly 3.5 chars/token for English).
- `openai` (for Node.js): The `gpt-3-encoder` or `tiktoken` libraries are commonly used. `tiktoken` is more current.
- **`tiktoken`:** This is a good general-purpose library for OpenAI models and those that use compatible tokenization (many models fine-tuned from Llama, etc., might be close). It supports various encodings.
- **Recommendation:**
1. Start by integrating `tiktoken`. We can select the encoding based on the provider or even specific model if needed (e.g., `cl100k_base` for gpt-4, gpt-3.5-turbo, DALL-E models).
2. For providers where `tiktoken` is not accurate (e.g., Google's Gemini, Perplexity if they have proprietary tokenizers), we might have to rely on character-based estimations (e.g., `length / N`) as a rougher guide or investigate if their specific SDKs offer token counting.
3. The Vercel AI SDK's `experimental_streamObject` and other functions _might_ internally handle some aspects of token counting for request preparation, but we need explicit counting for our logic _before_ the call.
For now, let's assume we'll add a `countTokens` utility that uses `tiktoken` for OpenAI and Anthropic (as Anthropic's guidance is character-based but `cl100k_base` is often a decent proxy for their tokenization for rough estimates, though not perfect), and a character-based fallback for others.
I will now generate the proposed changes for `scripts/modules/supported-models.json`. This will be a large diff.
After this, we'll move to:
1. Updating `.taskmasterconfig` defaults in `config-manager.js` and providing you the snippet for your user file.
2. Updating `config-manager.js` getters.
3. Implementing the logic in `ai-services-unified.js`.
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```
```json
// For a model like Anthropic Claude 3.7 Sonnet (Preview)
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 200000, // From Anthropic's documentation
"maxOutputTokens": 8192 // Anthropic default, user can override in .taskmasterconfig
}
// For a model like OpenAI GPT-4o
{
"id": "gpt-4o",
"swe_score": 0.332,
"cost_per_1m_tokens": { "input": 2.5, "output": 10.0 },
"allowed_roles": ["main", "fallback"],
"contextWindowTokens": 128000, // Official context window
"maxOutputTokens": 16384 // Max output for chat completions is 16k for gpt-4o (used to be 4k/8k for older gpt-4)
// but the model card mentions 128k total. The API call parameter for `max_tokens` sets this output cap.
}
```

View File

@@ -187,6 +187,32 @@ task-master validate-dependencies
task-master fix-dependencies
```
## Move Tasks
```bash
# Move a task or subtask to a new position
task-master move --from=<id> --to=<id>
# Examples:
# Move task to become a subtask
task-master move --from=5 --to=7
# Move subtask to become a standalone task
task-master move --from=5.2 --to=7
# Move subtask to a different parent
task-master move --from=5.2 --to=7.3
# Reorder subtasks within the same parent
task-master move --from=5.2 --to=5.4
# Move a task to a new ID position (creates placeholder if doesn't exist)
task-master move --from=5 --to=25
# Move multiple tasks at once (must have the same number of IDs)
task-master move --from=10,11,12 --to=16,17,18
```
## Add a New Task
```bash

View File

@@ -15,13 +15,15 @@ Taskmaster uses two primary methods for configuration:
"provider": "anthropic",
"modelId": "claude-3-7-sonnet-20250219",
"maxTokens": 64000,
"temperature": 0.2
"temperature": 0.2,
"baseURL": "https://api.anthropic.com/v1"
},
"research": {
"provider": "perplexity",
"modelId": "sonar-pro",
"maxTokens": 8700,
"temperature": 0.1
"temperature": 0.1,
"baseURL": "https://api.perplexity.ai/v1"
},
"fallback": {
"provider": "anthropic",
@@ -36,8 +38,10 @@ Taskmaster uses two primary methods for configuration:
"defaultSubtasks": 5,
"defaultPriority": "medium",
"projectName": "Your Project Name",
"ollamaBaseUrl": "http://localhost:11434/api",
"azureOpenaiBaseUrl": "https://your-endpoint.openai.azure.com/"
"ollamaBaseURL": "http://localhost:11434/api",
"azureBaseURL": "https://your-endpoint.azure.com/",
"vertexProjectId": "your-gcp-project-id",
"vertexLocation": "us-central1"
}
}
```
@@ -51,14 +55,18 @@ Taskmaster uses two primary methods for configuration:
- `ANTHROPIC_API_KEY`: Your Anthropic API key.
- `PERPLEXITY_API_KEY`: Your Perplexity API key.
- `OPENAI_API_KEY`: Your OpenAI API key.
- `GOOGLE_API_KEY`: Your Google API key.
- `GOOGLE_API_KEY`: Your Google API key (also used for Vertex AI provider).
- `MISTRAL_API_KEY`: Your Mistral API key.
- `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key (also requires `AZURE_OPENAI_ENDPOINT`).
- `OPENROUTER_API_KEY`: Your OpenRouter API key.
- `XAI_API_KEY`: Your X-AI API key.
- **Optional Endpoint Overrides (in .taskmasterconfig):**
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key.
- **Optional Endpoint Overrides:**
- **Per-role `baseURL` in `.taskmasterconfig`:** You can add a `baseURL` property to any model role (`main`, `research`, `fallback`) to override the default API endpoint for that provider. If omitted, the provider's standard endpoint is used.
- `AZURE_OPENAI_ENDPOINT`: Required if using Azure OpenAI key (can also be set as `baseURL` for the Azure model role).
- `OLLAMA_BASE_URL`: Override the default Ollama API URL (Default: `http://localhost:11434/api`).
- `VERTEX_PROJECT_ID`: Your Google Cloud project ID for Vertex AI. Required when using the 'vertex' provider.
- `VERTEX_LOCATION`: Google Cloud region for Vertex AI (e.g., 'us-central1'). Default is 'us-central1'.
- `GOOGLE_APPLICATION_CREDENTIALS`: Path to service account credentials JSON file for Google Cloud auth (alternative to API key for Vertex AI).
**Important:** Settings like model ID selections (`main`, `research`, `fallback`), `maxTokens`, `temperature`, `logLevel`, `defaultSubtasks`, `defaultPriority`, and `projectName` are **managed in `.taskmasterconfig`**, not environment variables.
@@ -75,6 +83,11 @@ PERPLEXITY_API_KEY=pplx-your-key-here
# Optional Endpoint Overrides
# AZURE_OPENAI_ENDPOINT=https://your-azure-endpoint.openai.azure.com/
# OLLAMA_BASE_URL=http://custom-ollama-host:11434/api
# Google Vertex AI Configuration (Required if using 'vertex' provider)
# VERTEX_PROJECT_ID=your-gcp-project-id
# VERTEX_LOCATION=us-central1
# GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json
```
## Troubleshooting
@@ -99,3 +112,45 @@ git clone https://github.com/eyaltoledano/claude-task-master.git
cd claude-task-master
node scripts/init.js
```
## Provider-Specific Configuration
### Google Vertex AI Configuration
Google Vertex AI is Google Cloud's enterprise AI platform and requires specific configuration:
1. **Prerequisites**:
- A Google Cloud account with Vertex AI API enabled
- Either a Google API key with Vertex AI permissions OR a service account with appropriate roles
- A Google Cloud project ID
2. **Authentication Options**:
- **API Key**: Set the `GOOGLE_API_KEY` environment variable
- **Service Account**: Set `GOOGLE_APPLICATION_CREDENTIALS` to point to your service account JSON file
3. **Required Configuration**:
- Set `VERTEX_PROJECT_ID` to your Google Cloud project ID
- Set `VERTEX_LOCATION` to your preferred Google Cloud region (default: us-central1)
4. **Example Setup**:
```bash
# In .env file
GOOGLE_API_KEY=AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXX
VERTEX_PROJECT_ID=my-gcp-project-123
VERTEX_LOCATION=us-central1
```
Or using service account:
```bash
# In .env file
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
VERTEX_PROJECT_ID=my-gcp-project-123
VERTEX_LOCATION=us-central1
```
5. **In .taskmasterconfig**:
```json
"global": {
"vertexProjectId": "my-gcp-project-123",
"vertexLocation": "us-central1"
}
```

View File

@@ -30,7 +30,7 @@ I need to regenerate the subtasks for task 3 with a different approach. Can you
## Handling changes
```
We've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
I've decided to use MongoDB instead of PostgreSQL. Can you update all future tasks to reflect this change?
```
## Completing work
@@ -40,6 +40,34 @@ I've finished implementing the authentication system described in task 2. All te
Please mark it as complete and tell me what I should work on next.
```
## Reorganizing tasks
```
I think subtask 5.2 would fit better as part of task 7. Can you move it there?
```
(Agent runs: `task-master move --from=5.2 --to=7.3`)
```
Task 8 should actually be a subtask of task 4. Can you reorganize this?
```
(Agent runs: `task-master move --from=8 --to=4.1`)
```
I just merged the main branch and there's a conflict in tasks.json. My teammates created tasks 10-15 on their branch while I created tasks 10-12 on my branch. Can you help me resolve this by moving my tasks?
```
(Agent runs:
```bash
task-master move --from=10 --to=16
task-master move --from=11 --to=17
task-master move --from=12 --to=18
```
)
## Analyzing complexity
```

125
docs/models.md Normal file
View File

@@ -0,0 +1,125 @@
# Available Models as of May 27, 2025
## Main Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | ---------------------------------------------- | --------- | ---------- | ----------- |
| anthropic | claude-sonnet-4-20250514 | 0.727 | 3 | 15 |
| anthropic | claude-opus-4-20250514 | 0.725 | 15 | 75 |
| anthropic | claude-3-7-sonnet-20250219 | 0.623 | 3 | 15 |
| anthropic | claude-3-5-sonnet-20241022 | 0.49 | 3 | 15 |
| openai | gpt-4o | 0.332 | 2.5 | 10 |
| openai | o1 | 0.489 | 15 | 60 |
| openai | o3 | 0.5 | 10 | 40 |
| openai | o3-mini | 0.493 | 1.1 | 4.4 |
| openai | o4-mini | 0.45 | 1.1 | 4.4 |
| openai | o1-mini | 0.4 | 1.1 | 4.4 |
| openai | o1-pro | — | 150 | 600 |
| openai | gpt-4-5-preview | 0.38 | 75 | 150 |
| openai | gpt-4-1-mini | — | 0.4 | 1.6 |
| openai | gpt-4-1-nano | — | 0.1 | 0.4 |
| openai | gpt-4o-mini | 0.3 | 0.15 | 0.6 |
| google | gemini-2.5-pro-preview-05-06 | 0.638 | — | — |
| google | gemini-2.5-pro-preview-03-25 | 0.638 | — | — |
| google | gemini-2.5-flash-preview-04-17 | — | — | — |
| google | gemini-2.0-flash | 0.754 | 0.15 | 0.6 |
| google | gemini-2.0-flash-lite | — | — | — |
| perplexity | sonar-reasoning-pro | 0.211 | 2 | 8 |
| perplexity | sonar-reasoning | 0.211 | 1 | 5 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
| ollama | devstral:latest | — | 0 | 0 |
| ollama | qwen3:latest | — | 0 | 0 |
| ollama | qwen3:14b | — | 0 | 0 |
| ollama | qwen3:32b | — | 0 | 0 |
| ollama | mistral-small3.1:latest | — | 0 | 0 |
| ollama | llama3.3:latest | — | 0 | 0 |
| ollama | phi4:latest | — | 0 | 0 |
| openrouter | google/gemini-2.5-flash-preview-05-20 | — | 0.15 | 0.6 |
| openrouter | google/gemini-2.5-flash-preview-05-20:thinking | — | 0.15 | 3.5 |
| openrouter | google/gemini-2.5-pro-exp-03-25 | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324:free | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324 | — | 0.27 | 1.1 |
| openrouter | openai/gpt-4.1 | — | 2 | 8 |
| openrouter | openai/gpt-4.1-mini | — | 0.4 | 1.6 |
| openrouter | openai/gpt-4.1-nano | — | 0.1 | 0.4 |
| openrouter | openai/o3 | — | 10 | 40 |
| openrouter | openai/codex-mini | — | 1.5 | 6 |
| openrouter | openai/gpt-4o-mini | — | 0.15 | 0.6 |
| openrouter | openai/o4-mini | 0.45 | 1.1 | 4.4 |
| openrouter | openai/o4-mini-high | — | 1.1 | 4.4 |
| openrouter | openai/o1-pro | — | 150 | 600 |
| openrouter | meta-llama/llama-3.3-70b-instruct | — | 120 | 600 |
| openrouter | meta-llama/llama-4-maverick | — | 0.18 | 0.6 |
| openrouter | meta-llama/llama-4-scout | — | 0.08 | 0.3 |
| openrouter | qwen/qwen-max | — | 1.6 | 6.4 |
| openrouter | qwen/qwen-turbo | — | 0.05 | 0.2 |
| openrouter | qwen/qwen3-235b-a22b | — | 0.14 | 2 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct:free | — | 0 | 0 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct | — | 0.1 | 0.3 |
| openrouter | mistralai/devstral-small | — | 0.1 | 0.3 |
| openrouter | mistralai/mistral-nemo | — | 0.03 | 0.07 |
| openrouter | thudm/glm-4-32b:free | — | 0 | 0 |
## Research Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | -------------------------- | --------- | ---------- | ----------- |
| openai | gpt-4o-search-preview | 0.33 | 2.5 | 10 |
| openai | gpt-4o-mini-search-preview | 0.3 | 0.15 | 0.6 |
| perplexity | sonar-pro | — | 3 | 15 |
| perplexity | sonar | — | 1 | 1 |
| perplexity | deep-research | 0.211 | 2 | 8 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
## Fallback Models
| Provider | Model Name | SWE Score | Input Cost | Output Cost |
| ---------- | ---------------------------------------------- | --------- | ---------- | ----------- |
| anthropic | claude-sonnet-4-20250514 | 0.727 | 3 | 15 |
| anthropic | claude-opus-4-20250514 | 0.725 | 15 | 75 |
| anthropic | claude-3-7-sonnet-20250219 | 0.623 | 3 | 15 |
| anthropic | claude-3-5-sonnet-20241022 | 0.49 | 3 | 15 |
| openai | gpt-4o | 0.332 | 2.5 | 10 |
| openai | o3 | 0.5 | 10 | 40 |
| openai | o4-mini | 0.45 | 1.1 | 4.4 |
| google | gemini-2.5-pro-preview-05-06 | 0.638 | — | — |
| google | gemini-2.5-pro-preview-03-25 | 0.638 | — | — |
| google | gemini-2.5-flash-preview-04-17 | — | — | — |
| google | gemini-2.0-flash | 0.754 | 0.15 | 0.6 |
| google | gemini-2.0-flash-lite | — | — | — |
| perplexity | sonar-reasoning-pro | 0.211 | 2 | 8 |
| perplexity | sonar-reasoning | 0.211 | 1 | 5 |
| xai | grok-3 | — | 3 | 15 |
| xai | grok-3-fast | — | 5 | 25 |
| ollama | devstral:latest | — | 0 | 0 |
| ollama | qwen3:latest | — | 0 | 0 |
| ollama | qwen3:14b | — | 0 | 0 |
| ollama | qwen3:32b | — | 0 | 0 |
| ollama | mistral-small3.1:latest | — | 0 | 0 |
| ollama | llama3.3:latest | — | 0 | 0 |
| ollama | phi4:latest | — | 0 | 0 |
| openrouter | google/gemini-2.5-flash-preview-05-20 | — | 0.15 | 0.6 |
| openrouter | google/gemini-2.5-flash-preview-05-20:thinking | — | 0.15 | 3.5 |
| openrouter | google/gemini-2.5-pro-exp-03-25 | — | 0 | 0 |
| openrouter | deepseek/deepseek-chat-v3-0324:free | — | 0 | 0 |
| openrouter | openai/gpt-4.1 | — | 2 | 8 |
| openrouter | openai/gpt-4.1-mini | — | 0.4 | 1.6 |
| openrouter | openai/gpt-4.1-nano | — | 0.1 | 0.4 |
| openrouter | openai/o3 | — | 10 | 40 |
| openrouter | openai/codex-mini | — | 1.5 | 6 |
| openrouter | openai/gpt-4o-mini | — | 0.15 | 0.6 |
| openrouter | openai/o4-mini | 0.45 | 1.1 | 4.4 |
| openrouter | openai/o4-mini-high | — | 1.1 | 4.4 |
| openrouter | openai/o1-pro | — | 150 | 600 |
| openrouter | meta-llama/llama-3.3-70b-instruct | — | 120 | 600 |
| openrouter | meta-llama/llama-4-maverick | — | 0.18 | 0.6 |
| openrouter | meta-llama/llama-4-scout | — | 0.08 | 0.3 |
| openrouter | qwen/qwen-max | — | 1.6 | 6.4 |
| openrouter | qwen/qwen-turbo | — | 0.05 | 0.2 |
| openrouter | qwen/qwen3-235b-a22b | — | 0.14 | 2 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct:free | — | 0 | 0 |
| openrouter | mistralai/mistral-small-3.1-24b-instruct | — | 0.1 | 0.3 |
| openrouter | mistralai/mistral-nemo | — | 0.03 | 0.07 |
| openrouter | thudm/glm-4-32b:free | — | 0 | 0 |

View File

@@ -0,0 +1,131 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const supportedModelsPath = path.join(
__dirname,
'..',
'modules',
'supported-models.json'
);
const outputMarkdownPath = path.join(
__dirname,
'..',
'..',
'docs',
'models.md'
);
function formatCost(cost) {
if (cost === null || cost === undefined) {
return '—';
}
return cost;
}
function formatSweScore(score) {
if (score === null || score === undefined || score === 0) {
return '—';
}
return score.toString();
}
function generateMarkdownTable(title, models) {
if (!models || models.length === 0) {
return `## ${title}\n\nNo models in this category.\n\n`;
}
let table = `## ${title}\n\n`;
table += '| Provider | Model Name | SWE Score | Input Cost | Output Cost |\n';
table += '|---|---|---|---|---|\n';
models.forEach((model) => {
table += `| ${model.provider} | ${model.modelName} | ${formatSweScore(model.sweScore)} | ${formatCost(model.inputCost)} | ${formatCost(model.outputCost)} |\n`;
});
table += '\n';
return table;
}
function main() {
try {
const correctSupportedModelsPath = path.join(
__dirname,
'..',
'..',
'scripts',
'modules',
'supported-models.json'
);
const correctOutputMarkdownPath = path.join(__dirname, '..', 'models.md');
const supportedModelsContent = fs.readFileSync(
correctSupportedModelsPath,
'utf8'
);
const supportedModels = JSON.parse(supportedModelsContent);
const mainModels = [];
const researchModels = [];
const fallbackModels = [];
for (const provider in supportedModels) {
if (Object.hasOwnProperty.call(supportedModels, provider)) {
const models = supportedModels[provider];
models.forEach((model) => {
const modelEntry = {
provider: provider,
modelName: model.id,
sweScore: model.swe_score,
inputCost: model.cost_per_1m_tokens
? model.cost_per_1m_tokens.input
: null,
outputCost: model.cost_per_1m_tokens
? model.cost_per_1m_tokens.output
: null
};
if (model.allowed_roles.includes('main')) {
mainModels.push(modelEntry);
}
if (model.allowed_roles.includes('research')) {
researchModels.push(modelEntry);
}
if (model.allowed_roles.includes('fallback')) {
fallbackModels.push(modelEntry);
}
});
}
}
const date = new Date();
const monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
const formattedDate = `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;
let markdownContent = `# Available Models as of ${formattedDate}\n\n`;
markdownContent += generateMarkdownTable('Main Models', mainModels);
markdownContent += generateMarkdownTable('Research Models', researchModels);
markdownContent += generateMarkdownTable('Fallback Models', fallbackModels);
fs.writeFileSync(correctOutputMarkdownPath, markdownContent, 'utf8');
console.log(`Successfully updated ${correctOutputMarkdownPath}`);
} catch (error) {
console.error('Error transforming models.json to models.md:', error);
process.exit(1);
}
}
main();

View File

@@ -268,7 +268,61 @@ task-master update --from=4 --prompt="Update to use MongoDB, researching best pr
This will rewrite or re-scope subsequent tasks in tasks.json while preserving completed work.
### 6. Breaking Down Complex Tasks
### 6. Reorganizing Tasks
If you need to reorganize your task structure:
```
I think subtask 5.2 would fit better as part of task 7 instead. Can you move it there?
```
The agent will execute:
```bash
task-master move --from=5.2 --to=7.3
```
You can reorganize tasks in various ways:
- Moving a standalone task to become a subtask: `--from=5 --to=7`
- Moving a subtask to become a standalone task: `--from=5.2 --to=7`
- Moving a subtask to a different parent: `--from=5.2 --to=7.3`
- Reordering subtasks within the same parent: `--from=5.2 --to=5.4`
- Moving a task to a new ID position: `--from=5 --to=25` (even if task 25 doesn't exist yet)
- Moving multiple tasks at once: `--from=10,11,12 --to=16,17,18` (must have same number of IDs, Taskmaster will look through each position)
When moving tasks to new IDs:
- The system automatically creates placeholder tasks for non-existent destination IDs
- This prevents accidental data loss during reorganization
- Any tasks that depend on moved tasks will have their dependencies updated
- When moving a parent task, all its subtasks are automatically moved with it and renumbered
This is particularly useful as your project understanding evolves and you need to refine your task structure.
### 7. Resolving Merge Conflicts with Tasks
When working with a team, you might encounter merge conflicts in your tasks.json file if multiple team members create tasks on different branches. The move command makes resolving these conflicts straightforward:
```
I just merged the main branch and there's a conflict with tasks.json. My teammates created tasks 10-15 while I created tasks 10-12 on my branch. Can you help me resolve this?
```
The agent will help you:
1. Keep your teammates' tasks (10-15)
2. Move your tasks to new positions to avoid conflicts:
```bash
# Move your tasks to new positions (e.g., 16-18)
task-master move --from=10 --to=16
task-master move --from=11 --to=17
task-master move --from=12 --to=18
```
This approach preserves everyone's work while maintaining a clean task structure, making it much easier to handle task conflicts than trying to manually merge JSON files.
### 8. Breaking Down Complex Tasks
For complex tasks that need more granularity:

131
llms-install.md Normal file
View File

@@ -0,0 +1,131 @@
``# Taskmaster AI Installation Guide
This guide helps AI assistants install and configure Taskmaster for users in their development projects.
## What is Taskmaster?
Taskmaster is an AI-driven task management system designed for development workflows. It helps break down projects into manageable tasks, track dependencies, and maintain development momentum through structured, AI-enhanced planning.
## Installation Steps
### Step 1: Add MCP Configuration
Add the following configuration to the user's MCP settings file (`.cursor/mcp.json` for Cursor, or equivalent for other editors):
```json
{
"mcpServers": {
"taskmaster-ai": {
"command": "npx",
"args": ["-y", "--package=task-master-ai", "task-master-ai"],
"env": {
"ANTHROPIC_API_KEY": "user_will_add_their_key_here",
"PERPLEXITY_API_KEY": "user_will_add_their_key_here",
"OPENAI_API_KEY": "user_will_add_their_key_here",
"GOOGLE_API_KEY": "user_will_add_their_key_here",
"MISTRAL_API_KEY": "user_will_add_their_key_here",
"OPENROUTER_API_KEY": "user_will_add_their_key_here",
"XAI_API_KEY": "user_will_add_their_key_here"
}
}
}
}
```
### Step 2: API Key Requirements
Inform the user they need **at least one** API key from the following providers:
- **Anthropic** (for Claude models) - Recommended
- **OpenAI** (for GPT models)
- **Google** (for Gemini models)
- **Perplexity** (for research features) - Highly recommended
- **Mistral** (for Mistral models)
- **OpenRouter** (access to multiple models)
- **xAI** (for Grok models)
The user will be able to define 3 separate roles (can be the same provider or separate providers) for main AI operations, research operations (research providers/models only), and a fallback model in case of errors.
### Step 3: Initialize Project
Once the MCP server is configured and API keys are added, initialize Taskmaster in the user's project:
> Can you initialize Task Master in my project?
This will run the `initialize_project` tool to set up the basic file structure.
### Step 4: Create Initial Tasks
Users have two options for creating initial tasks:
**Option A: Parse a PRD (Recommended)**
If they have a Product Requirements Document:
> Can you parse my PRD file at [path/to/prd.txt] to generate initial tasks?
If the user does not have a PRD, the AI agent can help them create one and store it in scripts/prd.txt for parsing.
**Option B: Start from scratch**
> Can you help me add my first task: [describe the task]
## Common Usage Patterns
### Daily Workflow
> What's the next task I should work on?
> Can you show me the details for task [ID]?
> Can you mark task [ID] as done?
### Task Management
> Can you break down task [ID] into subtasks?
> Can you add a new task: [description]
> Can you analyze the complexity of my tasks?
### Project Organization
> Can you show me all my pending tasks?
> Can you move task [ID] to become a subtask of [parent ID]?
> Can you update task [ID] with this new information: [details]
## Verification Steps
After installation, verify everything is working:
1. **Check MCP Connection**: The AI should be able to access Task Master tools
2. **Test Basic Commands**: Try `get_tasks` to list current tasks
3. **Verify API Keys**: Ensure AI-powered commands work (like `add_task`)
Note: An API key fallback exists that allows the MCP server to read API keys from `.env` instead of the MCP JSON config. It is recommended to have keys in both places in case the MCP server is unable to read keys from its environment for whatever reason.
When adding keys to `.env` only, the `models` tool will explain that the keys are not OK for MCP. Despite this, the fallback should kick in and the API keys will be read from the `.env` file.
## Troubleshooting
**If MCP server doesn't start:**
- Verify the JSON configuration is valid
- Check that Node.js is installed
- Ensure API keys are properly formatted
**If AI commands fail:**
- Verify at least one API key is configured
- Check API key permissions and quotas
- Try using a different model via the `models` tool
## CLI Fallback
Taskmaster is also available via CLI commands, by installing with `npm install task-master-ai@latest` in a terminal. Running `task-master help` will show all available commands, which offer a 1:1 experience with the MCP server. As the AI agent, you should refer to the system prompts and rules provided to you to identify Taskmaster-specific rules that help you understand how and when to use it.
## Next Steps
Once installed, users can:
- Create new tasks with `add-task` or parse a PRD (scripts/prd.txt) into tasks with `parse-prd`
- Set up model preferences with `models` tool
- Expand tasks into subtasks with `expand-all` and `expand-task`
- Explore advanced features like research mode and complexity analysis
For detailed documentation, refer to the Task Master docs directory.``

View File

@@ -94,6 +94,7 @@ export async function addTaskDirect(args, log, context = {}) {
let manualTaskData = null;
let newTaskId;
let telemetryData;
if (isManualCreation) {
// Create manual task data object
@@ -109,7 +110,7 @@ export async function addTaskDirect(args, log, context = {}) {
);
// Call the addTask function with manual task data
newTaskId = await addTask(
const result = await addTask(
tasksPath,
null, // prompt is null for manual creation
taskDependencies,
@@ -117,13 +118,17 @@ export async function addTaskDirect(args, log, context = {}) {
{
session,
mcpLog,
projectRoot
projectRoot,
commandName: 'add-task',
outputType: 'mcp'
},
'json', // outputFormat
manualTaskData, // Pass the manual task data
false, // research flag is false for manual creation
projectRoot // Pass projectRoot
);
newTaskId = result.newTaskId;
telemetryData = result.telemetryData;
} else {
// AI-driven task creation
log.info(
@@ -131,7 +136,7 @@ export async function addTaskDirect(args, log, context = {}) {
);
// Call the addTask function, passing the research flag
newTaskId = await addTask(
const result = await addTask(
tasksPath,
prompt, // Use the prompt for AI creation
taskDependencies,
@@ -139,12 +144,16 @@ export async function addTaskDirect(args, log, context = {}) {
{
session,
mcpLog,
projectRoot
projectRoot,
commandName: 'add-task',
outputType: 'mcp'
},
'json', // outputFormat
null, // manualTaskData is null for AI creation
research // Pass the research flag
);
newTaskId = result.newTaskId;
telemetryData = result.telemetryData;
}
// Restore normal logging
@@ -154,7 +163,8 @@ export async function addTaskDirect(args, log, context = {}) {
success: true,
data: {
taskId: newTaskId,
message: `Successfully added new task #${newTaskId}`
message: `Successfully added new task #${newTaskId}`,
telemetryData: telemetryData
}
};
} catch (error) {

View File

@@ -18,6 +18,9 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
* @param {string} args.outputPath - Explicit absolute path to save the report.
* @param {string|number} [args.threshold] - Minimum complexity score to recommend expansion (1-10)
* @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis
* @param {string} [args.ids] - Comma-separated list of task IDs to analyze
* @param {number} [args.from] - Starting task ID in a range to analyze
* @param {number} [args.to] - Ending task ID in a range to analyze
* @param {string} [args.projectRoot] - Project root path.
* @param {Object} log - Logger object
* @param {Object} [context={}] - Context object containing session data
@@ -26,7 +29,16 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
*/
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
const { session } = context;
const { tasksJsonPath, outputPath, threshold, research, projectRoot } = args;
const {
tasksJsonPath,
outputPath,
threshold,
research,
projectRoot,
ids,
from,
to
} = args;
const logWrapper = createLogWrapper(log);
@@ -58,6 +70,14 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
log.info(`Analyzing task complexity from: ${tasksPath}`);
log.info(`Output report will be saved to: ${resolvedOutputPath}`);
if (ids) {
log.info(`Analyzing specific task IDs: ${ids}`);
} else if (from || to) {
const fromStr = from !== undefined ? from : 'first';
const toStr = to !== undefined ? to : 'last';
log.info(`Analyzing tasks in range: ${fromStr} to ${toStr}`);
}
if (research) {
log.info('Using research role for complexity analysis');
}
@@ -68,7 +88,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
output: outputPath,
threshold: threshold,
research: research === true, // Ensure boolean
projectRoot: projectRoot // Pass projectRoot here
projectRoot: projectRoot, // Pass projectRoot here
id: ids, // Pass the ids parameter to the core function as 'id'
from: from, // Pass from parameter
to: to // Pass to parameter
};
// --- End Initial Checks ---
@@ -79,17 +102,19 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
}
let report;
let coreResult;
try {
// --- Call Core Function (Pass context separately) ---
// Pass coreOptions as the first argument
// Pass context object { session, mcpLog } as the second argument
report = await analyzeTaskComplexity(
coreOptions, // Pass options object
{ session, mcpLog: logWrapper } // Pass context object
// Removed the explicit 'json' format argument, assuming context handling is sufficient
// If issues persist, we might need to add an explicit format param to analyzeTaskComplexity
);
coreResult = await analyzeTaskComplexity(coreOptions, {
session,
mcpLog: logWrapper,
commandName: 'analyze-complexity',
outputType: 'mcp'
});
report = coreResult.report;
} catch (error) {
log.error(
`Error in analyzeTaskComplexity core function: ${error.message}`
@@ -125,8 +150,11 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
};
}
// Added a check to ensure report is defined before accessing its properties
if (!report || typeof report !== 'object') {
if (
!coreResult ||
!coreResult.report ||
typeof coreResult.report !== 'object'
) {
log.error(
'Core analysis function returned an invalid or undefined response.'
);
@@ -141,8 +169,8 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
try {
// Ensure complexityAnalysis exists and is an array
const analysisArray = Array.isArray(report.complexityAnalysis)
? report.complexityAnalysis
const analysisArray = Array.isArray(coreResult.report.complexityAnalysis)
? coreResult.report.complexityAnalysis
: [];
// Count tasks by complexity (remains the same)
@@ -159,15 +187,16 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
return {
success: true,
data: {
message: `Task complexity analysis complete. Report saved to ${outputPath}`, // Use outputPath from args
reportPath: outputPath, // Use outputPath from args
message: `Task complexity analysis complete. Report saved to ${outputPath}`,
reportPath: outputPath,
reportSummary: {
taskCount: analysisArray.length,
highComplexityTasks,
mediumComplexityTasks,
lowComplexityTasks
},
fullReport: report // Now includes the full report
fullReport: coreResult.report,
telemetryData: coreResult.telemetryData
}
};
} catch (parseError) {

View File

@@ -8,7 +8,6 @@ import {
enableSilentMode,
disableSilentMode
} from '../../../../scripts/modules/utils.js';
import { getCachedOrExecute } from '../../tools/utils.js';
/**
* Direct function wrapper for displaying the complexity report with error handling and caching.
@@ -86,30 +85,20 @@ export async function complexityReportDirect(args, log) {
// Use the caching utility
try {
const result = await getCachedOrExecute({
cacheKey,
actionFn: coreActionFn,
log
});
log.info(
`complexityReportDirect completed. From cache: ${result.fromCache}`
);
return result; // Returns { success, data/error, fromCache }
const result = await coreActionFn();
log.info('complexityReportDirect completed');
return result;
} catch (error) {
// Catch unexpected errors from getCachedOrExecute itself
// Ensure silent mode is disabled
disableSilentMode();
log.error(
`Unexpected error during getCachedOrExecute for complexityReport: ${error.message}`
);
log.error(`Unexpected error during complexityReport: ${error.message}`);
return {
success: false,
error: {
code: 'UNEXPECTED_ERROR',
message: error.message
},
fromCache: false
}
};
}
} catch (error) {

View File

@@ -63,12 +63,18 @@ export async function expandAllTasksDirect(args, log, context = {}) {
{ session, mcpLog, projectRoot }
);
// Core function now returns a summary object
// Core function now returns a summary object including the *aggregated* telemetryData
return {
success: true,
data: {
message: `Expand all operation completed. Expanded: ${result.expandedCount}, Failed: ${result.failedCount}, Skipped: ${result.skippedCount}`,
details: result // Include the full result details
details: {
expandedCount: result.expandedCount,
failedCount: result.failedCount,
skippedCount: result.skippedCount,
tasksToExpand: result.tasksToExpand
},
telemetryData: result.telemetryData // Pass the aggregated object
}
};
} catch (error) {

View File

@@ -193,13 +193,19 @@ export async function expandTaskDirect(args, log, context = {}) {
if (!wasSilent) enableSilentMode();
// Call the core expandTask function with the wrapped logger and projectRoot
const updatedTaskResult = await expandTask(
const coreResult = await expandTask(
tasksPath,
taskId,
numSubtasks,
useResearch,
additionalContext,
{ mcpLog, session, projectRoot },
{
mcpLog,
session,
projectRoot,
commandName: 'expand-task',
outputType: 'mcp'
},
forceFlag
);
@@ -215,16 +221,17 @@ export async function expandTaskDirect(args, log, context = {}) {
? updatedTask.subtasks.length - subtasksCountBefore
: 0;
// Return the result
// Return the result, including telemetryData
log.info(
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
);
return {
success: true,
data: {
task: updatedTask,
task: coreResult.task,
subtasksAdded,
hasExistingSubtasks
hasExistingSubtasks,
telemetryData: coreResult.telemetryData
},
fromCache: false
};

View File

@@ -4,7 +4,6 @@
*/
import { listTasks } from '../../../../scripts/modules/task-manager.js';
import { getCachedOrExecute } from '../../tools/utils.js';
import {
enableSilentMode,
disableSilentMode
@@ -19,7 +18,7 @@ import {
*/
export async function listTasksDirect(args, log) {
// Destructure the explicit tasksJsonPath from args
const { tasksJsonPath, status, withSubtasks } = args;
const { tasksJsonPath, reportPath, status, withSubtasks } = args;
if (!tasksJsonPath) {
log.error('listTasksDirect called without tasksJsonPath');
@@ -36,7 +35,6 @@ export async function listTasksDirect(args, log) {
// Use the explicit tasksJsonPath for cache key
const statusFilter = status || 'all';
const withSubtasksFilter = withSubtasks || false;
const cacheKey = `listTasks:${tasksJsonPath}:${statusFilter}:${withSubtasksFilter}`;
// Define the action function to be executed on cache miss
const coreListTasksAction = async () => {
@@ -51,6 +49,7 @@ export async function listTasksDirect(args, log) {
const resultData = listTasks(
tasksJsonPath,
statusFilter,
reportPath,
withSubtasksFilter,
'json'
);
@@ -65,6 +64,7 @@ export async function listTasksDirect(args, log) {
}
};
}
log.info(
`Core listTasks function retrieved ${resultData.tasks.length} tasks`
);
@@ -88,25 +88,19 @@ export async function listTasksDirect(args, log) {
}
};
// Use the caching utility
try {
const result = await getCachedOrExecute({
cacheKey,
actionFn: coreListTasksAction,
log
});
log.info(`listTasksDirect completed. From cache: ${result.fromCache}`);
return result; // Returns { success, data/error, fromCache }
const result = await coreListTasksAction();
log.info('listTasksDirect completed');
return result;
} catch (error) {
// Catch unexpected errors from getCachedOrExecute itself (though unlikely)
log.error(
`Unexpected error during getCachedOrExecute for listTasks: ${error.message}`
);
log.error(`Unexpected error during listTasks: ${error.message}`);
console.error(error.stack);
return {
success: false,
error: { code: 'CACHE_UTIL_ERROR', message: error.message },
fromCache: false
error: {
code: 'UNEXPECTED_ERROR',
message: error.message
}
};
}
}

View File

@@ -0,0 +1,99 @@
/**
* Direct function wrapper for moveTask
*/
import { moveTask } from '../../../../scripts/modules/task-manager.js';
import { findTasksJsonPath } from '../utils/path-utils.js';
import {
enableSilentMode,
disableSilentMode
} from '../../../../scripts/modules/utils.js';
/**
* Move a task or subtask to a new position
* @param {Object} args - Function arguments
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file
* @param {string} args.sourceId - ID of the task/subtask to move (e.g., '5' or '5.2')
* @param {string} args.destinationId - ID of the destination (e.g., '7' or '7.3')
* @param {string} args.file - Alternative path to the tasks.json file
* @param {string} args.projectRoot - Project root directory
* @param {Object} log - Logger object
* @returns {Promise<{success: boolean, data?: Object, error?: Object}>}
*/
export async function moveTaskDirect(args, log, context = {}) {
const { session } = context;
// Validate required parameters
if (!args.sourceId) {
return {
success: false,
error: {
message: 'Source ID is required',
code: 'MISSING_SOURCE_ID'
}
};
}
if (!args.destinationId) {
return {
success: false,
error: {
message: 'Destination ID is required',
code: 'MISSING_DESTINATION_ID'
}
};
}
try {
// Find tasks.json path if not provided
let tasksPath = args.tasksJsonPath || args.file;
if (!tasksPath) {
if (!args.projectRoot) {
return {
success: false,
error: {
message:
'Project root is required if tasksJsonPath is not provided',
code: 'MISSING_PROJECT_ROOT'
}
};
}
tasksPath = findTasksJsonPath(args, log);
}
// Enable silent mode to prevent console output during MCP operation
enableSilentMode();
// Call the core moveTask function, always generate files
const result = await moveTask(
tasksPath,
args.sourceId,
args.destinationId,
true
);
// Restore console output
disableSilentMode();
return {
success: true,
data: {
movedTask: result.movedTask,
message: `Successfully moved task/subtask ${args.sourceId} to ${args.destinationId}`
}
};
} catch (error) {
// Restore console output in case of error
disableSilentMode();
log.error(`Failed to move task: ${error.message}`);
return {
success: false,
error: {
message: error.message,
code: 'MOVE_TASK_ERROR'
}
};
}
}

View File

@@ -4,8 +4,10 @@
*/
import { findNextTask } from '../../../../scripts/modules/task-manager.js';
import { readJSON } from '../../../../scripts/modules/utils.js';
import { getCachedOrExecute } from '../../tools/utils.js';
import {
readJSON,
readComplexityReport
} from '../../../../scripts/modules/utils.js';
import {
enableSilentMode,
disableSilentMode
@@ -21,7 +23,7 @@ import {
*/
export async function nextTaskDirect(args, log) {
// Destructure expected args
const { tasksJsonPath } = args;
const { tasksJsonPath, reportPath } = args;
if (!tasksJsonPath) {
log.error('nextTaskDirect called without tasksJsonPath');
@@ -35,9 +37,6 @@ export async function nextTaskDirect(args, log) {
};
}
// Generate cache key using the provided task path
const cacheKey = `nextTask:${tasksJsonPath}`;
// Define the action function to be executed on cache miss
const coreNextTaskAction = async () => {
try {
@@ -59,8 +58,11 @@ export async function nextTaskDirect(args, log) {
};
}
// Read the complexity report
const complexityReport = readComplexityReport(reportPath);
// Find the next task
const nextTask = findNextTask(data.tasks);
const nextTask = findNextTask(data.tasks, complexityReport);
if (!nextTask) {
log.info(
@@ -118,18 +120,11 @@ export async function nextTaskDirect(args, log) {
// Use the caching utility
try {
const result = await getCachedOrExecute({
cacheKey,
actionFn: coreNextTaskAction,
log
});
log.info(`nextTaskDirect completed. From cache: ${result.fromCache}`);
return result; // Returns { success, data/error, fromCache }
const result = await coreNextTaskAction();
log.info(`nextTaskDirect completed.`);
return result;
} catch (error) {
// Catch unexpected errors from getCachedOrExecute itself
log.error(
`Unexpected error during getCachedOrExecute for nextTask: ${error.message}`
);
log.error(`Unexpected error during nextTask: ${error.message}`);
return {
success: false,
error: {

View File

@@ -31,6 +31,7 @@ export async function parsePRDDirect(args, log, context = {}) {
numTasks: numTasksArg,
force,
append,
research,
projectRoot
} = args;
@@ -105,19 +106,23 @@ export async function parsePRDDirect(args, log, context = {}) {
}
}
const useForce = force === true;
const useAppend = append === true;
if (useAppend) {
if (append) {
logWrapper.info('Append mode enabled.');
if (useForce) {
if (force) {
logWrapper.warn(
'Both --force and --append flags were provided. --force takes precedence; append mode will be ignored.'
);
}
}
if (research) {
logWrapper.info(
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${useForce}, Append: ${useAppend}, ProjectRoot: ${projectRoot}`
'Research mode enabled. Using Perplexity AI for enhanced PRD analysis.'
);
}
logWrapper.info(
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${force}, Append: ${append}, Research: ${research}, ProjectRoot: ${projectRoot}`
);
const wasSilent = isSilentMode();
@@ -131,21 +136,29 @@ export async function parsePRDDirect(args, log, context = {}) {
inputPath,
outputPath,
numTasks,
{ session, mcpLog: logWrapper, projectRoot, useForce, useAppend },
{
session,
mcpLog: logWrapper,
projectRoot,
force,
append,
research,
commandName: 'parse-prd',
outputType: 'mcp'
},
'json'
);
// parsePRD returns { success: true, tasks: processedTasks } on success
if (result && result.success && Array.isArray(result.tasks)) {
logWrapper.success(
`Successfully parsed PRD. Generated ${result.tasks.length} tasks.`
);
// Adjust check for the new return structure
if (result && result.success) {
const successMsg = `Successfully parsed PRD and generated tasks in ${result.tasksPath}`;
logWrapper.success(successMsg);
return {
success: true,
data: {
message: `Successfully parsed PRD and generated ${result.tasks.length} tasks.`,
outputPath: outputPath,
taskCount: result.tasks.length
message: successMsg,
outputPath: result.tasksPath,
telemetryData: result.telemetryData
}
};
} else {

View File

@@ -9,7 +9,7 @@ import {
disableSilentMode,
isSilentMode
} from '../../../../scripts/modules/utils.js';
import { nextTaskDirect } from './next-task.js';
/**
* Direct function wrapper for setTaskStatus with error handling.
*
@@ -19,7 +19,7 @@ import {
*/
export async function setTaskStatusDirect(args, log) {
// Destructure expected args, including the resolved tasksJsonPath
const { tasksJsonPath, id, status } = args;
const { tasksJsonPath, id, status, complexityReportPath } = args;
try {
log.info(`Setting task status with args: ${JSON.stringify(args)}`);
@@ -85,6 +85,39 @@ export async function setTaskStatusDirect(args, log) {
},
fromCache: false // This operation always modifies state and should never be cached
};
// If the task was completed, attempt to fetch the next task
if (result.data.status === 'done') {
try {
log.info(`Attempting to fetch next task for task ${taskId}`);
const nextResult = await nextTaskDirect(
{
tasksJsonPath: tasksJsonPath,
reportPath: complexityReportPath
},
log
);
if (nextResult.success) {
log.info(
`Successfully retrieved next task: ${nextResult.data.nextTask}`
);
result.data = {
...result.data,
nextTask: nextResult.data.nextTask,
isNextSubtask: nextResult.data.isSubtask,
nextSteps: nextResult.data.nextSteps
};
} else {
log.warn(
`Failed to retrieve next task: ${nextResult.error?.message || 'Unknown error'}`
);
}
} catch (nextErr) {
log.error(`Error retrieving next task: ${nextErr.message}`);
}
}
return result;
} catch (error) {
log.error(`Error setting task status: ${error.message}`);

View File

@@ -3,11 +3,10 @@
* Direct function implementation for showing task details
*/
import { findTaskById, readJSON } from '../../../../scripts/modules/utils.js';
import { getCachedOrExecute } from '../../tools/utils.js';
import {
enableSilentMode,
disableSilentMode
findTaskById,
readComplexityReport,
readJSON
} from '../../../../scripts/modules/utils.js';
import { findTasksJsonPath } from '../utils/path-utils.js';
@@ -17,6 +16,7 @@ import { findTasksJsonPath } from '../utils/path-utils.js';
* @param {Object} args - Command arguments.
* @param {string} args.id - Task ID to show.
* @param {string} [args.file] - Optional path to the tasks file (passed to findTasksJsonPath).
* @param {string} args.reportPath - Explicit path to the complexity report file.
* @param {string} [args.status] - Optional status to filter subtasks by.
* @param {string} args.projectRoot - Absolute path to the project root directory (already normalized by tool).
* @param {Object} log - Logger object.
@@ -27,7 +27,7 @@ export async function showTaskDirect(args, log) {
// Destructure session from context if needed later, otherwise ignore
// const { session } = context;
// Destructure projectRoot and other args. projectRoot is assumed normalized.
const { id, file, status, projectRoot } = args;
const { id, file, reportPath, status, projectRoot } = args;
log.info(
`Showing task direct function. ID: ${id}, File: ${file}, Status Filter: ${status}, ProjectRoot: ${projectRoot}`
@@ -64,9 +64,12 @@ export async function showTaskDirect(args, log) {
};
}
const complexityReport = readComplexityReport(reportPath);
const { task, originalSubtaskCount } = findTaskById(
tasksData.tasks,
id,
complexityReport,
status
);

View File

@@ -108,18 +108,24 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
try {
// Execute core updateSubtaskById function
const updatedSubtask = await updateSubtaskById(
const coreResult = await updateSubtaskById(
tasksPath,
subtaskIdStr,
prompt,
useResearch,
{ mcpLog: logWrapper, session, projectRoot },
{
mcpLog: logWrapper,
session,
projectRoot,
commandName: 'update-subtask',
outputType: 'mcp'
},
'json'
);
if (updatedSubtask === null) {
if (!coreResult || coreResult.updatedSubtask === null) {
const message = `Subtask ${id} or its parent task not found.`;
logWrapper.error(message); // Log as error since it couldn't be found
logWrapper.error(message);
return {
success: false,
error: { code: 'SUBTASK_NOT_FOUND', message: message },
@@ -136,9 +142,10 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
message: `Successfully updated subtask with ID ${subtaskIdStr}`,
subtaskId: subtaskIdStr,
parentId: subtaskIdStr.split('.')[0],
subtask: updatedSubtask,
subtask: coreResult.updatedSubtask,
tasksPath,
useResearch
useResearch,
telemetryData: coreResult.telemetryData
},
fromCache: false
};

View File

@@ -110,7 +110,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
try {
// Execute core updateTaskById function with proper parameters
const updatedTask = await updateTaskById(
const coreResult = await updateTaskById(
tasksPath,
taskId,
prompt,
@@ -118,19 +118,26 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
{
mcpLog: logWrapper,
session,
projectRoot
projectRoot,
commandName: 'update-task',
outputType: 'mcp'
},
'json'
);
// Check if the core function indicated the task wasn't updated (e.g., status was 'done')
if (updatedTask === null) {
// Check if the core function returned null or an object without success
if (!coreResult || coreResult.updatedTask === null) {
// Core function logs the reason, just return success with info
const message = `Task ${taskId} was not updated (likely already completed).`;
logWrapper.info(message);
return {
success: true,
data: { message: message, taskId: taskId, updated: false },
data: {
message: message,
taskId: taskId,
updated: false,
telemetryData: coreResult?.telemetryData
},
fromCache: false
};
}
@@ -146,7 +153,8 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
tasksPath: tasksPath,
useResearch: useResearch,
updated: true,
updatedTask: updatedTask
updatedTask: coreResult.updatedTask,
telemetryData: coreResult.telemetryData
},
fromCache: false
};

View File

@@ -6,6 +6,10 @@
import path from 'path';
import { updateTasks } from '../../../../scripts/modules/task-manager.js';
import { createLogWrapper } from '../../tools/utils.js';
import {
enableSilentMode,
disableSilentMode
} from '../../../../scripts/modules/utils.js';
/**
* Direct function wrapper for updating tasks based on new context.
@@ -81,7 +85,6 @@ export async function updateTasksDirect(args, log, context = {}) {
'json'
);
// updateTasks returns { success: true, updatedTasks: [...] } on success
if (result && result.success && Array.isArray(result.updatedTasks)) {
logWrapper.success(
`Successfully updated ${result.updatedTasks.length} tasks.`
@@ -91,7 +94,8 @@ export async function updateTasksDirect(args, log, context = {}) {
data: {
message: `Successfully updated ${result.updatedTasks.length} tasks.`,
tasksFile,
updatedCount: result.updatedTasks.length
updatedCount: result.updatedTasks.length,
telemetryData: result.telemetryData
}
};
} else {

View File

@@ -30,6 +30,7 @@ import { addDependencyDirect } from './direct-functions/add-dependency.js';
import { removeTaskDirect } from './direct-functions/remove-task.js';
import { initializeProjectDirect } from './direct-functions/initialize-project.js';
import { modelsDirect } from './direct-functions/models.js';
import { moveTaskDirect } from './direct-functions/move-task.js';
// Re-export utility functions
export { findTasksJsonPath } from './utils/path-utils.js';
@@ -60,7 +61,8 @@ export const directFunctions = new Map([
['addDependencyDirect', addDependencyDirect],
['removeTaskDirect', removeTaskDirect],
['initializeProjectDirect', initializeProjectDirect],
['modelsDirect', modelsDirect]
['modelsDirect', modelsDirect],
['moveTaskDirect', moveTaskDirect]
]);
// Re-export all direct function implementations
@@ -89,5 +91,6 @@ export {
addDependencyDirect,
removeTaskDirect,
initializeProjectDirect,
modelsDirect
modelsDirect,
moveTaskDirect
};

View File

@@ -339,6 +339,49 @@ export function findPRDDocumentPath(projectRoot, explicitPath, log) {
return null;
}
export function findComplexityReportPath(projectRoot, explicitPath, log) {
// If explicit path is provided, check if it exists
if (explicitPath) {
const fullPath = path.isAbsolute(explicitPath)
? explicitPath
: path.resolve(projectRoot, explicitPath);
if (fs.existsSync(fullPath)) {
log.info(`Using provided PRD document path: ${fullPath}`);
return fullPath;
} else {
log.warn(
`Provided PRD document path not found: ${fullPath}, will search for alternatives`
);
}
}
// Common locations and file patterns for PRD documents
const commonLocations = [
'', // Project root
'scripts/'
];
const commonFileNames = [
'complexity-report.json',
'task-complexity-report.json'
];
// Check all possible combinations
for (const location of commonLocations) {
for (const fileName of commonFileNames) {
const potentialPath = path.join(projectRoot, location, fileName);
if (fs.existsSync(potentialPath)) {
log.info(`Found PRD document at: ${potentialPath}`);
return potentialPath;
}
}
}
log.warn(`No PRD document found in common locations within ${projectRoot}`);
return null;
}
/**
* Resolves the tasks output directory path
* @param {string} projectRoot - The project root directory

View File

@@ -49,6 +49,24 @@ export function registerAnalyzeProjectComplexityTool(server) {
.describe(
'Path to the tasks file relative to project root (default: tasks/tasks.json).'
),
ids: z
.string()
.optional()
.describe(
'Comma-separated list of task IDs to analyze specifically (e.g., "1,3,5").'
),
from: z.coerce
.number()
.int()
.positive()
.optional()
.describe('Starting task ID in a range to analyze.'),
to: z.coerce
.number()
.int()
.positive()
.optional()
.describe('Ending task ID in a range to analyze.'),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
@@ -107,7 +125,10 @@ export function registerAnalyzeProjectComplexityTool(server) {
outputPath: outputPath,
threshold: args.threshold,
research: args.research,
projectRoot: args.projectRoot
projectRoot: args.projectRoot,
ids: args.ids,
from: args.from,
to: args.to
},
log,
{ session }

View File

@@ -10,7 +10,10 @@ import {
withNormalizedProjectRoot
} from './utils.js';
import { showTaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js';
import {
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
/**
* Custom processor function that removes allTasks from the response
@@ -50,6 +53,12 @@ export function registerShowTaskTool(server) {
.string()
.optional()
.describe('Path to the tasks file relative to project root'),
complexityReport: z
.string()
.optional()
.describe(
'Path to the complexity report file (relative to project root or absolute)'
),
projectRoot: z
.string()
.optional()
@@ -81,9 +90,22 @@ export function registerShowTaskTool(server) {
}
// Call the direct function, passing the normalized projectRoot
// Resolve the path to complexity report
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await showTaskDirect(
{
tasksJsonPath: tasksJsonPath,
reportPath: complexityReportPath,
// Pass other relevant args
id: id,
status: status,
projectRoot: projectRoot

View File

@@ -10,7 +10,10 @@ import {
withNormalizedProjectRoot
} from './utils.js';
import { listTasksDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js';
import {
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
/**
* Register the getTasks tool with the MCP server
@@ -38,6 +41,12 @@ export function registerListTasksTool(server) {
.describe(
'Path to the tasks file (relative to project root or absolute)'
),
complexityReport: z
.string()
.optional()
.describe(
'Path to the complexity report file (relative to project root or absolute)'
),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
@@ -60,11 +69,23 @@ export function registerListTasksTool(server) {
);
}
// Resolve the path to complexity report
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
args.projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await listTasksDirect(
{
tasksJsonPath: tasksJsonPath,
status: args.status,
withSubtasks: args.withSubtasks
withSubtasks: args.withSubtasks,
reportPath: complexityReportPath
},
log
);

View File

@@ -28,6 +28,7 @@ import { registerAddDependencyTool } from './add-dependency.js';
import { registerRemoveTaskTool } from './remove-task.js';
import { registerInitializeProjectTool } from './initialize-project.js';
import { registerModelsTool } from './models.js';
import { registerMoveTaskTool } from './move-task.js';
/**
* Register all Task Master tools with the MCP server
@@ -61,6 +62,7 @@ export function registerTaskMasterTools(server) {
registerRemoveTaskTool(server);
registerRemoveSubtaskTool(server);
registerClearSubtasksTool(server);
registerMoveTaskTool(server);
// Group 5: Task Analysis & Expansion
registerAnalyzeProjectComplexityTool(server);

View File

@@ -0,0 +1,129 @@
/**
* tools/move-task.js
* Tool for moving tasks or subtasks to a new position
*/
import { z } from 'zod';
import {
handleApiResult,
createErrorResponse,
withNormalizedProjectRoot
} from './utils.js';
import { moveTaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js';
/**
* Register the moveTask tool with the MCP server
* @param {Object} server - FastMCP server instance
*/
export function registerMoveTaskTool(server) {
server.addTool({
name: 'move_task',
description: 'Move a task or subtask to a new position',
parameters: z.object({
from: z
.string()
.describe(
'ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")'
),
to: z
.string()
.describe(
'ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated'
),
file: z.string().optional().describe('Custom path to tasks.json file'),
projectRoot: z
.string()
.optional()
.describe(
'Root directory of the project (typically derived from session)'
)
}),
execute: withNormalizedProjectRoot(async (args, { log, session }) => {
try {
// Find tasks.json path if not provided
let tasksJsonPath = args.file;
if (!tasksJsonPath) {
tasksJsonPath = findTasksJsonPath(args, log);
}
// Parse comma-separated IDs
const fromIds = args.from.split(',').map((id) => id.trim());
const toIds = args.to.split(',').map((id) => id.trim());
// Validate matching IDs count
if (fromIds.length !== toIds.length) {
return createErrorResponse(
'The number of source and destination IDs must match',
'MISMATCHED_ID_COUNT'
);
}
// If moving multiple tasks
if (fromIds.length > 1) {
const results = [];
// Move tasks one by one, only generate files on the last move
for (let i = 0; i < fromIds.length; i++) {
const fromId = fromIds[i];
const toId = toIds[i];
// Skip if source and destination are the same
if (fromId === toId) {
log.info(`Skipping ${fromId} -> ${toId} (same ID)`);
continue;
}
const shouldGenerateFiles = i === fromIds.length - 1;
const result = await moveTaskDirect(
{
sourceId: fromId,
destinationId: toId,
tasksJsonPath,
projectRoot: args.projectRoot
},
log,
{ session }
);
if (!result.success) {
log.error(
`Failed to move ${fromId} to ${toId}: ${result.error.message}`
);
} else {
results.push(result.data);
}
}
return {
success: true,
data: {
moves: results,
message: `Successfully moved ${results.length} tasks`
}
};
} else {
// Moving a single task
return handleApiResult(
await moveTaskDirect(
{
sourceId: args.from,
destinationId: args.to,
tasksJsonPath,
projectRoot: args.projectRoot
},
log,
{ session }
),
log
);
}
} catch (error) {
return createErrorResponse(
`Failed to move task: ${error.message}`,
'MOVE_TASK_ERROR'
);
}
})
});
}

View File

@@ -10,7 +10,10 @@ import {
withNormalizedProjectRoot
} from './utils.js';
import { nextTaskDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js';
import {
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
/**
* Register the next-task tool with the MCP server
@@ -23,6 +26,12 @@ export function registerNextTaskTool(server) {
'Find the next task to work on based on dependencies and status',
parameters: z.object({
file: z.string().optional().describe('Absolute path to the tasks file'),
complexityReport: z
.string()
.optional()
.describe(
'Path to the complexity report file (relative to project root or absolute)'
),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
@@ -45,9 +54,21 @@ export function registerNextTaskTool(server) {
);
}
// Resolve the path to complexity report
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
args.projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await nextTaskDirect(
{
tasksJsonPath: tasksJsonPath
tasksJsonPath: tasksJsonPath,
reportPath: complexityReportPath
},
log
);

View File

@@ -49,6 +49,13 @@ export function registerParsePRDTool(server) {
.optional()
.default(false)
.describe('Append generated tasks to existing file.'),
research: z
.boolean()
.optional()
.default(false)
.describe(
'Use the research model for research-backed task generation, providing more comprehensive, accurate and up-to-date task details.'
),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
@@ -68,6 +75,7 @@ export function registerParsePRDTool(server) {
numTasks: args.numTasks,
force: args.force,
append: args.append,
research: args.research,
projectRoot: args.projectRoot
},
log,

View File

@@ -9,8 +9,15 @@ import {
createErrorResponse,
withNormalizedProjectRoot
} from './utils.js';
import { setTaskStatusDirect } from '../core/task-master-core.js';
import { findTasksJsonPath } from '../core/utils/path-utils.js';
import {
setTaskStatusDirect,
nextTaskDirect
} from '../core/task-master-core.js';
import {
findTasksJsonPath,
findComplexityReportPath
} from '../core/utils/path-utils.js';
import { TASK_STATUS_OPTIONS } from '../../../src/constants/task-status.js';
/**
* Register the setTaskStatus tool with the MCP server
@@ -27,11 +34,17 @@ export function registerSetTaskStatusTool(server) {
"Task ID or subtask ID (e.g., '15', '15.2'). Can be comma-separated to update multiple tasks/subtasks at once."
),
status: z
.string()
.enum(TASK_STATUS_OPTIONS)
.describe(
"New status to set (e.g., 'pending', 'done', 'in-progress', 'review', 'deferred', 'cancelled'."
),
file: z.string().optional().describe('Absolute path to the tasks file'),
complexityReport: z
.string()
.optional()
.describe(
'Path to the complexity report file (relative to project root or absolute)'
),
projectRoot: z
.string()
.describe('The directory of the project. Must be an absolute path.')
@@ -54,11 +67,23 @@ export function registerSetTaskStatusTool(server) {
);
}
let complexityReportPath;
try {
complexityReportPath = findComplexityReportPath(
args.projectRoot,
args.complexityReport,
log
);
} catch (error) {
log.error(`Error finding complexity report: ${error.message}`);
}
const result = await setTaskStatusDirect(
{
tasksJsonPath: tasksJsonPath,
id: args.id,
status: args.status
status: args.status,
complexityReportPath
},
log
);

View File

@@ -22,7 +22,7 @@ import {
*/
function getProjectRoot(projectRootRaw, log) {
// PRECEDENCE ORDER:
// 1. Environment variable override
// 1. Environment variable override (TASK_MASTER_PROJECT_ROOT)
// 2. Explicitly provided projectRoot in args
// 3. Previously found/cached project root
// 4. Current directory if it has project markers
@@ -578,6 +578,7 @@ function getRawProjectRootFromSession(session, log) {
/**
* Higher-order function to wrap MCP tool execute methods.
* Ensures args.projectRoot is present and normalized before execution.
* Uses TASK_MASTER_PROJECT_ROOT environment variable with proper precedence.
* @param {Function} executeFn - The original async execute(args, context) function.
* @returns {Function} The wrapped async execute function.
*/
@@ -588,31 +589,52 @@ function withNormalizedProjectRoot(executeFn) {
let rootSource = 'unknown';
try {
// Determine raw root: prioritize args, then session
let rawRoot = args.projectRoot;
if (!rawRoot) {
rawRoot = getRawProjectRootFromSession(session, log);
// PRECEDENCE ORDER:
// 1. TASK_MASTER_PROJECT_ROOT environment variable (from process.env or session)
// 2. args.projectRoot (explicitly provided)
// 3. Session-based project root resolution
// 4. Current directory fallback
// 1. Check for TASK_MASTER_PROJECT_ROOT environment variable first
if (process.env.TASK_MASTER_PROJECT_ROOT) {
const envRoot = process.env.TASK_MASTER_PROJECT_ROOT;
normalizedRoot = path.isAbsolute(envRoot)
? envRoot
: path.resolve(process.cwd(), envRoot);
rootSource = 'TASK_MASTER_PROJECT_ROOT environment variable';
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// Also check session environment variables for TASK_MASTER_PROJECT_ROOT
else if (session?.env?.TASK_MASTER_PROJECT_ROOT) {
const envRoot = session.env.TASK_MASTER_PROJECT_ROOT;
normalizedRoot = path.isAbsolute(envRoot)
? envRoot
: path.resolve(process.cwd(), envRoot);
rootSource = 'TASK_MASTER_PROJECT_ROOT session environment variable';
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// 2. If no environment variable, try args.projectRoot
else if (args.projectRoot) {
normalizedRoot = normalizeProjectRoot(args.projectRoot, log);
rootSource = 'args.projectRoot';
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
// 3. If no args.projectRoot, try session-based resolution
else {
const sessionRoot = getProjectRootFromSession(session, log);
if (sessionRoot) {
normalizedRoot = sessionRoot; // getProjectRootFromSession already normalizes
rootSource = 'session';
} else {
rootSource = 'args';
log.info(`Using project root from ${rootSource}: ${normalizedRoot}`);
}
if (!rawRoot) {
log.error('Could not determine project root from args or session.');
return createErrorResponse(
'Could not determine project root. Please provide projectRoot argument or ensure session contains root info.'
);
}
// Normalize the determined raw root
normalizedRoot = normalizeProjectRoot(rawRoot, log);
if (!normalizedRoot) {
log.error(
`Failed to normalize project root obtained from ${rootSource}: ${rawRoot}`
'Could not determine project root from environment, args, or session.'
);
return createErrorResponse(
`Invalid project root provided or derived from ${rootSource}: ${rawRoot}`
'Could not determine project root. Please provide projectRoot argument or ensure TASK_MASTER_PROJECT_ROOT environment variable is set.'
);
}

1866
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "task-master-ai",
"version": "0.12.1",
"version": "0.15.0",
"description": "A task management system for ambitious AI-driven development that doesn't overwhelm and confuse Cursor.",
"main": "index.js",
"type": "module",
@@ -39,23 +39,29 @@
"author": "Eyal Toledano",
"license": "MIT WITH Commons-Clause",
"dependencies": {
"@ai-sdk/amazon-bedrock": "^2.2.9",
"@ai-sdk/anthropic": "^1.2.10",
"@ai-sdk/azure": "^1.3.17",
"@ai-sdk/google": "^1.2.13",
"@ai-sdk/google-vertex": "^2.2.23",
"@ai-sdk/mistral": "^1.2.7",
"@ai-sdk/openai": "^1.3.20",
"@ai-sdk/perplexity": "^1.1.7",
"@ai-sdk/xai": "^1.2.15",
"@anthropic-ai/sdk": "^0.39.0",
"@aws-sdk/credential-providers": "^3.817.0",
"@openrouter/ai-sdk-provider": "^0.4.5",
"ai": "^4.3.10",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-table3": "^0.6.5",
"commander": "^11.1.0",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.21.2",
"fastmcp": "^1.20.5",
"figlet": "^1.8.0",
"fuse.js": "^7.0.0",
"fuse.js": "^7.1.0",
"gradient-string": "^3.0.0",
"helmet": "^8.1.0",
"inquirer": "^12.5.0",
@@ -64,7 +70,8 @@
"ollama-ai-provider": "^1.2.0",
"openai": "^4.89.0",
"ora": "^8.2.0",
"uuid": "^11.1.0"
"uuid": "^11.1.0",
"zod": "^3.23.8"
},
"engines": {
"node": ">=14.0.0"
@@ -78,37 +85,31 @@
"url": "https://github.com/eyaltoledano/claude-task-master/issues"
},
"files": [
"scripts/init.js",
"scripts/dev.js",
"scripts/modules/**",
"scripts/**",
"assets/**",
".cursor/**",
"README-task-master.md",
"index.js",
"bin/**",
"mcp-server/**"
"mcp-server/**",
"src/**"
],
"overrides": {
"node-fetch": "^3.3.2",
"node-fetch": "^2.6.12",
"whatwg-url": "^11.0.0"
},
"devDependencies": {
"@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.28.1",
"@types/jest": "^29.5.14",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"cli-table3": "^0.6.5",
"execa": "^8.0.1",
"ink": "^5.0.1",
"jest": "^29.7.0",
"jest-environment-node": "^29.7.0",
"mock-fs": "^5.5.0",
"node-fetch": "^3.3.2",
"prettier": "^3.5.3",
"react": "^18.3.1",
"supertest": "^7.1.0",
"tsx": "^4.16.2",
"zod": "^3.23.8"
"tsx": "^4.16.2"
}
}

View File

@@ -32,7 +32,7 @@ The script can be configured through environment variables in a `.env` file at t
- `PERPLEXITY_API_KEY`: Your Perplexity API key for research-backed subtask generation
- `PERPLEXITY_MODEL`: Specify which Perplexity model to use (default: "sonar-medium-online")
- `DEBUG`: Enable debug logging (default: false)
- `LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
- `TASKMASTER_LOG_LEVEL`: Log level - debug, info, warn, error (default: info)
- `DEFAULT_SUBTASKS`: Default number of subtasks when expanding (default: 3)
- `DEFAULT_PRIORITY`: Default priority for generated tasks (default: medium)
- `PROJECT_NAME`: Override default project name in tasks.json
@@ -225,7 +225,7 @@ To use the Perplexity integration:
## Logging
The script supports different logging levels controlled by the `LOG_LEVEL` environment variable:
The script supports different logging levels controlled by the `TASKMASTER_LOG_LEVEL` environment variable:
- `debug`: Detailed information, typically useful for troubleshooting
- `info`: Confirmation that things are working as expected (default)

View File

@@ -38,10 +38,10 @@ const LOG_LEVELS = {
success: 4
};
// Get log level from environment or default to info
const LOG_LEVEL = process.env.LOG_LEVEL
? LOG_LEVELS[process.env.LOG_LEVEL.toLowerCase()]
: LOG_LEVELS.info;
// Determine log level from environment variable or default to 'info'
const LOG_LEVEL = process.env.TASKMASTER_LOG_LEVEL
? LOG_LEVELS[process.env.TASKMASTER_LOG_LEVEL.toLowerCase()]
: LOG_LEVELS.info; // Default to info
// Create a color gradient for the banner
const coolGradient = gradient(['#00b4d8', '#0077b6', '#03045e']);

View File

@@ -14,58 +14,77 @@ import {
getResearchModelId,
getFallbackProvider,
getFallbackModelId,
getParametersForRole
getParametersForRole,
getUserId,
MODEL_MAP,
getDebugFlag,
getBaseUrlForRole,
isApiKeySet,
getOllamaBaseURL,
getAzureBaseURL,
getVertexProjectId,
getVertexLocation
} from './config-manager.js';
import { log, resolveEnvVariable, findProjectRoot } from './utils.js';
import { log, findProjectRoot, resolveEnvVariable } from './utils.js';
import * as anthropic from '../../src/ai-providers/anthropic.js';
import * as perplexity from '../../src/ai-providers/perplexity.js';
import * as google from '../../src/ai-providers/google.js';
import * as openai from '../../src/ai-providers/openai.js';
import * as xai from '../../src/ai-providers/xai.js';
import * as openrouter from '../../src/ai-providers/openrouter.js';
// TODO: Import other provider modules when implemented (ollama, etc.)
// Import provider classes
import {
AnthropicAIProvider,
PerplexityAIProvider,
GoogleAIProvider,
OpenAIProvider,
XAIProvider,
OpenRouterAIProvider,
OllamaAIProvider,
BedrockAIProvider,
AzureProvider,
VertexAIProvider
} from '../../src/ai-providers/index.js';
// --- Provider Function Map ---
// Maps provider names (lowercase) to their respective service functions
const PROVIDER_FUNCTIONS = {
anthropic: {
generateText: anthropic.generateAnthropicText,
streamText: anthropic.streamAnthropicText,
generateObject: anthropic.generateAnthropicObject
},
perplexity: {
generateText: perplexity.generatePerplexityText,
streamText: perplexity.streamPerplexityText,
generateObject: perplexity.generatePerplexityObject
},
google: {
// Add Google entry
generateText: google.generateGoogleText,
streamText: google.streamGoogleText,
generateObject: google.generateGoogleObject
},
openai: {
// ADD: OpenAI entry
generateText: openai.generateOpenAIText,
streamText: openai.streamOpenAIText,
generateObject: openai.generateOpenAIObject
},
xai: {
// ADD: xAI entry
generateText: xai.generateXaiText,
streamText: xai.streamXaiText,
generateObject: xai.generateXaiObject // Note: Object generation might be unsupported
},
openrouter: {
// ADD: OpenRouter entry
generateText: openrouter.generateOpenRouterText,
streamText: openrouter.streamOpenRouterText,
generateObject: openrouter.generateOpenRouterObject
}
// TODO: Add entries for ollama, etc. when implemented
// Create provider instances
const PROVIDERS = {
anthropic: new AnthropicAIProvider(),
perplexity: new PerplexityAIProvider(),
google: new GoogleAIProvider(),
openai: new OpenAIProvider(),
xai: new XAIProvider(),
openrouter: new OpenRouterAIProvider(),
ollama: new OllamaAIProvider(),
bedrock: new BedrockAIProvider(),
azure: new AzureProvider(),
vertex: new VertexAIProvider()
};
// Helper function to get cost for a specific model
function _getCostForModel(providerName, modelId) {
if (!MODEL_MAP || !MODEL_MAP[providerName]) {
log(
'warn',
`Provider "${providerName}" not found in MODEL_MAP. Cannot determine cost for model ${modelId}.`
);
return { inputCost: 0, outputCost: 0, currency: 'USD' }; // Default to zero cost
}
const modelData = MODEL_MAP[providerName].find((m) => m.id === modelId);
if (!modelData || !modelData.cost_per_1m_tokens) {
log(
'debug',
`Cost data not found for model "${modelId}" under provider "${providerName}". Assuming zero cost.`
);
return { inputCost: 0, outputCost: 0, currency: 'USD' }; // Default to zero cost
}
// Ensure currency is part of the returned object, defaulting if not present
const currency = modelData.cost_per_1m_tokens.currency || 'USD';
return {
inputCost: modelData.cost_per_1m_tokens.input || 0,
outputCost: modelData.cost_per_1m_tokens.output || 0,
currency: currency
};
}
// --- Configuration for Retries ---
const MAX_RETRIES = 2;
const INITIAL_RETRY_DELAY_MS = 1000;
@@ -149,14 +168,12 @@ function _resolveApiKey(providerName, session, projectRoot = null) {
mistral: 'MISTRAL_API_KEY',
azure: 'AZURE_OPENAI_API_KEY',
openrouter: 'OPENROUTER_API_KEY',
xai: 'XAI_API_KEY'
xai: 'XAI_API_KEY',
ollama: 'OLLAMA_API_KEY',
bedrock: 'AWS_ACCESS_KEY_ID',
vertex: 'GOOGLE_API_KEY'
};
// Double check this -- I have had to use an api key for ollama in the past
// if (providerName === 'ollama') {
// return null; // Ollama typically doesn't require an API key for basic setup
// }
const envVarName = keyMap[providerName];
if (!envVarName) {
throw new Error(
@@ -165,6 +182,12 @@ function _resolveApiKey(providerName, session, projectRoot = null) {
}
const apiKey = resolveEnvVariable(envVarName, session, projectRoot);
// Special handling for providers that can use alternative auth
if (providerName === 'ollama' || providerName === 'bedrock') {
return apiKey || null;
}
if (!apiKey) {
throw new Error(
`Required API key ${envVarName} for provider '${providerName}' is not set in environment, session, or .env file.`
@@ -185,29 +208,34 @@ function _resolveApiKey(providerName, session, projectRoot = null) {
* @throws {Error} If the call fails after all retries.
*/
async function _attemptProviderCallWithRetries(
providerApiFn,
provider,
serviceType,
callParams,
providerName,
modelId,
attemptRole
) {
let retries = 0;
const fnName = providerApiFn.name;
const fnName = serviceType;
while (retries <= MAX_RETRIES) {
try {
if (getDebugFlag()) {
log(
'info',
`Attempt ${retries + 1}/${MAX_RETRIES + 1} calling ${fnName} (Provider: ${providerName}, Model: ${modelId}, Role: ${attemptRole})`
);
}
// Call the specific provider function directly
const result = await providerApiFn(callParams);
// Call the appropriate method on the provider instance
const result = await provider[serviceType](callParams);
if (getDebugFlag()) {
log(
'info',
`${fnName} succeeded for role ${attemptRole} (Provider: ${providerName}) on attempt ${retries + 1}`
);
}
return result;
} catch (error) {
log(
@@ -220,13 +248,13 @@ async function _attemptProviderCallWithRetries(
const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retries - 1);
log(
'info',
`Retryable error detected. Retrying in ${delay / 1000}s...`
`Something went wrong on the provider side. Retrying in ${delay / 1000}s...`
);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
log(
'error',
`Non-retryable error or max retries reached for role ${attemptRole} (${fnName} / ${providerName}).`
`Something went wrong on the provider side. Max retries reached for role ${attemptRole} (${fnName} / ${providerName}).`
);
throw error;
}
@@ -242,7 +270,15 @@ async function _attemptProviderCallWithRetries(
* Base logic for unified service functions.
* @param {string} serviceType - Type of service ('generateText', 'streamText', 'generateObject').
* @param {object} params - Original parameters passed to the service function.
* @param {string} params.role - The initial client role.
* @param {object} [params.session=null] - Optional MCP session object.
* @param {string} [params.projectRoot] - Optional project root path.
* @param {string} params.commandName - Name of the command invoking the service.
* @param {string} params.outputType - 'cli' or 'mcp'.
* @param {string} [params.systemPrompt] - Optional system prompt.
* @param {string} [params.prompt] - The prompt for the AI.
* @param {string} [params.schema] - The Zod schema for the expected object.
* @param {string} [params.objectName] - Name for object/tool.
* @returns {Promise<any>} Result from the underlying provider call.
*/
async function _unifiedServiceRunner(serviceType, params) {
@@ -254,15 +290,21 @@ async function _unifiedServiceRunner(serviceType, params) {
prompt,
schema,
objectName,
commandName,
outputType,
...restApiParams
} = params;
if (getDebugFlag()) {
log('info', `${serviceType}Service called`, {
role: initialRole,
commandName,
outputType,
projectRoot
});
}
// Determine the effective project root (passed in or detected)
const effectiveProjectRoot = projectRoot || findProjectRoot();
const userId = getUserId(effectiveProjectRoot);
let sequence;
if (initialRole === 'main') {
@@ -284,13 +326,18 @@ async function _unifiedServiceRunner(serviceType, params) {
'AI service call failed for all configured roles.';
for (const currentRole of sequence) {
let providerName, modelId, apiKey, roleParams, providerFnSet, providerApiFn;
let providerName,
modelId,
apiKey,
roleParams,
provider,
baseURL,
providerResponse,
telemetryData = null;
try {
log('info', `New AI service call with role: ${currentRole}`);
// 1. Get Config: Provider, Model, Parameters for the current role
// Pass effectiveProjectRoot to config getters
if (currentRole === 'main') {
providerName = getMainProvider(effectiveProjectRoot);
modelId = getMainModelId(effectiveProjectRoot);
@@ -323,15 +370,12 @@ async function _unifiedServiceRunner(serviceType, params) {
continue;
}
// Pass effectiveProjectRoot to getParametersForRole
roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
// 2. Get Provider Function Set
providerFnSet = PROVIDER_FUNCTIONS[providerName?.toLowerCase()];
if (!providerFnSet) {
// Get provider instance
provider = PROVIDERS[providerName?.toLowerCase()];
if (!provider) {
log(
'warn',
`Skipping role '${currentRole}': Provider '${providerName}' not supported or map entry missing.`
`Skipping role '${currentRole}': Provider '${providerName}' not supported.`
);
lastError =
lastError ||
@@ -339,30 +383,86 @@ async function _unifiedServiceRunner(serviceType, params) {
continue;
}
// Use the original service type to get the function
providerApiFn = providerFnSet[serviceType];
if (typeof providerApiFn !== 'function') {
// Check API key if needed
if (providerName?.toLowerCase() !== 'ollama') {
if (!isApiKeySet(providerName, session, effectiveProjectRoot)) {
log(
'warn',
`Skipping role '${currentRole}': Service type '${serviceType}' not implemented for provider '${providerName}'.`
`Skipping role '${currentRole}' (Provider: ${providerName}): API key not set or invalid.`
);
lastError =
lastError ||
new Error(
`Service '${serviceType}' not implemented for provider ${providerName}`
`API key for provider '${providerName}' (role: ${currentRole}) is not set.`
);
continue;
continue; // Skip to the next role in the sequence
}
}
// 3. Resolve API Key (will throw if required and missing)
// Pass effectiveProjectRoot to _resolveApiKey
// Get base URL if configured (optional for most providers)
baseURL = getBaseUrlForRole(currentRole, effectiveProjectRoot);
// For Azure, use the global Azure base URL if role-specific URL is not configured
if (providerName?.toLowerCase() === 'azure' && !baseURL) {
baseURL = getAzureBaseURL(effectiveProjectRoot);
log('debug', `Using global Azure base URL: ${baseURL}`);
} else if (providerName?.toLowerCase() === 'ollama' && !baseURL) {
// For Ollama, use the global Ollama base URL if role-specific URL is not configured
baseURL = getOllamaBaseURL(effectiveProjectRoot);
log('debug', `Using global Ollama base URL: ${baseURL}`);
}
// Get AI parameters for the current role
roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
apiKey = _resolveApiKey(
providerName?.toLowerCase(),
session,
effectiveProjectRoot
);
// 4. Construct Messages Array
// Prepare provider-specific configuration
let providerSpecificParams = {};
// Handle Vertex AI specific configuration
if (providerName?.toLowerCase() === 'vertex') {
// Get Vertex project ID and location
const projectId =
getVertexProjectId(effectiveProjectRoot) ||
resolveEnvVariable(
'VERTEX_PROJECT_ID',
session,
effectiveProjectRoot
);
const location =
getVertexLocation(effectiveProjectRoot) ||
resolveEnvVariable(
'VERTEX_LOCATION',
session,
effectiveProjectRoot
) ||
'us-central1';
// Get credentials path if available
const credentialsPath = resolveEnvVariable(
'GOOGLE_APPLICATION_CREDENTIALS',
session,
effectiveProjectRoot
);
// Add Vertex-specific parameters
providerSpecificParams = {
projectId,
location,
...(credentialsPath && { credentials: { credentialsFromEnv: true } })
};
log(
'debug',
`Using Vertex AI configuration: Project ID=${projectId}, Location=${location}`
);
}
const messages = [];
if (systemPrompt) {
messages.push({ role: 'system', content: systemPrompt });
@@ -387,36 +487,73 @@ async function _unifiedServiceRunner(serviceType, params) {
// }
if (prompt) {
// Ensure prompt exists before adding
messages.push({ role: 'user', content: prompt });
} else {
// Throw an error if the prompt is missing, as it's essential
throw new Error('User prompt content is missing.');
}
// 5. Prepare call parameters (using messages array)
const callParams = {
apiKey,
modelId,
maxTokens: roleParams.maxTokens,
temperature: roleParams.temperature,
messages,
...(baseURL && { baseURL }),
...(serviceType === 'generateObject' && { schema, objectName }),
...providerSpecificParams,
...restApiParams
};
// 6. Attempt the call with retries
const result = await _attemptProviderCallWithRetries(
providerApiFn,
providerResponse = await _attemptProviderCallWithRetries(
provider,
serviceType,
callParams,
providerName,
modelId,
currentRole
);
log('info', `${serviceType}Service succeeded using role: ${currentRole}`);
if (userId && providerResponse && providerResponse.usage) {
try {
telemetryData = await logAiUsage({
userId,
commandName,
providerName,
modelId,
inputTokens: providerResponse.usage.inputTokens,
outputTokens: providerResponse.usage.outputTokens,
outputType
});
} catch (telemetryError) {
// logAiUsage already logs its own errors and returns null on failure
// No need to log again here, telemetryData will remain null
}
} else if (userId && providerResponse && !providerResponse.usage) {
log(
'warn',
`Cannot log telemetry for ${commandName} (${providerName}/${modelId}): AI result missing 'usage' data. (May be expected for streams)`
);
}
return result;
let finalMainResult;
if (serviceType === 'generateText') {
finalMainResult = providerResponse.text;
} else if (serviceType === 'generateObject') {
finalMainResult = providerResponse.object;
} else if (serviceType === 'streamText') {
finalMainResult = providerResponse;
} else {
log(
'error',
`Unknown serviceType in _unifiedServiceRunner: ${serviceType}`
);
finalMainResult = providerResponse;
}
return {
mainResult: finalMainResult,
telemetryData: telemetryData
};
} catch (error) {
const cleanMessage = _extractErrorMessage(error);
log(
@@ -445,9 +582,7 @@ async function _unifiedServiceRunner(serviceType, params) {
}
}
// If loop completes, all roles failed
log('error', `All roles in the sequence [${sequence.join(', ')}] failed.`);
// Throw a new error with the cleaner message from the last failure
throw new Error(lastCleanErrorMessage);
}
@@ -461,11 +596,16 @@ async function _unifiedServiceRunner(serviceType, params) {
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
* @param {string} params.prompt - The prompt for the AI.
* @param {string} [params.systemPrompt] - Optional system prompt.
* // Other specific generateText params can be included here.
* @returns {Promise<string>} The generated text content.
* @param {string} params.commandName - Name of the command invoking the service.
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'.
* @returns {Promise<object>} Result object containing generated text and usage data.
*/
async function generateTextService(params) {
return _unifiedServiceRunner('generateText', params);
// Ensure default outputType if not provided
const defaults = { outputType: 'cli' };
const combinedParams = { ...defaults, ...params };
// TODO: Validate commandName exists?
return _unifiedServiceRunner('generateText', combinedParams);
}
/**
@@ -478,11 +618,18 @@ async function generateTextService(params) {
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
* @param {string} params.prompt - The prompt for the AI.
* @param {string} [params.systemPrompt] - Optional system prompt.
* // Other specific streamText params can be included here.
* @returns {Promise<ReadableStream<string>>} A readable stream of text deltas.
* @param {string} params.commandName - Name of the command invoking the service.
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'.
* @returns {Promise<object>} Result object containing the stream and usage data.
*/
async function streamTextService(params) {
return _unifiedServiceRunner('streamText', params);
const defaults = { outputType: 'cli' };
const combinedParams = { ...defaults, ...params };
// TODO: Validate commandName exists?
// NOTE: Telemetry for streaming might be tricky as usage data often comes at the end.
// The current implementation logs *after* the stream is returned.
// We might need to adjust how usage is captured/logged for streams.
return _unifiedServiceRunner('streamText', combinedParams);
}
/**
@@ -498,15 +645,89 @@ async function streamTextService(params) {
* @param {string} [params.systemPrompt] - Optional system prompt.
* @param {string} [params.objectName='generated_object'] - Name for object/tool.
* @param {number} [params.maxRetries=3] - Max retries for object generation.
* @returns {Promise<object>} The generated object matching the schema.
* @param {string} params.commandName - Name of the command invoking the service.
* @param {string} [params.outputType='cli'] - 'cli' or 'mcp'.
* @returns {Promise<object>} Result object containing the generated object and usage data.
*/
async function generateObjectService(params) {
const defaults = {
objectName: 'generated_object',
maxRetries: 3
maxRetries: 3,
outputType: 'cli'
};
const combinedParams = { ...defaults, ...params };
// TODO: Validate commandName exists?
return _unifiedServiceRunner('generateObject', combinedParams);
}
export { generateTextService, streamTextService, generateObjectService };
// --- Telemetry Function ---
/**
* Logs AI usage telemetry data.
* For now, it just logs to the console. Sending will be implemented later.
* @param {object} params - Telemetry parameters.
* @param {string} params.userId - Unique user identifier.
* @param {string} params.commandName - The command that triggered the AI call.
* @param {string} params.providerName - The AI provider used (e.g., 'openai').
* @param {string} params.modelId - The specific AI model ID used.
* @param {number} params.inputTokens - Number of input tokens.
* @param {number} params.outputTokens - Number of output tokens.
*/
async function logAiUsage({
userId,
commandName,
providerName,
modelId,
inputTokens,
outputTokens,
outputType
}) {
try {
const isMCP = outputType === 'mcp';
const timestamp = new Date().toISOString();
const totalTokens = (inputTokens || 0) + (outputTokens || 0);
// Destructure currency along with costs
const { inputCost, outputCost, currency } = _getCostForModel(
providerName,
modelId
);
const totalCost =
((inputTokens || 0) / 1_000_000) * inputCost +
((outputTokens || 0) / 1_000_000) * outputCost;
const telemetryData = {
timestamp,
userId,
commandName,
modelUsed: modelId, // Consistent field name from requirements
providerName, // Keep provider name for context
inputTokens: inputTokens || 0,
outputTokens: outputTokens || 0,
totalTokens,
totalCost: parseFloat(totalCost.toFixed(6)),
currency // Add currency to the telemetry data
};
if (getDebugFlag()) {
log('info', 'AI Usage Telemetry:', telemetryData);
}
// TODO (Subtask 77.2): Send telemetryData securely to the external endpoint.
return telemetryData;
} catch (error) {
log('error', `Failed to log AI usage telemetry: ${error.message}`, {
error
});
// Don't re-throw; telemetry failure shouldn't block core functionality.
return null;
}
}
export {
generateTextService,
streamTextService,
generateObjectService,
logAiUsage
};

View File

@@ -9,10 +9,11 @@ import chalk from 'chalk';
import boxen from 'boxen';
import fs from 'fs';
import https from 'https';
import http from 'http';
import inquirer from 'inquirer';
import ora from 'ora'; // Import ora
import { log, readJSON } from './utils.js';
import { log, readJSON, findProjectRoot } from './utils.js';
import {
parsePRD,
updateTasks,
@@ -30,7 +31,8 @@ import {
updateSubtaskById,
removeTask,
findTaskById,
taskExists
taskExists,
moveTask
} from './task-manager.js';
import {
@@ -47,7 +49,8 @@ import {
writeConfig,
ConfigurationError,
isConfigFilePresent,
getAvailableModels
getAvailableModels,
getBaseUrlForRole
} from './config-manager.js';
import {
@@ -62,7 +65,8 @@ import {
stopLoadingIndicator,
displayModelConfiguration,
displayAvailableModels,
displayApiKeyStatus
displayApiKeyStatus,
displayAiUsageSummary
} from './ui.js';
import { initializeProject } from '../init.js';
@@ -72,8 +76,11 @@ import {
setModel,
getApiKeyStatusReport
} from './task-manager/models.js';
import { findProjectRoot } from './utils.js';
import {
isValidTaskStatus,
TASK_STATUS_OPTIONS
} from '../../src/constants/task-status.js';
import { getTaskMasterVersion } from '../../src/utils/getVersion.js';
/**
* Runs the interactive setup process for model configuration.
* @param {string|null} projectRoot - The resolved project root directory.
@@ -147,6 +154,64 @@ async function runInteractiveSetup(projectRoot) {
});
}
// Helper function to fetch Ollama models (duplicated for CLI context)
function fetchOllamaModelsCLI(baseURL = 'http://localhost:11434/api') {
return new Promise((resolve) => {
try {
// Parse the base URL to extract hostname, port, and base path
const url = new URL(baseURL);
const isHttps = url.protocol === 'https:';
const port = url.port || (isHttps ? 443 : 80);
const basePath = url.pathname.endsWith('/')
? url.pathname.slice(0, -1)
: url.pathname;
const options = {
hostname: url.hostname,
port: parseInt(port, 10),
path: `${basePath}/tags`,
method: 'GET',
headers: {
Accept: 'application/json'
}
};
const requestLib = isHttps ? https : http;
const req = requestLib.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
try {
const parsedData = JSON.parse(data);
resolve(parsedData.models || []); // Return the array of models
} catch (e) {
console.error('Error parsing Ollama response:', e);
resolve(null); // Indicate failure
}
} else {
console.error(
`Ollama API request failed with status code: ${res.statusCode}`
);
resolve(null); // Indicate failure
}
});
});
req.on('error', (e) => {
console.error('Error fetching Ollama models:', e);
resolve(null); // Indicate failure
});
req.end();
} catch (e) {
console.error('Error parsing Ollama base URL:', e);
resolve(null); // Indicate failure
}
});
}
// Helper to get choices and default index for a role
const getPromptData = (role, allowNone = false) => {
const currentModel = currentModels[role]; // Use the fetched data
@@ -174,6 +239,16 @@ async function runInteractiveSetup(projectRoot) {
value: '__CUSTOM_OPENROUTER__'
};
const customOllamaOption = {
name: '* Custom Ollama model', // Symbol updated
value: '__CUSTOM_OLLAMA__'
};
const customBedrockOption = {
name: '* Custom Bedrock model', // Add Bedrock custom option
value: '__CUSTOM_BEDROCK__'
};
let choices = [];
let defaultIndex = 0; // Default to 'Cancel'
@@ -219,6 +294,8 @@ async function runInteractiveSetup(projectRoot) {
}
commonPrefix.push(cancelOption);
commonPrefix.push(customOpenRouterOption);
commonPrefix.push(customOllamaOption);
commonPrefix.push(customBedrockOption);
let prefixLength = commonPrefix.length; // Initial prefix length
@@ -349,6 +426,82 @@ async function runInteractiveSetup(projectRoot) {
setupSuccess = false;
return true; // Continue setup, but mark as failed
}
} else if (selectedValue === '__CUSTOM_OLLAMA__') {
isCustomSelection = true;
const { customId } = await inquirer.prompt([
{
type: 'input',
name: 'customId',
message: `Enter the custom Ollama Model ID for the ${role} role:`
}
]);
if (!customId) {
console.log(chalk.yellow('No custom ID entered. Skipping role.'));
return true; // Continue setup, but don't set this role
}
modelIdToSet = customId;
providerHint = 'ollama';
// Get the Ollama base URL from config for this role
const ollamaBaseURL = getBaseUrlForRole(role, projectRoot);
// Validate against live Ollama list
const ollamaModels = await fetchOllamaModelsCLI(ollamaBaseURL);
if (ollamaModels === null) {
console.error(
chalk.red(
`Error: Unable to connect to Ollama server at ${ollamaBaseURL}. Please ensure Ollama is running and try again.`
)
);
setupSuccess = false;
return true; // Continue setup, but mark as failed
} else if (!ollamaModels.some((m) => m.model === modelIdToSet)) {
console.error(
chalk.red(
`Error: Model ID "${modelIdToSet}" not found in the Ollama instance. Please verify the model is pulled and available.`
)
);
console.log(
chalk.yellow(
`You can check available models with: curl ${ollamaBaseURL}/tags`
)
);
setupSuccess = false;
return true; // Continue setup, but mark as failed
}
} else if (selectedValue === '__CUSTOM_BEDROCK__') {
isCustomSelection = true;
const { customId } = await inquirer.prompt([
{
type: 'input',
name: 'customId',
message: `Enter the custom Bedrock Model ID for the ${role} role (e.g., anthropic.claude-3-sonnet-20240229-v1:0):`
}
]);
if (!customId) {
console.log(chalk.yellow('No custom ID entered. Skipping role.'));
return true; // Continue setup, but don't set this role
}
modelIdToSet = customId;
providerHint = 'bedrock';
// Check if AWS environment variables exist
if (
!process.env.AWS_ACCESS_KEY_ID ||
!process.env.AWS_SECRET_ACCESS_KEY
) {
console.error(
chalk.red(
`Error: AWS_ACCESS_KEY_ID and/or AWS_SECRET_ACCESS_KEY environment variables are missing. Please set them before using custom Bedrock models.`
)
);
setupSuccess = false;
return true; // Continue setup, but mark as failed
}
console.log(
chalk.blue(
`Custom Bedrock model "${modelIdToSet}" will be used. No validation performed.`
)
);
} else if (
selectedValue &&
typeof selectedValue === 'object' &&
@@ -486,11 +639,6 @@ function registerCommands(programInstance) {
process.exit(1);
});
// Default help
programInstance.on('--help', function () {
displayHelp();
});
// parse-prd command
programInstance
.command('parse-prd')
@@ -507,6 +655,10 @@ function registerCommands(programInstance) {
'--append',
'Append new tasks to existing tasks.json instead of overwriting'
)
.option(
'-r, --research',
'Use Perplexity AI for research-backed task generation, providing more comprehensive and accurate task breakdown'
)
.action(async (file, options) => {
// Use input option if file argument not provided
const inputFile = file || options.input;
@@ -515,8 +667,9 @@ function registerCommands(programInstance) {
const outputPath = options.output;
const force = options.force || false;
const append = options.append || false;
let useForce = false;
let useAppend = false;
const research = options.research || false;
let useForce = force;
let useAppend = append;
// Helper function to check if tasks.json exists and confirm overwrite
async function confirmOverwriteIfNeeded() {
@@ -544,10 +697,11 @@ function registerCommands(programInstance) {
if (!(await confirmOverwriteIfNeeded())) return;
console.log(chalk.blue(`Generating ${numTasks} tasks...`));
spinner = ora('Parsing PRD and generating tasks...').start();
spinner = ora('Parsing PRD and generating tasks...\n').start();
await parsePRD(defaultPrdPath, outputPath, numTasks, {
useAppend,
useForce
append: useAppend, // Changed key from useAppend to append
force: useForce, // Changed key from useForce to force
research: research
});
spinner.succeed('Tasks generated successfully!');
return;
@@ -571,13 +725,15 @@ function registerCommands(programInstance) {
' -o, --output <file> Output file path (default: "tasks/tasks.json")\n' +
' -n, --num-tasks <number> Number of tasks to generate (default: 10)\n' +
' -f, --force Skip confirmation when overwriting existing tasks\n' +
' --append Append new tasks to existing tasks.json instead of overwriting\n\n' +
' --append Append new tasks to existing tasks.json instead of overwriting\n' +
' -r, --research Use Perplexity AI for research-backed task generation\n\n' +
chalk.cyan('Example:') +
'\n' +
' task-master parse-prd requirements.txt --num-tasks 15\n' +
' task-master parse-prd --input=requirements.txt\n' +
' task-master parse-prd --force\n' +
' task-master parse-prd requirements_v2.txt --append\n\n' +
' task-master parse-prd requirements_v2.txt --append\n' +
' task-master parse-prd requirements.txt --research\n\n' +
chalk.yellow('Note: This command will:') +
'\n' +
' 1. Look for a PRD file at scripts/prd.txt by default\n' +
@@ -605,11 +761,19 @@ function registerCommands(programInstance) {
if (append) {
console.log(chalk.blue('Appending to existing tasks...'));
}
if (research) {
console.log(
chalk.blue(
'Using Perplexity AI for research-backed task generation'
)
);
}
spinner = ora('Parsing PRD and generating tasks...').start();
spinner = ora('Parsing PRD and generating tasks...\n').start();
await parsePRD(inputFile, outputPath, numTasks, {
append: useAppend,
force: useForce
force: useForce,
research: research
});
spinner.succeed('Tasks generated successfully!');
} catch (error) {
@@ -1031,6 +1195,8 @@ function registerCommands(programInstance) {
// set-status command
programInstance
.command('set-status')
.alias('mark')
.alias('set')
.description('Set the status of a task')
.option(
'-i, --id <id>',
@@ -1038,7 +1204,7 @@ function registerCommands(programInstance) {
)
.option(
'-s, --status <status>',
'New status (todo, in-progress, review, done)'
`New status (one of: ${TASK_STATUS_OPTIONS.join(', ')})`
)
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (options) => {
@@ -1051,6 +1217,16 @@ function registerCommands(programInstance) {
process.exit(1);
}
if (!isValidTaskStatus(status)) {
console.error(
chalk.red(
`Error: Invalid status value: ${status}. Use one of: ${TASK_STATUS_OPTIONS.join(', ')}`
)
);
process.exit(1);
}
console.log(
chalk.blue(`Setting status of task(s) ${taskId} to: ${status}`)
);
@@ -1063,10 +1239,16 @@ function registerCommands(programInstance) {
.command('list')
.description('List all tasks')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option(
'-r, --report <report>',
'Path to the complexity report file',
'scripts/task-complexity-report.json'
)
.option('-s, --status <status>', 'Filter by status')
.option('--with-subtasks', 'Show subtasks for each task')
.action(async (options) => {
const tasksPath = options.file;
const reportPath = options.report;
const statusFilter = options.status;
const withSubtasks = options.withSubtasks || false;
@@ -1078,7 +1260,7 @@ function registerCommands(programInstance) {
console.log(chalk.blue('Including subtasks in listing'));
}
await listTasks(tasksPath, statusFilter, withSubtasks);
await listTasks(tasksPath, statusFilter, reportPath, withSubtasks);
});
// expand command
@@ -1128,12 +1310,6 @@ function registerCommands(programInstance) {
{} // Pass empty context for CLI calls
// outputFormat defaults to 'text' in expandAllTasks for CLI
);
// Optional: Display summary from result
console.log(chalk.green(`Expansion Summary:`));
console.log(chalk.green(` - Attempted: ${result.tasksToExpand}`));
console.log(chalk.green(` - Expanded: ${result.expandedCount}`));
console.log(chalk.yellow(` - Skipped: ${result.skippedCount}`));
console.log(chalk.red(` - Failed: ${result.failedCount}`));
} catch (error) {
console.error(
chalk.red(`Error expanding all tasks: ${error.message}`)
@@ -1201,6 +1377,12 @@ function registerCommands(programInstance) {
'-r, --research',
'Use Perplexity AI for research-backed complexity analysis'
)
.option(
'-i, --id <ids>',
'Comma-separated list of specific task IDs to analyze (e.g., "1,3,5")'
)
.option('--from <id>', 'Starting task ID in a range to analyze')
.option('--to <id>', 'Ending task ID in a range to analyze')
.action(async (options) => {
const tasksPath = options.file || 'tasks/tasks.json';
const outputPath = options.output;
@@ -1211,6 +1393,16 @@ function registerCommands(programInstance) {
console.log(chalk.blue(`Analyzing task complexity from: ${tasksPath}`));
console.log(chalk.blue(`Output report will be saved to: ${outputPath}`));
if (options.id) {
console.log(chalk.blue(`Analyzing specific task IDs: ${options.id}`));
} else if (options.from || options.to) {
const fromStr = options.from ? options.from : 'first';
const toStr = options.to ? options.to : 'last';
console.log(
chalk.blue(`Analyzing tasks in range: ${fromStr} to ${toStr}`)
);
}
if (useResearch) {
console.log(
chalk.blue(
@@ -1263,7 +1455,7 @@ function registerCommands(programInstance) {
// add-task command
programInstance
.command('add-task')
.description('Add a new task using AI or manual input')
.description('Add a new task using AI, optionally providing manual details')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option(
'-p, --prompt <prompt>',
@@ -1278,10 +1470,6 @@ function registerCommands(programInstance) {
'--details <details>',
'Implementation details (for manual task creation)'
)
.option(
'--test-strategy <testStrategy>',
'Test strategy (for manual task creation)'
)
.option(
'--dependencies <dependencies>',
'Comma-separated list of task IDs this task depends on'
@@ -1308,16 +1496,14 @@ function registerCommands(programInstance) {
process.exit(1);
}
try {
// Prepare dependencies if provided
let dependencies = [];
if (options.dependencies) {
dependencies = options.dependencies
.split(',')
.map((id) => parseInt(id.trim(), 10));
}
const tasksPath =
options.file ||
path.join(findProjectRoot() || '.', 'tasks', 'tasks.json') || // Ensure tasksPath is also relative to a found root or current dir
'tasks/tasks.json';
// Correctly determine projectRoot
const projectRoot = findProjectRoot();
// Create manual task data if title and description are provided
let manualTaskData = null;
if (isManualCreation) {
manualTaskData = {
@@ -1326,56 +1512,54 @@ function registerCommands(programInstance) {
details: options.details || '',
testStrategy: options.testStrategy || ''
};
// Restore specific logging for manual creation
console.log(
chalk.blue(`Creating task manually with title: "${options.title}"`)
);
if (dependencies.length > 0) {
console.log(
chalk.blue(`Dependencies: [${dependencies.join(', ')}]`)
);
}
if (options.priority) {
console.log(chalk.blue(`Priority: ${options.priority}`));
}
} else {
// Restore specific logging for AI creation
console.log(
chalk.blue(
`Creating task with AI using prompt: "${options.prompt}"`
)
chalk.blue(`Creating task with AI using prompt: "${options.prompt}"`)
);
if (dependencies.length > 0) {
}
// Log dependencies and priority if provided (restored)
const dependenciesArray = options.dependencies
? options.dependencies.split(',').map((id) => id.trim())
: [];
if (dependenciesArray.length > 0) {
console.log(
chalk.blue(`Dependencies: [${dependencies.join(', ')}]`)
chalk.blue(`Dependencies: [${dependenciesArray.join(', ')}]`)
);
}
if (options.priority) {
console.log(chalk.blue(`Priority: ${options.priority}`));
}
}
// Pass mcpLog and session for MCP mode
const newTaskId = await addTask(
options.file,
options.prompt, // Pass prompt (will be null/undefined if not provided)
dependencies,
const context = {
projectRoot,
commandName: 'add-task',
outputType: 'cli'
};
try {
const { newTaskId, telemetryData } = await addTask(
tasksPath,
options.prompt,
dependenciesArray,
options.priority,
{
// For CLI, session context isn't directly available like MCP
// We don't need to pass session here for CLI API key resolution
// as dotenv loads .env, and utils.resolveEnvVariable checks process.env
},
'text', // outputFormat
manualTaskData, // Pass the potentially created manualTaskData object
options.research || false // Pass the research flag value
context,
'text',
manualTaskData,
options.research
);
console.log(chalk.green(`✓ Added new task #${newTaskId}`));
console.log(chalk.gray('Next: Complete this task or add more tasks'));
// addTask handles detailed CLI success logging AND telemetry display when outputFormat is 'text'
// No need to call displayAiUsageSummary here anymore.
} catch (error) {
console.error(chalk.red(`Error adding task: ${error.message}`));
if (error.stack && getDebugFlag()) {
console.error(error.stack);
if (error.details) {
console.error(chalk.red(error.details));
}
process.exit(1);
}
@@ -1388,9 +1572,15 @@ function registerCommands(programInstance) {
`Show the next task to work on based on dependencies and status${chalk.reset('')}`
)
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option(
'-r, --report <report>',
'Path to the complexity report file',
'scripts/task-complexity-report.json'
)
.action(async (options) => {
const tasksPath = options.file;
await displayNextTask(tasksPath);
const reportPath = options.report;
await displayNextTask(tasksPath, reportPath);
});
// show command
@@ -1403,6 +1593,11 @@ function registerCommands(programInstance) {
.option('-i, --id <id>', 'Task ID to show')
.option('-s, --status <status>', 'Filter subtasks by status') // ADDED status option
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option(
'-r, --report <report>',
'Path to the complexity report file',
'scripts/task-complexity-report.json'
)
.action(async (taskId, options) => {
const idArg = taskId || options.id;
const statusFilter = options.status; // ADDED: Capture status filter
@@ -1413,8 +1608,9 @@ function registerCommands(programInstance) {
}
const tasksPath = options.file;
const reportPath = options.report;
// PASS statusFilter to the display function
await displayTaskById(tasksPath, idArg, statusFilter);
await displayTaskById(tasksPath, idArg, reportPath, statusFilter);
});
// add-dependency command
@@ -1663,6 +1859,7 @@ function registerCommands(programInstance) {
}
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
showAddSubtaskHelp();
process.exit(1);
}
})
@@ -2069,7 +2266,7 @@ function registerCommands(programInstance) {
);
// Exit with error if any removals failed
if (successfulRemovals.length === 0) {
if (result.removedTasks.length === 0) {
process.exit(1);
}
}
@@ -2137,6 +2334,10 @@ function registerCommands(programInstance) {
'--ollama',
'Allow setting a custom Ollama model ID (use with --set-*) '
)
.option(
'--bedrock',
'Allow setting a custom Bedrock model ID (use with --set-*) '
)
.addHelpText(
'after',
`
@@ -2146,17 +2347,26 @@ Examples:
$ task-master models --set-research sonar-pro # Set research model
$ task-master models --set-fallback claude-3-5-sonnet-20241022 # Set fallback
$ task-master models --set-main my-custom-model --ollama # Set custom Ollama model for main role
$ task-master models --set-main anthropic.claude-3-sonnet-20240229-v1:0 --bedrock # Set custom Bedrock model for main role
$ task-master models --set-main some/other-model --openrouter # Set custom OpenRouter model for main role
$ task-master models --setup # Run interactive setup`
)
.action(async (options) => {
const projectRoot = findProjectRoot(); // Find project root for context
// Validate flags: cannot use both --openrouter and --ollama simultaneously
if (options.openrouter && options.ollama) {
const projectRoot = findProjectRoot();
if (!projectRoot) {
console.error(chalk.red('Error: Could not find project root.'));
process.exit(1);
}
// Validate flags: cannot use multiple provider flags simultaneously
const providerFlags = [
options.openrouter,
options.ollama,
options.bedrock
].filter(Boolean).length;
if (providerFlags > 1) {
console.error(
chalk.red(
'Error: Cannot use both --openrouter and --ollama flags simultaneously.'
'Error: Cannot use multiple provider flags (--openrouter, --ollama, --bedrock) simultaneously.'
)
);
process.exit(1);
@@ -2196,6 +2406,8 @@ Examples:
? 'openrouter'
: options.ollama
? 'ollama'
: options.bedrock
? 'bedrock'
: undefined
});
if (result.success) {
@@ -2216,6 +2428,8 @@ Examples:
? 'openrouter'
: options.ollama
? 'ollama'
: options.bedrock
? 'bedrock'
: undefined
});
if (result.success) {
@@ -2238,6 +2452,8 @@ Examples:
? 'openrouter'
: options.ollama
? 'ollama'
: options.bedrock
? 'bedrock'
: undefined
});
if (result.success) {
@@ -2334,6 +2550,135 @@ Examples:
return; // Stop execution here
});
// move-task command
programInstance
.command('move')
.description('Move a task or subtask to a new position')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option(
'--from <id>',
'ID of the task/subtask to move (e.g., "5" or "5.2"). Can be comma-separated to move multiple tasks (e.g., "5,6,7")'
)
.option(
'--to <id>',
'ID of the destination (e.g., "7" or "7.3"). Must match the number of source IDs if comma-separated'
)
.action(async (options) => {
const tasksPath = options.file;
const sourceId = options.from;
const destinationId = options.to;
if (!sourceId || !destinationId) {
console.error(
chalk.red('Error: Both --from and --to parameters are required')
);
console.log(
chalk.yellow(
'Usage: task-master move --from=<sourceId> --to=<destinationId>'
)
);
process.exit(1);
}
// Check if we're moving multiple tasks (comma-separated IDs)
const sourceIds = sourceId.split(',').map((id) => id.trim());
const destinationIds = destinationId.split(',').map((id) => id.trim());
// Validate that the number of source and destination IDs match
if (sourceIds.length !== destinationIds.length) {
console.error(
chalk.red(
'Error: The number of source and destination IDs must match'
)
);
console.log(
chalk.yellow('Example: task-master move --from=5,6,7 --to=10,11,12')
);
process.exit(1);
}
// If moving multiple tasks
if (sourceIds.length > 1) {
console.log(
chalk.blue(
`Moving multiple tasks: ${sourceIds.join(', ')} to ${destinationIds.join(', ')}...`
)
);
try {
// Read tasks data once to validate destination IDs
const tasksData = readJSON(tasksPath);
if (!tasksData || !tasksData.tasks) {
console.error(
chalk.red(`Error: Invalid or missing tasks file at ${tasksPath}`)
);
process.exit(1);
}
// Move tasks one by one
for (let i = 0; i < sourceIds.length; i++) {
const fromId = sourceIds[i];
const toId = destinationIds[i];
// Skip if source and destination are the same
if (fromId === toId) {
console.log(
chalk.yellow(`Skipping ${fromId} -> ${toId} (same ID)`)
);
continue;
}
console.log(
chalk.blue(`Moving task/subtask ${fromId} to ${toId}...`)
);
try {
await moveTask(
tasksPath,
fromId,
toId,
i === sourceIds.length - 1
);
console.log(
chalk.green(
`✓ Successfully moved task/subtask ${fromId} to ${toId}`
)
);
} catch (error) {
console.error(
chalk.red(`Error moving ${fromId} to ${toId}: ${error.message}`)
);
// Continue with the next task rather than exiting
}
}
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
process.exit(1);
}
} else {
// Moving a single task (existing logic)
console.log(
chalk.blue(`Moving task/subtask ${sourceId} to ${destinationId}...`)
);
try {
const result = await moveTask(
tasksPath,
sourceId,
destinationId,
true
);
console.log(
chalk.green(
`✓ Successfully moved task/subtask ${sourceId} to ${destinationId}`
)
);
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
process.exit(1);
}
}
});
return programInstance;
}
@@ -2366,14 +2711,7 @@ function setupCLI() {
return 'unknown'; // Default fallback if package.json fails
})
.helpOption('-h, --help', 'Display help')
.addHelpCommand(false) // Disable default help command
.on('--help', () => {
displayHelp(); // Use your custom help display instead
})
.on('-h', () => {
displayHelp();
process.exit(0);
});
.addHelpCommand(false); // Disable default help command
// Modify the help option to use your custom display
programInstance.helpInformation = () => {
@@ -2393,28 +2731,7 @@ function setupCLI() {
*/
async function checkForUpdate() {
// Get current version from package.json ONLY
let currentVersion = 'unknown'; // Initialize with a default
try {
// Try to get the version from the installed package (if applicable) or current dir
let packageJsonPath = path.join(
process.cwd(),
'node_modules',
'task-master-ai',
'package.json'
);
// Fallback to current directory package.json if not found in node_modules
if (!fs.existsSync(packageJsonPath)) {
packageJsonPath = path.join(process.cwd(), 'package.json');
}
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
currentVersion = packageJson.version;
}
} catch (error) {
// Silently fail and use default
log('debug', `Error reading current package version: ${error.message}`);
}
const currentVersion = getTaskMasterVersion();
return new Promise((resolve) => {
// Get the latest version from npm registry

View File

@@ -2,7 +2,7 @@ import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import { fileURLToPath } from 'url';
import { log, resolveEnvVariable, findProjectRoot } from './utils.js';
import { log, findProjectRoot, resolveEnvVariable } from './utils.js';
// Calculate __dirname in ESM
const __filename = fileURLToPath(import.meta.url);
@@ -61,7 +61,7 @@ const DEFAULTS = {
defaultSubtasks: 5,
defaultPriority: 'medium',
projectName: 'Task Master',
ollamaBaseUrl: 'http://localhost:11434/api'
ollamaBaseURL: 'http://localhost:11434/api'
}
};
@@ -361,9 +361,34 @@ function getProjectName(explicitRoot = null) {
return getGlobalConfig(explicitRoot).projectName;
}
function getOllamaBaseUrl(explicitRoot = null) {
function getOllamaBaseURL(explicitRoot = null) {
// Directly return value from config
return getGlobalConfig(explicitRoot).ollamaBaseUrl;
return getGlobalConfig(explicitRoot).ollamaBaseURL;
}
function getAzureBaseURL(explicitRoot = null) {
// Directly return value from config
return getGlobalConfig(explicitRoot).azureBaseURL;
}
/**
* Gets the Google Cloud project ID for Vertex AI from configuration
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string|null} The project ID or null if not configured
*/
function getVertexProjectId(explicitRoot = null) {
// Return value from config
return getGlobalConfig(explicitRoot).vertexProjectId;
}
/**
* Gets the Google Cloud location for Vertex AI from configuration
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string} The location or default value of "us-central1"
*/
function getVertexLocation(explicitRoot = null) {
// Return value from config or default
return getGlobalConfig(explicitRoot).vertexLocation || 'us-central1';
}
/**
@@ -450,7 +475,8 @@ function isApiKeySet(providerName, session = null, projectRoot = null) {
mistral: 'MISTRAL_API_KEY',
azure: 'AZURE_OPENAI_API_KEY',
openrouter: 'OPENROUTER_API_KEY',
xai: 'XAI_API_KEY'
xai: 'XAI_API_KEY',
vertex: 'GOOGLE_API_KEY' // Vertex uses the same key as Google
// Add other providers as needed
};
@@ -542,6 +568,10 @@ function getMcpApiKeyStatus(providerName, projectRoot = null) {
apiKeyToCheck = mcpEnv.AZURE_OPENAI_API_KEY;
placeholderValue = 'YOUR_AZURE_OPENAI_API_KEY_HERE';
break;
case 'vertex':
apiKeyToCheck = mcpEnv.GOOGLE_API_KEY; // Vertex uses Google API key
placeholderValue = 'YOUR_GOOGLE_API_KEY_HERE';
break;
default:
return false; // Unknown provider
}
@@ -669,6 +699,34 @@ function isConfigFilePresent(explicitRoot = null) {
return fs.existsSync(configPath);
}
/**
* Gets the user ID from the configuration.
* @param {string|null} explicitRoot - Optional explicit path to the project root.
* @returns {string|null} The user ID or null if not found.
*/
function getUserId(explicitRoot = null) {
const config = getConfig(explicitRoot);
if (!config.global) {
config.global = {}; // Ensure global object exists
}
if (!config.global.userId) {
config.global.userId = '1234567890';
// Attempt to write the updated config.
// It's important that writeConfig correctly resolves the path
// using explicitRoot, similar to how getConfig does.
const success = writeConfig(config, explicitRoot);
if (!success) {
// Log an error or handle the failure to write,
// though for now, we'll proceed with the in-memory default.
log(
'warning',
'Failed to write updated configuration with new userId. Please let the developers know.'
);
}
}
return config.global.userId;
}
/**
* Gets a list of all provider names defined in the MODEL_MAP.
* @returns {string[]} An array of provider names.
@@ -677,12 +735,19 @@ function getAllProviders() {
return Object.keys(MODEL_MAP || {});
}
function getBaseUrlForRole(role, explicitRoot = null) {
const roleConfig = getModelConfigForRole(role, explicitRoot);
return roleConfig && typeof roleConfig.baseURL === 'string'
? roleConfig.baseURL
: undefined;
}
export {
// Core config access
getConfig,
writeConfig,
ConfigurationError, // Export custom error type
isConfigFilePresent, // Add the new function export
ConfigurationError,
isConfigFilePresent,
// Validation
validateProvider,
@@ -704,6 +769,7 @@ export {
getFallbackModelId,
getFallbackMaxTokens,
getFallbackTemperature,
getBaseUrlForRole,
// Global setting getters (No env var overrides)
getLogLevel,
@@ -712,13 +778,16 @@ export {
getDefaultSubtasks,
getDefaultPriority,
getProjectName,
getOllamaBaseUrl,
getOllamaBaseURL,
getAzureBaseURL,
getParametersForRole,
getUserId,
// API Key Checkers (still relevant)
isApiKeySet,
getMcpApiKeyStatus,
// ADD: Function to get all provider names
getAllProviders
getAllProviders,
getVertexProjectId,
getVertexLocation
};

View File

@@ -1,5 +1,19 @@
{
"anthropic": [
{
"id": "claude-sonnet-4-20250514",
"swe_score": 0.727,
"cost_per_1m_tokens": { "input": 3.0, "output": 15.0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 64000
},
{
"id": "claude-opus-4-20250514",
"swe_score": 0.725,
"cost_per_1m_tokens": { "input": 15.0, "output": 75.0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 32000
},
{
"id": "claude-3-7-sonnet-20250219",
"swe_score": 0.623,
@@ -99,34 +113,39 @@
],
"google": [
{
"id": "gemini-2.5-pro-exp-03-25",
"id": "gemini-2.5-pro-preview-05-06",
"swe_score": 0.638,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"]
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
},
{
"id": "gemini-2.5-pro-preview-03-25",
"swe_score": 0.638,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
},
{
"id": "gemini-2.5-flash-preview-04-17",
"swe_score": 0,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"]
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
},
{
"id": "gemini-2.0-flash",
"swe_score": 0.754,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"]
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
},
{
"id": "gemini-2.0-flash-thinking-experimental",
"swe_score": 0.754,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "gemini-2.0-pro",
"id": "gemini-2.0-flash-lite",
"swe_score": 0,
"cost_per_1m_tokens": null,
"allowed_roles": ["main", "fallback"]
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048000
}
],
"perplexity": [
@@ -186,43 +205,43 @@
],
"ollama": [
{
"id": "gemma3:27b",
"id": "devstral:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "gemma3:12b",
"id": "qwen3:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "qwq",
"id": "qwen3:14b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "deepseek-r1",
"id": "qwen3:32b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "mistral-small3.1",
"id": "mistral-small3.1:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "llama3.3",
"id": "llama3.3:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
},
{
"id": "phi4",
"id": "phi4:latest",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"]
@@ -230,9 +249,16 @@
],
"openrouter": [
{
"id": "google/gemini-2.0-flash-001",
"id": "google/gemini-2.5-flash-preview-05-20",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048576
},
{
"id": "google/gemini-2.5-flash-preview-05-20:thinking",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 1048576
},
@@ -258,40 +284,25 @@
"max_tokens": 64000
},
{
"id": "deepseek/deepseek-r1:free",
"id": "openai/gpt-4.1",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"cost_per_1m_tokens": { "input": 2, "output": 8 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 163840
"max_tokens": 1000000
},
{
"id": "microsoft/mai-ds-r1:free",
"id": "openai/gpt-4.1-mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"cost_per_1m_tokens": { "input": 0.4, "output": 1.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 163840
"max_tokens": 1000000
},
{
"id": "google/gemini-2.5-pro-preview-03-25",
"id": "openai/gpt-4.1-nano",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 1.25, "output": 10 },
"cost_per_1m_tokens": { "input": 0.1, "output": 0.4 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 65535
},
{
"id": "google/gemini-2.5-flash-preview",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main"],
"max_tokens": 65535
},
{
"id": "google/gemini-2.5-flash-preview:thinking",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 3.5 },
"allowed_roles": ["main"],
"max_tokens": 65535
"max_tokens": 1000000
},
{
"id": "openai/o3",
@@ -300,6 +311,20 @@
"allowed_roles": ["main", "fallback"],
"max_tokens": 200000
},
{
"id": "openai/codex-mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 1.5, "output": 6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{
"id": "openai/gpt-4o-mini",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.15, "output": 0.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{
"id": "openai/o4-mini",
"swe_score": 0.45,
@@ -329,46 +354,18 @@
"max_tokens": 1048576
},
{
"id": "google/gemma-3-12b-it:free",
"id": "meta-llama/llama-4-maverick",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"cost_per_1m_tokens": { "input": 0.18, "output": 0.6 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
"max_tokens": 1000000
},
{
"id": "google/gemma-3-12b-it",
"id": "meta-llama/llama-4-scout",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 50, "output": 100 },
"cost_per_1m_tokens": { "input": 0.08, "output": 0.3 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
},
{
"id": "google/gemma-3-27b-it:free",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 96000
},
{
"id": "google/gemma-3-27b-it",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 100, "output": 200 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
},
{
"id": "qwen/qwq-32b:free",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0, "output": 0 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 40000
},
{
"id": "qwen/qwq-32b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 150, "output": 200 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 131072
"max_tokens": 1000000
},
{
"id": "qwen/qwen-max",
@@ -384,6 +381,13 @@
"allowed_roles": ["main", "fallback"],
"max_tokens": 1000000
},
{
"id": "qwen/qwen3-235b-a22b",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.14, "output": 2 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 24000
},
{
"id": "mistralai/mistral-small-3.1-24b-instruct:free",
"swe_score": 0,
@@ -398,6 +402,20 @@
"allowed_roles": ["main", "fallback"],
"max_tokens": 128000
},
{
"id": "mistralai/devstral-small",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.1, "output": 0.3 },
"allowed_roles": ["main"],
"max_tokens": 110000
},
{
"id": "mistralai/mistral-nemo",
"swe_score": 0,
"cost_per_1m_tokens": { "input": 0.03, "output": 0.07 },
"allowed_roles": ["main", "fallback"],
"max_tokens": 100000
},
{
"id": "thudm/glm-4-32b:free",
"swe_score": 0,

View File

@@ -23,7 +23,8 @@ import updateSubtaskById from './task-manager/update-subtask-by-id.js';
import removeTask from './task-manager/remove-task.js';
import taskExists from './task-manager/task-exists.js';
import isTaskDependentOn from './task-manager/is-task-dependent.js';
import moveTask from './task-manager/move-task.js';
import { readComplexityReport } from './utils.js';
// Export task manager functions
export {
parsePRD,
@@ -45,5 +46,7 @@ export {
removeTask,
findTaskById,
taskExists,
isTaskDependentOn
isTaskDependentOn,
moveTask,
readComplexityReport
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,15 @@
import chalk from 'chalk';
import boxen from 'boxen';
import readline from 'readline';
import fs from 'fs';
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
import {
startLoadingIndicator,
stopLoadingIndicator,
displayAiUsageSummary
} from '../ui.js';
import { generateTextService } from '../ai-services-unified.js';
@@ -47,6 +52,9 @@ Do not include any explanatory text, markdown formatting, or code block markers
* @param {string|number} [options.threshold] - Complexity threshold
* @param {boolean} [options.research] - Use research role
* @param {string} [options.projectRoot] - Project root path (for MCP/env fallback).
* @param {string} [options.id] - Comma-separated list of task IDs to analyze specifically
* @param {number} [options.from] - Starting task ID in a range to analyze
* @param {number} [options.to] - Ending task ID in a range to analyze
* @param {Object} [options._filteredTasksData] - Pre-filtered task data (internal use)
* @param {number} [options._originalTaskCount] - Original task count (internal use)
* @param {Object} context - Context object, potentially containing session and mcpLog
@@ -61,6 +69,15 @@ async function analyzeTaskComplexity(options, context = {}) {
const thresholdScore = parseFloat(options.threshold || '5');
const useResearch = options.research || false;
const projectRoot = options.projectRoot;
// New parameters for task ID filtering
const specificIds = options.id
? options.id
.split(',')
.map((id) => parseInt(id.trim(), 10))
.filter((id) => !isNaN(id))
: null;
const fromId = options.from !== undefined ? parseInt(options.from, 10) : null;
const toId = options.to !== undefined ? parseInt(options.to, 10) : null;
const outputFormat = mcpLog ? 'json' : 'text';
@@ -84,13 +101,14 @@ async function analyzeTaskComplexity(options, context = {}) {
reportLog(`Reading tasks from ${tasksPath}...`, 'info');
let tasksData;
let originalTaskCount = 0;
let originalData = null;
if (options._filteredTasksData) {
tasksData = options._filteredTasksData;
originalTaskCount = options._originalTaskCount || tasksData.tasks.length;
if (!options._originalTaskCount) {
try {
const originalData = readJSON(tasksPath);
originalData = readJSON(tasksPath);
if (originalData && originalData.tasks) {
originalTaskCount = originalData.tasks.length;
}
@@ -99,22 +117,80 @@ async function analyzeTaskComplexity(options, context = {}) {
}
}
} else {
tasksData = readJSON(tasksPath);
originalData = readJSON(tasksPath);
if (
!tasksData ||
!tasksData.tasks ||
!Array.isArray(tasksData.tasks) ||
tasksData.tasks.length === 0
!originalData ||
!originalData.tasks ||
!Array.isArray(originalData.tasks) ||
originalData.tasks.length === 0
) {
throw new Error('No tasks found in the tasks file');
}
originalTaskCount = tasksData.tasks.length;
originalTaskCount = originalData.tasks.length;
// Filter tasks based on active status
const activeStatuses = ['pending', 'blocked', 'in-progress'];
const filteredTasks = tasksData.tasks.filter((task) =>
let filteredTasks = originalData.tasks.filter((task) =>
activeStatuses.includes(task.status?.toLowerCase() || 'pending')
);
// Apply ID filtering if specified
if (specificIds && specificIds.length > 0) {
reportLog(
`Filtering tasks by specific IDs: ${specificIds.join(', ')}`,
'info'
);
filteredTasks = filteredTasks.filter((task) =>
specificIds.includes(task.id)
);
if (outputFormat === 'text') {
if (filteredTasks.length === 0 && specificIds.length > 0) {
console.log(
chalk.yellow(
`Warning: No active tasks found with IDs: ${specificIds.join(', ')}`
)
);
} else if (filteredTasks.length < specificIds.length) {
const foundIds = filteredTasks.map((t) => t.id);
const missingIds = specificIds.filter(
(id) => !foundIds.includes(id)
);
console.log(
chalk.yellow(
`Warning: Some requested task IDs were not found or are not active: ${missingIds.join(', ')}`
)
);
}
}
}
// Apply range filtering if specified
else if (fromId !== null || toId !== null) {
const effectiveFromId = fromId !== null ? fromId : 1;
const effectiveToId =
toId !== null
? toId
: Math.max(...originalData.tasks.map((t) => t.id));
reportLog(
`Filtering tasks by ID range: ${effectiveFromId} to ${effectiveToId}`,
'info'
);
filteredTasks = filteredTasks.filter(
(task) => task.id >= effectiveFromId && task.id <= effectiveToId
);
if (outputFormat === 'text' && filteredTasks.length === 0) {
console.log(
chalk.yellow(
`Warning: No active tasks found in range: ${effectiveFromId}-${effectiveToId}`
)
);
}
}
tasksData = {
...tasksData,
...originalData,
tasks: filteredTasks,
_originalTaskCount: originalTaskCount
};
@@ -125,7 +201,18 @@ async function analyzeTaskComplexity(options, context = {}) {
`Found ${originalTaskCount} total tasks in the task file.`,
'info'
);
if (skippedCount > 0) {
// Updated messaging to reflect filtering logic
if (specificIds || fromId !== null || toId !== null) {
const filterMsg = specificIds
? `Analyzing ${tasksData.tasks.length} tasks with specific IDs: ${specificIds.join(', ')}`
: `Analyzing ${tasksData.tasks.length} tasks in range: ${fromId || 1} to ${toId || 'end'}`;
reportLog(filterMsg, 'info');
if (outputFormat === 'text') {
console.log(chalk.blue(filterMsg));
}
} else if (skippedCount > 0) {
const skipMessage = `Skipping ${skippedCount} tasks marked as done/cancelled/deferred. Analyzing ${tasksData.tasks.length} active tasks.`;
reportLog(skipMessage, 'info');
if (outputFormat === 'text') {
@@ -133,7 +220,59 @@ async function analyzeTaskComplexity(options, context = {}) {
}
}
// Check for existing report before doing analysis
let existingReport = null;
let existingAnalysisMap = new Map(); // For quick lookups by task ID
try {
if (fs.existsSync(outputPath)) {
existingReport = readJSON(outputPath);
reportLog(`Found existing complexity report at ${outputPath}`, 'info');
if (
existingReport &&
existingReport.complexityAnalysis &&
Array.isArray(existingReport.complexityAnalysis)
) {
// Create lookup map of existing analysis entries
existingReport.complexityAnalysis.forEach((item) => {
existingAnalysisMap.set(item.taskId, item);
});
reportLog(
`Existing report contains ${existingReport.complexityAnalysis.length} task analyses`,
'info'
);
}
}
} catch (readError) {
reportLog(
`Warning: Could not read existing report: ${readError.message}`,
'warn'
);
existingReport = null;
existingAnalysisMap.clear();
}
if (tasksData.tasks.length === 0) {
// If using ID filtering but no matching tasks, return existing report or empty
if (existingReport && (specificIds || fromId !== null || toId !== null)) {
reportLog(
`No matching tasks found for analysis. Keeping existing report.`,
'info'
);
if (outputFormat === 'text') {
console.log(
chalk.yellow(
`No matching tasks found for analysis. Keeping existing report.`
)
);
}
return {
report: existingReport,
telemetryData: null
};
}
// Otherwise create empty report
const emptyReport = {
meta: {
generatedAt: new Date().toISOString(),
@@ -142,9 +281,9 @@ async function analyzeTaskComplexity(options, context = {}) {
projectName: getProjectName(session),
usedResearch: useResearch
},
complexityAnalysis: []
complexityAnalysis: existingReport?.complexityAnalysis || []
};
reportLog(`Writing empty complexity report to ${outputPath}...`, 'info');
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
writeJSON(outputPath, emptyReport);
reportLog(
`Task complexity analysis complete. Report written to ${outputPath}`,
@@ -192,39 +331,40 @@ async function analyzeTaskComplexity(options, context = {}) {
)
);
}
return emptyReport;
return {
report: emptyReport,
telemetryData: null
};
}
// Continue with regular analysis path
const prompt = generateInternalComplexityAnalysisPrompt(tasksData);
// System prompt remains simple for text generation
const systemPrompt =
'You are an expert software architect and project manager analyzing task complexity. Respond only with the requested valid JSON array.';
let loadingIndicator = null;
if (outputFormat === 'text') {
loadingIndicator = startLoadingIndicator('Calling AI service...');
loadingIndicator = startLoadingIndicator(
`${useResearch ? 'Researching' : 'Analyzing'} the complexity of your tasks with AI...\n`
);
}
let fullResponse = ''; // To store the raw text response
let aiServiceResponse = null;
let complexityAnalysis = null;
try {
const role = useResearch ? 'research' : 'main';
reportLog(`Using AI service with role: ${role}`, 'info');
fullResponse = await generateTextService({
aiServiceResponse = await generateTextService({
prompt,
systemPrompt,
role,
session,
projectRoot
projectRoot,
commandName: 'analyze-complexity',
outputType: mcpLog ? 'mcp' : 'cli'
});
reportLog(
'Successfully received text response via AI service',
'success'
);
// --- Stop Loading Indicator (Unchanged) ---
if (loadingIndicator) {
stopLoadingIndicator(loadingIndicator);
loadingIndicator = null;
@@ -236,26 +376,18 @@ async function analyzeTaskComplexity(options, context = {}) {
chalk.green('AI service call complete. Parsing response...')
);
}
// --- End Stop Loading Indicator ---
// --- Re-introduce Manual JSON Parsing & Cleanup ---
reportLog(`Parsing complexity analysis from text response...`, 'info');
let complexityAnalysis;
try {
let cleanedResponse = fullResponse;
// Basic trim first
let cleanedResponse = aiServiceResponse.mainResult;
cleanedResponse = cleanedResponse.trim();
// Remove potential markdown code block fences
const codeBlockMatch = cleanedResponse.match(
/```(?:json)?\s*([\s\S]*?)\s*```/
);
if (codeBlockMatch) {
cleanedResponse = codeBlockMatch[1].trim(); // Trim content inside block
reportLog('Extracted JSON from code block', 'info');
cleanedResponse = codeBlockMatch[1].trim();
} else {
// If no code block, ensure it starts with '[' and ends with ']'
// This is less robust but a common fallback
const firstBracket = cleanedResponse.indexOf('[');
const lastBracket = cleanedResponse.lastIndexOf(']');
if (firstBracket !== -1 && lastBracket > firstBracket) {
@@ -263,13 +395,11 @@ async function analyzeTaskComplexity(options, context = {}) {
firstBracket,
lastBracket + 1
);
reportLog('Extracted content between first [ and last ]', 'info');
} else {
reportLog(
'Warning: Response does not appear to be a JSON array.',
'warn'
);
// Keep going, maybe JSON.parse can handle it or will fail informatively
}
}
@@ -283,48 +413,23 @@ async function analyzeTaskComplexity(options, context = {}) {
);
}
try {
complexityAnalysis = JSON.parse(cleanedResponse);
} catch (jsonError) {
} catch (parseError) {
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
reportLog(
'Initial JSON parsing failed. Raw response might be malformed.',
'error'
);
reportLog(`Original JSON Error: ${jsonError.message}`, 'error');
if (outputFormat === 'text' && getDebugFlag(session)) {
console.log(chalk.red('--- Start Raw Malformed Response ---'));
console.log(chalk.gray(fullResponse));
console.log(chalk.red('--- End Raw Malformed Response ---'));
}
// Re-throw the specific JSON parsing error
throw new Error(
`Failed to parse JSON response: ${jsonError.message}`
);
}
// Ensure it's an array after parsing
if (!Array.isArray(complexityAnalysis)) {
throw new Error('Parsed response is not a valid JSON array.');
}
} catch (error) {
// Catch errors specifically from the parsing/cleanup block
if (loadingIndicator) stopLoadingIndicator(loadingIndicator); // Ensure indicator stops
reportLog(
`Error parsing complexity analysis JSON: ${error.message}`,
`Error parsing complexity analysis JSON: ${parseError.message}`,
'error'
);
if (outputFormat === 'text') {
console.error(
chalk.red(
`Error parsing complexity analysis JSON: ${error.message}`
`Error parsing complexity analysis JSON: ${parseError.message}`
)
);
}
throw error; // Re-throw parsing error
throw parseError;
}
// --- End Manual JSON Parsing & Cleanup ---
// --- Post-processing (Missing Task Check) - (Unchanged) ---
const taskIds = tasksData.tasks.map((t) => t.id);
const analysisTaskIds = complexityAnalysis.map((a) => a.taskId);
const missingTaskIds = taskIds.filter(
@@ -359,35 +464,64 @@ async function analyzeTaskComplexity(options, context = {}) {
}
}
}
// --- End Post-processing ---
// --- Report Creation & Writing (Unchanged) ---
const finalReport = {
// Merge with existing report
let finalComplexityAnalysis = [];
if (existingReport && Array.isArray(existingReport.complexityAnalysis)) {
// Create a map of task IDs that we just analyzed
const analyzedTaskIds = new Set(
complexityAnalysis.map((item) => item.taskId)
);
// Keep existing entries that weren't in this analysis run
const existingEntriesNotAnalyzed =
existingReport.complexityAnalysis.filter(
(item) => !analyzedTaskIds.has(item.taskId)
);
// Combine with new analysis
finalComplexityAnalysis = [
...existingEntriesNotAnalyzed,
...complexityAnalysis
];
reportLog(
`Merged ${complexityAnalysis.length} new analyses with ${existingEntriesNotAnalyzed.length} existing entries`,
'info'
);
} else {
// No existing report or invalid format, just use the new analysis
finalComplexityAnalysis = complexityAnalysis;
}
const report = {
meta: {
generatedAt: new Date().toISOString(),
tasksAnalyzed: tasksData.tasks.length,
totalTasks: originalTaskCount,
analysisCount: finalComplexityAnalysis.length,
thresholdScore: thresholdScore,
projectName: getProjectName(session),
usedResearch: useResearch
},
complexityAnalysis: complexityAnalysis
complexityAnalysis: finalComplexityAnalysis
};
reportLog(`Writing complexity report to ${outputPath}...`, 'info');
writeJSON(outputPath, finalReport);
writeJSON(outputPath, report);
reportLog(
`Task complexity analysis complete. Report written to ${outputPath}`,
'success'
);
// --- End Report Creation & Writing ---
// --- Display CLI Summary (Unchanged) ---
if (outputFormat === 'text') {
console.log(
chalk.green(
`Task complexity analysis complete. Report written to ${outputPath}`
)
);
// Calculate statistics specifically for this analysis run
const highComplexity = complexityAnalysis.filter(
(t) => t.complexityScore >= 8
).length;
@@ -399,18 +533,25 @@ async function analyzeTaskComplexity(options, context = {}) {
).length;
const totalAnalyzed = complexityAnalysis.length;
console.log('\nComplexity Analysis Summary:');
console.log('\nCurrent Analysis Summary:');
console.log('----------------------------');
console.log(
`Active tasks sent for analysis: ${tasksData.tasks.length}`
);
console.log(`Tasks successfully analyzed: ${totalAnalyzed}`);
console.log(`Tasks analyzed in this run: ${totalAnalyzed}`);
console.log(`High complexity tasks: ${highComplexity}`);
console.log(`Medium complexity tasks: ${mediumComplexity}`);
console.log(`Low complexity tasks: ${lowComplexity}`);
if (existingReport) {
console.log('\nUpdated Report Summary:');
console.log('----------------------------');
console.log(
`Sum verification: ${highComplexity + mediumComplexity + lowComplexity} (should equal ${totalAnalyzed})`
`Total analyses in report: ${finalComplexityAnalysis.length}`
);
console.log(
`Analyses from previous runs: ${finalComplexityAnalysis.length - totalAnalyzed}`
);
console.log(`New/updated analyses: ${totalAnalyzed}`);
}
console.log(`Research-backed analysis: ${useResearch ? 'Yes' : 'No'}`);
console.log(
`\nSee ${outputPath} for the full report and expansion commands.`
@@ -435,23 +576,28 @@ async function analyzeTaskComplexity(options, context = {}) {
if (getDebugFlag(session)) {
console.debug(
chalk.gray(
`Final analysis object: ${JSON.stringify(finalReport, null, 2)}`
`Final analysis object: ${JSON.stringify(report, null, 2)}`
)
);
}
}
// --- End Display CLI Summary ---
return finalReport;
} catch (error) {
// Catches errors from generateTextService call
if (aiServiceResponse.telemetryData) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
}
return {
report: report,
telemetryData: aiServiceResponse?.telemetryData
};
} catch (aiError) {
if (loadingIndicator) stopLoadingIndicator(loadingIndicator);
reportLog(`Error during AI service call: ${error.message}`, 'error');
reportLog(`Error during AI service call: ${aiError.message}`, 'error');
if (outputFormat === 'text') {
console.error(
chalk.red(`Error during AI service call: ${error.message}`)
chalk.red(`Error during AI service call: ${aiError.message}`)
);
if (error.message.includes('API key')) {
if (aiError.message.includes('API key')) {
console.log(
chalk.yellow(
'\nPlease ensure your API keys are correctly configured in .env or ~/.taskmaster/.env'
@@ -462,10 +608,9 @@ async function analyzeTaskComplexity(options, context = {}) {
);
}
}
throw error; // Re-throw AI service error
throw aiError;
}
} catch (error) {
// Catches general errors (file read, etc.)
reportLog(`Error analyzing task complexity: ${error.message}`, 'error');
if (outputFormat === 'text') {
console.error(

View File

@@ -1,7 +1,14 @@
import { log, readJSON, isSilentMode } from '../utils.js';
import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
import {
startLoadingIndicator,
stopLoadingIndicator,
displayAiUsageSummary
} from '../ui.js';
import expandTask from './expand-task.js';
import { getDebugFlag } from '../config-manager.js';
import { aggregateTelemetry } from '../utils.js';
import chalk from 'chalk';
import boxen from 'boxen';
/**
* Expand all eligible pending or in-progress tasks using the expandTask function.
@@ -14,7 +21,7 @@ import { getDebugFlag } from '../config-manager.js';
* @param {Object} [context.session] - Session object from MCP.
* @param {Object} [context.mcpLog] - MCP logger object.
* @param {string} [outputFormat='text'] - Output format ('text' or 'json'). MCP calls should use 'json'.
* @returns {Promise<{success: boolean, expandedCount: number, failedCount: number, skippedCount: number, tasksToExpand: number, message?: string}>} - Result summary.
* @returns {Promise<{success: boolean, expandedCount: number, failedCount: number, skippedCount: number, tasksToExpand: number, telemetryData: Array<Object>}>} - Result summary.
*/
async function expandAllTasks(
tasksPath,
@@ -51,8 +58,8 @@ async function expandAllTasks(
let loadingIndicator = null;
let expandedCount = 0;
let failedCount = 0;
// No skipped count needed now as the filter handles it upfront
let tasksToExpandCount = 0; // Renamed for clarity
let tasksToExpandCount = 0;
const allTelemetryData = []; // Still collect individual data first
if (!isMCPCall && outputFormat === 'text') {
loadingIndicator = startLoadingIndicator(
@@ -90,6 +97,7 @@ async function expandAllTasks(
failedCount: 0,
skippedCount: 0,
tasksToExpand: 0,
telemetryData: allTelemetryData,
message: 'No tasks eligible for expansion.'
};
// --- End Fix ---
@@ -97,19 +105,6 @@ async function expandAllTasks(
// Iterate over the already filtered tasks
for (const task of tasksToExpand) {
// --- Remove Redundant Check ---
// The check below is no longer needed as the initial filter handles it
/*
if (task.subtasks && task.subtasks.length > 0 && !force) {
logger.info(
`Skipping task ${task.id}: Already has subtasks. Use --force to overwrite.`
);
skippedCount++;
continue;
}
*/
// --- End Removed Redundant Check ---
// Start indicator for individual task expansion in CLI mode
let taskIndicator = null;
if (!isMCPCall && outputFormat === 'text') {
@@ -117,17 +112,23 @@ async function expandAllTasks(
}
try {
// Call the refactored expandTask function
await expandTask(
// Call the refactored expandTask function AND capture result
const result = await expandTask(
tasksPath,
task.id,
numSubtasks, // Pass numSubtasks, expandTask handles defaults/complexity
numSubtasks,
useResearch,
additionalContext,
context, // Pass the whole context object { session, mcpLog }
force // Pass the force flag down
force
);
expandedCount++;
// Collect individual telemetry data
if (result && result.telemetryData) {
allTelemetryData.push(result.telemetryData);
}
if (taskIndicator) {
stopLoadingIndicator(taskIndicator, `Task ${task.id} expanded.`);
}
@@ -146,18 +147,48 @@ async function expandAllTasks(
}
}
// Log final summary (removed skipped count from message)
// --- AGGREGATION AND DISPLAY ---
logger.info(
`Expansion complete: ${expandedCount} expanded, ${failedCount} failed.`
);
// Return summary (skippedCount is now 0) - Add success: true here as well for consistency
// Aggregate the collected telemetry data
const aggregatedTelemetryData = aggregateTelemetry(
allTelemetryData,
'expand-all-tasks'
);
if (outputFormat === 'text') {
const summaryContent =
`${chalk.white.bold('Expansion Summary:')}\n\n` +
`${chalk.cyan('-')} Attempted: ${chalk.bold(tasksToExpandCount)}\n` +
`${chalk.green('-')} Expanded: ${chalk.bold(expandedCount)}\n` +
// Skipped count is always 0 now due to pre-filtering
`${chalk.gray('-')} Skipped: ${chalk.bold(0)}\n` +
`${chalk.red('-')} Failed: ${chalk.bold(failedCount)}`;
console.log(
boxen(summaryContent, {
padding: 1,
margin: { top: 1 },
borderColor: failedCount > 0 ? 'red' : 'green', // Red if failures, green otherwise
borderStyle: 'round'
})
);
}
if (outputFormat === 'text' && aggregatedTelemetryData) {
displayAiUsageSummary(aggregatedTelemetryData, 'cli');
}
// Return summary including the AGGREGATED telemetry data
return {
success: true, // Indicate overall success
success: true,
expandedCount,
failedCount,
skippedCount: 0,
tasksToExpand: tasksToExpandCount
tasksToExpand: tasksToExpandCount,
telemetryData: aggregatedTelemetryData
};
} catch (error) {
if (loadingIndicator)

View File

@@ -4,7 +4,11 @@ import { z } from 'zod';
import { log, readJSON, writeJSON, isSilentMode } from '../utils.js';
import { startLoadingIndicator, stopLoadingIndicator } from '../ui.js';
import {
startLoadingIndicator,
stopLoadingIndicator,
displayAiUsageSummary
} from '../ui.js';
import { generateTextService } from '../ai-services-unified.js';
@@ -142,7 +146,7 @@ function generateResearchUserPrompt(
"id": <number>, // Sequential ID starting from ${nextSubtaskId}
"title": "<string>",
"description": "<string>",
"dependencies": [<number>], // e.g., [${nextSubtaskId + 1}]
"dependencies": [<number>], // e.g., [${nextSubtaskId + 1}]. If no dependencies, use an empty array [].
"details": "<string>",
"testStrategy": "<string>" // Optional
},
@@ -162,6 +166,8 @@ ${contextPrompt}
CRITICAL: Respond ONLY with a valid JSON object containing a single key "subtasks". The value must be an array of the generated subtasks, strictly matching this structure:
${schemaDescription}
Important: For the 'dependencies' field, if a subtask has no dependencies, you MUST use an empty array, for example: "dependencies": []. Do not use null or omit the field.
Do not include ANY explanatory text, markdown, or code block markers. Just the JSON object.`;
}
@@ -182,77 +188,153 @@ function parseSubtasksFromText(
parentTaskId,
logger
) {
logger.info('Attempting to parse subtasks object from text response...');
if (typeof text !== 'string') {
logger.error(
`AI response text is not a string. Received type: ${typeof text}, Value: ${text}`
);
throw new Error('AI response text is not a string.');
}
if (!text || text.trim() === '') {
throw new Error('AI response text is empty.');
throw new Error('AI response text is empty after trimming.');
}
let cleanedResponse = text.trim();
const originalResponseForDebug = cleanedResponse;
const originalTrimmedResponse = text.trim(); // Store the original trimmed response
let jsonToParse = originalTrimmedResponse; // Initialize jsonToParse with it
// 1. Extract from Markdown code block first
const codeBlockMatch = cleanedResponse.match(
/```(?:json)?\s*([\s\S]*?)\s*```/
logger.debug(
`Original AI Response for parsing (full length: ${jsonToParse.length}): ${jsonToParse.substring(0, 1000)}...`
);
if (codeBlockMatch) {
cleanedResponse = codeBlockMatch[1].trim();
logger.info('Extracted JSON content from Markdown code block.');
} else {
// 2. If no code block, find first '{' and last '}' for the object
const firstBrace = cleanedResponse.indexOf('{');
const lastBrace = cleanedResponse.lastIndexOf('}');
if (firstBrace !== -1 && lastBrace > firstBrace) {
cleanedResponse = cleanedResponse.substring(firstBrace, lastBrace + 1);
logger.info('Extracted content between first { and last }.');
} else {
logger.warn(
'Response does not appear to contain a JSON object structure. Parsing raw response.'
// --- Pre-emptive cleanup for known AI JSON issues ---
// Fix for "dependencies": , or "dependencies":,
if (jsonToParse.includes('"dependencies":')) {
const malformedPattern = /"dependencies":\s*,/g;
if (malformedPattern.test(jsonToParse)) {
logger.warn('Attempting to fix malformed "dependencies": , issue.');
jsonToParse = jsonToParse.replace(
malformedPattern,
'"dependencies": [],'
);
logger.debug(
`JSON after fixing "dependencies": ${jsonToParse.substring(0, 500)}...`
);
}
}
// --- End pre-emptive cleanup ---
// 3. Attempt to parse the object
let parsedObject;
let primaryParseAttemptFailed = false;
// --- Attempt 1: Simple Parse (with optional Markdown cleanup) ---
logger.debug('Attempting simple parse...');
try {
parsedObject = JSON.parse(cleanedResponse);
} catch (parseError) {
logger.error(`Failed to parse JSON object: ${parseError.message}`);
logger.error(
`Problematic JSON string (first 500 chars): ${cleanedResponse.substring(0, 500)}`
);
logger.error(
`Original Raw Response (first 500 chars): ${originalResponseForDebug.substring(0, 500)}`
);
throw new Error(
`Failed to parse JSON response object: ${parseError.message}`
// Check for markdown code block
const codeBlockMatch = jsonToParse.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
let contentToParseDirectly = jsonToParse;
if (codeBlockMatch && codeBlockMatch[1]) {
contentToParseDirectly = codeBlockMatch[1].trim();
logger.debug('Simple parse: Extracted content from markdown code block.');
} else {
logger.debug(
'Simple parse: No markdown code block found, using trimmed original.'
);
}
// 4. Validate the object structure and extract the subtasks array
parsedObject = JSON.parse(contentToParseDirectly);
logger.debug('Simple parse successful!');
// Quick check if it looks like our target object
if (
!parsedObject ||
typeof parsedObject !== 'object' ||
!Array.isArray(parsedObject.subtasks)
) {
logger.warn(
'Simple parse succeeded, but result is not the expected {"subtasks": []} structure. Will proceed to advanced extraction.'
);
primaryParseAttemptFailed = true;
parsedObject = null; // Reset parsedObject so we enter the advanced logic
}
// If it IS the correct structure, we'll skip advanced extraction.
} catch (e) {
logger.warn(
`Simple parse failed: ${e.message}. Proceeding to advanced extraction logic.`
);
primaryParseAttemptFailed = true;
// jsonToParse is already originalTrimmedResponse if simple parse failed before modifying it for markdown
}
// --- Attempt 2: Advanced Extraction (if simple parse failed or produced wrong structure) ---
if (primaryParseAttemptFailed || !parsedObject) {
// Ensure we try advanced if simple parse gave wrong structure
logger.debug('Attempting advanced extraction logic...');
// Reset jsonToParse to the original full trimmed response for advanced logic
jsonToParse = originalTrimmedResponse;
// (Insert the more complex extraction logic here - the one we worked on with:
// - targetPattern = '{"subtasks":';
// - careful brace counting for that targetPattern
// - fallbacks to last '{' and '}' if targetPattern logic fails)
// This was the logic from my previous message. Let's assume it's here.
// This block should ultimately set `jsonToParse` to the best candidate string.
// Example snippet of that advanced logic's start:
const targetPattern = '{"subtasks":';
const patternStartIndex = jsonToParse.indexOf(targetPattern);
if (patternStartIndex !== -1) {
let openBraces = 0;
let firstBraceFound = false;
let extractedJsonBlock = '';
// ... (loop for brace counting as before) ...
// ... (if successful, jsonToParse = extractedJsonBlock) ...
// ... (if that fails, fallbacks as before) ...
} else {
// ... (fallback to last '{' and '}' if targetPattern not found) ...
}
// End of advanced logic excerpt
logger.debug(
`Advanced extraction: JSON string that will be parsed: ${jsonToParse.substring(0, 500)}...`
);
try {
parsedObject = JSON.parse(jsonToParse);
logger.debug('Advanced extraction parse successful!');
} catch (parseError) {
logger.error(
`Advanced extraction: Failed to parse JSON object: ${parseError.message}`
);
logger.error(
`Advanced extraction: Problematic JSON string for parse (first 500 chars): ${jsonToParse.substring(0, 500)}`
);
throw new Error( // Re-throw a more specific error if advanced also fails
`Failed to parse JSON response object after both simple and advanced attempts: ${parseError.message}`
);
}
}
// --- Validation (applies to successfully parsedObject from either attempt) ---
if (
!parsedObject ||
typeof parsedObject !== 'object' ||
!Array.isArray(parsedObject.subtasks)
) {
logger.error(
`Parsed content is not an object or missing 'subtasks' array. Content: ${JSON.stringify(parsedObject).substring(0, 200)}`
`Final parsed content is not an object or missing 'subtasks' array. Content: ${JSON.stringify(parsedObject).substring(0, 200)}`
);
throw new Error(
'Parsed AI response is not a valid object containing a "subtasks" array.'
'Parsed AI response is not a valid object containing a "subtasks" array after all attempts.'
);
}
const parsedSubtasks = parsedObject.subtasks; // Extract the array
const parsedSubtasks = parsedObject.subtasks;
logger.info(
`Successfully parsed ${parsedSubtasks.length} potential subtasks from the object.`
);
if (expectedCount && parsedSubtasks.length !== expectedCount) {
logger.warn(
`Expected ${expectedCount} subtasks, but parsed ${parsedSubtasks.length}.`
);
}
// 5. Validate and Normalize each subtask using Zod schema
let currentId = startId;
const validatedSubtasks = [];
const validationErrors = [];
@@ -260,22 +342,21 @@ function parseSubtasksFromText(
for (const rawSubtask of parsedSubtasks) {
const correctedSubtask = {
...rawSubtask,
id: currentId, // Enforce sequential ID
id: currentId,
dependencies: Array.isArray(rawSubtask.dependencies)
? rawSubtask.dependencies
.map((dep) => (typeof dep === 'string' ? parseInt(dep, 10) : dep))
.filter(
(depId) => !isNaN(depId) && depId >= startId && depId < currentId
) // Ensure deps are numbers, valid range
)
: [],
status: 'pending' // Enforce pending status
// parentTaskId can be added if needed: parentTaskId: parentTaskId
status: 'pending'
};
const result = subtaskSchema.safeParse(correctedSubtask);
if (result.success) {
validatedSubtasks.push(result.data); // Add the validated data
validatedSubtasks.push(result.data);
} else {
logger.warn(
`Subtask validation failed for raw data: ${JSON.stringify(rawSubtask).substring(0, 100)}...`
@@ -285,18 +366,14 @@ function parseSubtasksFromText(
logger.warn(errorMessage);
validationErrors.push(`Subtask ${currentId}: ${errorMessage}`);
});
// Optionally, decide whether to include partially valid tasks or skip them
// For now, we'll skip invalid ones
}
currentId++; // Increment ID for the next *potential* subtask
currentId++;
}
if (validationErrors.length > 0) {
logger.error(
`Found ${validationErrors.length} validation errors in the generated subtasks.`
);
// Optionally throw an error here if strict validation is required
// throw new Error(`Subtask validation failed:\n${validationErrors.join('\n')}`);
logger.warn('Proceeding with only the successfully validated subtasks.');
}
@@ -305,8 +382,6 @@ function parseSubtasksFromText(
'AI response contained potential subtasks, but none passed validation.'
);
}
// Ensure we don't return more than expected, preferring validated ones
return validatedSubtasks.slice(0, expectedCount || validatedSubtasks.length);
}
@@ -336,9 +411,13 @@ async function expandTask(
context = {},
force = false
) {
const { session, mcpLog } = context;
const { session, mcpLog, projectRoot: contextProjectRoot } = context;
const outputFormat = mcpLog ? 'json' : 'text';
// Determine projectRoot: Use from context if available, otherwise derive from tasksPath
const projectRoot =
contextProjectRoot || path.dirname(path.dirname(tasksPath));
// Use mcpLog if available, otherwise use the default console log wrapper
const logger = mcpLog || {
info: (msg) => !isSilentMode() && log('info', msg),
@@ -363,7 +442,9 @@ async function expandTask(
);
if (taskIndex === -1) throw new Error(`Task ${taskId} not found`);
const task = data.tasks[taskIndex];
logger.info(`Expanding task ${taskId}: ${task.title}`);
logger.info(
`Expanding task ${taskId}: ${task.title}${useResearch ? ' with research' : ''}`
);
// --- End Task Loading/Filtering ---
// --- Handle Force Flag: Clear existing subtasks if force=true ---
@@ -381,7 +462,6 @@ async function expandTask(
let complexityReasoningContext = '';
let systemPrompt; // Declare systemPrompt here
const projectRoot = path.dirname(path.dirname(tasksPath));
const complexityReportPath = path.join(
projectRoot,
'scripts/task-complexity-report.json'
@@ -488,28 +568,27 @@ async function expandTask(
let loadingIndicator = null;
if (outputFormat === 'text') {
loadingIndicator = startLoadingIndicator(
`Generating ${finalSubtaskCount} subtasks...`
`Generating ${finalSubtaskCount} subtasks...\n`
);
}
let responseText = '';
let aiServiceResponse = null;
try {
const role = useResearch ? 'research' : 'main';
logger.info(`Using AI service with role: ${role}`);
// Call generateTextService with the determined prompts
responseText = await generateTextService({
// Call generateTextService with the determined prompts and telemetry params
aiServiceResponse = await generateTextService({
prompt: promptContent,
systemPrompt: systemPrompt, // Use the determined system prompt
systemPrompt: systemPrompt,
role,
session,
projectRoot
projectRoot,
commandName: 'expand-task',
outputType: outputFormat
});
logger.info(
'Successfully received text response from AI service',
'success'
);
responseText = aiServiceResponse.mainResult;
// Parse Subtasks
generatedSubtasks = parseSubtasksFromText(
@@ -550,14 +629,23 @@ async function expandTask(
// --- End Change: Append instead of replace ---
data.tasks[taskIndex] = task; // Assign the modified task back
logger.info(`Writing updated tasks to ${tasksPath}`);
writeJSON(tasksPath, data);
logger.info(`Generating individual task files...`);
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
logger.info(`Task files generated.`);
// --- End Task Update & File Writing ---
return task; // Return the updated task object
// Display AI Usage Summary for CLI
if (
outputFormat === 'text' &&
aiServiceResponse &&
aiServiceResponse.telemetryData
) {
displayAiUsageSummary(aiServiceResponse.telemetryData, 'cli');
}
// Return the updated task object AND telemetry data
return {
task,
telemetryData: aiServiceResponse?.telemetryData
};
} catch (error) {
// Catches errors from file reading, parsing, AI call etc.
logger.error(`Error expanding task ${taskId}: ${error.message}`, 'error');

View File

@@ -1,3 +1,6 @@
import { log } from '../utils.js';
import { addComplexityToTask } from '../utils.js';
/**
* Return the next work item:
* • Prefer an eligible SUBTASK that belongs to any parent task
@@ -15,9 +18,10 @@
* ─ parentId → number (present only when it's a subtask)
*
* @param {Object[]} tasks full array of top-level tasks, each may contain .subtasks[]
* @param {Object} [complexityReport=null] - Optional complexity report object
* @returns {Object|null} next work item or null if nothing is eligible
*/
function findNextTask(tasks) {
function findNextTask(tasks, complexityReport = null) {
// ---------- helpers ----------------------------------------------------
const priorityValues = { high: 3, medium: 2, low: 1 };
@@ -91,7 +95,14 @@ function findNextTask(tasks) {
if (aPar !== bPar) return aPar - bPar;
return aSub - bSub;
});
return candidateSubtasks[0];
const nextTask = candidateSubtasks[0];
// Add complexity to the task before returning
if (nextTask && complexityReport) {
addComplexityToTask(nextTask, complexityReport);
}
return nextTask;
}
// ---------- 2) fall back to top-level tasks (original logic) ------------
@@ -116,6 +127,11 @@ function findNextTask(tasks) {
return a.id - b.id;
})[0];
// Add complexity to the task before returning
if (nextTask && complexityReport) {
addComplexityToTask(nextTask, complexityReport);
}
return nextTask;
}

View File

@@ -19,8 +19,6 @@ function generateTaskFiles(tasksPath, outputDir, options = {}) {
// Determine if we're in MCP mode by checking for mcpLog
const isMcpMode = !!options?.mcpLog;
log('info', `Preparing to regenerate task files in ${tasksPath}`);
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
throw new Error(`No valid tasks found in ${tasksPath}`);
@@ -31,12 +29,59 @@ function generateTaskFiles(tasksPath, outputDir, options = {}) {
fs.mkdirSync(outputDir, { recursive: true });
}
log('info', `Found ${data.tasks.length} tasks to regenerate`);
log('info', `Preparing to regenerate ${data.tasks.length} task files`);
// Validate and fix dependencies before generating files
log('info', `Validating and fixing dependencies`);
validateAndFixDependencies(data, tasksPath);
// Get valid task IDs from tasks.json
const validTaskIds = data.tasks.map((task) => task.id);
// Cleanup orphaned task files
log('info', 'Checking for orphaned task files to clean up...');
try {
// Get all task files in the output directory
const files = fs.readdirSync(outputDir);
const taskFilePattern = /^task_(\d+)\.txt$/;
// Filter for task files and check if they match a valid task ID
const orphanedFiles = files.filter((file) => {
const match = file.match(taskFilePattern);
if (match) {
const fileTaskId = parseInt(match[1], 10);
return !validTaskIds.includes(fileTaskId);
}
return false;
});
// Delete orphaned files
if (orphanedFiles.length > 0) {
log(
'info',
`Found ${orphanedFiles.length} orphaned task files to remove`
);
orphanedFiles.forEach((file) => {
const filePath = path.join(outputDir, file);
try {
fs.unlinkSync(filePath);
log('info', `Removed orphaned task file: ${file}`);
} catch (err) {
log(
'warn',
`Failed to remove orphaned task file ${file}: ${err.message}`
);
}
});
} else {
log('info', 'No orphaned task files found');
}
} catch (err) {
log('warn', `Error cleaning up orphaned task files: ${err.message}`);
// Continue with file generation even if cleanup fails
}
// Generate task files
log('info', 'Generating individual task files...');
data.tasks.forEach((task) => {

View File

@@ -2,13 +2,20 @@ import chalk from 'chalk';
import boxen from 'boxen';
import Table from 'cli-table3';
import { log, readJSON, truncate } from '../utils.js';
import {
log,
readJSON,
truncate,
readComplexityReport,
addComplexityToTask
} from '../utils.js';
import findNextTask from './find-next-task.js';
import {
displayBanner,
getStatusWithColor,
formatDependenciesWithStatus,
getComplexityWithColor,
createProgressBar
} from '../ui.js';
@@ -16,6 +23,7 @@ import {
* List all tasks
* @param {string} tasksPath - Path to the tasks.json file
* @param {string} statusFilter - Filter by status
* @param {string} reportPath - Path to the complexity report
* @param {boolean} withSubtasks - Whether to show subtasks
* @param {string} outputFormat - Output format (text or json)
* @returns {Object} - Task list result for json format
@@ -23,6 +31,7 @@ import {
function listTasks(
tasksPath,
statusFilter,
reportPath = null,
withSubtasks = false,
outputFormat = 'text'
) {
@@ -37,6 +46,13 @@ function listTasks(
throw new Error(`No valid tasks found in ${tasksPath}`);
}
// Add complexity scores to tasks if report exists
const complexityReport = readComplexityReport(reportPath);
// Apply complexity scores to tasks
if (complexityReport && complexityReport.complexityAnalysis) {
data.tasks.forEach((task) => addComplexityToTask(task, complexityReport));
}
// Filter tasks by status if specified
const filteredTasks =
statusFilter && statusFilter.toLowerCase() !== 'all' // <-- Added check for 'all'
@@ -257,8 +273,8 @@ function listTasks(
);
const avgDependenciesPerTask = totalDependencies / data.tasks.length;
// Find next task to work on
const nextItem = findNextTask(data.tasks);
// Find next task to work on, passing the complexity report
const nextItem = findNextTask(data.tasks, complexityReport);
// Get terminal width - more reliable method
let terminalWidth;
@@ -301,8 +317,11 @@ function listTasks(
`${chalk.blue('•')} ${chalk.white('Avg dependencies per task:')} ${avgDependenciesPerTask.toFixed(1)}\n\n` +
chalk.cyan.bold('Next Task to Work On:') +
'\n' +
`ID: ${chalk.cyan(nextItem ? nextItem.id : 'N/A')} - ${nextItem ? chalk.white.bold(truncate(nextItem.title, 40)) : chalk.yellow('No task available')}\n` +
`Priority: ${nextItem ? chalk.white(nextItem.priority || 'medium') : ''} Dependencies: ${nextItem ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true) : ''}`;
`ID: ${chalk.cyan(nextItem ? nextItem.id : 'N/A')} - ${nextItem ? chalk.white.bold(truncate(nextItem.title, 40)) : chalk.yellow('No task available')}
` +
`Priority: ${nextItem ? chalk.white(nextItem.priority || 'medium') : ''} Dependencies: ${nextItem ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true, complexityReport) : ''}
` +
`Complexity: ${nextItem && nextItem.complexityScore ? getComplexityWithColor(nextItem.complexityScore) : chalk.gray('N/A')}`;
// Calculate width for side-by-side display
// Box borders, padding take approximately 4 chars on each side
@@ -412,9 +431,16 @@ function listTasks(
// Make dependencies column smaller as requested (-20%)
const depsWidthPct = 20;
const complexityWidthPct = 10;
// Calculate title/description width as remaining space (+20% from dependencies reduction)
const titleWidthPct =
100 - idWidthPct - statusWidthPct - priorityWidthPct - depsWidthPct;
100 -
idWidthPct -
statusWidthPct -
priorityWidthPct -
depsWidthPct -
complexityWidthPct;
// Allow 10 characters for borders and padding
const availableWidth = terminalWidth - 10;
@@ -424,6 +450,9 @@ function listTasks(
const statusWidth = Math.floor(availableWidth * (statusWidthPct / 100));
const priorityWidth = Math.floor(availableWidth * (priorityWidthPct / 100));
const depsWidth = Math.floor(availableWidth * (depsWidthPct / 100));
const complexityWidth = Math.floor(
availableWidth * (complexityWidthPct / 100)
);
const titleWidth = Math.floor(availableWidth * (titleWidthPct / 100));
// Create a table with correct borders and spacing
@@ -433,9 +462,17 @@ function listTasks(
chalk.cyan.bold('Title'),
chalk.cyan.bold('Status'),
chalk.cyan.bold('Priority'),
chalk.cyan.bold('Dependencies')
chalk.cyan.bold('Dependencies'),
chalk.cyan.bold('Complexity')
],
colWidths: [
idWidth,
titleWidth,
statusWidth,
priorityWidth,
depsWidth,
complexityWidth // Added complexity column width
],
colWidths: [idWidth, titleWidth, statusWidth, priorityWidth, depsWidth],
style: {
head: [], // No special styling for header
border: [], // No special styling for border
@@ -454,7 +491,8 @@ function listTasks(
depText = formatDependenciesWithStatus(
task.dependencies,
data.tasks,
true
true,
complexityReport
);
} else {
depText = chalk.gray('None');
@@ -480,7 +518,10 @@ function listTasks(
truncate(cleanTitle, titleWidth - 3),
status,
priorityColor(truncate(task.priority || 'medium', priorityWidth - 2)),
depText // No truncation for dependencies
depText,
task.complexityScore
? getComplexityWithColor(task.complexityScore)
: chalk.gray('N/A')
]);
// Add subtasks if requested
@@ -516,6 +557,8 @@ function listTasks(
// Default to regular task dependency
const depTask = data.tasks.find((t) => t.id === depId);
if (depTask) {
// Add complexity to depTask before checking status
addComplexityToTask(depTask, complexityReport);
const isDone =
depTask.status === 'done' || depTask.status === 'completed';
const isInProgress = depTask.status === 'in-progress';
@@ -541,7 +584,10 @@ function listTasks(
chalk.dim(`└─ ${truncate(subtask.title, titleWidth - 5)}`),
getStatusWithColor(subtask.status, true),
chalk.dim('-'),
subtaskDepText // No truncation for dependencies
subtaskDepText,
subtask.complexityScore
? chalk.gray(`${subtask.complexityScore}`)
: chalk.gray('N/A')
]);
});
}
@@ -597,6 +643,8 @@ function listTasks(
subtasksSection = `\n\n${chalk.white.bold('Subtasks:')}\n`;
subtasksSection += parentTaskForSubtasks.subtasks
.map((subtask) => {
// Add complexity to subtask before display
addComplexityToTask(subtask, complexityReport);
// Using a more simplified format for subtask status display
const status = subtask.status || 'pending';
const statusColors = {
@@ -625,8 +673,8 @@ function listTasks(
'\n\n' +
// Use nextItem.priority, nextItem.status, nextItem.dependencies
`${chalk.white('Priority:')} ${priorityColors[nextItem.priority || 'medium'](nextItem.priority || 'medium')} ${chalk.white('Status:')} ${getStatusWithColor(nextItem.status, true)}\n` +
`${chalk.white('Dependencies:')} ${nextItem.dependencies && nextItem.dependencies.length > 0 ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true) : chalk.gray('None')}\n\n` +
// Use nextItem.description (Note: findNextTask doesn't return description, need to fetch original task/subtask for this)
`${chalk.white('Dependencies:')} ${nextItem.dependencies && nextItem.dependencies.length > 0 ? formatDependenciesWithStatus(nextItem.dependencies, data.tasks, true, complexityReport) : chalk.gray('None')}\n\n` +
// Use nextTask.description (Note: findNextTask doesn't return description, need to fetch original task/subtask for this)
// *** Fetching original item for description and details ***
`${chalk.white('Description:')} ${getWorkItemDescription(nextItem, data.tasks)}` +
subtasksSection + // <-- Subtasks are handled above now

View File

@@ -6,6 +6,7 @@
import path from 'path';
import fs from 'fs';
import https from 'https';
import http from 'http';
import {
getMainModelId,
getResearchModelId,
@@ -19,7 +20,8 @@ import {
getConfig,
writeConfig,
isConfigFilePresent,
getAllProviders
getAllProviders,
getBaseUrlForRole
} from '../config-manager.js';
/**
@@ -68,6 +70,68 @@ function fetchOpenRouterModels() {
});
}
/**
* Fetches the list of models from Ollama instance.
* @param {string} baseURL - The base URL for the Ollama API (e.g., "http://localhost:11434/api")
* @returns {Promise<Array|null>} A promise that resolves with the list of model objects or null if fetch fails.
*/
function fetchOllamaModels(baseURL = 'http://localhost:11434/api') {
return new Promise((resolve) => {
try {
// Parse the base URL to extract hostname, port, and base path
const url = new URL(baseURL);
const isHttps = url.protocol === 'https:';
const port = url.port || (isHttps ? 443 : 80);
const basePath = url.pathname.endsWith('/')
? url.pathname.slice(0, -1)
: url.pathname;
const options = {
hostname: url.hostname,
port: parseInt(port, 10),
path: `${basePath}/tags`,
method: 'GET',
headers: {
Accept: 'application/json'
}
};
const requestLib = isHttps ? https : http;
const req = requestLib.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
try {
const parsedData = JSON.parse(data);
resolve(parsedData.models || []); // Return the array of models
} catch (e) {
console.error('Error parsing Ollama response:', e);
resolve(null); // Indicate failure
}
} else {
console.error(
`Ollama API request failed with status code: ${res.statusCode}`
);
resolve(null); // Indicate failure
}
});
});
req.on('error', (e) => {
console.error('Error fetching Ollama models:', e);
resolve(null); // Indicate failure
});
req.end();
} catch (e) {
console.error('Error parsing Ollama base URL:', e);
resolve(null); // Indicate failure
}
});
}
/**
* Get the current model configuration
* @param {Object} [options] - Options for the operation
@@ -416,10 +480,29 @@ async function setModel(role, modelId, options = {}) {
);
}
} else if (providerHint === 'ollama') {
// Hinted as Ollama - set provider directly WITHOUT checking OpenRouter
// Check Ollama ONLY because hint was ollama
report('info', `Checking Ollama for ${modelId} (as hinted)...`);
// Get the Ollama base URL from config
const ollamaBaseURL = getBaseUrlForRole(role, projectRoot);
const ollamaModels = await fetchOllamaModels(ollamaBaseURL);
if (ollamaModels === null) {
// Connection failed - server probably not running
throw new Error(
`Unable to connect to Ollama server at ${ollamaBaseURL}. Please ensure Ollama is running and try again.`
);
} else if (ollamaModels.some((m) => m.model === modelId)) {
determinedProvider = 'ollama';
warningMessage = `Warning: Custom Ollama model '${modelId}' set. Ensure your Ollama server is running and has pulled this model. Taskmaster cannot guarantee compatibility.`;
report('warn', warningMessage);
} else {
// Server is running but model not found
const tagsUrl = `${ollamaBaseURL}/tags`;
throw new Error(
`Model ID "${modelId}" not found in the Ollama instance. Please verify the model is pulled and available. You can check available models with: curl ${tagsUrl}`
);
}
} else {
// Invalid provider hint - should not happen
throw new Error(`Invalid provider hint received: ${providerHint}`);

View File

@@ -0,0 +1,571 @@
import path from 'path';
import { log, readJSON, writeJSON } from '../utils.js';
import { isTaskDependentOn } from '../task-manager.js';
import generateTaskFiles from './generate-task-files.js';
/**
* Move a task or subtask to a new position
* @param {string} tasksPath - Path to tasks.json file
* @param {string} sourceId - ID of the task/subtask to move (e.g., '5' or '5.2')
* @param {string} destinationId - ID of the destination (e.g., '7' or '7.3')
* @param {boolean} generateFiles - Whether to regenerate task files after moving
* @returns {Object} Result object with moved task details
*/
async function moveTask(
tasksPath,
sourceId,
destinationId,
generateFiles = true
) {
try {
log('info', `Moving task/subtask ${sourceId} to ${destinationId}...`);
// Read the existing tasks
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
throw new Error(`Invalid or missing tasks file at ${tasksPath}`);
}
// Parse source ID to determine if it's a task or subtask
const isSourceSubtask = sourceId.includes('.');
let sourceTask,
sourceParentTask,
sourceSubtask,
sourceTaskIndex,
sourceSubtaskIndex;
// Parse destination ID to determine the target
const isDestinationSubtask = destinationId.includes('.');
let destTask, destParentTask, destSubtask, destTaskIndex, destSubtaskIndex;
// Validate source exists
if (isSourceSubtask) {
// Source is a subtask
const [parentIdStr, subtaskIdStr] = sourceId.split('.');
const parentIdNum = parseInt(parentIdStr, 10);
const subtaskIdNum = parseInt(subtaskIdStr, 10);
sourceParentTask = data.tasks.find((t) => t.id === parentIdNum);
if (!sourceParentTask) {
throw new Error(`Source parent task with ID ${parentIdNum} not found`);
}
if (
!sourceParentTask.subtasks ||
sourceParentTask.subtasks.length === 0
) {
throw new Error(`Source parent task ${parentIdNum} has no subtasks`);
}
sourceSubtaskIndex = sourceParentTask.subtasks.findIndex(
(st) => st.id === subtaskIdNum
);
if (sourceSubtaskIndex === -1) {
throw new Error(`Source subtask ${sourceId} not found`);
}
sourceSubtask = { ...sourceParentTask.subtasks[sourceSubtaskIndex] };
} else {
// Source is a task
const sourceIdNum = parseInt(sourceId, 10);
sourceTaskIndex = data.tasks.findIndex((t) => t.id === sourceIdNum);
if (sourceTaskIndex === -1) {
throw new Error(`Source task with ID ${sourceIdNum} not found`);
}
sourceTask = { ...data.tasks[sourceTaskIndex] };
}
// Validate destination exists
if (isDestinationSubtask) {
// Destination is a subtask (target will be the parent of this subtask)
const [parentIdStr, subtaskIdStr] = destinationId.split('.');
const parentIdNum = parseInt(parentIdStr, 10);
const subtaskIdNum = parseInt(subtaskIdStr, 10);
destParentTask = data.tasks.find((t) => t.id === parentIdNum);
if (!destParentTask) {
throw new Error(
`Destination parent task with ID ${parentIdNum} not found`
);
}
if (!destParentTask.subtasks || destParentTask.subtasks.length === 0) {
throw new Error(
`Destination parent task ${parentIdNum} has no subtasks`
);
}
destSubtaskIndex = destParentTask.subtasks.findIndex(
(st) => st.id === subtaskIdNum
);
if (destSubtaskIndex === -1) {
throw new Error(`Destination subtask ${destinationId} not found`);
}
destSubtask = destParentTask.subtasks[destSubtaskIndex];
} else {
// Destination is a task
const destIdNum = parseInt(destinationId, 10);
destTaskIndex = data.tasks.findIndex((t) => t.id === destIdNum);
if (destTaskIndex === -1) {
// Create placeholder for destination if it doesn't exist
log('info', `Creating placeholder for destination task ${destIdNum}`);
const newTask = {
id: destIdNum,
title: `Task ${destIdNum}`,
description: '',
status: 'pending',
priority: 'medium',
details: '',
testStrategy: ''
};
// Find correct position to insert the new task
let insertIndex = 0;
while (
insertIndex < data.tasks.length &&
data.tasks[insertIndex].id < destIdNum
) {
insertIndex++;
}
// Insert the new task at the appropriate position
data.tasks.splice(insertIndex, 0, newTask);
destTaskIndex = insertIndex;
destTask = data.tasks[destTaskIndex];
} else {
destTask = data.tasks[destTaskIndex];
// Check if destination task is already a "real" task with content
// Only allow moving to destination IDs that don't have meaningful content
if (
destTask.title !== `Task ${destTask.id}` ||
destTask.description !== '' ||
destTask.details !== ''
) {
throw new Error(
`Cannot move to task ID ${destIdNum} as it already contains content. Choose a different destination ID.`
);
}
}
}
// Validate that we aren't trying to move a task to itself
if (sourceId === destinationId) {
throw new Error('Cannot move a task/subtask to itself');
}
// Prevent moving a parent to its own subtask
if (!isSourceSubtask && isDestinationSubtask) {
const destParentId = parseInt(destinationId.split('.')[0], 10);
if (parseInt(sourceId, 10) === destParentId) {
throw new Error('Cannot move a parent task to one of its own subtasks');
}
}
// Check for circular dependency when moving tasks
if (!isSourceSubtask && !isDestinationSubtask) {
const sourceIdNum = parseInt(sourceId, 10);
const destIdNum = parseInt(destinationId, 10);
// Check if destination is dependent on source
if (isTaskDependentOn(data.tasks, destTask, sourceIdNum)) {
throw new Error(
`Cannot move task ${sourceId} to task ${destinationId} as it would create a circular dependency`
);
}
}
let movedTask;
// Handle different move scenarios
if (!isSourceSubtask && !isDestinationSubtask) {
// Check if destination is a placeholder we just created
if (
destTask.title === `Task ${destTask.id}` &&
destTask.description === '' &&
destTask.details === ''
) {
// Case 0: Move task to a new position/ID (destination is a placeholder)
movedTask = moveTaskToNewId(
data,
sourceTask,
sourceTaskIndex,
destTask,
destTaskIndex
);
} else {
// Case 1: Move standalone task to become a subtask of another task
movedTask = moveTaskToTask(data, sourceTask, sourceTaskIndex, destTask);
}
} else if (!isSourceSubtask && isDestinationSubtask) {
// Case 2: Move standalone task to become a subtask at a specific position
movedTask = moveTaskToSubtaskPosition(
data,
sourceTask,
sourceTaskIndex,
destParentTask,
destSubtaskIndex
);
} else if (isSourceSubtask && !isDestinationSubtask) {
// Case 3: Move subtask to become a standalone task
movedTask = moveSubtaskToTask(
data,
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destTask
);
} else if (isSourceSubtask && isDestinationSubtask) {
// Case 4: Move subtask to another parent or position
// First check if it's the same parent
const sourceParentId = parseInt(sourceId.split('.')[0], 10);
const destParentId = parseInt(destinationId.split('.')[0], 10);
if (sourceParentId === destParentId) {
// Case 4a: Move subtask within the same parent (reordering)
movedTask = reorderSubtask(
sourceParentTask,
sourceSubtaskIndex,
destSubtaskIndex
);
} else {
// Case 4b: Move subtask to a different parent
movedTask = moveSubtaskToAnotherParent(
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destParentTask,
destSubtaskIndex
);
}
}
// Write the updated tasks back to the file
writeJSON(tasksPath, data);
// Generate task files if requested
if (generateFiles) {
log('info', 'Regenerating task files...');
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
}
return movedTask;
} catch (error) {
log('error', `Error moving task/subtask: ${error.message}`);
throw error;
}
}
/**
* Move a standalone task to become a subtask of another task
* @param {Object} data - Tasks data object
* @param {Object} sourceTask - Source task to move
* @param {number} sourceTaskIndex - Index of source task in data.tasks
* @param {Object} destTask - Destination task
* @returns {Object} Moved task object
*/
function moveTaskToTask(data, sourceTask, sourceTaskIndex, destTask) {
// Initialize subtasks array if it doesn't exist
if (!destTask.subtasks) {
destTask.subtasks = [];
}
// Find the highest subtask ID to determine the next ID
const highestSubtaskId =
destTask.subtasks.length > 0
? Math.max(...destTask.subtasks.map((st) => st.id))
: 0;
const newSubtaskId = highestSubtaskId + 1;
// Create the new subtask from the source task
const newSubtask = {
...sourceTask,
id: newSubtaskId,
parentTaskId: destTask.id
};
// Add to destination's subtasks
destTask.subtasks.push(newSubtask);
// Remove the original task from the tasks array
data.tasks.splice(sourceTaskIndex, 1);
log(
'info',
`Moved task ${sourceTask.id} to become subtask ${destTask.id}.${newSubtaskId}`
);
return newSubtask;
}
/**
* Move a standalone task to become a subtask at a specific position
* @param {Object} data - Tasks data object
* @param {Object} sourceTask - Source task to move
* @param {number} sourceTaskIndex - Index of source task in data.tasks
* @param {Object} destParentTask - Destination parent task
* @param {number} destSubtaskIndex - Index of the subtask before which to insert
* @returns {Object} Moved task object
*/
function moveTaskToSubtaskPosition(
data,
sourceTask,
sourceTaskIndex,
destParentTask,
destSubtaskIndex
) {
// Initialize subtasks array if it doesn't exist
if (!destParentTask.subtasks) {
destParentTask.subtasks = [];
}
// Find the highest subtask ID to determine the next ID
const highestSubtaskId =
destParentTask.subtasks.length > 0
? Math.max(...destParentTask.subtasks.map((st) => st.id))
: 0;
const newSubtaskId = highestSubtaskId + 1;
// Create the new subtask from the source task
const newSubtask = {
...sourceTask,
id: newSubtaskId,
parentTaskId: destParentTask.id
};
// Insert at specific position
destParentTask.subtasks.splice(destSubtaskIndex + 1, 0, newSubtask);
// Remove the original task from the tasks array
data.tasks.splice(sourceTaskIndex, 1);
log(
'info',
`Moved task ${sourceTask.id} to become subtask ${destParentTask.id}.${newSubtaskId}`
);
return newSubtask;
}
/**
* Move a subtask to become a standalone task
* @param {Object} data - Tasks data object
* @param {Object} sourceSubtask - Source subtask to move
* @param {Object} sourceParentTask - Parent task of the source subtask
* @param {number} sourceSubtaskIndex - Index of source subtask in parent's subtasks
* @param {Object} destTask - Destination task (for position reference)
* @returns {Object} Moved task object
*/
function moveSubtaskToTask(
data,
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destTask
) {
// Find the highest task ID to determine the next ID
const highestId = Math.max(...data.tasks.map((t) => t.id));
const newTaskId = highestId + 1;
// Create the new task from the subtask
const newTask = {
...sourceSubtask,
id: newTaskId,
priority: sourceParentTask.priority || 'medium' // Inherit priority from parent
};
delete newTask.parentTaskId;
// Add the parent task as a dependency if not already present
if (!newTask.dependencies) {
newTask.dependencies = [];
}
if (!newTask.dependencies.includes(sourceParentTask.id)) {
newTask.dependencies.push(sourceParentTask.id);
}
// Find the destination index to insert the new task
const destTaskIndex = data.tasks.findIndex((t) => t.id === destTask.id);
// Insert the new task after the destination task
data.tasks.splice(destTaskIndex + 1, 0, newTask);
// Remove the subtask from the parent
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
// If parent has no more subtasks, remove the subtasks array
if (sourceParentTask.subtasks.length === 0) {
delete sourceParentTask.subtasks;
}
log(
'info',
`Moved subtask ${sourceParentTask.id}.${sourceSubtask.id} to become task ${newTaskId}`
);
return newTask;
}
/**
* Reorder a subtask within the same parent
* @param {Object} parentTask - Parent task containing the subtask
* @param {number} sourceIndex - Current index of the subtask
* @param {number} destIndex - Destination index for the subtask
* @returns {Object} Moved subtask object
*/
function reorderSubtask(parentTask, sourceIndex, destIndex) {
// Get the subtask to move
const subtask = parentTask.subtasks[sourceIndex];
// Remove the subtask from its current position
parentTask.subtasks.splice(sourceIndex, 1);
// Insert the subtask at the new position
// If destIndex was after sourceIndex, it's now one less because we removed an item
const adjustedDestIndex = sourceIndex < destIndex ? destIndex - 1 : destIndex;
parentTask.subtasks.splice(adjustedDestIndex, 0, subtask);
log(
'info',
`Reordered subtask ${parentTask.id}.${subtask.id} within parent task ${parentTask.id}`
);
return subtask;
}
/**
* Move a subtask to a different parent
* @param {Object} sourceSubtask - Source subtask to move
* @param {Object} sourceParentTask - Parent task of the source subtask
* @param {number} sourceSubtaskIndex - Index of source subtask in parent's subtasks
* @param {Object} destParentTask - Destination parent task
* @param {number} destSubtaskIndex - Index of the subtask before which to insert
* @returns {Object} Moved subtask object
*/
function moveSubtaskToAnotherParent(
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destParentTask,
destSubtaskIndex
) {
// Find the highest subtask ID in the destination parent
const highestSubtaskId =
destParentTask.subtasks.length > 0
? Math.max(...destParentTask.subtasks.map((st) => st.id))
: 0;
const newSubtaskId = highestSubtaskId + 1;
// Create the new subtask with updated parent reference
const newSubtask = {
...sourceSubtask,
id: newSubtaskId,
parentTaskId: destParentTask.id
};
// If the subtask depends on its original parent, keep that dependency
if (!newSubtask.dependencies) {
newSubtask.dependencies = [];
}
if (!newSubtask.dependencies.includes(sourceParentTask.id)) {
newSubtask.dependencies.push(sourceParentTask.id);
}
// Insert at the destination position
destParentTask.subtasks.splice(destSubtaskIndex + 1, 0, newSubtask);
// Remove the subtask from the original parent
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
// If original parent has no more subtasks, remove the subtasks array
if (sourceParentTask.subtasks.length === 0) {
delete sourceParentTask.subtasks;
}
log(
'info',
`Moved subtask ${sourceParentTask.id}.${sourceSubtask.id} to become subtask ${destParentTask.id}.${newSubtaskId}`
);
return newSubtask;
}
/**
* Move a standalone task to a new ID position
* @param {Object} data - Tasks data object
* @param {Object} sourceTask - Source task to move
* @param {number} sourceTaskIndex - Index of source task in data.tasks
* @param {Object} destTask - Destination placeholder task
* @param {number} destTaskIndex - Index of destination task in data.tasks
* @returns {Object} Moved task object
*/
function moveTaskToNewId(
data,
sourceTask,
sourceTaskIndex,
destTask,
destTaskIndex
) {
// Create a copy of the source task with the new ID
const movedTask = {
...sourceTask,
id: destTask.id
};
// Get numeric IDs for comparison
const sourceIdNum = parseInt(sourceTask.id, 10);
const destIdNum = parseInt(destTask.id, 10);
// Handle subtasks if present
if (sourceTask.subtasks && sourceTask.subtasks.length > 0) {
// Update subtasks to reference the new parent ID if needed
movedTask.subtasks = sourceTask.subtasks.map((subtask) => ({
...subtask,
parentTaskId: destIdNum
}));
}
// Update any dependencies in other tasks that referenced the old ID
data.tasks.forEach((task) => {
if (task.dependencies && task.dependencies.includes(sourceIdNum)) {
// Replace the old ID with the new ID
const depIndex = task.dependencies.indexOf(sourceIdNum);
task.dependencies[depIndex] = destIdNum;
}
// Also check for subtask dependencies that might reference this task
if (task.subtasks && task.subtasks.length > 0) {
task.subtasks.forEach((subtask) => {
if (
subtask.dependencies &&
subtask.dependencies.includes(sourceIdNum)
) {
const depIndex = subtask.dependencies.indexOf(sourceIdNum);
subtask.dependencies[depIndex] = destIdNum;
}
});
}
});
// Remove the original task from its position
data.tasks.splice(sourceTaskIndex, 1);
// If we're moving to a position after the original, adjust the destination index
// since removing the original shifts everything down by 1
const adjustedDestIndex =
sourceTaskIndex < destTaskIndex ? destTaskIndex - 1 : destTaskIndex;
// Remove the placeholder destination task
data.tasks.splice(adjustedDestIndex, 1);
// Insert the moved task at the destination position
data.tasks.splice(adjustedDestIndex, 0, movedTask);
log('info', `Moved task ${sourceIdNum} to new ID ${destIdNum}`);
return movedTask;
}
export default moveTask;

Some files were not shown because too many files have changed in this diff Show More