feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
---
description: Guidelines for implementing and maintaining tests for Task Master CLI
globs: "**/*.test.js,tests/**/*"
---
# Testing Guidelines for Task Master CLI
2025-04-09 16:29:24 -04:00
*Note:* Never use asynchronous operations in tests. Always mock tests properly based on the way the tested functions are defined and used. Do not arbitrarily create tests. Based them on the low-level details and execution of the underlying code being tested.
feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
## Test Organization Structure
feat(mcp): Refactor MCP tools for direct function calls & add docs
This commit introduces a major refactoring of the MCP server implementation to prioritize direct function calls over CLI execution, enhancing performance and reliability. It also includes substantial updates to documentation for consistency and interlinking.
**MCP Server & Core Logic Refactoring:**
1. **Introduce Direct Function Wrappers ():**
* Created to house direct wrappers for core Task Master functions (imported from ).
* Implemented as the first wrapper, calling .
* Added utility within to centralize file location logic, removing duplication.
* Established the map for registering these wrappers.
2. **Enhance MCP Utilities ():**
* Added : A primary utility function to streamline MCP tool methods. It handles logging, argument processing (incl. project root normalization), calling the direct action function (e.g., ), processing results via , and formatting the final MCP response.
* Added : Standardizes processing of objects returned by direct function wrappers.
* Added : Filters sensitive/large fields (like , ) from responses sent to the MCP client.
* Added , , to support the new workflow.
* Refactored to use internally, simplifying its usage (though it's now primarily a fallback).
3. **Update MCP Tools (, ):**
* Refactored to use with , significantly simplifying the tool's method.
* Updated (initially) to use the improved (Note: further refactoring to use a direct wrapper for would follow the pattern).
**Documentation Enhancements:**
4. **Comprehensive Interlinking:** Added links across rule files (, , , , , ) to connect related guidelines, improving navigation.
5. **Standardize CLI Syntax ():** Removed legacy ℹ️ Initialized Perplexity client with OpenAI compatibility layer examples, reinforcing ℹ️ Initialized Perplexity client with OpenAI compatibility layer
_____ _ __ __ _
|_ _|_ _ ___| | __ | \/ | __ _ ___| |_ ___ _ __
| |/ _` / __| |/ / | |\/| |/ _` / __| __/ _ \ '__|
| | (_| \__ \ < | | | | (_| \__ \ || __/ |
|_|\__,_|___/_|\_\ |_| |_|\__,_|___/\__\___|_|
by https://x.com/eyaltoledano
╭────────────────────────────────────────────╮
│ │
│ Version: 0.9.30 Project: Task Master │
│ │
╰────────────────────────────────────────────╯
╭─────────────────────╮
│ │
│ Task Master CLI │
│ │
╰─────────────────────╯
╭───────────────────╮
│ Task Generation │
╰───────────────────╯
parse-prd --input=<file.txt> [--tasks=10] Generate tasks from a PRD document
generate Create individual task files from tasks…
╭───────────────────╮
│ Task Management │
╰───────────────────╯
list [--status=<status>] [--with-subtas… List all tasks with their status
set-status --id=<id> --status=<status> Update task status (done, pending, etc.)
update --from=<id> --prompt="<context>" Update tasks based on new requirements
add-task --prompt="<text>" [--dependencies=… Add a new task using AI
add-dependency --id=<id> --depends-on=<id> Add a dependency to a task
remove-dependency --id=<id> --depends-on=<id> Remove a dependency from a task
╭──────────────────────────╮
│ Task Analysis & Detail │
╰──────────────────────────╯
analyze-complexity [--research] [--threshold=5] Analyze tasks and generate expansion re…
complexity-report [--file=<path>] Display the complexity analysis report
expand --id=<id> [--num=5] [--research] [… Break down tasks into detailed subtasks
expand --all [--force] [--research] Expand all pending tasks with subtasks
clear-subtasks --id=<id> Remove subtasks from specified tasks
╭─────────────────────────────╮
│ Task Navigation & Viewing │
╰─────────────────────────────╯
next Show the next task to work on based on …
show <id> Display detailed information about a sp…
╭─────────────────────────╮
│ Dependency Management │
╰─────────────────────────╯
validate-dependenci… Identify invalid dependencies without f…
fix-dependencies Fix invalid dependencies automatically
╭─────────────────────────╮
│ Environment Variables │
╰─────────────────────────╯
ANTHROPIC_API_KEY Your Anthropic API key Required
MODEL Claude model to use Default: claude-3-7-sonn…
MAX_TOKENS Maximum tokens for responses Default: 4000
TEMPERATURE Temperature for model responses Default: 0.7
PERPLEXITY_API_KEY Perplexity API key for research Optional
PERPLEXITY_MODEL Perplexity model to use Default: sonar-pro
DEBUG Enable debug logging Default: false
LOG_LEVEL Console output level (debug,info,warn,error) Default: info
DEFAULT_SUBTASKS Default number of subtasks to generate Default: 3
DEFAULT_PRIORITY Default task priority Default: medium
PROJECT_NAME Project name displayed in UI Default: Task Master
_____ _ __ __ _
|_ _|_ _ ___| | __ | \/ | __ _ ___| |_ ___ _ __
| |/ _` / __| |/ / | |\/| |/ _` / __| __/ _ \ '__|
| | (_| \__ \ < | | | | (_| \__ \ || __/ |
|_|\__,_|___/_|\_\ |_| |_|\__,_|___/\__\___|_|
by https://x.com/eyaltoledano
╭────────────────────────────────────────────╮
│ │
│ Version: 0.9.30 Project: Task Master │
│ │
╰────────────────────────────────────────────╯
╭─────────────────────╮
│ │
│ Task Master CLI │
│ │
╰─────────────────────╯
╭───────────────────╮
│ Task Generation │
╰───────────────────╯
parse-prd --input=<file.txt> [--tasks=10] Generate tasks from a PRD document
generate Create individual task files from tasks…
╭───────────────────╮
│ Task Management │
╰───────────────────╯
list [--status=<status>] [--with-subtas… List all tasks with their status
set-status --id=<id> --status=<status> Update task status (done, pending, etc.)
update --from=<id> --prompt="<context>" Update tasks based on new requirements
add-task --prompt="<text>" [--dependencies=… Add a new task using AI
add-dependency --id=<id> --depends-on=<id> Add a dependency to a task
remove-dependency --id=<id> --depends-on=<id> Remove a dependency from a task
╭──────────────────────────╮
│ Task Analysis & Detail │
╰──────────────────────────╯
analyze-complexity [--research] [--threshold=5] Analyze tasks and generate expansion re…
complexity-report [--file=<path>] Display the complexity analysis report
expand --id=<id> [--num=5] [--research] [… Break down tasks into detailed subtasks
expand --all [--force] [--research] Expand all pending tasks with subtasks
clear-subtasks --id=<id> Remove subtasks from specified tasks
╭─────────────────────────────╮
│ Task Navigation & Viewing │
╰─────────────────────────────╯
next Show the next task to work on based on …
show <id> Display detailed information about a sp…
╭─────────────────────────╮
│ Dependency Management │
╰─────────────────────────╯
validate-dependenci… Identify invalid dependencies without f…
fix-dependencies Fix invalid dependencies automatically
╭─────────────────────────╮
│ Environment Variables │
╰─────────────────────────╯
ANTHROPIC_API_KEY Your Anthropic API key Required
MODEL Claude model to use Default: claude-3-7-sonn…
MAX_TOKENS Maximum tokens for responses Default: 4000
TEMPERATURE Temperature for model responses Default: 0.7
PERPLEXITY_API_KEY Perplexity API key for research Optional
PERPLEXITY_MODEL Perplexity model to use Default: sonar-pro
DEBUG Enable debug logging Default: false
LOG_LEVEL Console output level (debug,info,warn,error) Default: info
DEFAULT_SUBTASKS Default number of subtasks to generate Default: 3
DEFAULT_PRIORITY Default task priority Default: medium
PROJECT_NAME Project name displayed in UI Default: Task Master as the primary CLI.
6. **Add MCP Architecture & Workflow Sections:** Added detailed sections in and explaining MCP server structure and the workflow for adding new MCP tool integrations using the direct function pattern.
7. **Clarify MCP Role:** Updated and to better explain the MCP server's role and its specific utilities.
Overall, this establishes a cleaner, more performant, and maintainable pattern for integrating Task Master functionality with the MCP server, supported by improved documentation.
2025-03-30 00:29:12 -04:00
- **Unit Tests** (See [`architecture.mdc`](mdc:.cursor/rules/architecture.mdc) for module breakdown)
feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
- Located in `tests/unit/`
- Test individual functions and utilities in isolation
- Mock all external dependencies
- Keep tests small, focused, and fast
- Example naming: `utils.test.js`, `task-manager.test.js`
- **Integration Tests**
- Located in `tests/integration/`
- Test interactions between modules
- Focus on component interfaces rather than implementation details
- Use more realistic but still controlled test environments
- Example naming: `task-workflow.test.js`, `command-integration.test.js`
- **End-to-End Tests**
- Located in `tests/e2e/`
- Test complete workflows from a user perspective
- Focus on CLI commands as they would be used by users
- Example naming: `create-task.e2e.test.js`, `expand-task.e2e.test.js`
- **Test Fixtures**
- Located in `tests/fixtures/`
- Provide reusable test data
- Keep fixtures small and representative
- Export fixtures as named exports for reuse
## Test File Organization
```javascript
// 1. Imports
import { jest } from '@jest/globals';
// 2. Mock setup (MUST come before importing the modules under test)
jest.mock('fs');
jest.mock('@anthropic-ai/sdk');
jest.mock('../../scripts/modules/utils.js', () => ({
CONFIG: {
projectVersion: '1.5.0'
},
log: jest.fn()
}));
// 3. Import modules AFTER all mocks are defined
import { functionToTest } from '../../scripts/modules/module-name.js';
import { testFixture } from '../fixtures/fixture-name.js';
import fs from 'fs';
// 4. Set up spies on mocked modules (if needed)
const mockReadFileSync = jest.spyOn(fs, 'readFileSync');
// 5. Test suite with descriptive name
describe('Feature or Function Name', () => {
// 6. Setup and teardown (if needed)
beforeEach(() => {
jest.clearAllMocks();
// Additional setup code
});
afterEach(() => {
// Cleanup code
});
// 7. Grouped tests for related functionality
describe('specific functionality', () => {
// 8. Individual test cases with clear descriptions
test('should behave in expected way when given specific input', () => {
// Arrange - set up test data
const input = testFixture.sampleInput;
mockReadFileSync.mockReturnValue('mocked content');
// Act - call the function being tested
const result = functionToTest(input);
// Assert - verify the result
expect(result).toBe(expectedOutput);
expect(mockReadFileSync).toHaveBeenCalledWith(expect.stringContaining('path'));
});
});
});
```
2025-04-09 18:18:13 -04:00
## Commander.js Command Testing Best Practices
When testing CLI commands built with Commander.js, several special considerations must be made to avoid common pitfalls:
- **Direct Action Handler Testing**
- ✅ **DO**: Test the command action handlers directly rather than trying to mock the entire Commander.js chain
- ✅ **DO**: Create simplified test-specific implementations of command handlers that match the original behavior
- ✅ **DO**: Explicitly handle all options, including defaults and shorthand flags (e.g., `-p` for `--prompt`)
- ✅ **DO**: Include null/undefined checks in test implementations for parameters that might be optional
- ✅ **DO**: Use fixtures from `tests/fixtures/` for consistent sample data across tests
```javascript
// ✅ DO: Create a simplified test version of the command handler
const testAddTaskAction = async (options) => {
options = options || {}; // Ensure options aren't undefined
// Validate parameters
const isManualCreation = options.title && options.description;
const prompt = options.prompt || options.p; // Handle shorthand flags
if (!prompt && !isManualCreation) {
throw new Error('Expected error message');
}
// Call the mocked task manager
return mockTaskManager.addTask(/* parameters */);
};
test('should handle required parameters correctly', async () => {
// Call the test implementation directly
await expect(async () => {
await testAddTaskAction({ file: 'tasks.json' });
}).rejects.toThrow('Expected error message');
});
```
- **Commander Chain Mocking (If Necessary)**
- ✅ **DO**: Mock ALL chainable methods (`option`, `argument`, `action`, `on`, etc.)
- ✅ **DO**: Return `this` (or the mock object) from all chainable method mocks
- ✅ **DO**: Remember to mock not only the initial object but also all objects returned by methods
- ✅ **DO**: Implement a mechanism to capture the action handler for direct testing
```javascript
// If you must mock the Commander.js chain:
const mockCommand = {
command: jest.fn().mockReturnThis(),
description: jest.fn().mockReturnThis(),
option: jest.fn().mockReturnThis(),
argument: jest.fn().mockReturnThis(), // Don't forget this one
action: jest.fn(fn => {
actionHandler = fn; // Capture the handler for testing
return mockCommand;
}),
on: jest.fn().mockReturnThis() // Don't forget this one
};
```
- **Parameter Handling**
- ✅ **DO**: Check for both main flag and shorthand flags (e.g., `prompt` and `p`)
- ✅ **DO**: Handle parameters like Commander would (comma-separated lists, etc.)
- ✅ **DO**: Set proper default values as defined in the command
- ✅ **DO**: Validate that required parameters are actually required in tests
```javascript
// Parse dependencies like Commander would
const dependencies = options.dependencies
? options.dependencies.split(',').map(id => id.trim())
: [];
```
- **Environment and Session Handling**
- ✅ **DO**: Properly mock session objects when required by functions
- ✅ **DO**: Reset environment variables between tests if modified
- ✅ **DO**: Use a consistent pattern for environment-dependent tests
```javascript
// Session parameter mock pattern
const sessionMock = { session: process.env };
// In test:
expect(mockAddTask).toHaveBeenCalledWith(
expect.any(String),
'Test prompt',
[],
'medium',
sessionMock,
false,
null,
null
);
```
- **Common Pitfalls to Avoid**
- ❌ **DON'T**: Try to use the real action implementation without proper mocking
- ❌ **DON'T**: Mock Commander partially - either mock it completely or test the action directly
- ❌ **DON'T**: Forget to handle optional parameters that may be undefined
- ❌ **DON'T**: Neglect to test shorthand flag functionality (e.g., `-p`, `-r`)
- ❌ **DON'T**: Create circular dependencies in your test mocks
- ❌ **DON'T**: Access variables before initialization in your test implementations
- ❌ **DON'T**: Include actual command execution in unit tests
- ❌ **DON'T**: Overwrite the same file path in multiple tests
```javascript
// ❌ DON'T: Create circular references in mocks
const badMock = {
method: jest.fn().mockImplementation(() => badMock.method())
};
// ❌ DON'T: Access uninitialized variables
const badImplementation = () => {
const result = uninitialized;
let uninitialized = 'value';
return result;
};
```
feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
## Jest Module Mocking Best Practices
- **Mock Hoisting Behavior**
- Jest hoists `jest.mock()` calls to the top of the file, even above imports
- Always declare mocks before importing the modules being tested
- Use the factory pattern for complex mocks that need access to other variables
```javascript
// ✅ DO: Place mocks before imports
jest.mock('commander');
import { program } from 'commander';
// ❌ DON'T: Define variables and then try to use them in mocks
const mockFn = jest.fn();
jest.mock('module', () => ({
func: mockFn // This won't work due to hoisting!
}));
```
- **Mocking Modules with Function References**
- Use `jest.spyOn()` after imports to create spies on mock functions
- Reference these spies in test assertions
```javascript
// Mock the module first
jest.mock('fs');
// Import the mocked module
import fs from 'fs';
// Create spies on the mock functions
const mockExistsSync = jest.spyOn(fs, 'existsSync').mockReturnValue(true);
test('should call existsSync', () => {
// Call function that uses fs.existsSync
const result = functionUnderTest();
// Verify the mock was called correctly
expect(mockExistsSync).toHaveBeenCalled();
});
```
- **Testing Functions with Callbacks**
- Get the callback from your mock's call arguments
- Execute it directly with test inputs
- Verify the results match expectations
```javascript
jest.mock('commander');
import { program } from 'commander';
import { setupCLI } from '../../scripts/modules/commands.js';
const mockVersion = jest.spyOn(program, 'version').mockReturnValue(program);
test('version callback should return correct version', () => {
// Call the function that registers the callback
setupCLI();
// Extract the callback function
const versionCallback = mockVersion.mock.calls[0][0];
expect(typeof versionCallback).toBe('function');
// Execute the callback and verify results
const result = versionCallback();
expect(result).toBe('1.5.0');
});
```
2025-03-24 19:44:24 -04:00
## ES Module Testing Strategies
When testing ES modules (`"type": "module"` in package.json), traditional mocking approaches require special handling to avoid reference and scoping issues.
- **Module Import Challenges**
- Functions imported from ES modules may still reference internal module-scoped variables
- Imported functions may not use your mocked dependencies even with proper jest.mock() setup
- ES module exports are read-only properties (cannot be reassigned during tests)
2025-04-14 19:50:15 -04:00
- **Mocking Modules Statically Imported**
- For modules imported with standard `import` statements at the top level:
- Use `jest.mock('path/to/module', factory)` **before** any imports.
- Jest hoists these mocks.
- Ensure the factory function returns the mocked structure correctly.
- **Mocking Dependencies for Dynamically Imported Modules**
- **Problem**: Standard `jest.mock()` often fails for dependencies of modules loaded later using dynamic `import('path/to/module')`. The mocks aren't applied correctly when the dynamic import resolves.
- **Solution**: Use `jest.unstable_mockModule(modulePath, factory)` **before** the dynamic `import()` call.
2025-03-24 19:44:24 -04:00
```javascript
2025-04-14 19:50:15 -04:00
// 1. Define mock function instances
const mockExistsSync = jest.fn();
const mockReadFileSync = jest.fn();
// ... other mocks
// 2. Mock the dependency module *before* the dynamic import
jest.unstable_mockModule('fs', () => ({
__esModule: true, // Important for ES module mocks
// Mock named exports
existsSync: mockExistsSync,
readFileSync: mockReadFileSync,
// Mock default export if necessary
// default: { ... }
}));
// 3. Dynamically import the module under test (e.g., in beforeAll or test case)
let moduleUnderTest;
beforeAll(async () => {
// Ensure mocks are reset if needed before import
mockExistsSync.mockReset();
mockReadFileSync.mockReset();
// ... reset other mocks ...
// Import *after* unstable_mockModule is called
moduleUnderTest = await import('../../scripts/modules/module-using-fs.js');
});
// 4. Now tests can use moduleUnderTest, and its 'fs' calls will hit the mocks
test('should use mocked fs.readFileSync', () => {
mockReadFileSync.mockReturnValue('mock data');
moduleUnderTest.readFileAndProcess();
expect(mockReadFileSync).toHaveBeenCalled();
// ... other assertions
2025-03-24 19:44:24 -04:00
});
2025-04-14 19:50:15 -04:00
```
- ✅ **DO**: Call `jest.unstable_mockModule()` before `await import()`.
- ✅ **DO**: Include `__esModule: true` in the mock factory for ES modules.
- ✅ **DO**: Mock named and default exports as needed within the factory.
- ✅ **DO**: Reset mock functions (`mockFn.mockReset()`) before the dynamic import if they might have been called previously.
- **Mocking Entire Modules (Static Import)**
```javascript
// Mock the entire module with custom implementation for static imports
// ... (existing example remains valid) ...
2025-03-24 19:44:24 -04:00
```
- **Direct Implementation Testing**
- Instead of calling the actual function which may have module-scope reference issues:
```javascript
2025-04-14 19:50:15 -04:00
// ... (existing example remains valid) ...
2025-03-24 19:44:24 -04:00
```
- **Avoiding Module Property Assignment**
```javascript
2025-04-14 19:50:15 -04:00
// ... (existing example remains valid) ...
2025-03-24 19:44:24 -04:00
```
- **Handling Mock Verification Failures**
- If verification like `expect(mockFn).toHaveBeenCalled()` fails:
2025-04-14 19:50:15 -04:00
1. Check that your mock setup (`jest.mock` or `jest.unstable_mockModule`) is correctly placed **before** imports (static or dynamic).
2. Ensure you're using the right mock instance and it's properly passed to the module.
3. Verify your test invokes behavior that *should* call the mock.
4. Use `jest.clearAllMocks()` or specific `mockFn.mockReset()` in `beforeEach` to prevent state leakage between tests.
5. **Check Console Assertions**: If verifying `console.log`, `console.warn`, or `console.error` calls, ensure your assertion matches the *actual* arguments passed. If the code logs a single formatted string, assert against that single string (using `expect.stringContaining` or exact match), not multiple `expect.stringContaining` arguments.
```javascript
// Example: Code logs console.error(`Error: ${message}. Details: ${details}`)
// ❌ DON'T: Assert multiple arguments if only one is logged
// expect(console.error).toHaveBeenCalledWith(
// expect.stringContaining('Error:'),
// expect.stringContaining('Details:')
// );
// ✅ DO: Assert the single string argument
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Error: Specific message. Details: More details')
);
// or for exact match:
expect(console.error).toHaveBeenCalledWith(
'Error: Specific message. Details: More details'
);
```
6. Consider implementing a simpler test that *only* verifies the mock behavior in isolation.
2025-03-24 19:44:24 -04:00
feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
## Mocking Guidelines
- **File System Operations**
```javascript
import mockFs from 'mock-fs';
beforeEach(() => {
mockFs({
'tasks': {
'tasks.json': JSON.stringify({
meta: { projectName: 'Test Project' },
tasks: []
})
}
});
});
afterEach(() => {
mockFs.restore();
});
```
- **API Calls (Anthropic/Claude)**
```javascript
import { Anthropic } from '@anthropic-ai/sdk';
jest.mock('@anthropic-ai/sdk');
beforeEach(() => {
Anthropic.mockImplementation(() => ({
messages: {
create: jest.fn().mockResolvedValue({
content: [{ text: 'Mocked response' }]
})
}
}));
});
```
- **Environment Variables**
```javascript
const originalEnv = process.env;
beforeEach(() => {
jest.resetModules();
process.env = { ...originalEnv };
process.env.MODEL = 'test-model';
});
afterEach(() => {
process.env = originalEnv;
});
```
## Testing Common Components
- **CLI Commands**
feat(mcp): Refactor MCP tools for direct function calls & add docs
This commit introduces a major refactoring of the MCP server implementation to prioritize direct function calls over CLI execution, enhancing performance and reliability. It also includes substantial updates to documentation for consistency and interlinking.
**MCP Server & Core Logic Refactoring:**
1. **Introduce Direct Function Wrappers ():**
* Created to house direct wrappers for core Task Master functions (imported from ).
* Implemented as the first wrapper, calling .
* Added utility within to centralize file location logic, removing duplication.
* Established the map for registering these wrappers.
2. **Enhance MCP Utilities ():**
* Added : A primary utility function to streamline MCP tool methods. It handles logging, argument processing (incl. project root normalization), calling the direct action function (e.g., ), processing results via , and formatting the final MCP response.
* Added : Standardizes processing of objects returned by direct function wrappers.
* Added : Filters sensitive/large fields (like , ) from responses sent to the MCP client.
* Added , , to support the new workflow.
* Refactored to use internally, simplifying its usage (though it's now primarily a fallback).
3. **Update MCP Tools (, ):**
* Refactored to use with , significantly simplifying the tool's method.
* Updated (initially) to use the improved (Note: further refactoring to use a direct wrapper for would follow the pattern).
**Documentation Enhancements:**
4. **Comprehensive Interlinking:** Added links across rule files (, , , , , ) to connect related guidelines, improving navigation.
5. **Standardize CLI Syntax ():** Removed legacy ℹ️ Initialized Perplexity client with OpenAI compatibility layer examples, reinforcing ℹ️ Initialized Perplexity client with OpenAI compatibility layer
_____ _ __ __ _
|_ _|_ _ ___| | __ | \/ | __ _ ___| |_ ___ _ __
| |/ _` / __| |/ / | |\/| |/ _` / __| __/ _ \ '__|
| | (_| \__ \ < | | | | (_| \__ \ || __/ |
|_|\__,_|___/_|\_\ |_| |_|\__,_|___/\__\___|_|
by https://x.com/eyaltoledano
╭────────────────────────────────────────────╮
│ │
│ Version: 0.9.30 Project: Task Master │
│ │
╰────────────────────────────────────────────╯
╭─────────────────────╮
│ │
│ Task Master CLI │
│ │
╰─────────────────────╯
╭───────────────────╮
│ Task Generation │
╰───────────────────╯
parse-prd --input=<file.txt> [--tasks=10] Generate tasks from a PRD document
generate Create individual task files from tasks…
╭───────────────────╮
│ Task Management │
╰───────────────────╯
list [--status=<status>] [--with-subtas… List all tasks with their status
set-status --id=<id> --status=<status> Update task status (done, pending, etc.)
update --from=<id> --prompt="<context>" Update tasks based on new requirements
add-task --prompt="<text>" [--dependencies=… Add a new task using AI
add-dependency --id=<id> --depends-on=<id> Add a dependency to a task
remove-dependency --id=<id> --depends-on=<id> Remove a dependency from a task
╭──────────────────────────╮
│ Task Analysis & Detail │
╰──────────────────────────╯
analyze-complexity [--research] [--threshold=5] Analyze tasks and generate expansion re…
complexity-report [--file=<path>] Display the complexity analysis report
expand --id=<id> [--num=5] [--research] [… Break down tasks into detailed subtasks
expand --all [--force] [--research] Expand all pending tasks with subtasks
clear-subtasks --id=<id> Remove subtasks from specified tasks
╭─────────────────────────────╮
│ Task Navigation & Viewing │
╰─────────────────────────────╯
next Show the next task to work on based on …
show <id> Display detailed information about a sp…
╭─────────────────────────╮
│ Dependency Management │
╰─────────────────────────╯
validate-dependenci… Identify invalid dependencies without f…
fix-dependencies Fix invalid dependencies automatically
╭─────────────────────────╮
│ Environment Variables │
╰─────────────────────────╯
ANTHROPIC_API_KEY Your Anthropic API key Required
MODEL Claude model to use Default: claude-3-7-sonn…
MAX_TOKENS Maximum tokens for responses Default: 4000
TEMPERATURE Temperature for model responses Default: 0.7
PERPLEXITY_API_KEY Perplexity API key for research Optional
PERPLEXITY_MODEL Perplexity model to use Default: sonar-pro
DEBUG Enable debug logging Default: false
LOG_LEVEL Console output level (debug,info,warn,error) Default: info
DEFAULT_SUBTASKS Default number of subtasks to generate Default: 3
DEFAULT_PRIORITY Default task priority Default: medium
PROJECT_NAME Project name displayed in UI Default: Task Master
_____ _ __ __ _
|_ _|_ _ ___| | __ | \/ | __ _ ___| |_ ___ _ __
| |/ _` / __| |/ / | |\/| |/ _` / __| __/ _ \ '__|
| | (_| \__ \ < | | | | (_| \__ \ || __/ |
|_|\__,_|___/_|\_\ |_| |_|\__,_|___/\__\___|_|
by https://x.com/eyaltoledano
╭────────────────────────────────────────────╮
│ │
│ Version: 0.9.30 Project: Task Master │
│ │
╰────────────────────────────────────────────╯
╭─────────────────────╮
│ │
│ Task Master CLI │
│ │
╰─────────────────────╯
╭───────────────────╮
│ Task Generation │
╰───────────────────╯
parse-prd --input=<file.txt> [--tasks=10] Generate tasks from a PRD document
generate Create individual task files from tasks…
╭───────────────────╮
│ Task Management │
╰───────────────────╯
list [--status=<status>] [--with-subtas… List all tasks with their status
set-status --id=<id> --status=<status> Update task status (done, pending, etc.)
update --from=<id> --prompt="<context>" Update tasks based on new requirements
add-task --prompt="<text>" [--dependencies=… Add a new task using AI
add-dependency --id=<id> --depends-on=<id> Add a dependency to a task
remove-dependency --id=<id> --depends-on=<id> Remove a dependency from a task
╭──────────────────────────╮
│ Task Analysis & Detail │
╰──────────────────────────╯
analyze-complexity [--research] [--threshold=5] Analyze tasks and generate expansion re…
complexity-report [--file=<path>] Display the complexity analysis report
expand --id=<id> [--num=5] [--research] [… Break down tasks into detailed subtasks
expand --all [--force] [--research] Expand all pending tasks with subtasks
clear-subtasks --id=<id> Remove subtasks from specified tasks
╭─────────────────────────────╮
│ Task Navigation & Viewing │
╰─────────────────────────────╯
next Show the next task to work on based on …
show <id> Display detailed information about a sp…
╭─────────────────────────╮
│ Dependency Management │
╰─────────────────────────╯
validate-dependenci… Identify invalid dependencies without f…
fix-dependencies Fix invalid dependencies automatically
╭─────────────────────────╮
│ Environment Variables │
╰─────────────────────────╯
ANTHROPIC_API_KEY Your Anthropic API key Required
MODEL Claude model to use Default: claude-3-7-sonn…
MAX_TOKENS Maximum tokens for responses Default: 4000
TEMPERATURE Temperature for model responses Default: 0.7
PERPLEXITY_API_KEY Perplexity API key for research Optional
PERPLEXITY_MODEL Perplexity model to use Default: sonar-pro
DEBUG Enable debug logging Default: false
LOG_LEVEL Console output level (debug,info,warn,error) Default: info
DEFAULT_SUBTASKS Default number of subtasks to generate Default: 3
DEFAULT_PRIORITY Default task priority Default: medium
PROJECT_NAME Project name displayed in UI Default: Task Master as the primary CLI.
6. **Add MCP Architecture & Workflow Sections:** Added detailed sections in and explaining MCP server structure and the workflow for adding new MCP tool integrations using the direct function pattern.
7. **Clarify MCP Role:** Updated and to better explain the MCP server's role and its specific utilities.
Overall, this establishes a cleaner, more performant, and maintainable pattern for integrating Task Master functionality with the MCP server, supported by improved documentation.
2025-03-30 00:29:12 -04:00
- Mock the action handlers (defined in [`commands.js`](mdc:scripts/modules/commands.js)) and verify they're called with correct arguments
feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
- Test command registration and option parsing
- Use `commander` test utilities or custom mocks
- **Task Operations**
- Use sample task fixtures for consistent test data
- Mock file system operations
- Test both success and error paths
- **UI Functions**
- Mock console output and verify correct formatting
- Test conditional output logic
- When testing strings with emojis or formatting, use `toContain()` or `toMatch()` rather than exact `toBe()` comparisons
feat: Add skipped tests for task-manager and utils modules, and address potential issues
This commit introduces a comprehensive set of skipped tests to both and . These skipped tests serve as a blueprint for future test implementation, outlining the necessary test cases for currently untested functionalities.
- Ensures sync with bin/ folder by adding -r/--research to the command
- Fixes an issue that improperly parsed command line args
- Ensures confirmation card on dependency add/remove
- Properly formats some sub-task dependencies
**Potentially addressed issues:**
While primarily focused on adding test coverage, this commit also implicitly addresses potential issues by:
- **Improving error handling coverage:** The addition of skipped tests for error scenarios in functions like , , , and highlights areas where error handling needs to be robustly tested and potentially improved in the codebase.
- **Enhancing dependency validation:** Skipped tests for include validation of dependencies, prompting a review of the dependency validation logic and ensuring its correctness.
- **Standardizing test coverage:** By creating a clear roadmap for testing all functions, this commit contributes to a more standardized and complete test suite, reducing the likelihood of undiscovered bugs in the future.
**task-manager.test.js:**
- Added skipped test blocks for the following functions:
- : Includes tests for handling valid JSON responses, malformed JSON, missing tasks in responses, Perplexity AI research integration, Claude fallback, and parallel task processing.
- : Covers tests for updating tasks based on context, handling Claude streaming, Perplexity AI integration, scenarios with no tasks to update, and error handling during updates.
- : Includes tests for generating task files from , formatting dependencies with status indicators, handling tasks without subtasks, empty task arrays, and dependency validation before file generation.
- : Covers tests for updating task status, subtask status using dot notation, updating multiple tasks, automatic subtask status updates, parent task update suggestions, and handling non-existent task IDs.
- : Includes tests for updating regular and subtask statuses, handling parent tasks without subtasks, and non-existent subtask IDs.
- : Covers tests for displaying all tasks, filtering by status, displaying subtasks, showing completion statistics, identifying the next task, and handling empty task arrays.
- : Includes tests for generating subtasks, using complexity reports for subtask counts, Perplexity AI integration, appending subtasks, skipping completed tasks, and error handling during subtask generation.
- : Covers tests for expanding all pending tasks, sorting by complexity, skipping tasks with existing subtasks (unless forced), using task-specific parameters from complexity reports, handling empty task arrays, and error handling for individual tasks.
- : Includes tests for clearing subtasks from specific and multiple tasks, handling tasks without subtasks, non-existent task IDs, and regenerating task files after clearing subtasks.
- : Covers tests for adding new tasks using AI, handling Claude streaming, validating dependencies, handling malformed AI responses, and using existing task context for generation.
**utils.test.js:**
- Added skipped test blocks for the following functions:
- : Tests for logging messages according to log levels and filtering messages below configured levels.
- : Tests for reading and parsing valid JSON files, handling file not found errors, and invalid JSON formats.
- : Tests for writing JSON data to files and handling file write errors.
- : Tests for escaping double quotes in prompts and handling prompts without special characters.
- : Tests for reading and parsing complexity reports, handling missing report files, and custom report paths.
- : Tests for finding tasks in reports by ID, handling non-existent task IDs, and invalid report structures.
- : Tests for verifying existing task and subtask IDs, handling non-existent IDs, and invalid inputs.
- : Tests for formatting numeric and string task IDs and preserving dot notation for subtasks.
- : Tests for detecting simple and complex cycles in dependency graphs, handling acyclic graphs, and empty dependency maps.
These skipped tests provide a clear roadmap for future test development, ensuring comprehensive coverage for core functionalities in both modules. They document the intended behavior of each function and outline various scenarios, including happy paths, edge cases, and error conditions, thereby improving the overall test strategy and maintainability of the Task Master CLI.
2025-03-24 18:54:35 -04:00
- For functions with different behavior modes (e.g., `forConsole`, `forTable` parameters), create separate tests for each mode
- Test the structure of formatted output (e.g., check that it's a comma-separated list with the right number of items) rather than exact string matching
- When testing chalk-formatted output, remember that strict equality comparison (`toBe()`) can fail even when the visible output looks identical
- Consider using more flexible assertions like checking for the presence of key elements when working with styled text
- Mock chalk functions to return the input text to make testing easier while still verifying correct function calls
feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
## Test Quality Guidelines
- ✅ **DO**: Write tests before implementing features (TDD approach when possible)
- ✅ **DO**: Test edge cases and error conditions, not just happy paths
- ✅ **DO**: Keep tests independent and isolated from each other
- ✅ **DO**: Use descriptive test names that explain the expected behavior
- ✅ **DO**: Maintain test fixtures separate from test logic
- ✅ **DO**: Aim for 80%+ code coverage, with critical paths at 100%
- ✅ **DO**: Follow the mock-first-then-import pattern for all Jest mocks
- ❌ **DON'T**: Test implementation details that might change
- ❌ **DON'T**: Write brittle tests that depend on specific output formatting
- ❌ **DON'T**: Skip testing error handling and validation
- ❌ **DON'T**: Duplicate test fixtures across multiple test files
- ❌ **DON'T**: Write tests that depend on execution order
- ❌ **DON'T**: Define mock variables before `jest.mock()` calls (they won't be accessible due to hoisting)
2025-03-25 16:56:48 -04:00
- **Task File Operations**
- ✅ DO: Use test-specific file paths (e.g., 'test-tasks.json') for all operations
- ✅ DO: Mock `readJSON` and `writeJSON` to avoid real file system interactions
- ✅ DO: Verify file operations use the correct paths in `expect` statements
- ✅ DO: Use different paths for each test to avoid test interdependence
- ✅ DO: Verify modifications on the in-memory task objects passed to `writeJSON`
- ❌ DON'T: Modify real task files (tasks.json) during tests
- ❌ DON'T: Skip testing file operations because they're "just I/O"
```javascript
// ✅ DO: Test file operations without real file system changes
test('should update task status in tasks.json', async () => {
// Setup mock to return sample data
readJSON.mockResolvedValue(JSON.parse(JSON.stringify(sampleTasks)));
// Use test-specific file path
await setTaskStatus('test-tasks.json', '2', 'done');
// Verify correct file path was read
expect(readJSON).toHaveBeenCalledWith('test-tasks.json');
// Verify correct file path was written with updated content
expect(writeJSON).toHaveBeenCalledWith(
'test-tasks.json',
expect.objectContaining({
tasks: expect.arrayContaining([
expect.objectContaining({
id: 2,
status: 'done'
})
])
})
);
});
```
feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
## Running Tests
```bash
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage reporting
npm run test:coverage
# Run a specific test file
npm test -- tests/unit/specific-file.test.js
# Run tests matching a pattern
npm test -- -t "pattern to match"
```
## Troubleshooting Test Issues
- **Mock Functions Not Called**
- Ensure mocks are defined before imports (Jest hoists `jest.mock()` calls)
- Check that you're referencing the correct mock instance
- Verify the import paths match exactly
- **Unexpected Mock Behavior**
- Clear mocks between tests with `jest.clearAllMocks()` in `beforeEach`
- Check mock implementation for conditional behavior
- Ensure mock return values are correctly configured for each test
- **Tests Affecting Each Other**
- Isolate tests by properly mocking shared resources
- Reset state in `beforeEach` and `afterEach` hooks
- Avoid global state modifications
2025-03-26 15:07:31 -04:00
## Common Testing Pitfalls and Solutions
- **Complex Library Mocking**
- **Problem**: Trying to create full mocks of complex libraries like Commander.js can be error-prone
- **Solution**: Instead of mocking the entire library, test the command handlers directly by calling your action handlers with the expected arguments
```javascript
// ❌ DON'T: Create complex mocks of Commander.js
class MockCommand {
constructor() { /* Complex mock implementation */ }
option() { /* ... */ }
action() { /* ... */ }
// Many methods to implement
}
// ✅ DO: Test the command handlers directly
test('should use default PRD path when no arguments provided', async () => {
// Call the action handler directly with the right params
await parsePrdAction(undefined, { numTasks: '10', output: 'tasks/tasks.json' });
// Assert on behavior
expect(mockParsePRD).toHaveBeenCalledWith('scripts/prd.txt', 'tasks/tasks.json', 10);
});
```
- **ES Module Mocking Challenges**
- **Problem**: ES modules don't support `require()` and imports are read-only
- **Solution**: Use Jest's module factory pattern and ensure mocks are defined before imports
```javascript
// ❌ DON'T: Try to modify imported modules
import { detectCamelCaseFlags } from '../../scripts/modules/utils.js';
detectCamelCaseFlags = jest.fn(); // Error: Assignment to constant variable
// ❌ DON'T: Try to use require with ES modules
const utils = require('../../scripts/modules/utils.js'); // Error in ES modules
// ✅ DO: Use Jest module factory pattern
jest.mock('../../scripts/modules/utils.js', () => ({
detectCamelCaseFlags: jest.fn(),
toKebabCase: jest.fn()
}));
// Import after mocks are defined
import { detectCamelCaseFlags } from '../../scripts/modules/utils.js';
```
- **Function Redeclaration Errors**
- **Problem**: Declaring the same function twice in a test file causes errors
- **Solution**: Use different function names or create local test-specific implementations
```javascript
// ❌ DON'T: Redefine imported functions with the same name
import { detectCamelCaseFlags } from '../../scripts/modules/utils.js';
function detectCamelCaseFlags() { /* Test implementation */ }
// Error: Identifier has already been declared
// ✅ DO: Use a different name for test implementations
function testDetectCamelCaseFlags() { /* Test implementation */ }
```
- **Console.log Circular References**
- **Problem**: Creating infinite recursion by spying on console.log while also allowing it to log
- **Solution**: Implement a mock that doesn't call the original function
```javascript
// ❌ DON'T: Create circular references with console.log
const mockConsoleLog = jest.spyOn(console, 'log');
mockConsoleLog.mockImplementation(console.log); // Creates infinite recursion
// ✅ DO: Use a non-recursive mock implementation
const mockConsoleLog = jest.spyOn(console, 'log').mockImplementation(() => {});
```
- **Mock Function Method Issues**
- **Problem**: Trying to use jest.fn() methods on imported functions that aren't properly mocked
- **Solution**: Create explicit jest.fn() mocks for functions you need to call jest methods on
```javascript
// ❌ DON'T: Try to use jest methods on imported functions without proper mocking
import { parsePRD } from '../../scripts/modules/task-manager.js';
parsePRD.mockClear(); // Error: parsePRD.mockClear is not a function
// ✅ DO: Create proper jest.fn() mocks
const mockParsePRD = jest.fn().mockResolvedValue(undefined);
jest.mock('../../scripts/modules/task-manager.js', () => ({
parsePRD: mockParsePRD
}));
// Now you can use:
mockParsePRD.mockClear();
```
- **EventEmitter Max Listeners Warning**
- **Problem**: Commander.js adds many listeners in complex mocks, causing warnings
- **Solution**: Either increase the max listeners limit or avoid deep mocking
```javascript
// Option 1: Increase max listeners if you must mock Commander
class MockCommand extends EventEmitter {
constructor() {
super();
this.setMaxListeners(20); // Avoid MaxListenersExceededWarning
}
}
// Option 2 (preferred): Test command handlers directly instead
// (as shown in the first example)
```
- **Test Isolation Issues**
- **Problem**: Tests affecting each other due to shared mock state
- **Solution**: Reset all mocks in beforeEach and use separate test-specific mocks
```javascript
// ❌ DON'T: Allow mock state to persist between tests
const globalMock = jest.fn().mockReturnValue('test');
// ✅ DO: Clear mocks before each test
beforeEach(() => {
jest.clearAllMocks();
// Set up test-specific mock behavior
mockFunction.mockReturnValue('test-specific value');
});
```
2025-04-09 16:29:24 -04:00
## Testing AI Service Integrations
- **DO NOT import real AI service clients**
- ❌ DON'T: Import actual AI clients from their libraries
- ✅ DO: Create fully mocked versions that return predictable responses
2025-03-25 17:20:09 -04:00
```javascript
2025-04-09 16:29:24 -04:00
// ❌ DON'T: Import and instantiate real AI clients
import { Anthropic } from '@anthropic-ai/sdk';
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
// ✅ DO: Mock the entire module with controlled behavior
jest.mock('@anthropic-ai/sdk', () => ({
Anthropic: jest.fn().mockImplementation(() => ({
messages: {
create: jest.fn().mockResolvedValue({
2025-04-09 18:18:13 -04:00
content: [{ type: 'text', text: 'Mocked AI response' }]
2025-04-09 16:29:24 -04:00
})
}
}))
}));
2025-03-25 17:20:09 -04:00
```
2025-04-09 16:29:24 -04:00
- **DO NOT rely on environment variables for API keys**
- ❌ DON'T: Assume environment variables are set in tests
- ✅ DO: Set mock environment variables in test setup
2025-03-25 17:20:09 -04:00
```javascript
2025-04-09 16:29:24 -04:00
// In tests/setup.js or at the top of test file
process.env.ANTHROPIC_API_KEY = 'test-mock-api-key-for-tests';
process.env.PERPLEXITY_API_KEY = 'test-mock-perplexity-key-for-tests';
2025-03-25 17:20:09 -04:00
```
2025-04-09 16:29:24 -04:00
- **DO NOT use real AI client initialization logic**
- ❌ DON'T: Use code that attempts to initialize or validate real AI clients
- ✅ DO: Create test-specific paths that bypass client initialization
2025-03-25 17:20:09 -04:00
```javascript
2025-04-09 16:29:24 -04:00
// ❌ DON'T: Test functions that require valid AI client initialization
// This will fail without proper API keys or network access
test('should use AI client', async () => {
const result = await functionThatInitializesAIClient();
expect(result).toBeDefined();
});
// ✅ DO: Test with bypassed initialization or manual task paths
test('should handle manual task creation without AI', () => {
// Using a path that doesn't require AI client initialization
const result = addTaskDirect({
title: 'Manual Task',
description: 'Test Description'
}, mockLogger);
expect(result.success).toBe(true);
2025-03-25 17:20:09 -04:00
});
```
2025-04-09 16:29:24 -04:00
## Testing Asynchronous Code
- **DO NOT rely on asynchronous operations in tests**
- ❌ DON'T: Use real async/await or Promise resolution in tests
- ✅ DO: Make all mocks return synchronous values when possible
2025-03-25 17:20:09 -04:00
```javascript
2025-04-09 16:29:24 -04:00
// ❌ DON'T: Use real async functions that might fail unpredictably
test('should handle async operation', async () => {
const result = await realAsyncFunction(); // Can time out or fail for external reasons
expect(result).toBe(expectedValue);
2025-03-25 17:20:09 -04:00
});
2025-04-09 16:29:24 -04:00
// ✅ DO: Make async operations synchronous in tests
test('should handle operation', () => {
mockAsyncFunction.mockReturnValue({ success: true, data: 'test' });
const result = functionUnderTest();
expect(result).toEqual({ success: true, data: 'test' });
2025-03-25 17:20:09 -04:00
});
2025-04-09 16:29:24 -04:00
```
- **DO NOT test exact error messages**
- ❌ DON'T: Assert on exact error message text that might change
- ✅ DO: Test for error presence and general properties
```javascript
// ❌ DON'T: Test for exact error message text
expect(result.error).toBe('Could not connect to API: Network error');
// ✅ DO: Test for general error properties or message patterns
expect(result.success).toBe(false);
expect(result.error).toContain('Could not connect');
// Or even better:
expect(result).toMatchObject({
success: false,
error: expect.stringContaining('connect')
2025-03-25 17:20:09 -04:00
});
```
2025-04-09 16:29:24 -04:00
## Reliable Testing Techniques
- **Create Simplified Test Functions**
- Create simplified versions of complex functions that focus only on core logic
- Remove file system operations, API calls, and other external dependencies
- Pass all dependencies as parameters to make testing easier
2025-03-25 17:20:09 -04:00
```javascript
2025-04-09 16:29:24 -04:00
// Original function (hard to test)
const setTaskStatus = async (taskId, newStatus) => {
const tasksPath = 'tasks/tasks.json';
const data = await readJSON(tasksPath);
// [implementation]
await writeJSON(tasksPath, data);
return { success: true };
};
// Test-friendly version (easier to test)
const updateTaskStatus = (tasks, taskId, newStatus) => {
// Pure logic without side effects
const updatedTasks = [...tasks];
const taskIndex = findTaskById(updatedTasks, taskId);
if (taskIndex === -1) return { success: false, error: 'Task not found' };
updatedTasks[taskIndex].status = newStatus;
return { success: true, tasks: updatedTasks };
};
2025-03-25 17:20:09 -04:00
```
feat: Enhance Task Master CLI with Testing Framework, Perplexity AI Integration, and Refactored Core Logic
This commit introduces significant enhancements and refactoring to the Task Master CLI, focusing on improved testing, integration with Perplexity AI for research-backed task updates, and core logic refactoring for better maintainability and functionality.
**Testing Infrastructure Setup:**
- Implemented Jest as the primary testing framework, setting up a comprehensive testing environment.
- Added new test scripts to including , , and for streamlined testing workflows.
- Integrated necessary devDependencies for testing, such as , , , , and , to support unit, integration, and end-to-end testing.
**Dependency Updates:**
- Updated and to reflect the latest dependency versions, ensuring project stability and access to the newest features and security patches.
- Upgraded to version 0.9.16 and usage: openai [-h] [-v] [-b API_BASE] [-k API_KEY] [-p PROXY [PROXY ...]]
[-o ORGANIZATION] [-t {openai,azure}]
[--api-version API_VERSION] [--azure-endpoint AZURE_ENDPOINT]
[--azure-ad-token AZURE_AD_TOKEN] [-V]
{api,tools,migrate,grit} ...
positional arguments:
{api,tools,migrate,grit}
api Direct API calls
tools Client side tools for convenience
options:
-h, --help show this help message and exit
-v, --verbose Set verbosity.
-b, --api-base API_BASE
What API base url to use.
-k, --api-key API_KEY
What API key to use.
-p, --proxy PROXY [PROXY ...]
What proxy to use.
-o, --organization ORGANIZATION
Which organization to run as (will use your default
organization if not specified)
-t, --api-type {openai,azure}
The backend API to call, must be `openai` or `azure`
--api-version API_VERSION
The Azure API version, e.g.
'https://learn.microsoft.com/en-us/azure/ai-
services/openai/reference#rest-api-versioning'
--azure-endpoint AZURE_ENDPOINT
The Azure endpoint, e.g.
'https://endpoint.openai.azure.com'
--azure-ad-token AZURE_AD_TOKEN
A token from Azure Active Directory,
https://www.microsoft.com/en-
us/security/business/identity-access/microsoft-entra-
id
-V, --version show program's version number and exit to 4.89.0.
- Added dependency (version 2.3.0) and updated related dependencies to their latest versions.
**Perplexity AI Integration for Research-Backed Updates:**
- Introduced an option to leverage Perplexity AI for task updates, enabling research-backed enhancements to task details.
- Implemented logic to initialize a Perplexity AI client if the environment variable is available.
- Modified the function to accept a parameter, allowing dynamic selection between Perplexity AI and Claude AI for task updates based on API key availability and user preference.
- Enhanced to handle responses from Perplexity AI and update tasks accordingly, including improved error handling and logging for robust operation.
**Core Logic Refactoring and Improvements:**
- Refactored the function to utilize task IDs instead of dependency IDs, ensuring consistency and clarity in dependency management.
- Implemented a new function to rigorously check for both circular dependencies and self-dependencies within tasks, improving task relationship integrity.
- Enhanced UI elements in :
- Refactored to incorporate icons for different task statuses and utilize a object for color mapping, improving visual representation of task status.
- Updated to display colored complexity scores with emojis, providing a more intuitive and visually appealing representation of task complexity.
- Refactored the task data structure creation and validation process:
- Updated the JSON Schema for to reflect a more streamlined and efficient task structure.
- Implemented Task Model Classes for better data modeling and type safety.
- Improved File System Operations for task data management.
- Developed robust Validation Functions and an Error Handling System to ensure data integrity and application stability.
**Testing Guidelines Implementation:**
- Implemented guidelines for writing testable code when developing new features, promoting a test-driven development approach.
- Added testing requirements and best practices for unit, integration, and edge case testing to ensure comprehensive test coverage.
- Updated the development workflow to mandate writing tests before proceeding with configuration and documentation updates, reinforcing the importance of testing throughout the development lifecycle.
This commit collectively enhances the Task Master CLI's reliability, functionality, and developer experience through improved testing practices, AI-powered research capabilities, and a more robust and maintainable codebase.
2025-03-24 13:28:08 -04:00
See [tests/README.md](mdc:tests/README.md) for more details on the testing approach.
2025-04-09 18:18:13 -04:00
Refer to [jest.config.js](mdc:jest.config.js) for Jest configuration options.
## Variable Hoisting and Module Initialization Issues
When testing ES modules or working with complex module imports, you may encounter variable hoisting and initialization issues. These can be particularly tricky to debug and often appear as "Cannot access 'X' before initialization" errors.
- **Understanding Module Initialization Order**
- ✅ **DO**: Declare and initialize global variables at the top of modules
- ✅ **DO**: Use proper function declarations to avoid hoisting issues
- ✅ **DO**: Initialize variables before they are referenced, especially in imported modules
- ✅ **DO**: Be aware that imports are hoisted to the top of the file
```javascript
// ✅ DO: Define global state variables at the top of the module
let silentMode = false; // Declare and initialize first
const CONFIG = { /* configuration */ };
function isSilentMode() {
return silentMode; // Reference variable after it's initialized
}
function log(level, message) {
if (isSilentMode()) return; // Use the function instead of accessing variable directly
// ...
}
```
- **Testing Modules with Initialization-Dependent Functions**
- ✅ **DO**: Create test-specific implementations that initialize all variables correctly
- ✅ **DO**: Use factory functions in mocks to ensure proper initialization order
- ✅ **DO**: Be careful with how you mock or stub functions that depend on module state
```javascript
// ✅ DO: Test-specific implementation that avoids initialization issues
const testLog = (level, ...args) => {
// Local implementation with proper initialization
const isSilent = false; // Explicit initialization
if (isSilent) return;
// Test implementation...
};
```
- **Common Hoisting-Related Errors to Avoid**
- ❌ **DON'T**: Reference variables before their declaration in module scope
- ❌ **DON'T**: Create circular dependencies between modules
- ❌ **DON'T**: Rely on variable initialization order across module boundaries
- ❌ **DON'T**: Define functions that use hoisted variables before they're initialized
```javascript
// ❌ DON'T: Create reference-before-initialization patterns
function badFunction() {
if (silentMode) { /* ... */ } // ReferenceError if silentMode is declared later
}
let silentMode = false;
// ❌ DON'T: Create cross-module references that depend on initialization order
// module-a.js
import { getSetting } from './module-b.js';
export const config = { value: getSetting() };
// module-b.js
import { config } from './module-a.js';
export function getSetting() {
return config.value; // Circular dependency causing initialization issues
}
```
- **Dynamic Imports as a Solution**
- ✅ **DO**: Use dynamic imports (`import()`) to avoid initialization order issues
- ✅ **DO**: Structure modules to avoid circular dependencies that cause initialization issues
- ✅ **DO**: Consider factory functions for modules with complex state
```javascript
// ✅ DO: Use dynamic imports to avoid initialization issues
async function getTaskManager() {
return import('./task-manager.js');
}
async function someFunction() {
const taskManager = await getTaskManager();
return taskManager.someMethod();
}
```
- **Testing Approach for Modules with Initialization Issues**
- ✅ **DO**: Create self-contained test implementations rather than using real implementations
- ✅ **DO**: Mock dependencies at module boundaries instead of trying to mock deep dependencies
- ✅ **DO**: Isolate module-specific state in tests
```javascript
// ✅ DO: Create isolated test implementation instead of reusing module code
test('should log messages when not in silent mode', () => {
// Local test implementation instead of importing from module
const testLog = (level, message) => {
if (false) return; // Always non-silent for this test
mockConsole(level, message);
};
testLog('info', 'test message');
expect(mockConsole).toHaveBeenCalledWith('info', 'test message');
});
```