Refactor: Modularize Task Master CLI into Modules Directory

Simplified the Task Master CLI by organizing code into modules within the  directory.

**Why:**

- **Better Organization:** Code is now grouped by function (AI, commands, dependencies, tasks, UI, utilities).
- **Easier to Maintain:**  Smaller modules are simpler to update and fix.
- **Scalable:**  New features can be added more easily in a structured way.

**What Changed:**

- Moved code from single   _____         _      __  __           _
 |_   _|_ _ ___| | __ |  \/  | __ _ ___| |_ ___ _ __
   | |/ _` / __| |/ / | |\/| |/ _` / __| __/ _ \ '__|
   | | (_| \__ \   <  | |  | | (_| \__ \ ||  __/ |
   |_|\__,_|___/_|\_\ |_|  |_|\__,_|___/\__\___|_|

by https://x.com/eyaltoledano
╭────────────────────────────────────────────╮
│                                            │
│   Version: 0.9.16   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-small-onl…
    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       file into these new modules:
    - : AI interactions (Claude, Perplexity)
    - :  CLI command definitions (Commander.js)
    - : Task dependency handling
    - : Core task operations (create, list, update, etc.)
    - : User interface elements (display, formatting)
    - : Utility functions and configuration
    - :  Exports all modules
- Replaced direct use of   _____         _      __  __           _
 |_   _|_ _ ___| | __ |  \/  | __ _ ___| |_ ___ _ __
   | |/ _` / __| |/ / | |\/| |/ _` / __| __/ _ \ '__|
   | | (_| \__ \   <  | |  | | (_| \__ \ ||  __/ |
   |_|\__,_|___/_|\_\ |_|  |_|\__,_|___/\__\___|_|

by https://x.com/eyaltoledano
╭────────────────────────────────────────────╮
│                                            │
│   Version: 0.9.16   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-small-onl…
    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       with the global  command (see ).
- Updated documentation () to reflect the new  command.

**Benefits:**

Code is now cleaner, easier to work with, and ready for future growth.

Use the  command (or ) to run the CLI.  See  for command details.
This commit is contained in:
Eyal Toledano
2025-03-23 23:19:37 -04:00
parent 70d307a711
commit 204e318190
41 changed files with 7942 additions and 6725 deletions

163
.cursor/rules/commands.mdc Normal file
View File

@@ -0,0 +1,163 @@
---
description: Guidelines for implementing CLI commands using Commander.js
globs: scripts/modules/commands.js
alwaysApply: false
---
# Command-Line Interface Implementation Guidelines
## Command Structure Standards
- **Basic Command Template**:
```javascript
// ✅ DO: Follow this structure for all commands
programInstance
.command('command-name')
.description('Clear, concise description of what the command does')
.option('-s, --short-option <value>', 'Option description', 'default value')
.option('--long-option <value>', 'Option description')
.action(async (options) => {
// Command implementation
});
```
- **Command Handler Organization**:
- ✅ DO: Keep action handlers concise and focused
- ✅ DO: Extract core functionality to appropriate modules
- ✅ DO: Include validation for required parameters
- ❌ DON'T: Implement business logic in command handlers
## Option Naming Conventions
- **Command Names**:
- ✅ DO: Use kebab-case for command names (`analyze-complexity`)
- ❌ DON'T: Use camelCase for command names (`analyzeComplexity`)
- ✅ DO: Use descriptive, action-oriented names
- **Option Names**:
- ✅ DO: Use camelCase for long-form option names (`--outputFormat`)
- ✅ DO: Provide single-letter shortcuts when appropriate (`-f, --file`)
- ✅ DO: Use consistent option names across similar commands
- ❌ DON'T: Use different names for the same concept (`--file` in one command, `--path` in another)
```javascript
// ✅ DO: Use consistent option naming
.option('-f, --file <path>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-o, --output <dir>', 'Output directory', 'tasks')
// ❌ DON'T: Use inconsistent naming
.option('-f, --file <path>', 'Path to the tasks file')
.option('-p, --path <dir>', 'Output directory') // Should be --output
```
## Input Validation
- **Required Parameters**:
- ✅ DO: Check that required parameters are provided
- ✅ DO: Provide clear error messages when parameters are missing
- ✅ DO: Use early returns with process.exit(1) for validation failures
```javascript
// ✅ DO: Validate required parameters early
if (!prompt) {
console.error(chalk.red('Error: --prompt parameter is required. Please provide a task description.'));
process.exit(1);
}
```
- **Parameter Type Conversion**:
- ✅ DO: Convert string inputs to appropriate types (numbers, booleans)
- ✅ DO: Handle conversion errors gracefully
```javascript
// ✅ DO: Parse numeric parameters properly
const fromId = parseInt(options.from, 10);
if (isNaN(fromId)) {
console.error(chalk.red('Error: --from must be a valid number'));
process.exit(1);
}
```
## User Feedback
- **Operation Status**:
- ✅ DO: Provide clear feedback about the operation being performed
- ✅ DO: Display success or error messages after completion
- ✅ DO: Use colored output to distinguish between different message types
```javascript
// ✅ DO: Show operation status
console.log(chalk.blue(`Parsing PRD file: ${file}`));
console.log(chalk.blue(`Generating ${numTasks} tasks...`));
try {
await parsePRD(file, outputPath, numTasks);
console.log(chalk.green('Successfully generated tasks from PRD'));
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
process.exit(1);
}
```
## Command Registration
- **Command Grouping**:
- ✅ DO: Group related commands together in the code
- ✅ DO: Add related commands in a logical order
- ✅ DO: Use comments to delineate command groups
- **Command Export**:
- ✅ DO: Export the registerCommands function
- ✅ DO: Keep the CLI setup code clean and maintainable
```javascript
// ✅ DO: Follow this export pattern
export {
registerCommands,
setupCLI,
runCLI
};
```
## Error Handling
- **Exception Management**:
- ✅ DO: Wrap async operations in try/catch blocks
- ✅ DO: Display user-friendly error messages
- ✅ DO: Include detailed error information in debug mode
```javascript
// ✅ DO: Handle errors properly
try {
// Command implementation
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
if (CONFIG.debug) {
console.error(error);
}
process.exit(1);
}
```
## Integration with Other Modules
- **Import Organization**:
- ✅ DO: Group imports by module/functionality
- ✅ DO: Import only what's needed, not entire modules
- ❌ DON'T: Create circular dependencies
```javascript
// ✅ DO: Organize imports by module
import { program } from 'commander';
import path from 'path';
import chalk from 'chalk';
import { CONFIG, log, readJSON } from './utils.js';
import { displayBanner, displayHelp } from './ui.js';
import { parsePRD, listTasks } from './task-manager.js';
import { addDependency } from './dependency-manager.js';
```
Refer to [`commands.js`](mdc:scripts/modules/commands.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.

View File

@@ -0,0 +1,224 @@
---
description: Guidelines for managing task dependencies and relationships
globs: scripts/modules/dependency-manager.js
alwaysApply: false
---
# Dependency Management Guidelines
## Dependency Structure Principles
- **Dependency References**:
- ✅ DO: Represent task dependencies as arrays of task IDs
- ✅ DO: Use numeric IDs for direct task references
- ✅ DO: Use string IDs with dot notation (e.g., "1.2") for subtask references
- ❌ DON'T: Mix reference types without proper conversion
```javascript
// ✅ DO: Use consistent dependency formats
// For main tasks
task.dependencies = [1, 2, 3]; // Dependencies on other main tasks
// For subtasks
subtask.dependencies = [1, "3.2"]; // Dependency on main task 1 and subtask 2 of task 3
```
- **Subtask Dependencies**:
- ✅ DO: Allow numeric subtask IDs to reference other subtasks within the same parent
- ✅ DO: Convert between formats appropriately when needed
- ❌ DON'T: Create circular dependencies between subtasks
```javascript
// ✅ DO: Properly normalize subtask dependencies
// When a subtask refers to another subtask in the same parent
if (typeof depId === 'number' && depId < 100) {
// It's likely a reference to another subtask in the same parent task
const fullSubtaskId = `${parentId}.${depId}`;
// Now use fullSubtaskId for validation
}
```
## Dependency Validation
- **Existence Checking**:
- ✅ DO: Validate that referenced tasks exist before adding dependencies
- ✅ DO: Provide clear error messages for non-existent dependencies
- ✅ DO: Remove references to non-existent tasks during validation
```javascript
// ✅ DO: Check if the dependency exists before adding
if (!taskExists(data.tasks, formattedDependencyId)) {
log('error', `Dependency target ${formattedDependencyId} does not exist in tasks.json`);
process.exit(1);
}
```
- **Circular Dependency Prevention**:
- ✅ DO: Check for circular dependencies before adding new relationships
- ✅ DO: Use graph traversal algorithms (DFS) to detect cycles
- ✅ DO: Provide clear error messages explaining the circular chain
```javascript
// ✅ DO: Check for circular dependencies before adding
const dependencyChain = [formattedTaskId];
if (isCircularDependency(data.tasks, formattedDependencyId, dependencyChain)) {
log('error', `Cannot add dependency ${formattedDependencyId} to task ${formattedTaskId} as it would create a circular dependency.`);
process.exit(1);
}
```
- **Self-Dependency Prevention**:
- ✅ DO: Prevent tasks from depending on themselves
- ✅ DO: Handle both direct and indirect self-dependencies
```javascript
// ✅ DO: Prevent self-dependencies
if (String(formattedTaskId) === String(formattedDependencyId)) {
log('error', `Task ${formattedTaskId} cannot depend on itself.`);
process.exit(1);
}
```
## Dependency Modification
- **Adding Dependencies**:
- ✅ DO: Format task and dependency IDs consistently
- ✅ DO: Check for existing dependencies to prevent duplicates
- ✅ DO: Sort dependencies for better readability
```javascript
// ✅ DO: Format IDs consistently when adding dependencies
const formattedTaskId = typeof taskId === 'string' && taskId.includes('.')
? taskId : parseInt(taskId, 10);
const formattedDependencyId = formatTaskId(dependencyId);
```
- **Removing Dependencies**:
- ✅ DO: Check if the dependency exists before removing
- ✅ DO: Handle different ID formats consistently
- ✅ DO: Provide feedback about the removal result
```javascript
// ✅ DO: Properly handle dependency removal
const dependencyIndex = targetTask.dependencies.findIndex(dep => {
// Convert both to strings for comparison
let depStr = String(dep);
// Handle relative subtask references
if (typeof dep === 'number' && dep < 100 && isSubtask) {
const [parentId] = formattedTaskId.split('.');
depStr = `${parentId}.${dep}`;
}
return depStr === normalizedDependencyId;
});
if (dependencyIndex === -1) {
log('info', `Task ${formattedTaskId} does not depend on ${formattedDependencyId}, no changes made.`);
return;
}
// Remove the dependency
targetTask.dependencies.splice(dependencyIndex, 1);
```
## Dependency Cleanup
- **Duplicate Removal**:
- ✅ DO: Use Set objects to identify and remove duplicates
- ✅ DO: Handle both numeric and string ID formats
```javascript
// ✅ DO: Remove duplicate dependencies
const uniqueDeps = new Set();
const uniqueDependencies = task.dependencies.filter(depId => {
// Convert to string for comparison to handle both numeric and string IDs
const depIdStr = String(depId);
if (uniqueDeps.has(depIdStr)) {
log('warn', `Removing duplicate dependency from task ${task.id}: ${depId}`);
return false;
}
uniqueDeps.add(depIdStr);
return true;
});
```
- **Invalid Reference Cleanup**:
- ✅ DO: Check for and remove references to non-existent tasks
- ✅ DO: Check for and remove self-references
- ✅ DO: Track and report changes made during cleanup
```javascript
// ✅ DO: Filter invalid task dependencies
task.dependencies = task.dependencies.filter(depId => {
const numericId = typeof depId === 'string' ? parseInt(depId, 10) : depId;
if (!validTaskIds.has(numericId)) {
log('warn', `Removing invalid task dependency from task ${task.id}: ${depId} (task does not exist)`);
return false;
}
return true;
});
```
## Dependency Visualization
- **Status Indicators**:
- ✅ DO: Use visual indicators to show dependency status (✅/⏱️)
- ✅ DO: Format dependency lists consistently
```javascript
// ✅ DO: Format dependencies with status indicators
function formatDependenciesWithStatus(dependencies, allTasks) {
if (!dependencies || dependencies.length === 0) {
return 'None';
}
return dependencies.map(depId => {
const depTask = findTaskById(allTasks, depId);
if (!depTask) return `${depId} (Not found)`;
const isDone = depTask.status === 'done' || depTask.status === 'completed';
const statusIcon = isDone ? '✅' : '⏱️';
return `${statusIcon} ${depId} (${depTask.status})`;
}).join(', ');
}
```
## Cycle Detection
- **Graph Traversal**:
- ✅ DO: Use depth-first search (DFS) for cycle detection
- ✅ DO: Track visited nodes and recursion stack
- ✅ DO: Support both task and subtask dependencies
```javascript
// ✅ DO: Use proper cycle detection algorithms
function findCycles(subtaskId, dependencyMap, visited = new Set(), recursionStack = new Set()) {
// Mark the current node as visited and part of recursion stack
visited.add(subtaskId);
recursionStack.add(subtaskId);
const cyclesToBreak = [];
const dependencies = dependencyMap.get(subtaskId) || [];
for (const depId of dependencies) {
if (!visited.has(depId)) {
const cycles = findCycles(depId, dependencyMap, visited, recursionStack);
cyclesToBreak.push(...cycles);
}
else if (recursionStack.has(depId)) {
// Found a cycle, add the edge to break
cyclesToBreak.push(depId);
}
}
// Remove the node from recursion stack before returning
recursionStack.delete(subtaskId);
return cyclesToBreak;
}
```
Refer to [`dependency-manager.js`](mdc:scripts/modules/dependency-manager.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.

View File

@@ -308,3 +308,26 @@ alwaysApply: true
- Prompts for project settings if not provided
- Merges with existing files when appropriate
- Can be used to bootstrap a new Task Master project quickly
- **Code Analysis & Refactoring Techniques**
- **Top-Level Function Search**
- Use grep pattern matching to find all exported functions across the codebase
- Command: `grep -E "export (function|const) \w+|function \w+\(|const \w+ = \(|module\.exports" --include="*.js" -r ./`
- Benefits:
- Quickly identify all public API functions without reading implementation details
- Compare functions between files during refactoring (e.g., monolithic to modular structure)
- Verify all expected functions exist in refactored modules
- Identify duplicate functionality or naming conflicts
- Usage examples:
- When migrating from `scripts/dev.js` to modular structure: `grep -E "function \w+\(" scripts/dev.js`
- Check function exports in a directory: `grep -E "export (function|const)" scripts/modules/`
- Find potential naming conflicts: `grep -E "function (get|set|create|update)\w+\(" -r ./`
- Variations:
- Add `-n` flag to include line numbers
- Add `--include="*.ts"` to filter by file extension
- Use with `| sort` to alphabetize results
- Integration with refactoring workflow:
- Start by mapping all functions in the source file
- Create target module files based on function grouping
- Verify all functions were properly migrated
- Check for any unintentional duplications or omissions

View File

@@ -0,0 +1,211 @@
---
description: Guidelines for integrating new features into the Task Master CLI
globs: scripts/modules/*.js
alwaysApply: false
---
# Task Master Feature Integration Guidelines
## Feature Placement Decision Process
- **Identify Feature Type**:
- **Data Manipulation**: Features that create, read, update, or delete tasks belong in [`task-manager.js`](mdc:scripts/modules/task-manager.js)
- **Dependency Management**: Features that handle task relationships belong in [`dependency-manager.js`](mdc:scripts/modules/dependency-manager.js)
- **User Interface**: Features that display information to users belong in [`ui.js`](mdc:scripts/modules/ui.js)
- **AI Integration**: Features that use AI models belong in [`ai-services.js`](mdc:scripts/modules/ai-services.js)
- **Cross-Cutting**: Features that don't fit one category may need components in multiple modules
- **Command-Line Interface**:
- All new user-facing commands should be added to [`commands.js`](mdc:scripts/modules/commands.js)
- Use consistent patterns for option naming and help text
- Follow the Commander.js model for subcommand structure
## Implementation Pattern
The standard pattern for adding a feature follows this workflow:
1. **Core Logic**: Implement the business logic in the appropriate module
2. **UI Components**: Add any display functions to [`ui.js`](mdc:scripts/modules/ui.js)
3. **Command Integration**: Add the CLI command to [`commands.js`](mdc:scripts/modules/commands.js)
4. **Configuration**: Update any configuration in [`utils.js`](mdc:scripts/modules/utils.js) if needed
5. **Documentation**: Update help text and documentation in [dev_workflow.mdc](mdc:scripts/modules/dev_workflow.mdc)
```javascript
// 1. CORE LOGIC: Add function to appropriate module (example in task-manager.js)
/**
* Archives completed tasks to archive.json
* @param {string} tasksPath - Path to the tasks.json file
* @param {string} archivePath - Path to the archive.json file
* @returns {number} Number of tasks archived
*/
async function archiveTasks(tasksPath, archivePath = 'tasks/archive.json') {
// Implementation...
return archivedCount;
}
// Export from the module
export {
// ... existing exports ...
archiveTasks,
};
```
```javascript
// 2. UI COMPONENTS: Add display function to ui.js
/**
* Display archive operation results
* @param {string} archivePath - Path to the archive file
* @param {number} count - Number of tasks archived
*/
function displayArchiveResults(archivePath, count) {
console.log(boxen(
chalk.green(`Successfully archived ${count} tasks to ${archivePath}`),
{ padding: 1, borderColor: 'green', borderStyle: 'round' }
));
}
// Export from the module
export {
// ... existing exports ...
displayArchiveResults,
};
```
```javascript
// 3. COMMAND INTEGRATION: Add to commands.js
import { archiveTasks } from './task-manager.js';
import { displayArchiveResults } from './ui.js';
// In registerCommands function
programInstance
.command('archive')
.description('Archive completed tasks to separate file')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-o, --output <file>', 'Archive output file', 'tasks/archive.json')
.action(async (options) => {
const tasksPath = options.file;
const archivePath = options.output;
console.log(chalk.blue(`Archiving completed tasks from ${tasksPath} to ${archivePath}...`));
const archivedCount = await archiveTasks(tasksPath, archivePath);
displayArchiveResults(archivePath, archivedCount);
});
```
## Cross-Module Features
For features requiring components in multiple modules:
- ✅ **DO**: Create a clear unidirectional flow of dependencies
```javascript
// In task-manager.js
function analyzeTasksDifficulty(tasks) {
// Implementation...
return difficultyScores;
}
// In ui.js - depends on task-manager.js
import { analyzeTasksDifficulty } from './task-manager.js';
function displayDifficultyReport(tasks) {
const scores = analyzeTasksDifficulty(tasks);
// Render the scores...
}
```
- ❌ **DON'T**: Create circular dependencies between modules
```javascript
// In task-manager.js - depends on ui.js
import { displayDifficultyReport } from './ui.js';
function analyzeTasks() {
// Implementation...
displayDifficultyReport(tasks); // WRONG! Don't call UI functions from task-manager
}
// In ui.js - depends on task-manager.js
import { analyzeTasks } from './task-manager.js';
```
## Command-Line Interface Standards
- **Naming Conventions**:
- Use kebab-case for command names (`analyze-complexity`, not `analyzeComplexity`)
- Use camelCase for option names (`--outputFormat`, not `--output-format`)
- Use the same option names across commands when they represent the same concept
- **Command Structure**:
```javascript
programInstance
.command('command-name')
.description('Clear, concise description of what the command does')
.option('-s, --short-option <value>', 'Option description', 'default value')
.option('--long-option <value>', 'Option description')
.action(async (options) => {
// Command implementation
});
```
## Utility Function Guidelines
When adding utilities to [`utils.js`](mdc:scripts/modules/utils.js):
- Only add functions that could be used by multiple modules
- Keep utilities single-purpose and purely functional
- Document parameters and return values
```javascript
/**
* Formats a duration in milliseconds to a human-readable string
* @param {number} ms - Duration in milliseconds
* @returns {string} Formatted duration string (e.g., "2h 30m 15s")
*/
function formatDuration(ms) {
// Implementation...
return formatted;
}
```
## Testing New Features
Before submitting a new feature:
1. Verify export/import structure with:
```bash
grep -A15 "export {" scripts/modules/*.js
grep -A15 "import {" scripts/modules/*.js | grep -v "^--$"
```
2. Test the feature with valid input:
```bash
task-master your-command --option1=value
```
3. Test the feature with edge cases:
```bash
task-master your-command --option1=""
task-master your-command # without required options
```
## Documentation Requirements
For each new feature:
1. Add help text to the command definition
2. Update [`dev_workflow.mdc`](mdc:scripts/modules/dev_workflow.mdc) with command reference
3. Add examples to the appropriate sections in [`MODULE_PLAN.md`](mdc:scripts/modules/MODULE_PLAN.md)
Follow the existing command reference format:
```markdown
- **Command Reference: your-command**
- CLI Syntax: `task-master your-command [options]`
- Description: Brief explanation of what the command does
- Parameters:
- `--option1=<value>`: Description of option1 (default: 'default')
- `--option2=<value>`: Description of option2 (required)
- Example: `task-master your-command --option1=value --option2=value2`
- Notes: Additional details, limitations, or special considerations
```
For more information on module structure, see [`MODULE_PLAN.md`](mdc:scripts/modules/MODULE_PLAN.md) and follow [`self_improve.mdc`](mdc:scripts/modules/self_improve.mdc) for best practices on updating documentation.

331
.cursor/rules/tasks.mdc Normal file
View File

@@ -0,0 +1,331 @@
---
description: Guidelines for implementing task management operations
globs: scripts/modules/task-manager.js
alwaysApply: false
---
# Task Management Guidelines
## Task Structure Standards
- **Core Task Properties**:
- ✅ DO: Include all required properties in each task object
- ✅ DO: Provide default values for optional properties
- ❌ DON'T: Add extra properties that aren't in the standard schema
```javascript
// ✅ DO: Follow this structure for task objects
const task = {
id: nextId,
title: "Task title",
description: "Brief task description",
status: "pending", // "pending", "in-progress", "done", etc.
dependencies: [], // Array of task IDs
priority: "medium", // "high", "medium", "low"
details: "Detailed implementation instructions",
testStrategy: "Verification approach",
subtasks: [] // Array of subtask objects
};
```
- **Subtask Structure**:
- ✅ DO: Use consistent properties across subtasks
- ✅ DO: Maintain simple numeric IDs within parent tasks
- ❌ DON'T: Duplicate parent task properties in subtasks
```javascript
// ✅ DO: Structure subtasks consistently
const subtask = {
id: nextSubtaskId, // Simple numeric ID, unique within the parent task
title: "Subtask title",
description: "Brief subtask description",
status: "pending",
dependencies: [], // Can include numeric IDs (other subtasks) or full task IDs
details: "Detailed implementation instructions"
};
```
## Task Creation and Parsing
- **ID Management**:
- ✅ DO: Assign unique sequential IDs to tasks
- ✅ DO: Calculate the next ID based on existing tasks
- ❌ DON'T: Hardcode or reuse IDs
```javascript
// ✅ DO: Calculate the next available ID
const highestId = Math.max(...data.tasks.map(t => t.id));
const nextTaskId = highestId + 1;
```
- **PRD Parsing**:
- ✅ DO: Extract tasks from PRD documents using AI
- ✅ DO: Provide clear prompts to guide AI task generation
- ✅ DO: Validate and clean up AI-generated tasks
```javascript
// ✅ DO: Validate AI responses
try {
// Parse the JSON response
taskData = JSON.parse(jsonContent);
// Check that we have the required fields
if (!taskData.title || !taskData.description) {
throw new Error("Missing required fields in the generated task");
}
} catch (error) {
log('error', "Failed to parse AI's response as valid task JSON:", error);
process.exit(1);
}
```
## Task Updates and Modifications
- **Status Management**:
- ✅ DO: Provide functions for updating task status
- ✅ DO: Handle both individual tasks and subtasks
- ✅ DO: Consider subtask status when updating parent tasks
```javascript
// ✅ DO: Handle status updates for both tasks and subtasks
async function setTaskStatus(tasksPath, taskIdInput, newStatus) {
// Check if it's a subtask (e.g., "1.2")
if (taskIdInput.includes('.')) {
const [parentId, subtaskId] = taskIdInput.split('.').map(id => parseInt(id, 10));
// Find the parent task and subtask
const parentTask = data.tasks.find(t => t.id === parentId);
const subtask = parentTask.subtasks.find(st => st.id === subtaskId);
// Update subtask status
subtask.status = newStatus;
// Check if all subtasks are done
if (newStatus === 'done') {
const allSubtasksDone = parentTask.subtasks.every(st => st.status === 'done');
if (allSubtasksDone) {
// Suggest updating parent task
}
}
} else {
// Handle regular task
const task = data.tasks.find(t => t.id === parseInt(taskIdInput, 10));
task.status = newStatus;
// If marking as done, also mark subtasks
if (newStatus === 'done' && task.subtasks && task.subtasks.length > 0) {
task.subtasks.forEach(subtask => {
subtask.status = newStatus;
});
}
}
}
```
- **Task Expansion**:
- ✅ DO: Use AI to generate detailed subtasks
- ✅ DO: Consider complexity analysis for subtask counts
- ✅ DO: Ensure proper IDs for newly created subtasks
```javascript
// ✅ DO: Generate appropriate subtasks based on complexity
if (taskAnalysis) {
log('info', `Found complexity analysis for task ${taskId}: Score ${taskAnalysis.complexityScore}/10`);
// Use recommended number of subtasks if available
if (taskAnalysis.recommendedSubtasks && numSubtasks === CONFIG.defaultSubtasks) {
numSubtasks = taskAnalysis.recommendedSubtasks;
log('info', `Using recommended number of subtasks: ${numSubtasks}`);
}
}
```
## Task File Generation
- **File Formatting**:
- ✅ DO: Use consistent formatting for task files
- ✅ DO: Include all task properties in text files
- ✅ DO: Format dependencies with status indicators
```javascript
// ✅ DO: Use consistent file formatting
let content = `# Task ID: ${task.id}\n`;
content += `# Title: ${task.title}\n`;
content += `# Status: ${task.status || 'pending'}\n`;
// Format dependencies with their status
if (task.dependencies && task.dependencies.length > 0) {
content += `# Dependencies: ${formatDependenciesWithStatus(task.dependencies, data.tasks)}\n`;
} else {
content += '# Dependencies: None\n';
}
```
- **Subtask Inclusion**:
- ✅ DO: Include subtasks in parent task files
- ✅ DO: Use consistent indentation for subtask sections
- ✅ DO: Display subtask dependencies with proper formatting
```javascript
// ✅ DO: Format subtasks correctly in task files
if (task.subtasks && task.subtasks.length > 0) {
content += '\n# Subtasks:\n';
task.subtasks.forEach(subtask => {
content += `## ${subtask.id}. ${subtask.title} [${subtask.status || 'pending'}]\n`;
// Format subtask dependencies
if (subtask.dependencies && subtask.dependencies.length > 0) {
// Format the dependencies
content += `### Dependencies: ${formattedDeps}\n`;
} else {
content += '### Dependencies: None\n';
}
content += `### Description: ${subtask.description || ''}\n`;
content += '### Details:\n';
content += (subtask.details || '').split('\n').map(line => line).join('\n');
content += '\n\n';
});
}
```
## Task Listing and Display
- **Filtering and Organization**:
- ✅ DO: Allow filtering tasks by status
- ✅ DO: Handle subtask display in lists
- ✅ DO: Use consistent table formats
```javascript
// ✅ DO: Implement clear filtering and organization
// Filter tasks by status if specified
const filteredTasks = statusFilter
? data.tasks.filter(task =>
task.status && task.status.toLowerCase() === statusFilter.toLowerCase())
: data.tasks;
```
- **Progress Tracking**:
- ✅ DO: Calculate and display completion statistics
- ✅ DO: Track both task and subtask completion
- ✅ DO: Use visual progress indicators
```javascript
// ✅ DO: Track and display progress
// Calculate completion statistics
const totalTasks = data.tasks.length;
const completedTasks = data.tasks.filter(task =>
task.status === 'done' || task.status === 'completed').length;
const completionPercentage = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;
// Count subtasks
let totalSubtasks = 0;
let completedSubtasks = 0;
data.tasks.forEach(task => {
if (task.subtasks && task.subtasks.length > 0) {
totalSubtasks += task.subtasks.length;
completedSubtasks += task.subtasks.filter(st =>
st.status === 'done' || st.status === 'completed').length;
}
});
```
## Complexity Analysis
- **Scoring System**:
- ✅ DO: Use AI to analyze task complexity
- ✅ DO: Include complexity scores (1-10)
- ✅ DO: Generate specific expansion recommendations
```javascript
// ✅ DO: Handle complexity analysis properly
const report = {
meta: {
generatedAt: new Date().toISOString(),
tasksAnalyzed: tasksData.tasks.length,
thresholdScore: thresholdScore,
projectName: tasksData.meta?.projectName || 'Your Project Name',
usedResearch: useResearch
},
complexityAnalysis: complexityAnalysis
};
```
- **Analysis-Based Workflow**:
- ✅ DO: Use complexity reports to guide task expansion
- ✅ DO: Prioritize complex tasks for more detailed breakdown
- ✅ DO: Use expansion prompts from complexity analysis
```javascript
// ✅ DO: Apply complexity analysis to workflow
// Sort tasks by complexity if report exists, otherwise by ID
if (complexityReport && complexityReport.complexityAnalysis) {
log('info', 'Sorting tasks by complexity...');
// Create a map of task IDs to complexity scores
const complexityMap = new Map();
complexityReport.complexityAnalysis.forEach(analysis => {
complexityMap.set(analysis.taskId, analysis.complexityScore);
});
// Sort tasks by complexity score (high to low)
tasksToExpand.sort((a, b) => {
const scoreA = complexityMap.get(a.id) || 0;
const scoreB = complexityMap.get(b.id) || 0;
return scoreB - scoreA;
});
}
```
## Next Task Selection
- **Eligibility Criteria**:
- ✅ DO: Consider dependencies when finding next tasks
- ✅ DO: Prioritize by task priority and dependency count
- ✅ DO: Skip completed tasks
```javascript
// ✅ DO: Use proper task prioritization logic
function findNextTask(tasks) {
// Get all completed task IDs
const completedTaskIds = new Set(
tasks
.filter(t => t.status === 'done' || t.status === 'completed')
.map(t => t.id)
);
// Filter for pending tasks whose dependencies are all satisfied
const eligibleTasks = tasks.filter(task =>
(task.status === 'pending' || task.status === 'in-progress') &&
task.dependencies &&
task.dependencies.every(depId => completedTaskIds.has(depId))
);
// Sort by priority, dependency count, and ID
const priorityValues = { 'high': 3, 'medium': 2, 'low': 1 };
const nextTask = eligibleTasks.sort((a, b) => {
// Priority first
const priorityA = priorityValues[a.priority || 'medium'] || 2;
const priorityB = priorityValues[b.priority || 'medium'] || 2;
if (priorityB !== priorityA) {
return priorityB - priorityA; // Higher priority first
}
// Dependency count next
if (a.dependencies.length !== b.dependencies.length) {
return a.dependencies.length - b.dependencies.length; // Fewer dependencies first
}
// ID last
return a.id - b.id; // Lower ID first
})[0];
return nextTask;
}
```
Refer to [`task-manager.js`](mdc:scripts/modules/task-manager.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.

153
.cursor/rules/ui.mdc Normal file
View File

@@ -0,0 +1,153 @@
---
description: Guidelines for implementing and maintaining user interface components
globs: scripts/modules/ui.js
alwaysApply: false
---
# User Interface Implementation Guidelines
## Core UI Component Principles
- **Function Scope Separation**:
- ✅ DO: Keep display logic separate from business logic
- ✅ DO: Import data processing functions from other modules
- ❌ DON'T: Include task manipulations within UI functions
- ❌ DON'T: Create circular dependencies with other modules
- **Standard Display Pattern**:
```javascript
// ✅ DO: Follow this pattern for display functions
/**
* Display information about a task
* @param {Object} task - The task to display
*/
function displayTaskInfo(task) {
console.log(boxen(
chalk.white.bold(`Task: #${task.id} - ${task.title}`),
{ padding: 1, borderColor: 'blue', borderStyle: 'round' }
));
}
```
## Visual Styling Standards
- **Color Scheme**:
- Use `chalk.blue` for informational messages
- Use `chalk.green` for success messages
- Use `chalk.yellow` for warnings
- Use `chalk.red` for errors
- Use `chalk.cyan` for prompts and highlights
- Use `chalk.magenta` for subtask-related information
- **Box Styling**:
```javascript
// ✅ DO: Use consistent box styles by content type
// For success messages:
boxen(content, {
padding: 1,
borderColor: 'green',
borderStyle: 'round',
margin: { top: 1 }
})
// For errors:
boxen(content, {
padding: 1,
borderColor: 'red',
borderStyle: 'round'
})
// For information:
boxen(content, {
padding: 1,
borderColor: 'blue',
borderStyle: 'round',
margin: { top: 1, bottom: 1 }
})
```
## Table Display Guidelines
- **Table Structure**:
- Use [`cli-table3`](mdc:node_modules/cli-table3/README.md) for consistent table rendering
- Include colored headers with bold formatting
- Use appropriate column widths for readability
```javascript
// ✅ DO: Create well-structured tables
const table = new Table({
head: [
chalk.cyan.bold('ID'),
chalk.cyan.bold('Title'),
chalk.cyan.bold('Status'),
chalk.cyan.bold('Priority'),
chalk.cyan.bold('Dependencies')
],
colWidths: [5, 40, 15, 10, 20]
});
// Add content rows
table.push([
task.id,
truncate(task.title, 37),
getStatusWithColor(task.status),
chalk.white(task.priority || 'medium'),
formatDependenciesWithStatus(task.dependencies, allTasks, true)
]);
console.log(table.toString());
```
## Loading Indicators
- **Animation Standards**:
- Use [`ora`](mdc:node_modules/ora/readme.md) for spinner animations
- Create and stop loading indicators correctly
```javascript
// ✅ DO: Properly manage loading state
const loadingIndicator = startLoadingIndicator('Processing task data...');
try {
// Do async work...
stopLoadingIndicator(loadingIndicator);
// Show success message
} catch (error) {
stopLoadingIndicator(loadingIndicator);
// Show error message
}
```
## Helper Functions
- **Status Formatting**:
- Use `getStatusWithColor` for consistent status display
- Use `formatDependenciesWithStatus` for dependency lists
- Use `truncate` to handle text that may overflow display
- **Progress Reporting**:
- Use visual indicators for progress (bars, percentages)
- Include both numeric and visual representations
```javascript
// ✅ DO: Show clear progress indicators
console.log(`${chalk.cyan('Tasks:')} ${completedTasks}/${totalTasks} (${completionPercentage.toFixed(1)}%)`);
console.log(`${chalk.cyan('Progress:')} ${createProgressBar(completionPercentage)}`);
```
## Command Suggestions
- **Action Recommendations**:
- Provide next step suggestions after command completion
- Use a consistent format for suggested commands
```javascript
// ✅ DO: Show suggested next actions
console.log(boxen(
chalk.white.bold('Next Steps:') + '\n\n' +
`${chalk.cyan('1.')} Run ${chalk.yellow('task-master list')} to view all tasks\n` +
`${chalk.cyan('2.')} Run ${chalk.yellow('task-master show --id=' + newTaskId)} to view details`,
{ padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
));
```
Refer to [`ui.js`](mdc:scripts/modules/ui.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.

314
.cursor/rules/utilities.mdc Normal file
View File

@@ -0,0 +1,314 @@
---
description: Guidelines for implementing utility functions
globs: scripts/modules/utils.js
alwaysApply: false
---
# Utility Function Guidelines
## General Principles
- **Function Scope**:
- ✅ DO: Create utility functions that serve multiple modules
- ✅ DO: Keep functions single-purpose and focused
- ❌ DON'T: Include business logic in utility functions
- ❌ DON'T: Create utilities with side effects
```javascript
// ✅ DO: Create focused, reusable utilities
/**
* Truncates text to a specified length
* @param {string} text - The text to truncate
* @param {number} maxLength - The maximum length
* @returns {string} The truncated text
*/
function truncate(text, maxLength) {
if (!text || text.length <= maxLength) {
return text;
}
return text.slice(0, maxLength - 3) + '...';
}
```
```javascript
// ❌ DON'T: Add side effects to utilities
function truncate(text, maxLength) {
if (!text || text.length <= maxLength) {
return text;
}
// Side effect - modifying global state or logging
console.log(`Truncating text from ${text.length} to ${maxLength} chars`);
return text.slice(0, maxLength - 3) + '...';
}
```
## Documentation Standards
- **JSDoc Format**:
- ✅ DO: Document all parameters and return values
- ✅ DO: Include descriptions for complex logic
- ✅ DO: Add examples for non-obvious usage
- ❌ DON'T: Skip documentation for "simple" functions
```javascript
// ✅ DO: Provide complete JSDoc documentation
/**
* Reads and parses a JSON file
* @param {string} filepath - Path to the JSON file
* @returns {Object|null} Parsed JSON data or null if error occurs
*/
function readJSON(filepath) {
try {
const rawData = fs.readFileSync(filepath, 'utf8');
return JSON.parse(rawData);
} catch (error) {
log('error', `Error reading JSON file ${filepath}:`, error.message);
if (CONFIG.debug) {
console.error(error);
}
return null;
}
}
```
## Configuration Management
- **Environment Variables**:
- ✅ DO: Provide default values for all configuration
- ✅ DO: Use environment variables for customization
- ✅ DO: Document available configuration options
- ❌ DON'T: Hardcode values that should be configurable
```javascript
// ✅ DO: Set up configuration with defaults and environment overrides
const CONFIG = {
model: process.env.MODEL || 'claude-3-7-sonnet-20250219',
maxTokens: parseInt(process.env.MAX_TOKENS || '4000'),
temperature: parseFloat(process.env.TEMPERATURE || '0.7'),
debug: process.env.DEBUG === "true",
logLevel: process.env.LOG_LEVEL || "info",
defaultSubtasks: parseInt(process.env.DEFAULT_SUBTASKS || "3"),
defaultPriority: process.env.DEFAULT_PRIORITY || "medium",
projectName: process.env.PROJECT_NAME || "Task Master",
projectVersion: "1.5.0" // Version should be hardcoded
};
```
## Logging Utilities
- **Log Levels**:
- ✅ DO: Support multiple log levels (debug, info, warn, error)
- ✅ DO: Use appropriate icons for different log levels
- ✅ DO: Respect the configured log level
- ❌ DON'T: Add direct console.log calls outside the logging utility
```javascript
// ✅ DO: Implement a proper logging utility
const LOG_LEVELS = {
debug: 0,
info: 1,
warn: 2,
error: 3
};
function log(level, ...args) {
const icons = {
debug: chalk.gray('🔍'),
info: chalk.blue(''),
warn: chalk.yellow('⚠️'),
error: chalk.red('❌'),
success: chalk.green('✅')
};
if (LOG_LEVELS[level] >= LOG_LEVELS[CONFIG.logLevel]) {
const icon = icons[level] || '';
console.log(`${icon} ${args.join(' ')}`);
}
}
```
## File Operations
- **Error Handling**:
- ✅ DO: Use try/catch blocks for all file operations
- ✅ DO: Return null or a default value on failure
- ✅ DO: Log detailed error information
- ❌ DON'T: Allow exceptions to propagate unhandled
```javascript
// ✅ DO: Handle file operation errors properly
function writeJSON(filepath, data) {
try {
fs.writeFileSync(filepath, JSON.stringify(data, null, 2));
} catch (error) {
log('error', `Error writing JSON file ${filepath}:`, error.message);
if (CONFIG.debug) {
console.error(error);
}
}
}
```
## Task-Specific Utilities
- **Task ID Formatting**:
- ✅ DO: Create utilities for consistent ID handling
- ✅ DO: Support different ID formats (numeric, string, dot notation)
- ❌ DON'T: Duplicate formatting logic across modules
```javascript
// ✅ DO: Create utilities for common operations
/**
* Formats a task ID as a string
* @param {string|number} id - The task ID to format
* @returns {string} The formatted task ID
*/
function formatTaskId(id) {
if (typeof id === 'string' && id.includes('.')) {
return id; // Already formatted as a string with a dot (e.g., "1.2")
}
if (typeof id === 'number') {
return id.toString();
}
return id;
}
```
- **Task Search**:
- ✅ DO: Implement reusable task finding utilities
- ✅ DO: Support both task and subtask lookups
- ✅ DO: Add context to subtask results
```javascript
// ✅ DO: Create comprehensive search utilities
/**
* Finds a task by ID in the tasks array
* @param {Array} tasks - The tasks array
* @param {string|number} taskId - The task ID to find
* @returns {Object|null} The task object or null if not found
*/
function findTaskById(tasks, taskId) {
if (!taskId || !tasks || !Array.isArray(tasks)) {
return null;
}
// Check if it's a subtask ID (e.g., "1.2")
if (typeof taskId === 'string' && taskId.includes('.')) {
const [parentId, subtaskId] = taskId.split('.').map(id => parseInt(id, 10));
const parentTask = tasks.find(t => t.id === parentId);
if (!parentTask || !parentTask.subtasks) {
return null;
}
const subtask = parentTask.subtasks.find(st => st.id === subtaskId);
if (subtask) {
// Add reference to parent task for context
subtask.parentTask = {
id: parentTask.id,
title: parentTask.title,
status: parentTask.status
};
subtask.isSubtask = true;
}
return subtask || null;
}
const id = parseInt(taskId, 10);
return tasks.find(t => t.id === id) || null;
}
```
## Cycle Detection
- **Graph Algorithms**:
- ✅ DO: Implement cycle detection using graph traversal
- ✅ DO: Track visited nodes and recursion stack
- ✅ DO: Return specific information about cycles
```javascript
// ✅ DO: Implement proper cycle detection
/**
* Find cycles in a dependency graph using DFS
* @param {string} subtaskId - Current subtask ID
* @param {Map} dependencyMap - Map of subtask IDs to their dependencies
* @param {Set} visited - Set of visited nodes
* @param {Set} recursionStack - Set of nodes in current recursion stack
* @returns {Array} - List of dependency edges that need to be removed to break cycles
*/
function findCycles(subtaskId, dependencyMap, visited = new Set(), recursionStack = new Set(), path = []) {
// Mark the current node as visited and part of recursion stack
visited.add(subtaskId);
recursionStack.add(subtaskId);
path.push(subtaskId);
const cyclesToBreak = [];
// Get all dependencies of the current subtask
const dependencies = dependencyMap.get(subtaskId) || [];
// For each dependency
for (const depId of dependencies) {
// If not visited, recursively check for cycles
if (!visited.has(depId)) {
const cycles = findCycles(depId, dependencyMap, visited, recursionStack, [...path]);
cyclesToBreak.push(...cycles);
}
// If the dependency is in the recursion stack, we found a cycle
else if (recursionStack.has(depId)) {
// The last edge in the cycle is what we want to remove
cyclesToBreak.push(depId);
}
}
// Remove the node from recursion stack before returning
recursionStack.delete(subtaskId);
return cyclesToBreak;
}
```
## Export Organization
- **Grouping Related Functions**:
- ✅ DO: Export all utility functions in a single statement
- ✅ DO: Group related exports together
- ✅ DO: Export configuration constants
- ❌ DON'T: Use default exports
```javascript
// ✅ DO: Organize exports logically
export {
// Configuration
CONFIG,
LOG_LEVELS,
// Logging
log,
// File operations
readJSON,
writeJSON,
// String manipulation
sanitizePrompt,
truncate,
// Task utilities
readComplexityReport,
findTaskInComplexityReport,
taskExists,
formatTaskId,
findTaskById,
// Graph algorithms
findCycles,
};
```
Refer to [`utils.js`](mdc:scripts/modules/utils.js) for implementation examples and [`new_features.mdc`](mdc:.cursor/rules/new_features.mdc) for integration guidelines.

View File

@@ -52,6 +52,7 @@
"files": [
"scripts/init.js",
"scripts/dev.js",
"scripts/modules/**",
"assets/**",
".cursor/**",
"README-task-master.md",

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,538 @@
/**
* ai-services.js
* AI service interactions for the Task Master CLI
*/
import { Anthropic } from '@anthropic-ai/sdk';
import OpenAI from 'openai';
import dotenv from 'dotenv';
import { CONFIG, log, sanitizePrompt } from './utils.js';
import { startLoadingIndicator, stopLoadingIndicator } from './ui.js';
// Load environment variables
dotenv.config();
// Configure Anthropic client
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
// Lazy-loaded Perplexity client
let perplexity = null;
/**
* Get or initialize the Perplexity client
* @returns {OpenAI} Perplexity client
*/
function getPerplexityClient() {
if (!perplexity) {
if (!process.env.PERPLEXITY_API_KEY) {
throw new Error("PERPLEXITY_API_KEY environment variable is missing. Set it to use research-backed features.");
}
perplexity = new OpenAI({
apiKey: process.env.PERPLEXITY_API_KEY,
baseURL: 'https://api.perplexity.ai',
});
}
return perplexity;
}
/**
* Call Claude to generate tasks from a PRD
* @param {string} prdContent - PRD content
* @param {string} prdPath - Path to the PRD file
* @param {number} numTasks - Number of tasks to generate
* @param {number} retryCount - Retry count
* @returns {Object} Claude's response
*/
async function callClaude(prdContent, prdPath, numTasks, retryCount = 0) {
try {
log('info', 'Calling Claude...');
// Build the system prompt
const systemPrompt = `You are an AI assistant helping to break down a Product Requirements Document (PRD) into a set of sequential development tasks.
Your goal is to create ${numTasks} well-structured, actionable development tasks based on the PRD provided.
Each task should follow this JSON structure:
{
"id": number,
"title": string,
"description": string,
"status": "pending",
"dependencies": number[] (IDs of tasks this depends on),
"priority": "high" | "medium" | "low",
"details": string (implementation details),
"testStrategy": string (validation approach)
}
Guidelines:
1. Create exactly ${numTasks} tasks, numbered from 1 to ${numTasks}
2. Each task should be atomic and focused on a single responsibility
3. Order tasks logically - consider dependencies and implementation sequence
4. Early tasks should focus on setup, core functionality first, then advanced features
5. Include clear validation/testing approach for each task
6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs)
7. Assign priority (high/medium/low) based on criticality and dependency order
8. Include detailed implementation guidance in the "details" field
Expected output format:
{
"tasks": [
{
"id": 1,
"title": "Setup Project Repository",
"description": "...",
...
},
...
],
"metadata": {
"projectName": "PRD Implementation",
"totalTasks": ${numTasks},
"sourceFile": "${prdPath}",
"generatedAt": "YYYY-MM-DD"
}
}
Important: Your response must be valid JSON only, with no additional explanation or comments.`;
// Use streaming request to handle large responses and show progress
return await handleStreamingRequest(prdContent, prdPath, numTasks, CONFIG.maxTokens, systemPrompt);
} catch (error) {
log('error', 'Error calling Claude:', error.message);
// Retry logic
if (retryCount < 2) {
log('info', `Retrying (${retryCount + 1}/2)...`);
return await callClaude(prdContent, prdPath, numTasks, retryCount + 1);
} else {
throw error;
}
}
}
/**
* Handle streaming request to Claude
* @param {string} prdContent - PRD content
* @param {string} prdPath - Path to the PRD file
* @param {number} numTasks - Number of tasks to generate
* @param {number} maxTokens - Maximum tokens
* @param {string} systemPrompt - System prompt
* @returns {Object} Claude's response
*/
async function handleStreamingRequest(prdContent, prdPath, numTasks, maxTokens, systemPrompt) {
const loadingIndicator = startLoadingIndicator('Generating tasks from PRD...');
let responseText = '';
try {
const message = await anthropic.messages.create({
model: CONFIG.model,
max_tokens: maxTokens,
temperature: CONFIG.temperature,
system: systemPrompt,
messages: [
{
role: 'user',
content: `Here's the Product Requirements Document (PRD) to break down into ${numTasks} tasks:\n\n${prdContent}`
}
]
});
responseText = message.content[0].text;
stopLoadingIndicator(loadingIndicator);
return processClaudeResponse(responseText, numTasks, 0, prdContent, prdPath);
} catch (error) {
stopLoadingIndicator(loadingIndicator);
throw error;
}
}
/**
* Process Claude's response
* @param {string} textContent - Text content from Claude
* @param {number} numTasks - Number of tasks
* @param {number} retryCount - Retry count
* @param {string} prdContent - PRD content
* @param {string} prdPath - Path to the PRD file
* @returns {Object} Processed response
*/
function processClaudeResponse(textContent, numTasks, retryCount, prdContent, prdPath) {
try {
// Attempt to parse the JSON response
let jsonStart = textContent.indexOf('{');
let jsonEnd = textContent.lastIndexOf('}');
if (jsonStart === -1 || jsonEnd === -1) {
throw new Error("Could not find valid JSON in Claude's response");
}
let jsonContent = textContent.substring(jsonStart, jsonEnd + 1);
let parsedData = JSON.parse(jsonContent);
// Validate the structure of the generated tasks
if (!parsedData.tasks || !Array.isArray(parsedData.tasks)) {
throw new Error("Claude's response does not contain a valid tasks array");
}
// Ensure we have the correct number of tasks
if (parsedData.tasks.length !== numTasks) {
log('warn', `Expected ${numTasks} tasks, but received ${parsedData.tasks.length}`);
}
// Add metadata if missing
if (!parsedData.metadata) {
parsedData.metadata = {
projectName: "PRD Implementation",
totalTasks: parsedData.tasks.length,
sourceFile: prdPath,
generatedAt: new Date().toISOString().split('T')[0]
};
}
return parsedData;
} catch (error) {
log('error', "Error processing Claude's response:", error.message);
// Retry logic
if (retryCount < 2) {
log('info', `Retrying to parse response (${retryCount + 1}/2)...`);
// Try again with Claude for a cleaner response
if (retryCount === 1) {
log('info', "Calling Claude again for a cleaner response...");
return callClaude(prdContent, prdPath, numTasks, retryCount + 1);
}
return processClaudeResponse(textContent, numTasks, retryCount + 1, prdContent, prdPath);
} else {
throw error;
}
}
}
/**
* Generate subtasks for a task
* @param {Object} task - Task to generate subtasks for
* @param {number} numSubtasks - Number of subtasks to generate
* @param {number} nextSubtaskId - Next subtask ID
* @param {string} additionalContext - Additional context
* @returns {Array} Generated subtasks
*/
async function generateSubtasks(task, numSubtasks, nextSubtaskId, additionalContext = '') {
try {
log('info', `Generating ${numSubtasks} subtasks for task ${task.id}: ${task.title}`);
const loadingIndicator = startLoadingIndicator(`Generating subtasks for task ${task.id}...`);
const systemPrompt = `You are an AI assistant helping with task breakdown for software development.
You need to break down a high-level task into ${numSubtasks} specific subtasks that can be implemented one by one.
Subtasks should:
1. Be specific and actionable implementation steps
2. Follow a logical sequence
3. Each handle a distinct part of the parent task
4. Include clear guidance on implementation approach
5. Have appropriate dependency chains between subtasks
6. Collectively cover all aspects of the parent task
For each subtask, provide:
- A clear, specific title
- Detailed implementation steps
- Dependencies on previous subtasks
- Testing approach
Each subtask should be implementable in a focused coding session.`;
const contextPrompt = additionalContext ?
`\n\nAdditional context to consider: ${additionalContext}` : '';
const userPrompt = `Please break down this task into ${numSubtasks} specific, actionable subtasks:
Task ID: ${task.id}
Title: ${task.title}
Description: ${task.description}
Current details: ${task.details || 'None provided'}
${contextPrompt}
Return exactly ${numSubtasks} subtasks with the following JSON structure:
[
{
"id": ${nextSubtaskId},
"title": "First subtask title",
"description": "Detailed description",
"dependencies": [],
"details": "Implementation details"
},
...more subtasks...
]
Note on dependencies: Subtasks can depend on other subtasks with lower IDs. Use an empty array if there are no dependencies.`;
const message = await anthropic.messages.create({
model: CONFIG.model,
max_tokens: CONFIG.maxTokens,
temperature: CONFIG.temperature,
system: systemPrompt,
messages: [
{
role: 'user',
content: userPrompt
}
]
});
stopLoadingIndicator(loadingIndicator);
return parseSubtasksFromText(message.content[0].text, nextSubtaskId, numSubtasks, task.id);
} catch (error) {
log('error', `Error generating subtasks: ${error.message}`);
throw error;
}
}
/**
* Generate subtasks with research from Perplexity
* @param {Object} task - Task to generate subtasks for
* @param {number} numSubtasks - Number of subtasks to generate
* @param {number} nextSubtaskId - Next subtask ID
* @param {string} additionalContext - Additional context
* @returns {Array} Generated subtasks
*/
async function generateSubtasksWithPerplexity(task, numSubtasks = 3, nextSubtaskId = 1, additionalContext = '') {
try {
// First, perform research to get context
log('info', `Researching context for task ${task.id}: ${task.title}`);
const perplexityClient = getPerplexityClient();
const PERPLEXITY_MODEL = process.env.PERPLEXITY_MODEL || 'sonar-small-online';
const researchLoadingIndicator = startLoadingIndicator('Researching best practices with Perplexity AI...');
// Formulate research query based on task
const researchQuery = `I need to implement "${task.title}" which involves: "${task.description}".
What are current best practices, libraries, design patterns, and implementation approaches?
Include concrete code examples and technical considerations where relevant.`;
// Query Perplexity for research
const researchResponse = await perplexityClient.chat.completions.create({
model: PERPLEXITY_MODEL,
messages: [{
role: 'user',
content: researchQuery
}],
temperature: 0.1 // Lower temperature for more factual responses
});
const researchResult = researchResponse.choices[0].message.content;
stopLoadingIndicator(researchLoadingIndicator);
log('info', 'Research completed, now generating subtasks with additional context');
// Use the research result as additional context for Claude to generate subtasks
const combinedContext = `
RESEARCH FINDINGS:
${researchResult}
ADDITIONAL CONTEXT PROVIDED BY USER:
${additionalContext || "No additional context provided."}
`;
// Now generate subtasks with Claude
const loadingIndicator = startLoadingIndicator(`Generating research-backed subtasks for task ${task.id}...`);
const systemPrompt = `You are an AI assistant helping with task breakdown for software development.
You need to break down a high-level task into ${numSubtasks} specific subtasks that can be implemented one by one.
You have been provided with research on current best practices and implementation approaches.
Use this research to inform and enhance your subtask breakdown.
Subtasks should:
1. Be specific and actionable implementation steps
2. Follow a logical sequence
3. Each handle a distinct part of the parent task
4. Include clear guidance on implementation approach, referencing the research where relevant
5. Have appropriate dependency chains between subtasks
6. Collectively cover all aspects of the parent task
For each subtask, provide:
- A clear, specific title
- Detailed implementation steps that incorporate best practices from the research
- Dependencies on previous subtasks
- Testing approach
Each subtask should be implementable in a focused coding session.`;
const userPrompt = `Please break down this task into ${numSubtasks} specific, actionable subtasks,
using the research findings to inform your breakdown:
Task ID: ${task.id}
Title: ${task.title}
Description: ${task.description}
Current details: ${task.details || 'None provided'}
${combinedContext}
Return exactly ${numSubtasks} subtasks with the following JSON structure:
[
{
"id": ${nextSubtaskId},
"title": "First subtask title",
"description": "Detailed description",
"dependencies": [],
"details": "Implementation details"
},
...more subtasks...
]
Note on dependencies: Subtasks can depend on other subtasks with lower IDs. Use an empty array if there are no dependencies.`;
const message = await anthropic.messages.create({
model: CONFIG.model,
max_tokens: CONFIG.maxTokens,
temperature: CONFIG.temperature,
system: systemPrompt,
messages: [
{
role: 'user',
content: userPrompt
}
]
});
stopLoadingIndicator(loadingIndicator);
return parseSubtasksFromText(message.content[0].text, nextSubtaskId, numSubtasks, task.id);
} catch (error) {
log('error', `Error generating research-backed subtasks: ${error.message}`);
throw error;
}
}
/**
* Parse subtasks from Claude's response text
* @param {string} text - Response text
* @param {number} startId - Starting subtask ID
* @param {number} expectedCount - Expected number of subtasks
* @param {number} parentTaskId - Parent task ID
* @returns {Array} Parsed subtasks
*/
function parseSubtasksFromText(text, startId, expectedCount, parentTaskId) {
try {
// Locate JSON array in the text
const jsonStartIndex = text.indexOf('[');
const jsonEndIndex = text.lastIndexOf(']');
if (jsonStartIndex === -1 || jsonEndIndex === -1 || jsonEndIndex < jsonStartIndex) {
throw new Error("Could not locate valid JSON array in the response");
}
// Extract and parse the JSON
const jsonText = text.substring(jsonStartIndex, jsonEndIndex + 1);
let subtasks = JSON.parse(jsonText);
// Validate
if (!Array.isArray(subtasks)) {
throw new Error("Parsed content is not an array");
}
// Log warning if count doesn't match expected
if (subtasks.length !== expectedCount) {
log('warn', `Expected ${expectedCount} subtasks, but parsed ${subtasks.length}`);
}
// Normalize subtask IDs if they don't match
subtasks = subtasks.map((subtask, index) => {
// Assign the correct ID if it doesn't match
if (subtask.id !== startId + index) {
log('warn', `Correcting subtask ID from ${subtask.id} to ${startId + index}`);
subtask.id = startId + index;
}
// Convert dependencies to numbers if they are strings
if (subtask.dependencies && Array.isArray(subtask.dependencies)) {
subtask.dependencies = subtask.dependencies.map(dep => {
return typeof dep === 'string' ? parseInt(dep, 10) : dep;
});
} else {
subtask.dependencies = [];
}
// Ensure status is 'pending'
subtask.status = 'pending';
// Add parentTaskId
subtask.parentTaskId = parentTaskId;
return subtask;
});
return subtasks;
} catch (error) {
log('error', `Error parsing subtasks: ${error.message}`);
// Create a fallback array of empty subtasks if parsing fails
log('warn', 'Creating fallback subtasks');
const fallbackSubtasks = [];
for (let i = 0; i < expectedCount; i++) {
fallbackSubtasks.push({
id: startId + i,
title: `Subtask ${startId + i}`,
description: "Auto-generated fallback subtask",
dependencies: [],
details: "This is a fallback subtask created because parsing failed. Please update with real details.",
status: 'pending',
parentTaskId: parentTaskId
});
}
return fallbackSubtasks;
}
}
/**
* Generate a prompt for complexity analysis
* @param {Array} tasksData - Tasks data
* @returns {string} Generated prompt
*/
function generateComplexityAnalysisPrompt(tasksData) {
return `Analyze the complexity of the following tasks and provide recommendations for subtask breakdown:
${tasksData.map(task => `
Task ID: ${task.id}
Title: ${task.title}
Description: ${task.description}
Details: ${task.details}
Dependencies: ${JSON.stringify(task.dependencies || [])}
Priority: ${task.priority || 'medium'}
`).join('\n---\n')}
Analyze each task and return a JSON array with the following structure for each task:
[
{
"taskId": number,
"taskTitle": string,
"complexityScore": number (1-10),
"recommendedSubtasks": number (${Math.max(3, CONFIG.defaultSubtasks - 1)}-${Math.min(8, CONFIG.defaultSubtasks + 2)}),
"expansionPrompt": string (a specific prompt for generating good subtasks),
"reasoning": string (brief explanation of your assessment)
},
...
]
IMPORTANT: Make sure to include an analysis for EVERY task listed above, with the correct taskId matching each task's ID.
`;
}
// Export AI service functions
export {
getPerplexityClient,
callClaude,
handleStreamingRequest,
processClaudeResponse,
generateSubtasks,
generateSubtasksWithPerplexity,
parseSubtasksFromText,
generateComplexityAnalysisPrompt
};

465
scripts/modules/commands.js Normal file
View File

@@ -0,0 +1,465 @@
/**
* commands.js
* Command-line interface for the Task Master CLI
*/
import { program } from 'commander';
import path from 'path';
import chalk from 'chalk';
import boxen from 'boxen';
import fs from 'fs';
import { CONFIG, log, readJSON } from './utils.js';
import {
parsePRD,
updateTasks,
generateTaskFiles,
setTaskStatus,
listTasks,
expandTask,
expandAllTasks,
clearSubtasks,
addTask,
analyzeTaskComplexity
} from './task-manager.js';
import {
addDependency,
removeDependency,
validateDependenciesCommand,
fixDependenciesCommand
} from './dependency-manager.js';
import {
displayBanner,
displayHelp,
displayNextTask,
displayTaskById,
displayComplexityReport,
} from './ui.js';
/**
* Configure and register CLI commands
* @param {Object} program - Commander program instance
*/
function registerCommands(programInstance) {
// Default help
programInstance.on('--help', function() {
displayHelp();
});
// parse-prd command
programInstance
.command('parse-prd')
.description('Parse a PRD file and generate tasks')
.argument('<file>', 'Path to the PRD file')
.option('-o, --output <file>', 'Output file path', 'tasks/tasks.json')
.option('-n, --num-tasks <number>', 'Number of tasks to generate', '10')
.action(async (file, options) => {
const numTasks = parseInt(options.numTasks, 10);
const outputPath = options.output;
console.log(chalk.blue(`Parsing PRD file: ${file}`));
console.log(chalk.blue(`Generating ${numTasks} tasks...`));
await parsePRD(file, outputPath, numTasks);
});
// update command
programInstance
.command('update')
.description('Update tasks based on new information or implementation changes')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('--from <id>', 'Task ID to start updating from (tasks with ID >= this value will be updated)', '1')
.option('-p, --prompt <text>', 'Prompt explaining the changes or new context (required)')
.action(async (options) => {
const tasksPath = options.file;
const fromId = parseInt(options.from, 10);
const prompt = options.prompt;
if (!prompt) {
console.error(chalk.red('Error: --prompt parameter is required. Please provide information about the changes.'));
process.exit(1);
}
console.log(chalk.blue(`Updating tasks from ID >= ${fromId} with prompt: "${prompt}"`));
console.log(chalk.blue(`Tasks file: ${tasksPath}`));
await updateTasks(tasksPath, fromId, prompt);
});
// generate command
programInstance
.command('generate')
.description('Generate task files from tasks.json')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-o, --output <dir>', 'Output directory', 'tasks')
.action(async (options) => {
const tasksPath = options.file;
const outputDir = options.output;
console.log(chalk.blue(`Generating task files from: ${tasksPath}`));
console.log(chalk.blue(`Output directory: ${outputDir}`));
await generateTaskFiles(tasksPath, outputDir);
});
// set-status command
programInstance
.command('set-status')
.description('Set the status of a task')
.option('-i, --id <id>', 'Task ID (can be comma-separated for multiple tasks)')
.option('-s, --status <status>', 'New status (todo, in-progress, review, done)')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (options) => {
const tasksPath = options.file;
const taskId = options.id;
const status = options.status;
if (!taskId || !status) {
console.error(chalk.red('Error: Both --id and --status are required'));
process.exit(1);
}
console.log(chalk.blue(`Setting status of task(s) ${taskId} to: ${status}`));
await setTaskStatus(tasksPath, taskId, status);
});
// list command
programInstance
.command('list')
.description('List all tasks')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-s, --status <status>', 'Filter by status')
.option('--with-subtasks', 'Show subtasks for each task')
.action(async (options) => {
const tasksPath = options.file;
const statusFilter = options.status;
const withSubtasks = options.withSubtasks || false;
console.log(chalk.blue(`Listing tasks from: ${tasksPath}`));
if (statusFilter) {
console.log(chalk.blue(`Filtering by status: ${statusFilter}`));
}
if (withSubtasks) {
console.log(chalk.blue('Including subtasks in listing'));
}
await listTasks(tasksPath, statusFilter, withSubtasks);
});
// expand command
programInstance
.command('expand')
.description('Break down tasks into detailed subtasks')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-i, --id <id>', 'Task ID to expand')
.option('-a, --all', 'Expand all tasks')
.option('-n, --num <number>', 'Number of subtasks to generate', CONFIG.defaultSubtasks.toString())
.option('--research', 'Enable Perplexity AI for research-backed subtask generation')
.option('-p, --prompt <text>', 'Additional context to guide subtask generation')
.option('--force', 'Force regeneration of subtasks for tasks that already have them')
.action(async (options) => {
const tasksPath = options.file;
const idArg = options.id ? parseInt(options.id, 10) : null;
const allFlag = options.all;
const numSubtasks = parseInt(options.num, 10);
const forceFlag = options.force;
const useResearch = options.research === true;
const additionalContext = options.prompt || '';
// Debug log to verify the value
log('debug', `Research enabled: ${useResearch}`);
if (allFlag) {
console.log(chalk.blue(`Expanding all tasks with ${numSubtasks} subtasks each...`));
if (useResearch) {
console.log(chalk.blue('Using Perplexity AI for research-backed subtask generation'));
} else {
console.log(chalk.yellow('Research-backed subtask generation disabled'));
}
if (additionalContext) {
console.log(chalk.blue(`Additional context: "${additionalContext}"`));
}
await expandAllTasks(numSubtasks, useResearch, additionalContext, forceFlag);
} else if (idArg) {
console.log(chalk.blue(`Expanding task ${idArg} with ${numSubtasks} subtasks...`));
if (useResearch) {
console.log(chalk.blue('Using Perplexity AI for research-backed subtask generation'));
} else {
console.log(chalk.yellow('Research-backed subtask generation disabled'));
}
if (additionalContext) {
console.log(chalk.blue(`Additional context: "${additionalContext}"`));
}
await expandTask(idArg, numSubtasks, useResearch, additionalContext);
} else {
console.error(chalk.red('Error: Please specify a task ID with --id=<id> or use --all to expand all tasks.'));
}
});
// analyze-complexity command
programInstance
.command('analyze-complexity')
.description(`Analyze tasks and generate expansion recommendations${chalk.reset('')}`)
.option('-o, --output <file>', 'Output file path for the report', 'scripts/task-complexity-report.json')
.option('-m, --model <model>', 'LLM model to use for analysis (defaults to configured model)')
.option('-t, --threshold <number>', 'Minimum complexity score to recommend expansion (1-10)', '5')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-r, --research', 'Use Perplexity AI for research-backed complexity analysis')
.action(async (options) => {
const tasksPath = options.file || 'tasks/tasks.json';
const outputPath = options.output;
const modelOverride = options.model;
const thresholdScore = parseFloat(options.threshold);
const useResearch = options.research || false;
console.log(chalk.blue(`Analyzing task complexity from: ${tasksPath}`));
console.log(chalk.blue(`Output report will be saved to: ${outputPath}`));
if (useResearch) {
console.log(chalk.blue('Using Perplexity AI for research-backed complexity analysis'));
}
await analyzeTaskComplexity(options);
});
// clear-subtasks command
programInstance
.command('clear-subtasks')
.description('Clear subtasks from specified tasks')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-i, --id <ids>', 'Task IDs (comma-separated) to clear subtasks from')
.option('--all', 'Clear subtasks from all tasks')
.action(async (options) => {
const tasksPath = options.file;
const taskIds = options.id;
const all = options.all;
if (!taskIds && !all) {
console.error(chalk.red('Error: Please specify task IDs with --id=<ids> or use --all to clear all tasks'));
process.exit(1);
}
if (all) {
// If --all is specified, get all task IDs
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
console.error(chalk.red('Error: No valid tasks found'));
process.exit(1);
}
const allIds = data.tasks.map(t => t.id).join(',');
clearSubtasks(tasksPath, allIds);
} else {
clearSubtasks(tasksPath, taskIds);
}
});
// add-task command
programInstance
.command('add-task')
.description('Add a new task using AI')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.option('-p, --prompt <text>', 'Description of the task to add (required)')
.option('-d, --dependencies <ids>', 'Comma-separated list of task IDs this task depends on')
.option('--priority <priority>', 'Task priority (high, medium, low)', 'medium')
.action(async (options) => {
const tasksPath = options.file;
const prompt = options.prompt;
const dependencies = options.dependencies ? options.dependencies.split(',').map(id => parseInt(id.trim(), 10)) : [];
const priority = options.priority;
if (!prompt) {
console.error(chalk.red('Error: --prompt parameter is required. Please provide a task description.'));
process.exit(1);
}
console.log(chalk.blue(`Adding new task with description: "${prompt}"`));
console.log(chalk.blue(`Dependencies: ${dependencies.length > 0 ? dependencies.join(', ') : 'None'}`));
console.log(chalk.blue(`Priority: ${priority}`));
await addTask(tasksPath, prompt, dependencies, priority);
});
// next command
programInstance
.command('next')
.description(`Show the next task to work on based on dependencies and status${chalk.reset('')}`)
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (options) => {
const tasksPath = options.file;
await displayNextTask(tasksPath);
});
// show command
programInstance
.command('show')
.description(`Display detailed information about a specific task${chalk.reset('')}`)
.argument('[id]', 'Task ID to show')
.option('-i, --id <id>', 'Task ID to show')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (taskId, options) => {
const idArg = taskId || options.id;
if (!idArg) {
console.error(chalk.red('Error: Please provide a task ID'));
process.exit(1);
}
const tasksPath = options.file;
await displayTaskById(tasksPath, idArg);
});
// add-dependency command
programInstance
.command('add-dependency')
.description('Add a dependency to a task')
.option('-i, --id <id>', 'Task ID to add dependency to')
.option('-d, --depends-on <id>', 'Task ID that will become a dependency')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (options) => {
const tasksPath = options.file;
const taskId = options.id;
const dependencyId = options.dependsOn;
if (!taskId || !dependencyId) {
console.error(chalk.red('Error: Both --id and --depends-on are required'));
process.exit(1);
}
await addDependency(tasksPath, parseInt(taskId, 10), parseInt(dependencyId, 10));
});
// remove-dependency command
programInstance
.command('remove-dependency')
.description('Remove a dependency from a task')
.option('-i, --id <id>', 'Task ID to remove dependency from')
.option('-d, --depends-on <id>', 'Task ID to remove as a dependency')
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (options) => {
const tasksPath = options.file;
const taskId = options.id;
const dependencyId = options.dependsOn;
if (!taskId || !dependencyId) {
console.error(chalk.red('Error: Both --id and --depends-on are required'));
process.exit(1);
}
await removeDependency(tasksPath, parseInt(taskId, 10), parseInt(dependencyId, 10));
});
// validate-dependencies command
programInstance
.command('validate-dependencies')
.description(`Identify invalid dependencies without fixing them${chalk.reset('')}`)
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (options) => {
await validateDependenciesCommand(options.file);
});
// fix-dependencies command
programInstance
.command('fix-dependencies')
.description(`Fix invalid dependencies automatically${chalk.reset('')}`)
.option('-f, --file <file>', 'Path to the tasks file', 'tasks/tasks.json')
.action(async (options) => {
await fixDependenciesCommand(options.file);
});
// complexity-report command
programInstance
.command('complexity-report')
.description(`Display the complexity analysis report${chalk.reset('')}`)
.option('-f, --file <file>', 'Path to the report file', 'scripts/task-complexity-report.json')
.action(async (options) => {
await displayComplexityReport(options.file);
});
// Add more commands as needed...
return programInstance;
}
/**
* Setup the CLI application
* @returns {Object} Configured Commander program
*/
function setupCLI() {
// Create a new program instance
const programInstance = program
.name('dev')
.description('AI-driven development task management')
.version(() => {
// Read version directly from package.json
try {
const packageJsonPath = path.join(process.cwd(), 'package.json');
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
return packageJson.version;
}
} catch (error) {
// Silently fall back to default version
}
return CONFIG.projectVersion; // Default fallback
})
.helpOption('-h, --help', 'Display help')
.addHelpCommand(false) // Disable default help command
.on('--help', () => {
displayHelp(); // Use your custom help display instead
})
.on('-h', () => {
displayHelp();
process.exit(0);
});
// Modify the help option to use your custom display
programInstance.helpInformation = () => {
displayHelp();
return '';
};
// Register commands
registerCommands(programInstance);
return programInstance;
}
/**
* Parse arguments and run the CLI
* @param {Array} argv - Command-line arguments
*/
async function runCLI(argv = process.argv) {
try {
// Display banner if not in a pipe
if (process.stdout.isTTY) {
displayBanner();
}
// If no arguments provided, show help
if (argv.length <= 2) {
displayHelp();
process.exit(0);
}
// Setup and parse
const programInstance = setupCLI();
await programInstance.parseAsync(argv);
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
if (CONFIG.debug) {
console.error(error);
}
process.exit(1);
}
}
export {
registerCommands,
setupCLI,
runCLI
};

File diff suppressed because it is too large Load Diff

11
scripts/modules/index.js Normal file
View File

@@ -0,0 +1,11 @@
/**
* index.js
* Main export point for all Task Master CLI modules
*/
// Export all modules
export * from './utils.js';
export * from './ui.js';
export * from './ai-services.js';
export * from './task-manager.js';
export * from './commands.js';

File diff suppressed because it is too large Load Diff

903
scripts/modules/ui.js Normal file
View File

@@ -0,0 +1,903 @@
/**
* ui.js
* User interface functions for the Task Master CLI
*/
import chalk from 'chalk';
import figlet from 'figlet';
import boxen from 'boxen';
import ora from 'ora';
import Table from 'cli-table3';
import gradient from 'gradient-string';
import { CONFIG, log, findTaskById, readJSON, readComplexityReport, truncate } from './utils.js';
import path from 'path';
import fs from 'fs';
import { findNextTask, analyzeTaskComplexity } from './task-manager.js';
// Create a color gradient for the banner
const coolGradient = gradient(['#00b4d8', '#0077b6', '#03045e']);
const warmGradient = gradient(['#fb8b24', '#e36414', '#9a031e']);
/**
* Display a fancy banner for the CLI
*/
function displayBanner() {
console.clear();
const bannerText = figlet.textSync('Task Master', {
font: 'Standard',
horizontalLayout: 'default',
verticalLayout: 'default'
});
console.log(coolGradient(bannerText));
// Add creator credit line below the banner
console.log(chalk.dim('by ') + chalk.cyan.underline('https://x.com/eyaltoledano'));
// Read version directly from package.json
let version = CONFIG.projectVersion; // Default fallback
try {
const packageJsonPath = path.join(process.cwd(), 'package.json');
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
version = packageJson.version;
}
} catch (error) {
// Silently fall back to default version
}
console.log(boxen(chalk.white(`${chalk.bold('Version:')} ${version} ${chalk.bold('Project:')} ${CONFIG.projectName}`), {
padding: 1,
margin: { top: 0, bottom: 1 },
borderStyle: 'round',
borderColor: 'cyan'
}));
}
/**
* Start a loading indicator with an animated spinner
* @param {string} message - Message to display next to the spinner
* @returns {Object} Spinner object
*/
function startLoadingIndicator(message) {
const spinner = ora({
text: message,
color: 'cyan'
}).start();
return spinner;
}
/**
* Stop a loading indicator
* @param {Object} spinner - Spinner object to stop
*/
function stopLoadingIndicator(spinner) {
if (spinner && spinner.stop) {
spinner.stop();
}
}
/**
* Create a progress bar using ASCII characters
* @param {number} percent - Progress percentage (0-100)
* @param {number} length - Length of the progress bar in characters
* @returns {string} Formatted progress bar
*/
function createProgressBar(percent, length = 30) {
const filled = Math.round(percent * length / 100);
const empty = length - filled;
const filledBar = '█'.repeat(filled);
const emptyBar = '░'.repeat(empty);
return `${filledBar}${emptyBar} ${percent.toFixed(0)}%`;
}
/**
* Get a colored status string based on the status value
* @param {string} status - Task status (e.g., "done", "pending", "in-progress")
* @returns {string} Colored status string
*/
function getStatusWithColor(status) {
if (!status) {
return chalk.gray('unknown');
}
const statusColors = {
'done': chalk.green,
'completed': chalk.green,
'pending': chalk.yellow,
'in-progress': chalk.blue,
'deferred': chalk.gray,
'blocked': chalk.red,
'review': chalk.magenta
};
const colorFunc = statusColors[status.toLowerCase()] || chalk.white;
return colorFunc(status);
}
/**
* Format dependencies list with status indicators
* @param {Array} dependencies - Array of dependency IDs
* @param {Array} allTasks - Array of all tasks
* @param {boolean} forConsole - Whether the output is for console display
* @returns {string} Formatted dependencies string
*/
function formatDependenciesWithStatus(dependencies, allTasks, forConsole = false) {
if (!dependencies || !Array.isArray(dependencies) || dependencies.length === 0) {
return forConsole ? chalk.gray('None') : 'None';
}
const formattedDeps = dependencies.map(depId => {
const depTask = findTaskById(allTasks, depId);
if (!depTask) {
return forConsole ?
chalk.red(`${depId} (Not found)`) :
`${depId} (Not found)`;
}
const status = depTask.status || 'pending';
const isDone = status.toLowerCase() === 'done' || status.toLowerCase() === 'completed';
if (forConsole) {
return isDone ?
chalk.green(`${depId}`) :
chalk.red(`${depId}`);
}
const statusIcon = isDone ? '✅' : '⏱️';
return `${statusIcon} ${depId} (${status})`;
});
return formattedDeps.join(', ');
}
/**
* Display a comprehensive help guide
*/
function displayHelp() {
displayBanner();
console.log(boxen(
chalk.white.bold('Task Master CLI'),
{ padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
));
// Command categories
const commandCategories = [
{
title: 'Task Generation',
color: 'cyan',
commands: [
{ name: 'parse-prd', args: '--input=<file.txt> [--tasks=10]',
desc: 'Generate tasks from a PRD document' },
{ name: 'generate', args: '',
desc: 'Create individual task files from tasks.json' }
]
},
{
title: 'Task Management',
color: 'green',
commands: [
{ name: 'list', args: '[--status=<status>] [--with-subtasks]',
desc: 'List all tasks with their status' },
{ name: 'set-status', args: '--id=<id> --status=<status>',
desc: 'Update task status (done, pending, etc.)' },
{ name: 'update', args: '--from=<id> --prompt="<context>"',
desc: 'Update tasks based on new requirements' },
{ name: 'add-task', args: '--prompt="<text>" [--dependencies=<ids>] [--priority=<priority>]',
desc: 'Add a new task using AI' },
{ name: 'add-dependency', args: '--id=<id> --depends-on=<id>',
desc: 'Add a dependency to a task' },
{ name: 'remove-dependency', args: '--id=<id> --depends-on=<id>',
desc: 'Remove a dependency from a task' }
]
},
{
title: 'Task Analysis & Detail',
color: 'yellow',
commands: [
{ name: 'analyze-complexity', args: '[--research] [--threshold=5]',
desc: 'Analyze tasks and generate expansion recommendations' },
{ name: 'complexity-report', args: '[--file=<path>]',
desc: 'Display the complexity analysis report' },
{ name: 'expand', args: '--id=<id> [--num=5] [--research] [--prompt="<context>"]',
desc: 'Break down tasks into detailed subtasks' },
{ name: 'expand --all', args: '[--force] [--research]',
desc: 'Expand all pending tasks with subtasks' },
{ name: 'clear-subtasks', args: '--id=<id>',
desc: 'Remove subtasks from specified tasks' }
]
},
{
title: 'Task Navigation & Viewing',
color: 'magenta',
commands: [
{ name: 'next', args: '',
desc: 'Show the next task to work on based on dependencies' },
{ name: 'show', args: '<id>',
desc: 'Display detailed information about a specific task' }
]
},
{
title: 'Dependency Management',
color: 'blue',
commands: [
{ name: 'validate-dependencies', args: '',
desc: 'Identify invalid dependencies without fixing them' },
{ name: 'fix-dependencies', args: '',
desc: 'Fix invalid dependencies automatically' }
]
}
];
// Display each category
commandCategories.forEach(category => {
console.log(boxen(
chalk[category.color].bold(category.title),
{
padding: { left: 2, right: 2, top: 0, bottom: 0 },
margin: { top: 1, bottom: 0 },
borderColor: category.color,
borderStyle: 'round'
}
));
const commandTable = new Table({
colWidths: [25, 40, 45],
chars: {
'top': '', 'top-mid': '', 'top-left': '', 'top-right': '',
'bottom': '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
'left': '', 'left-mid': '', 'mid': '', 'mid-mid': '',
'right': '', 'right-mid': '', 'middle': ' '
},
style: { border: [], 'padding-left': 4 }
});
category.commands.forEach((cmd, index) => {
commandTable.push([
`${chalk.yellow.bold(cmd.name)}${chalk.reset('')}`,
`${chalk.white(cmd.args)}${chalk.reset('')}`,
`${chalk.dim(cmd.desc)}${chalk.reset('')}`
]);
});
console.log(commandTable.toString());
console.log('');
});
// Display environment variables section
console.log(boxen(
chalk.cyan.bold('Environment Variables'),
{
padding: { left: 2, right: 2, top: 0, bottom: 0 },
margin: { top: 1, bottom: 0 },
borderColor: 'cyan',
borderStyle: 'round'
}
));
const envTable = new Table({
colWidths: [30, 50, 30],
chars: {
'top': '', 'top-mid': '', 'top-left': '', 'top-right': '',
'bottom': '', 'bottom-mid': '', 'bottom-left': '', 'bottom-right': '',
'left': '', 'left-mid': '', 'mid': '', 'mid-mid': '',
'right': '', 'right-mid': '', 'middle': ' '
},
style: { border: [], 'padding-left': 4 }
});
envTable.push(
[`${chalk.yellow('ANTHROPIC_API_KEY')}${chalk.reset('')}`,
`${chalk.white('Your Anthropic API key')}${chalk.reset('')}`,
`${chalk.dim('Required')}${chalk.reset('')}`],
[`${chalk.yellow('MODEL')}${chalk.reset('')}`,
`${chalk.white('Claude model to use')}${chalk.reset('')}`,
`${chalk.dim(`Default: ${CONFIG.model}`)}${chalk.reset('')}`],
[`${chalk.yellow('MAX_TOKENS')}${chalk.reset('')}`,
`${chalk.white('Maximum tokens for responses')}${chalk.reset('')}`,
`${chalk.dim(`Default: ${CONFIG.maxTokens}`)}${chalk.reset('')}`],
[`${chalk.yellow('TEMPERATURE')}${chalk.reset('')}`,
`${chalk.white('Temperature for model responses')}${chalk.reset('')}`,
`${chalk.dim(`Default: ${CONFIG.temperature}`)}${chalk.reset('')}`],
[`${chalk.yellow('PERPLEXITY_API_KEY')}${chalk.reset('')}`,
`${chalk.white('Perplexity API key for research')}${chalk.reset('')}`,
`${chalk.dim('Optional')}${chalk.reset('')}`],
[`${chalk.yellow('PERPLEXITY_MODEL')}${chalk.reset('')}`,
`${chalk.white('Perplexity model to use')}${chalk.reset('')}`,
`${chalk.dim('Default: sonar-small-online')}${chalk.reset('')}`],
[`${chalk.yellow('DEBUG')}${chalk.reset('')}`,
`${chalk.white('Enable debug logging')}${chalk.reset('')}`,
`${chalk.dim(`Default: ${CONFIG.debug}`)}${chalk.reset('')}`],
[`${chalk.yellow('LOG_LEVEL')}${chalk.reset('')}`,
`${chalk.white('Console output level (debug,info,warn,error)')}${chalk.reset('')}`,
`${chalk.dim(`Default: ${CONFIG.logLevel}`)}${chalk.reset('')}`],
[`${chalk.yellow('DEFAULT_SUBTASKS')}${chalk.reset('')}`,
`${chalk.white('Default number of subtasks to generate')}${chalk.reset('')}`,
`${chalk.dim(`Default: ${CONFIG.defaultSubtasks}`)}${chalk.reset('')}`],
[`${chalk.yellow('DEFAULT_PRIORITY')}${chalk.reset('')}`,
`${chalk.white('Default task priority')}${chalk.reset('')}`,
`${chalk.dim(`Default: ${CONFIG.defaultPriority}`)}${chalk.reset('')}`],
[`${chalk.yellow('PROJECT_NAME')}${chalk.reset('')}`,
`${chalk.white('Project name displayed in UI')}${chalk.reset('')}`,
`${chalk.dim(`Default: ${CONFIG.projectName}`)}${chalk.reset('')}`]
);
console.log(envTable.toString());
console.log('');
}
/**
* Get colored complexity score
* @param {number} score - Complexity score (1-10)
* @returns {string} Colored complexity score
*/
function getComplexityWithColor(score) {
if (score <= 3) return chalk.green(score.toString());
if (score <= 6) return chalk.yellow(score.toString());
return chalk.red(score.toString());
}
/**
* Display the next task to work on
* @param {string} tasksPath - Path to the tasks.json file
*/
async function displayNextTask(tasksPath) {
displayBanner();
// Read the tasks file
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
log('error', "No valid tasks found.");
process.exit(1);
}
// Find the next task
const nextTask = findNextTask(data.tasks);
if (!nextTask) {
console.log(boxen(
chalk.yellow('No eligible tasks found!\n\n') +
'All pending tasks have unsatisfied dependencies, or all tasks are completed.',
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
));
return;
}
// Display the task in a nice format
console.log(boxen(
chalk.white.bold(`Next Task: #${nextTask.id} - ${nextTask.title}`),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
));
// Create a table with task details
const taskTable = new Table({
style: {
head: [],
border: [],
'padding-top': 0,
'padding-bottom': 0,
compact: true
},
chars: {
'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''
},
colWidths: [15, 75]
});
// Priority with color
const priorityColors = {
'high': chalk.red.bold,
'medium': chalk.yellow,
'low': chalk.gray
};
const priorityColor = priorityColors[nextTask.priority || 'medium'] || chalk.white;
// Add task details to table
taskTable.push(
[chalk.cyan.bold('ID:'), nextTask.id.toString()],
[chalk.cyan.bold('Title:'), nextTask.title],
[chalk.cyan.bold('Priority:'), priorityColor(nextTask.priority || 'medium')],
[chalk.cyan.bold('Dependencies:'), formatDependenciesWithStatus(nextTask.dependencies, data.tasks, true)],
[chalk.cyan.bold('Description:'), nextTask.description]
);
console.log(taskTable.toString());
// If task has details, show them in a separate box
if (nextTask.details && nextTask.details.trim().length > 0) {
console.log(boxen(
chalk.white.bold('Implementation Details:') + '\n\n' +
nextTask.details,
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
));
}
// Show subtasks if they exist
if (nextTask.subtasks && nextTask.subtasks.length > 0) {
console.log(boxen(
chalk.white.bold('Subtasks'),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, margin: { top: 1, bottom: 0 }, borderColor: 'magenta', borderStyle: 'round' }
));
// Create a table for subtasks
const subtaskTable = new Table({
head: [
chalk.magenta.bold('ID'),
chalk.magenta.bold('Status'),
chalk.magenta.bold('Title'),
chalk.magenta.bold('Dependencies')
],
colWidths: [6, 12, 50, 20],
style: {
head: [],
border: [],
'padding-top': 0,
'padding-bottom': 0,
compact: true
},
chars: {
'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''
}
});
// Add subtasks to table
nextTask.subtasks.forEach(st => {
const statusColor = {
'done': chalk.green,
'completed': chalk.green,
'pending': chalk.yellow,
'in-progress': chalk.blue
}[st.status || 'pending'] || chalk.white;
// Format subtask dependencies
let subtaskDeps = 'None';
if (st.dependencies && st.dependencies.length > 0) {
// Format dependencies with correct notation
const formattedDeps = st.dependencies.map(depId => {
if (typeof depId === 'number' && depId < 100) {
return `${nextTask.id}.${depId}`;
}
return depId;
});
subtaskDeps = formatDependenciesWithStatus(formattedDeps, data.tasks, true);
}
subtaskTable.push([
`${nextTask.id}.${st.id}`,
statusColor(st.status || 'pending'),
st.title,
subtaskDeps
]);
});
console.log(subtaskTable.toString());
} else {
// Suggest expanding if no subtasks
console.log(boxen(
chalk.yellow('No subtasks found. Consider breaking down this task:') + '\n' +
chalk.white(`Run: ${chalk.cyan(`task-master expand --id=${nextTask.id}`)}`),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
));
}
// Show action suggestions
console.log(boxen(
chalk.white.bold('Suggested Actions:') + '\n' +
`${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`task-master set-status --id=${nextTask.id} --status=in-progress`)}\n` +
`${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`task-master set-status --id=${nextTask.id} --status=done`)}\n` +
(nextTask.subtasks && nextTask.subtasks.length > 0
? `${chalk.cyan('3.')} Update subtask status: ${chalk.yellow(`task-master set-status --id=${nextTask.id}.1 --status=done`)}`
: `${chalk.cyan('3.')} Break down into subtasks: ${chalk.yellow(`task-master expand --id=${nextTask.id}`)}`),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
));
}
/**
* Display a specific task by ID
* @param {string} tasksPath - Path to the tasks.json file
* @param {string|number} taskId - The ID of the task to display
*/
async function displayTaskById(tasksPath, taskId) {
displayBanner();
// Read the tasks file
const data = readJSON(tasksPath);
if (!data || !data.tasks) {
log('error', "No valid tasks found.");
process.exit(1);
}
// Find the task by ID
const task = findTaskById(data.tasks, taskId);
if (!task) {
console.log(boxen(
chalk.yellow(`Task with ID ${taskId} not found!`),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
));
return;
}
// Handle subtask display specially
if (task.isSubtask || task.parentTask) {
console.log(boxen(
chalk.white.bold(`Subtask: #${task.parentTask.id}.${task.id} - ${task.title}`),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'magenta', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
));
// Create a table with subtask details
const taskTable = new Table({
style: {
head: [],
border: [],
'padding-top': 0,
'padding-bottom': 0,
compact: true
},
chars: {
'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''
},
colWidths: [15, 75]
});
// Add subtask details to table
taskTable.push(
[chalk.cyan.bold('ID:'), `${task.parentTask.id}.${task.id}`],
[chalk.cyan.bold('Parent Task:'), `#${task.parentTask.id} - ${task.parentTask.title}`],
[chalk.cyan.bold('Title:'), task.title],
[chalk.cyan.bold('Status:'), getStatusWithColor(task.status || 'pending')],
[chalk.cyan.bold('Description:'), task.description || 'No description provided.']
);
console.log(taskTable.toString());
// Show action suggestions for subtask
console.log(boxen(
chalk.white.bold('Suggested Actions:') + '\n' +
`${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`task-master set-status --id=${task.parentTask.id}.${task.id} --status=in-progress`)}\n` +
`${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`task-master set-status --id=${task.parentTask.id}.${task.id} --status=done`)}\n` +
`${chalk.cyan('3.')} View parent task: ${chalk.yellow(`task-master show --id=${task.parentTask.id}`)}`,
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
));
return;
}
// Display a regular task
console.log(boxen(
chalk.white.bold(`Task: #${task.id} - ${task.title}`),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
));
// Create a table with task details
const taskTable = new Table({
style: {
head: [],
border: [],
'padding-top': 0,
'padding-bottom': 0,
compact: true
},
chars: {
'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''
},
colWidths: [15, 75]
});
// Priority with color
const priorityColors = {
'high': chalk.red.bold,
'medium': chalk.yellow,
'low': chalk.gray
};
const priorityColor = priorityColors[task.priority || 'medium'] || chalk.white;
// Add task details to table
taskTable.push(
[chalk.cyan.bold('ID:'), task.id.toString()],
[chalk.cyan.bold('Title:'), task.title],
[chalk.cyan.bold('Status:'), getStatusWithColor(task.status || 'pending')],
[chalk.cyan.bold('Priority:'), priorityColor(task.priority || 'medium')],
[chalk.cyan.bold('Dependencies:'), formatDependenciesWithStatus(task.dependencies, data.tasks, true)],
[chalk.cyan.bold('Description:'), task.description]
);
console.log(taskTable.toString());
// If task has details, show them in a separate box
if (task.details && task.details.trim().length > 0) {
console.log(boxen(
chalk.white.bold('Implementation Details:') + '\n\n' +
task.details,
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
));
}
// Show test strategy if available
if (task.testStrategy && task.testStrategy.trim().length > 0) {
console.log(boxen(
chalk.white.bold('Test Strategy:') + '\n\n' +
task.testStrategy,
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
));
}
// Show subtasks if they exist
if (task.subtasks && task.subtasks.length > 0) {
console.log(boxen(
chalk.white.bold('Subtasks'),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, margin: { top: 1, bottom: 0 }, borderColor: 'magenta', borderStyle: 'round' }
));
// Create a table for subtasks
const subtaskTable = new Table({
head: [
chalk.magenta.bold('ID'),
chalk.magenta.bold('Status'),
chalk.magenta.bold('Title'),
chalk.magenta.bold('Dependencies')
],
colWidths: [6, 12, 50, 20],
style: {
head: [],
border: [],
'padding-top': 0,
'padding-bottom': 0,
compact: true
},
chars: {
'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''
}
});
// Add subtasks to table
task.subtasks.forEach(st => {
const statusColor = {
'done': chalk.green,
'completed': chalk.green,
'pending': chalk.yellow,
'in-progress': chalk.blue
}[st.status || 'pending'] || chalk.white;
// Format subtask dependencies
let subtaskDeps = 'None';
if (st.dependencies && st.dependencies.length > 0) {
// Format dependencies with correct notation
const formattedDeps = st.dependencies.map(depId => {
if (typeof depId === 'number' && depId < 100) {
return `${task.id}.${depId}`;
}
return depId;
});
subtaskDeps = formatDependenciesWithStatus(formattedDeps, data.tasks, true);
}
subtaskTable.push([
`${task.id}.${st.id}`,
statusColor(st.status || 'pending'),
st.title,
subtaskDeps
]);
});
console.log(subtaskTable.toString());
} else {
// Suggest expanding if no subtasks
console.log(boxen(
chalk.yellow('No subtasks found. Consider breaking down this task:') + '\n' +
chalk.white(`Run: ${chalk.cyan(`task-master expand --id=${task.id}`)}`),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1, bottom: 0 } }
));
}
// Show action suggestions
console.log(boxen(
chalk.white.bold('Suggested Actions:') + '\n' +
`${chalk.cyan('1.')} Mark as in-progress: ${chalk.yellow(`task-master set-status --id=${task.id} --status=in-progress`)}\n` +
`${chalk.cyan('2.')} Mark as done when completed: ${chalk.yellow(`task-master set-status --id=${task.id} --status=done`)}\n` +
(task.subtasks && task.subtasks.length > 0
? `${chalk.cyan('3.')} Update subtask status: ${chalk.yellow(`task-master set-status --id=${task.id}.1 --status=done`)}`
: `${chalk.cyan('3.')} Break down into subtasks: ${chalk.yellow(`task-master expand --id=${task.id}`)}`),
{ padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'green', borderStyle: 'round', margin: { top: 1 } }
));
}
/**
* Display the complexity analysis report in a nice format
* @param {string} reportPath - Path to the complexity report file
*/
async function displayComplexityReport(reportPath) {
displayBanner();
// Check if the report exists
if (!fs.existsSync(reportPath)) {
console.log(boxen(
chalk.yellow(`No complexity report found at ${reportPath}\n\n`) +
'Would you like to generate one now?',
{ padding: 1, borderColor: 'yellow', borderStyle: 'round', margin: { top: 1 } }
));
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const answer = await new Promise(resolve => {
readline.question(chalk.cyan('Generate complexity report? (y/n): '), resolve);
});
readline.close();
if (answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes') {
// Call the analyze-complexity command
console.log(chalk.blue('Generating complexity report...'));
await analyzeTaskComplexity({
output: reportPath,
research: false, // Default to no research for speed
file: 'tasks/tasks.json'
});
// Read the newly generated report
return displayComplexityReport(reportPath);
} else {
console.log(chalk.yellow('Report generation cancelled.'));
return;
}
}
// Read the report
let report;
try {
report = JSON.parse(fs.readFileSync(reportPath, 'utf8'));
} catch (error) {
log('error', `Error reading complexity report: ${error.message}`);
return;
}
// Display report header
console.log(boxen(
chalk.white.bold('Task Complexity Analysis Report'),
{ padding: 1, borderColor: 'blue', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
));
// Display metadata
const metaTable = new Table({
style: {
head: [],
border: [],
'padding-top': 0,
'padding-bottom': 0,
compact: true
},
chars: {
'mid': '', 'left-mid': '', 'mid-mid': '', 'right-mid': ''
},
colWidths: [20, 50]
});
metaTable.push(
[chalk.cyan.bold('Generated:'), new Date(report.meta.generatedAt).toLocaleString()],
[chalk.cyan.bold('Tasks Analyzed:'), report.meta.tasksAnalyzed],
[chalk.cyan.bold('Threshold Score:'), report.meta.thresholdScore],
[chalk.cyan.bold('Project:'), report.meta.projectName],
[chalk.cyan.bold('Research-backed:'), report.meta.usedResearch ? 'Yes' : 'No']
);
console.log(metaTable.toString());
// Sort tasks by complexity score (highest first)
const sortedTasks = [...report.complexityAnalysis].sort((a, b) => b.complexityScore - a.complexityScore);
// Determine which tasks need expansion based on threshold
const tasksNeedingExpansion = sortedTasks.filter(task => task.complexityScore >= report.meta.thresholdScore);
const simpleTasks = sortedTasks.filter(task => task.complexityScore < report.meta.thresholdScore);
// Create progress bar to show complexity distribution
const complexityDistribution = [0, 0, 0]; // Low (0-4), Medium (5-7), High (8-10)
sortedTasks.forEach(task => {
if (task.complexityScore < 5) complexityDistribution[0]++;
else if (task.complexityScore < 8) complexityDistribution[1]++;
else complexityDistribution[2]++;
});
const percentLow = Math.round((complexityDistribution[0] / sortedTasks.length) * 100);
const percentMedium = Math.round((complexityDistribution[1] / sortedTasks.length) * 100);
const percentHigh = Math.round((complexityDistribution[2] / sortedTasks.length) * 100);
console.log(boxen(
chalk.white.bold('Complexity Distribution\n\n') +
`${chalk.green.bold('Low (1-4):')} ${complexityDistribution[0]} tasks (${percentLow}%)\n` +
`${chalk.yellow.bold('Medium (5-7):')} ${complexityDistribution[1]} tasks (${percentMedium}%)\n` +
`${chalk.red.bold('High (8-10):')} ${complexityDistribution[2]} tasks (${percentHigh}%)`,
{ padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1, bottom: 1 } }
));
// Create table for tasks that need expansion
if (tasksNeedingExpansion.length > 0) {
console.log(boxen(
chalk.yellow.bold(`Tasks Recommended for Expansion (${tasksNeedingExpansion.length})`),
{ padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'yellow', borderStyle: 'round' }
));
const complexTable = new Table({
head: [
chalk.yellow.bold('ID'),
chalk.yellow.bold('Title'),
chalk.yellow.bold('Score'),
chalk.yellow.bold('Subtasks'),
chalk.yellow.bold('Expansion Command')
],
colWidths: [5, 40, 8, 10, 45],
style: { head: [], border: [] }
});
tasksNeedingExpansion.forEach(task => {
complexTable.push([
task.taskId,
truncate(task.taskTitle, 37),
getComplexityWithColor(task.complexityScore),
task.recommendedSubtasks,
chalk.cyan(`task-master expand --id=${task.taskId} --num=${task.recommendedSubtasks}`)
]);
});
console.log(complexTable.toString());
}
// Create table for simple tasks
if (simpleTasks.length > 0) {
console.log(boxen(
chalk.green.bold(`Simple Tasks (${simpleTasks.length})`),
{ padding: { left: 2, right: 2, top: 0, bottom: 0 }, margin: { top: 1, bottom: 0 }, borderColor: 'green', borderStyle: 'round' }
));
const simpleTable = new Table({
head: [
chalk.green.bold('ID'),
chalk.green.bold('Title'),
chalk.green.bold('Score'),
chalk.green.bold('Reasoning')
],
colWidths: [5, 40, 8, 50],
style: { head: [], border: [] }
});
simpleTasks.forEach(task => {
simpleTable.push([
task.taskId,
truncate(task.taskTitle, 37),
getComplexityWithColor(task.complexityScore),
truncate(task.reasoning, 47)
]);
});
console.log(simpleTable.toString());
}
// Show action suggestions
console.log(boxen(
chalk.white.bold('Suggested Actions:') + '\n\n' +
`${chalk.cyan('1.')} Expand all complex tasks: ${chalk.yellow(`task-master expand --all`)}\n` +
`${chalk.cyan('2.')} Expand a specific task: ${chalk.yellow(`task-master expand --id=<id>`)}\n` +
`${chalk.cyan('3.')} Regenerate with research: ${chalk.yellow(`task-master analyze-complexity --research`)}`,
{ padding: 1, borderColor: 'cyan', borderStyle: 'round', margin: { top: 1 } }
));
}
// Export UI functions
export {
displayBanner,
startLoadingIndicator,
stopLoadingIndicator,
createProgressBar,
getStatusWithColor,
formatDependenciesWithStatus,
displayHelp,
getComplexityWithColor,
displayNextTask,
displayTaskById,
displayComplexityReport,
};

283
scripts/modules/utils.js Normal file
View File

@@ -0,0 +1,283 @@
/**
* utils.js
* Utility functions for the Task Master CLI
*/
import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
// Configuration and constants
const CONFIG = {
model: process.env.MODEL || 'claude-3-7-sonnet-20250219',
maxTokens: parseInt(process.env.MAX_TOKENS || '4000'),
temperature: parseFloat(process.env.TEMPERATURE || '0.7'),
debug: process.env.DEBUG === "true",
logLevel: process.env.LOG_LEVEL || "info",
defaultSubtasks: parseInt(process.env.DEFAULT_SUBTASKS || "3"),
defaultPriority: process.env.DEFAULT_PRIORITY || "medium",
projectName: process.env.PROJECT_NAME || "Task Master",
projectVersion: "1.5.0" // Hardcoded version - ALWAYS use this value, ignore environment variable
};
// Set up logging based on log level
const LOG_LEVELS = {
debug: 0,
info: 1,
warn: 2,
error: 3
};
/**
* Logs a message at the specified level
* @param {string} level - The log level (debug, info, warn, error)
* @param {...any} args - Arguments to log
*/
function log(level, ...args) {
const icons = {
debug: chalk.gray('🔍'),
info: chalk.blue(''),
warn: chalk.yellow('⚠️'),
error: chalk.red('❌'),
success: chalk.green('✅')
};
if (LOG_LEVELS[level] >= LOG_LEVELS[CONFIG.logLevel]) {
const icon = icons[level] || '';
console.log(`${icon} ${args.join(' ')}`);
}
}
/**
* Reads and parses a JSON file
* @param {string} filepath - Path to the JSON file
* @returns {Object} Parsed JSON data
*/
function readJSON(filepath) {
try {
const rawData = fs.readFileSync(filepath, 'utf8');
return JSON.parse(rawData);
} catch (error) {
log('error', `Error reading JSON file ${filepath}:`, error.message);
if (CONFIG.debug) {
console.error(error);
}
return null;
}
}
/**
* Writes data to a JSON file
* @param {string} filepath - Path to the JSON file
* @param {Object} data - Data to write
*/
function writeJSON(filepath, data) {
try {
fs.writeFileSync(filepath, JSON.stringify(data, null, 2));
} catch (error) {
log('error', `Error writing JSON file ${filepath}:`, error.message);
if (CONFIG.debug) {
console.error(error);
}
}
}
/**
* Sanitizes a prompt string for use in a shell command
* @param {string} prompt The prompt to sanitize
* @returns {string} Sanitized prompt
*/
function sanitizePrompt(prompt) {
// Replace double quotes with escaped double quotes
return prompt.replace(/"/g, '\\"');
}
/**
* Reads and parses the complexity report if it exists
* @param {string} customPath - Optional custom path to the report
* @returns {Object|null} The parsed complexity report or null if not found
*/
function readComplexityReport(customPath = null) {
try {
const reportPath = customPath || path.join(process.cwd(), 'scripts', 'task-complexity-report.json');
if (!fs.existsSync(reportPath)) {
return null;
}
const reportData = fs.readFileSync(reportPath, 'utf8');
return JSON.parse(reportData);
} catch (error) {
log('warn', `Could not read complexity report: ${error.message}`);
return null;
}
}
/**
* Finds a task analysis in the complexity report
* @param {Object} report - The complexity report
* @param {number} taskId - The task ID to find
* @returns {Object|null} The task analysis or null if not found
*/
function findTaskInComplexityReport(report, taskId) {
if (!report || !report.complexityAnalysis || !Array.isArray(report.complexityAnalysis)) {
return null;
}
return report.complexityAnalysis.find(task => task.taskId === taskId);
}
/**
* Checks if a task exists in the tasks array
* @param {Array} tasks - The tasks array
* @param {string|number} taskId - The task ID to check
* @returns {boolean} True if the task exists, false otherwise
*/
function taskExists(tasks, taskId) {
if (!taskId || !tasks || !Array.isArray(tasks)) {
return false;
}
// Handle both regular task IDs and subtask IDs (e.g., "1.2")
if (typeof taskId === 'string' && taskId.includes('.')) {
const [parentId, subtaskId] = taskId.split('.').map(id => parseInt(id, 10));
const parentTask = tasks.find(t => t.id === parentId);
if (!parentTask || !parentTask.subtasks) {
return false;
}
return parentTask.subtasks.some(st => st.id === subtaskId);
}
const id = parseInt(taskId, 10);
return tasks.some(t => t.id === id);
}
/**
* Formats a task ID as a string
* @param {string|number} id - The task ID to format
* @returns {string} The formatted task ID
*/
function formatTaskId(id) {
if (typeof id === 'string' && id.includes('.')) {
return id; // Already formatted as a string with a dot (e.g., "1.2")
}
if (typeof id === 'number') {
return id.toString();
}
return id;
}
/**
* Finds a task by ID in the tasks array
* @param {Array} tasks - The tasks array
* @param {string|number} taskId - The task ID to find
* @returns {Object|null} The task object or null if not found
*/
function findTaskById(tasks, taskId) {
if (!taskId || !tasks || !Array.isArray(tasks)) {
return null;
}
// Check if it's a subtask ID (e.g., "1.2")
if (typeof taskId === 'string' && taskId.includes('.')) {
const [parentId, subtaskId] = taskId.split('.').map(id => parseInt(id, 10));
const parentTask = tasks.find(t => t.id === parentId);
if (!parentTask || !parentTask.subtasks) {
return null;
}
const subtask = parentTask.subtasks.find(st => st.id === subtaskId);
if (subtask) {
// Add reference to parent task for context
subtask.parentTask = {
id: parentTask.id,
title: parentTask.title,
status: parentTask.status
};
subtask.isSubtask = true;
}
return subtask || null;
}
const id = parseInt(taskId, 10);
return tasks.find(t => t.id === id) || null;
}
/**
* Truncates text to a specified length
* @param {string} text - The text to truncate
* @param {number} maxLength - The maximum length
* @returns {string} The truncated text
*/
function truncate(text, maxLength) {
if (!text || text.length <= maxLength) {
return text;
}
return text.slice(0, maxLength - 3) + '...';
}
/**
* Find cycles in a dependency graph using DFS
* @param {string} subtaskId - Current subtask ID
* @param {Map} dependencyMap - Map of subtask IDs to their dependencies
* @param {Set} visited - Set of visited nodes
* @param {Set} recursionStack - Set of nodes in current recursion stack
* @returns {Array} - List of dependency edges that need to be removed to break cycles
*/
function findCycles(subtaskId, dependencyMap, visited = new Set(), recursionStack = new Set(), path = []) {
// Mark the current node as visited and part of recursion stack
visited.add(subtaskId);
recursionStack.add(subtaskId);
path.push(subtaskId);
const cyclesToBreak = [];
// Get all dependencies of the current subtask
const dependencies = dependencyMap.get(subtaskId) || [];
// For each dependency
for (const depId of dependencies) {
// If not visited, recursively check for cycles
if (!visited.has(depId)) {
const cycles = findCycles(depId, dependencyMap, visited, recursionStack, [...path]);
cyclesToBreak.push(...cycles);
}
// If the dependency is in the recursion stack, we found a cycle
else if (recursionStack.has(depId)) {
// Find the position of the dependency in the path
const cycleStartIndex = path.indexOf(depId);
// The last edge in the cycle is what we want to remove
const cycleEdges = path.slice(cycleStartIndex);
// We'll remove the last edge in the cycle (the one that points back)
cyclesToBreak.push(depId);
}
}
// Remove the node from recursion stack before returning
recursionStack.delete(subtaskId);
return cyclesToBreak;
}
// Export all utility functions and configuration
export {
CONFIG,
LOG_LEVELS,
log,
readJSON,
writeJSON,
sanitizePrompt,
readComplexityReport,
findTaskInComplexityReport,
taskExists,
formatTaskId,
findTaskById,
truncate,
findCycles,
};

View File

@@ -16,69 +16,33 @@ Create the foundational data structure including:
Verify that the tasks.json structure can be created, read, and validated. Test with sample data to ensure all fields are properly handled and that validation correctly identifies invalid structures.
# Subtasks:
## Subtask ID: 1
## Title: Design JSON Schema for tasks.json
## Status: done
## Dependencies: None
## Description: Create a formal JSON Schema definition that validates the structure of the tasks.json file. The schema should enforce the data model specified in the PRD, including the Task Model and Tasks Collection Model with all required fields (id, title, description, status, dependencies, priority, details, testStrategy, subtasks). Include type validation, required fields, and constraints on enumerated values (like status and priority options).
## Acceptance Criteria:
- JSON Schema file is created with proper validation for all fields in the Task and Tasks Collection models
- Schema validates that task IDs are unique integers
- Schema enforces valid status values ("pending", "done", "deferred")
- Schema enforces valid priority values ("high", "medium", "low")
- Schema validates the nested structure of subtasks
- Schema includes validation for the meta object with projectName, version, timestamps, etc.
## 1. Design JSON Schema for tasks.json [done]
### Dependencies: None
### Description: Create a formal JSON Schema definition that validates the structure of the tasks.json file. The schema should enforce the data model specified in the PRD, including the Task Model and Tasks Collection Model with all required fields (id, title, description, status, dependencies, priority, details, testStrategy, subtasks). Include type validation, required fields, and constraints on enumerated values (like status and priority options).
### Details:
## Subtask ID: 2
## Title: Implement Task Model Classes
## Status: done
## Dependencies: 1.1 ✅
## Description: Create JavaScript classes that represent the Task and Tasks Collection models. Implement constructor methods that validate input data, getter/setter methods for properties, and utility methods for common operations (like adding subtasks, changing status, etc.). These classes will serve as the programmatic interface to the task data structure.
## Acceptance Criteria:
- Task class with all required properties from the PRD
- TasksCollection class that manages an array of Task objects
- Methods for creating, retrieving, updating tasks
- Methods for managing subtasks within a task
- Input validation in constructors and setters
- Proper TypeScript/JSDoc type definitions for all classes and methods
## Subtask ID: 3
## Title: Create File System Operations for tasks.json
## Status: done
## Dependencies: 1.1 ✅, 1.2 ✅
## Description: Implement functions to read from and write to the tasks.json file. These functions should handle file system operations asynchronously, manage file locking to prevent corruption during concurrent operations, and ensure atomic writes (using temporary files and rename operations). Include initialization logic to create a default tasks.json file if one doesn't exist.
## Acceptance Criteria:
- Asynchronous read function that parses tasks.json into model objects
- Asynchronous write function that serializes model objects to tasks.json
- File locking mechanism to prevent concurrent write operations
- Atomic write operations to prevent file corruption
- Initialization function that creates default tasks.json if not present
- Functions properly handle relative and absolute paths
## 2. Implement Task Model Classes [done]
### Dependencies: 1 (done)
### Description: Create JavaScript classes that represent the Task and Tasks Collection models. Implement constructor methods that validate input data, getter/setter methods for properties, and utility methods for common operations (like adding subtasks, changing status, etc.). These classes will serve as the programmatic interface to the task data structure.
### Details:
## 3. Create File System Operations for tasks.json [done]
### Dependencies: 1 (done), 2 (done)
### Description: Implement functions to read from and write to the tasks.json file. These functions should handle file system operations asynchronously, manage file locking to prevent corruption during concurrent operations, and ensure atomic writes (using temporary files and rename operations). Include initialization logic to create a default tasks.json file if one doesn't exist.
### Details:
## 4. Implement Validation Functions [done]
### Dependencies: 1 (done), 2 (done)
### Description: Create a comprehensive set of validation functions that can verify the integrity of the task data structure. These should include validation of individual tasks, validation of the entire tasks collection, dependency cycle detection, and validation of relationships between tasks. These functions will be used both when loading data and before saving to ensure data integrity.
### Details:
## 5. Implement Error Handling System [done]
### Dependencies: 1 (done), 3 (done), 4 (done)
### Description: Create a robust error handling system for file operations and data validation. Implement custom error classes for different types of errors (file not found, permission denied, invalid data, etc.), error logging functionality, and recovery mechanisms where appropriate. This system should provide clear, actionable error messages to users while maintaining system stability.
### Details:
## Subtask ID: 4
## Title: Implement Validation Functions
## Status: done
## Dependencies: 1.1 ✅, 1.2 ✅
## Description: Create a comprehensive set of validation functions that can verify the integrity of the task data structure. These should include validation of individual tasks, validation of the entire tasks collection, dependency cycle detection, and validation of relationships between tasks. These functions will be used both when loading data and before saving to ensure data integrity.
## Acceptance Criteria:
- Functions to validate individual task objects against schema
- Function to validate entire tasks collection
- Dependency cycle detection algorithm
- Validation of parent-child relationships in subtasks
- Validation of task ID uniqueness
- Functions return detailed error messages for invalid data
- Unit tests covering various validation scenarios
## Subtask ID: 5
## Title: Implement Error Handling System
## Status: done
## Dependencies: 1.1 ✅, 1.3 ✅, 1.4 ✅
## Description: Create a robust error handling system for file operations and data validation. Implement custom error classes for different types of errors (file not found, permission denied, invalid data, etc.), error logging functionality, and recovery mechanisms where appropriate. This system should provide clear, actionable error messages to users while maintaining system stability.
## Acceptance Criteria:
- Custom error classes for different error types (FileError, ValidationError, etc.)
- Consistent error format with error code, message, and details
- Error logging functionality with configurable verbosity
- Recovery mechanisms for common error scenarios
- Graceful degradation when non-critical errors occur
- User-friendly error messages that suggest solutions
- Unit tests for error handling in various scenarios

View File

@@ -1,7 +1,7 @@
# Task ID: 2
# Title: Develop Command Line Interface Foundation
# Status: done
# Dependencies: 1
# Dependencies: ✅ 1 (done)
# Priority: high
# Description: Create the basic CLI structure using Commander.js with command parsing and help documentation.
# Details:
@@ -16,69 +16,33 @@ Implement the CLI foundation including:
Test each command with various parameters to ensure proper parsing. Verify help documentation is comprehensive and accurate. Test logging at different verbosity levels.
# Subtasks:
## Subtask ID: 1
## Title: Set up Commander.js Framework
## Status: done
## Dependencies: None
## Description: Initialize and configure Commander.js as the command-line parsing framework. Create the main CLI entry point file that will serve as the application's command-line interface. Set up the basic command structure with program name, version, and description from package.json. Implement the core program flow including command registration pattern and error handling.
## Acceptance Criteria:
- Commander.js is properly installed and configured in the project
- CLI entry point file is created with proper Node.js shebang and permissions
- Program metadata (name, version, description) is correctly loaded from package.json
- Basic command registration pattern is established
- Global error handling is implemented to catch and display unhandled exceptions
## 1. Set up Commander.js Framework [done]
### Dependencies: None
### Description: Initialize and configure Commander.js as the command-line parsing framework. Create the main CLI entry point file that will serve as the application's command-line interface. Set up the basic command structure with program name, version, and description from package.json. Implement the core program flow including command registration pattern and error handling.
### Details:
## Subtask ID: 2
## Title: Implement Global Options Handling
## Status: done
## Dependencies: 2.1 ✅
## Description: Add support for all required global options including --help, --version, --file, --quiet, --debug, and --json. Implement the logic to process these options and modify program behavior accordingly. Create a configuration object that stores these settings and can be accessed by all commands. Ensure options can be combined and have appropriate precedence rules.
## Acceptance Criteria:
- All specified global options (--help, --version, --file, --quiet, --debug, --json) are implemented
- Options correctly modify program behavior when specified
- Alternative tasks.json file can be specified with --file option
- Output verbosity is controlled by --quiet and --debug flags
- JSON output format is supported with the --json flag
- Help text is displayed when --help is specified
- Version information is displayed when --version is specified
## Subtask ID: 3
## Title: Create Command Help Documentation System
## Status: done
## Dependencies: 2.1 ✅, 2.2 ✅
## Description: Develop a comprehensive help documentation system that provides clear usage instructions for all commands and options. Implement both command-specific help and general program help. Ensure help text is well-formatted, consistent, and includes examples. Create a centralized system for managing help text to ensure consistency across the application.
## Acceptance Criteria:
- General program help shows all available commands and global options
- Command-specific help shows detailed usage information for each command
- Help text includes clear examples of command usage
- Help formatting is consistent and readable across all commands
- Help system handles both explicit help requests (--help) and invalid command syntax
## 2. Implement Global Options Handling [done]
### Dependencies: 1 (done)
### Description: Add support for all required global options including --help, --version, --file, --quiet, --debug, and --json. Implement the logic to process these options and modify program behavior accordingly. Create a configuration object that stores these settings and can be accessed by all commands. Ensure options can be combined and have appropriate precedence rules.
### Details:
## Subtask ID: 4
## Title: Implement Colorized Console Output
## Status: done
## Dependencies: 2.1 ✅
## Description: Create a utility module for colorized console output to improve readability and user experience. Implement different color schemes for various message types (info, warning, error, success). Add support for text styling (bold, underline, etc.) and ensure colors are used consistently throughout the application. Make sure colors can be disabled in environments that don't support them.
## Acceptance Criteria:
- Utility module provides consistent API for colorized output
- Different message types (info, warning, error, success) use appropriate colors
- Text styling options (bold, underline, etc.) are available
- Colors are disabled automatically in environments that don't support them
- Color usage is consistent across the application
- Output remains readable when colors are disabled
## Subtask ID: 5
## Title: Develop Configurable Logging System
## Status: done
## Dependencies: 2.1 ✅, 2.2 ✅, 2.4 ✅
## Description: Create a logging system with configurable verbosity levels that integrates with the CLI. Implement different logging levels (error, warn, info, debug, trace) and ensure log output respects the verbosity settings specified by global options. Add support for log output redirection to files. Ensure logs include appropriate timestamps and context information.
## Acceptance Criteria:
- Logging system supports multiple verbosity levels (error, warn, info, debug, trace)
- Log output respects verbosity settings from global options (--quiet, --debug)
- Logs include timestamps and appropriate context information
- Log messages use consistent formatting and appropriate colors
- Logging can be redirected to files when needed
- Debug logs provide detailed information useful for troubleshooting
- Logging system has minimal performance impact when not in use
## 3. Create Command Help Documentation System [done]
### Dependencies: 1 (done), 2 (done)
### Description: Develop a comprehensive help documentation system that provides clear usage instructions for all commands and options. Implement both command-specific help and general program help. Ensure help text is well-formatted, consistent, and includes examples. Create a centralized system for managing help text to ensure consistency across the application.
### Details:
## 4. Implement Colorized Console Output [done]
### Dependencies: 1 (done)
### Description: Create a utility module for colorized console output to improve readability and user experience. Implement different color schemes for various message types (info, warning, error, success). Add support for text styling (bold, underline, etc.) and ensure colors are used consistently throughout the application. Make sure colors can be disabled in environments that don't support them.
### Details:
## 5. Develop Configurable Logging System [done]
### Dependencies: 1 (done), 2 (done), 4 (done)
### Description: Create a logging system with configurable verbosity levels that integrates with the CLI. Implement different logging levels (error, warn, info, debug, trace) and ensure log output respects the verbosity settings specified by global options. Add support for log output redirection to files. Ensure logs include appropriate timestamps and context information.
### Details:
Each of these subtasks directly addresses a component of the CLI foundation as specified in the task description, and together they provide a complete implementation of the required functionality. The subtasks are ordered in a logical sequence that respects their dependencies.

View File

@@ -1,7 +1,7 @@
# Task ID: 3
# Title: Implement Basic Task Operations
# Status: done
# Dependencies: 1 ✅, 2 ✅
# Dependencies: ✅ 1 (done), ✅ 2 (done)
# Priority: high
# Description: Create core functionality for managing tasks including listing, creating, updating, and deleting tasks.
# Details:
@@ -18,50 +18,39 @@ Implement the following task operations:
Test each operation with valid and invalid inputs. Verify that dependencies are properly tracked and that status changes are reflected correctly in the tasks.json file.
# Subtasks:
## Subtask ID: 1
## Title: Implement Task Listing with Filtering
## Status: done
## Dependencies: None
## Description: Create a function that retrieves tasks from the tasks.json file and implements filtering options. Use the Commander.js CLI to add a 'list' command with various filter flags (e.g., --status, --priority, --dependency). Implement sorting options for the list output.
## Acceptance Criteria:
- 'list' command is available in the CLI with help documentation
## 1. Implement Task Listing with Filtering [done]
### Dependencies: None
### Description: Create a function that retrieves tasks from the tasks.json file and implements filtering options. Use the Commander.js CLI to add a 'list' command with various filter flags (e.g., --status, --priority, --dependency). Implement sorting options for the list output.
### Details:
## Subtask ID: 2
## Title: Develop Task Creation Functionality
## Status: done
## Dependencies: 3.1 ✅
## Description: Implement a 'create' command in the CLI that allows users to add new tasks to the tasks.json file. Prompt for required fields (title, description, priority) and optional fields (dependencies, details, test strategy). Validate input and assign a unique ID to the new task.
## Acceptance Criteria:
- 'create' command is available with interactive prompts for task details
## Subtask ID: 3
## Title: Implement Task Update Operations
## Status: done
## Dependencies: 3.1 ✅, 3.2 ✅
## Description: Create an 'update' command that allows modification of existing task properties. Implement options to update individual fields or enter an interactive mode for multiple updates. Ensure that updates maintain data integrity, especially for dependencies.
## Acceptance Criteria:
- 'update' command accepts a task ID and field-specific flags for quick updates
## 2. Develop Task Creation Functionality [done]
### Dependencies: 1 (done)
### Description: Implement a 'create' command in the CLI that allows users to add new tasks to the tasks.json file. Prompt for required fields (title, description, priority) and optional fields (dependencies, details, test strategy). Validate input and assign a unique ID to the new task.
### Details:
## Subtask ID: 4
## Title: Develop Task Deletion Functionality
## Status: done
## Dependencies: 3.1 ✅, 3.2 ✅, 3.3 ✅
## Description: Implement a 'delete' command to remove tasks from tasks.json. Include safeguards against deleting tasks with dependencies and provide a force option to override. Update any tasks that had the deleted task as a dependency.
## Acceptance Criteria:
- 'delete' command removes the specified task from tasks.json
## Subtask ID: 5
## Title: Implement Task Status Management
## Status: done
## Dependencies: 3.1 ✅, 3.2 ✅, 3.3 ✅
## Description: Create a 'status' command to change the status of tasks (pending/done/deferred). Implement logic to handle status changes, including updating dependent tasks if necessary. Add a batch mode for updating multiple task statuses at once.
## Acceptance Criteria:
- 'status' command changes task status correctly in tasks.json
## 3. Implement Task Update Operations [done]
### Dependencies: 1 (done), 2 (done)
### Description: Create an 'update' command that allows modification of existing task properties. Implement options to update individual fields or enter an interactive mode for multiple updates. Ensure that updates maintain data integrity, especially for dependencies.
### Details:
## 4. Develop Task Deletion Functionality [done]
### Dependencies: 1 (done), 2 (done), 3 (done)
### Description: Implement a 'delete' command to remove tasks from tasks.json. Include safeguards against deleting tasks with dependencies and provide a force option to override. Update any tasks that had the deleted task as a dependency.
### Details:
## 5. Implement Task Status Management [done]
### Dependencies: 1 (done), 2 (done), 3 (done)
### Description: Create a 'status' command to change the status of tasks (pending/done/deferred). Implement logic to handle status changes, including updating dependent tasks if necessary. Add a batch mode for updating multiple task statuses at once.
### Details:
## 6. Develop Task Dependency and Priority Management [done]
### Dependencies: 1 (done), 2 (done), 3 (done)
### Description: Implement 'dependency' and 'priority' commands to manage task relationships and importance. Create functions to add/remove dependencies and change priorities. Ensure the system prevents circular dependencies and maintains consistent priority levels.
### Details:
## Subtask ID: 6
## Title: Develop Task Dependency and Priority Management
## Status: done
## Dependencies: 3.1 ✅, 3.2 ✅, 3.3 ✅
## Description: Implement 'dependency' and 'priority' commands to manage task relationships and importance. Create functions to add/remove dependencies and change priorities. Ensure the system prevents circular dependencies and maintains consistent priority levels.
## Acceptance Criteria:
- 'dependency' command can add or remove task dependencies

View File

@@ -1,7 +1,7 @@
# Task ID: 4
# Title: Create Task File Generation System
# Status: done
# Dependencies: 1 ✅, 3 ✅
# Dependencies: ✅ 1 (done), ✅ 3 (done)
# Priority: medium
# Description: Implement the system for generating individual task files from the tasks.json data structure.
# Details:
@@ -16,72 +16,33 @@ Build the task file generation system including:
Generate task files from sample tasks.json data and verify the content matches the expected format. Test synchronization by modifying task files and ensuring changes are reflected in tasks.json.
# Subtasks:
## Subtask ID: 1
## Title: Design Task File Template Structure
## Status: done
## Dependencies: None
## Description: Create the template structure for individual task files that will be generated from tasks.json. This includes defining the format with sections for task ID, title, status, dependencies, priority, description, details, test strategy, and subtasks. Implement a template engine or string formatting system that can populate these templates with task data. The template should follow the format specified in the PRD's Task File Format section.
## Acceptance Criteria:
- Template structure matches the specification in the PRD
- Template includes all required sections (ID, title, status, dependencies, etc.)
- Template supports proper formatting of multi-line content like details and test strategy
- Template handles subtasks correctly, including proper indentation and formatting
- Template system is modular and can be easily modified if requirements change
## 1. Design Task File Template Structure [done]
### Dependencies: None
### Description: Create the template structure for individual task files that will be generated from tasks.json. This includes defining the format with sections for task ID, title, status, dependencies, priority, description, details, test strategy, and subtasks. Implement a template engine or string formatting system that can populate these templates with task data. The template should follow the format specified in the PRD's Task File Format section.
### Details:
## Subtask ID: 2
## Title: Implement Task File Generation Logic
## Status: done
## Dependencies: 4.1 ✅
## Description: Develop the core functionality to generate individual task files from the tasks.json data structure. This includes reading the tasks.json file, iterating through each task, applying the template to each task's data, and writing the resulting content to appropriately named files in the tasks directory. Ensure proper error handling for file operations and data validation.
## Acceptance Criteria:
- Successfully reads tasks from tasks.json
- Correctly applies template to each task's data
- Generates files with proper naming convention (e.g., task_001.txt)
- Creates the tasks directory if it doesn't exist
- Handles errors gracefully (file not found, permission issues, etc.)
- Validates task data before generation to prevent errors
- Logs generation process with appropriate verbosity levels
## Subtask ID: 3
## Title: Implement File Naming and Organization System
## Status: done
## Dependencies: 4.1 ✅
## Description: Create a consistent system for naming and organizing task files. Implement a function that generates standardized filenames based on task IDs (e.g., task_001.txt for task ID 1). Design the directory structure for storing task files according to the PRD specification. Ensure the system handles task ID formatting consistently and prevents filename collisions.
## Acceptance Criteria:
- Generates consistent filenames based on task IDs with proper zero-padding
- Creates and maintains the correct directory structure as specified in the PRD
- Handles special characters or edge cases in task IDs appropriately
- Prevents filename collisions between different tasks
- Provides utility functions for converting between task IDs and filenames
- Maintains backward compatibility if the naming scheme needs to evolve
## 2. Implement Task File Generation Logic [done]
### Dependencies: 1 (done)
### Description: Develop the core functionality to generate individual task files from the tasks.json data structure. This includes reading the tasks.json file, iterating through each task, applying the template to each task's data, and writing the resulting content to appropriately named files in the tasks directory. Ensure proper error handling for file operations and data validation.
### Details:
## Subtask ID: 4
## Title: Implement Task File to JSON Synchronization
## Status: done
## Dependencies: 4.1 ✅, 4.3 ✅, 4.2 ✅
## Description: Develop functionality to read modified task files and update the corresponding entries in tasks.json. This includes parsing the task file format, extracting structured data, validating the changes, and updating the tasks.json file accordingly. Ensure the system can handle concurrent modifications and resolve conflicts appropriately.
## Acceptance Criteria:
- Successfully parses task files to extract structured data
- Validates parsed data against the task model schema
- Updates tasks.json with changes from task files
- Handles conflicts when the same task is modified in both places
- Preserves task relationships and dependencies during synchronization
- Provides clear error messages for parsing or validation failures
- Updates the "updatedAt" timestamp in tasks.json metadata
## Subtask ID: 5
## Title: Implement Change Detection and Update Handling
## Status: done
## Dependencies: 4.1 ✅, 4.3 ✅, 4.4 ✅, 4.2 ✅
## Description: Create a system to detect changes in task files and tasks.json, and handle updates bidirectionally. This includes implementing file watching or comparison mechanisms, determining which version is newer, and applying changes in the appropriate direction. Ensure the system handles edge cases like deleted files, new tasks, and conflicting changes.
## Acceptance Criteria:
- Detects changes in both task files and tasks.json
- Determines which version is newer based on modification timestamps or content
- Applies changes in the appropriate direction (file to JSON or JSON to file)
- Handles edge cases like deleted files, new tasks, and renamed tasks
- Provides options for manual conflict resolution when necessary
- Maintains data integrity during the synchronization process
- Includes a command to force synchronization in either direction
- Logs all synchronization activities for troubleshooting
## 3. Implement File Naming and Organization System [done]
### Dependencies: 1 (done)
### Description: Create a consistent system for naming and organizing task files. Implement a function that generates standardized filenames based on task IDs (e.g., task_001.txt for task ID 1). Design the directory structure for storing task files according to the PRD specification. Ensure the system handles task ID formatting consistently and prevents filename collisions.
### Details:
## 4. Implement Task File to JSON Synchronization [done]
### Dependencies: 1 (done), 3 (done), 2 (done)
### Description: Develop functionality to read modified task files and update the corresponding entries in tasks.json. This includes parsing the task file format, extracting structured data, validating the changes, and updating the tasks.json file accordingly. Ensure the system can handle concurrent modifications and resolve conflicts appropriately.
### Details:
## 5. Implement Change Detection and Update Handling [done]
### Dependencies: 1 (done), 3 (done), 4 (done), 2 (done)
### Description: Create a system to detect changes in task files and tasks.json, and handle updates bidirectionally. This includes implementing file watching or comparison mechanisms, determining which version is newer, and applying changes in the appropriate direction. Ensure the system handles edge cases like deleted files, new tasks, and conflicting changes.
### Details:
Each of these subtasks addresses a specific component of the task file generation system, following a logical progression from template design to bidirectional synchronization. The dependencies ensure that prerequisites are completed before dependent work begins, and the acceptance criteria provide clear guidelines for verifying each subtask's completion.

View File

@@ -1,7 +1,7 @@
# Task ID: 5
# Title: Integrate Anthropic Claude API
# Status: done
# Dependencies: 1
# Dependencies: ✅ 1 (done)
# Priority: high
# Description: Set up the integration with Claude API for AI-powered task generation and expansion.
# Details:
@@ -17,78 +17,39 @@ Implement Claude API integration including:
Test API connectivity with sample prompts. Verify authentication works correctly with different API keys. Test error handling by simulating API failures.
# Subtasks:
## Subtask ID: 1
## Title: Configure API Authentication System
## Status: done
## Dependencies: None
## Description: Create a dedicated module for Anthropic API authentication. Implement a secure system to load API keys from environment variables using dotenv. Include validation to ensure API keys are properly formatted and present. Create a configuration object that will store all Claude-related settings including API keys, base URLs, and default parameters.
## Acceptance Criteria:
- Environment variables are properly loaded from .env file
- API key validation is implemented with appropriate error messages
- Configuration object includes all necessary Claude API parameters
- Authentication can be tested with a simple API call
- Documentation is added for required environment variables
## 1. Configure API Authentication System [done]
### Dependencies: None
### Description: Create a dedicated module for Anthropic API authentication. Implement a secure system to load API keys from environment variables using dotenv. Include validation to ensure API keys are properly formatted and present. Create a configuration object that will store all Claude-related settings including API keys, base URLs, and default parameters.
### Details:
## Subtask ID: 2
## Title: Develop Prompt Template System
## Status: done
## Dependencies: 5.1 ✅
## Description: Create a flexible prompt template system for Claude API interactions. Implement a PromptTemplate class that can handle variable substitution, system and user messages, and proper formatting according to Claude's requirements. Include templates for different operations (task generation, task expansion, etc.) with appropriate instructions and constraints for each use case.
## Acceptance Criteria:
- PromptTemplate class supports variable substitution
- System and user message separation is properly implemented
- Templates exist for all required operations (task generation, expansion, etc.)
- Templates include appropriate constraints and formatting instructions
- Template system is unit tested with various inputs
## Subtask ID: 3
## Title: Implement Response Handling and Parsing
## Status: done
## Dependencies: 5.1 ✅, 5.2 ✅
## Description: Create a response handling system that processes Claude API responses. Implement JSON parsing for structured outputs, error detection in responses, and extraction of relevant information. Build utility functions to transform Claude's responses into the application's data structures. Include validation to ensure responses meet expected formats.
## Acceptance Criteria:
- Response parsing functions handle both JSON and text formats
- Error detection identifies malformed or unexpected responses
- Utility functions transform responses into task data structures
- Validation ensures responses meet expected schemas
- Edge cases like empty or partial responses are handled gracefully
## 2. Develop Prompt Template System [done]
### Dependencies: 1 (done)
### Description: Create a flexible prompt template system for Claude API interactions. Implement a PromptTemplate class that can handle variable substitution, system and user messages, and proper formatting according to Claude's requirements. Include templates for different operations (task generation, task expansion, etc.) with appropriate instructions and constraints for each use case.
### Details:
## Subtask ID: 4
## Title: Build Error Management with Retry Logic
## Status: done
## Dependencies: 5.1 ✅, 5.3 ✅
## Description: Implement a robust error handling system for Claude API interactions. Create middleware that catches API errors, network issues, and timeout problems. Implement exponential backoff retry logic that increases wait time between retries. Add configurable retry limits and timeout settings. Include detailed logging for troubleshooting API issues.
## Acceptance Criteria:
- All API errors are caught and handled appropriately
- Exponential backoff retry logic is implemented
- Retry limits and timeouts are configurable
- Detailed error logging provides actionable information
- System degrades gracefully when API is unavailable
- Unit tests verify retry behavior with mocked API failures
## Subtask ID: 5
## Title: Implement Token Usage Tracking
## Status: done
## Dependencies: 5.1 ✅, 5.3 ✅
## Description: Create a token tracking system to monitor Claude API usage. Implement functions to count tokens in prompts and responses. Build a logging system that records token usage per operation. Add reporting capabilities to show token usage trends and costs. Implement configurable limits to prevent unexpected API costs.
## Acceptance Criteria:
- Token counting functions accurately estimate usage
- Usage logging records tokens per operation type
- Reporting functions show usage statistics and estimated costs
- Configurable limits can prevent excessive API usage
- Warning system alerts when approaching usage thresholds
- Token tracking data is persisted between application runs
## 3. Implement Response Handling and Parsing [done]
### Dependencies: 1 (done), 2 (done)
### Description: Create a response handling system that processes Claude API responses. Implement JSON parsing for structured outputs, error detection in responses, and extraction of relevant information. Build utility functions to transform Claude's responses into the application's data structures. Include validation to ensure responses meet expected formats.
### Details:
## 4. Build Error Management with Retry Logic [done]
### Dependencies: 1 (done), 3 (done)
### Description: Implement a robust error handling system for Claude API interactions. Create middleware that catches API errors, network issues, and timeout problems. Implement exponential backoff retry logic that increases wait time between retries. Add configurable retry limits and timeout settings. Include detailed logging for troubleshooting API issues.
### Details:
## 5. Implement Token Usage Tracking [done]
### Dependencies: 1 (done), 3 (done)
### Description: Create a token tracking system to monitor Claude API usage. Implement functions to count tokens in prompts and responses. Build a logging system that records token usage per operation. Add reporting capabilities to show token usage trends and costs. Implement configurable limits to prevent unexpected API costs.
### Details:
## 6. Create Model Parameter Configuration System [done]
### Dependencies: 1 (done), 5 (done)
### Description: Implement a flexible system for configuring Claude model parameters. Create a configuration module that manages model selection, temperature, top_p, max_tokens, and other parameters. Build functions to customize parameters based on operation type. Add validation to ensure parameters are within acceptable ranges. Include preset configurations for different use cases (creative, precise, etc.).
### Details:
## Subtask ID: 6
## Title: Create Model Parameter Configuration System
## Status: done
## Dependencies: 5.1 ✅, 5.5 ✅
## Description: Implement a flexible system for configuring Claude model parameters. Create a configuration module that manages model selection, temperature, top_p, max_tokens, and other parameters. Build functions to customize parameters based on operation type. Add validation to ensure parameters are within acceptable ranges. Include preset configurations for different use cases (creative, precise, etc.).
## Acceptance Criteria:
- Configuration module manages all Claude model parameters
- Parameter customization functions exist for different operations
- Validation ensures parameters are within acceptable ranges
- Preset configurations exist for different use cases
- Parameters can be overridden at runtime when needed
- Documentation explains parameter effects and recommended values
- Unit tests verify parameter validation and configuration loading

View File

@@ -1,7 +1,7 @@
# Task ID: 6
# Title: Build PRD Parsing System
# Status: done
# Dependencies: 1 ✅, 5 ✅
# Dependencies: ✅ 1 (done), ✅ 5 (done)
# Priority: high
# Description: Create the system for parsing Product Requirements Documents into structured task lists.
# Details:
@@ -17,75 +17,39 @@ Implement PRD parsing functionality including:
Test with sample PRDs of varying complexity. Verify that generated tasks accurately reflect the requirements in the PRD. Check that dependencies and priorities are logically assigned.
# Subtasks:
## Subtask ID: 1
## Title: Implement PRD File Reading Module
## Status: done
## Dependencies: None
## Description: Create a module that can read PRD files from a specified file path. The module should handle different file formats (txt, md, docx) and extract the text content. Implement error handling for file not found, permission issues, and invalid file formats. Add support for encoding detection and proper text extraction to ensure the content is correctly processed regardless of the source format.
## Acceptance Criteria:
- Function accepts a file path and returns the PRD content as a string
- Supports at least .txt and .md file formats (with extensibility for others)
- Implements robust error handling with meaningful error messages
- Successfully reads files of various sizes (up to 10MB)
- Preserves formatting where relevant for parsing (headings, lists, code blocks)
## 1. Implement PRD File Reading Module [done]
### Dependencies: None
### Description: Create a module that can read PRD files from a specified file path. The module should handle different file formats (txt, md, docx) and extract the text content. Implement error handling for file not found, permission issues, and invalid file formats. Add support for encoding detection and proper text extraction to ensure the content is correctly processed regardless of the source format.
### Details:
## Subtask ID: 2
## Title: Design and Engineer Effective PRD Parsing Prompts
## Status: done
## Dependencies: None
## Description: Create a set of carefully engineered prompts for Claude API that effectively extract structured task information from PRD content. Design prompts that guide Claude to identify tasks, dependencies, priorities, and implementation details from unstructured PRD text. Include system prompts, few-shot examples, and output format specifications to ensure consistent results.
## Acceptance Criteria:
- At least 3 different prompt templates optimized for different PRD styles/formats
- Prompts include clear instructions for identifying tasks, dependencies, and priorities
- Output format specification ensures Claude returns structured, parseable data
- Includes few-shot examples to guide Claude's understanding
- Prompts are optimized for token efficiency while maintaining effectiveness
## Subtask ID: 3
## Title: Implement PRD to Task Conversion System
## Status: done
## Dependencies: 6.1 ✅
## Description: Develop the core functionality that sends PRD content to Claude API and converts the response into the task data structure. This includes sending the engineered prompts with PRD content to Claude, parsing the structured response, and transforming it into valid task objects that conform to the task model. Implement validation to ensure the generated tasks meet all requirements.
## Acceptance Criteria:
- Successfully sends PRD content to Claude API with appropriate prompts
- Parses Claude's response into structured task objects
- Validates generated tasks against the task model schema
- Handles API errors and response parsing failures gracefully
- Generates unique and sequential task IDs
## 2. Design and Engineer Effective PRD Parsing Prompts [done]
### Dependencies: None
### Description: Create a set of carefully engineered prompts for Claude API that effectively extract structured task information from PRD content. Design prompts that guide Claude to identify tasks, dependencies, priorities, and implementation details from unstructured PRD text. Include system prompts, few-shot examples, and output format specifications to ensure consistent results.
### Details:
## Subtask ID: 4
## Title: Build Intelligent Dependency Inference System
## Status: done
## Dependencies: 6.1 ✅, 6.3 ✅
## Description: Create an algorithm that analyzes the generated tasks and infers logical dependencies between them. The system should identify which tasks must be completed before others based on the content and context of each task. Implement both explicit dependency detection (from Claude's output) and implicit dependency inference (based on task relationships and logical ordering).
## Acceptance Criteria:
- Correctly identifies explicit dependencies mentioned in task descriptions
- Infers implicit dependencies based on task context and relationships
- Prevents circular dependencies in the task graph
- Provides confidence scores for inferred dependencies
- Allows for manual override/adjustment of detected dependencies
## Subtask ID: 5
## Title: Implement Priority Assignment Logic
## Status: done
## Dependencies: 6.1 ✅, 6.3 ✅
## Description: Develop a system that assigns appropriate priorities (high, medium, low) to tasks based on their content, dependencies, and position in the PRD. Create algorithms that analyze task descriptions, identify critical path tasks, and consider factors like technical risk and business value. Implement both automated priority assignment and manual override capabilities.
## Acceptance Criteria:
- Assigns priorities based on multiple factors (dependencies, critical path, risk)
- Identifies foundation/infrastructure tasks as high priority
- Balances priorities across the project (not everything is high priority)
- Provides justification for priority assignments
- Allows for manual adjustment of priorities
## 3. Implement PRD to Task Conversion System [done]
### Dependencies: 1 (done)
### Description: Develop the core functionality that sends PRD content to Claude API and converts the response into the task data structure. This includes sending the engineered prompts with PRD content to Claude, parsing the structured response, and transforming it into valid task objects that conform to the task model. Implement validation to ensure the generated tasks meet all requirements.
### Details:
## 4. Build Intelligent Dependency Inference System [done]
### Dependencies: 1 (done), 3 (done)
### Description: Create an algorithm that analyzes the generated tasks and infers logical dependencies between them. The system should identify which tasks must be completed before others based on the content and context of each task. Implement both explicit dependency detection (from Claude's output) and implicit dependency inference (based on task relationships and logical ordering).
### Details:
## 5. Implement Priority Assignment Logic [done]
### Dependencies: 1 (done), 3 (done)
### Description: Develop a system that assigns appropriate priorities (high, medium, low) to tasks based on their content, dependencies, and position in the PRD. Create algorithms that analyze task descriptions, identify critical path tasks, and consider factors like technical risk and business value. Implement both automated priority assignment and manual override capabilities.
### Details:
## 6. Implement PRD Chunking for Large Documents [done]
### Dependencies: 1 (done), 5 (done), 3 (done)
### Description: Create a system that can handle large PRDs by breaking them into manageable chunks for processing. Implement intelligent document segmentation that preserves context across chunks, tracks section relationships, and maintains coherence in the generated tasks. Develop a mechanism to reassemble and deduplicate tasks generated from different chunks into a unified task list.
### Details:
## Subtask ID: 6
## Title: Implement PRD Chunking for Large Documents
## Status: done
## Dependencies: 6.1 ✅, 6.5 ✅, 6.3 ✅
## Description: Create a system that can handle large PRDs by breaking them into manageable chunks for processing. Implement intelligent document segmentation that preserves context across chunks, tracks section relationships, and maintains coherence in the generated tasks. Develop a mechanism to reassemble and deduplicate tasks generated from different chunks into a unified task list.
## Acceptance Criteria:
- Successfully processes PRDs larger than Claude's context window
- Intelligently splits documents at logical boundaries (sections, chapters)
- Preserves context when processing individual chunks
- Reassembles tasks from multiple chunks into a coherent task list
- Detects and resolves duplicate or overlapping tasks
- Maintains correct dependency relationships across chunks

View File

@@ -1,7 +1,7 @@
# Task ID: 7
# Title: Implement Task Expansion with Claude
# Status: done
# Dependencies: 3 ✅, 5 ✅
# Dependencies: ✅ 3 (done), ✅ 5 (done)
# Priority: medium
# Description: Create functionality to expand tasks into subtasks using Claude's AI capabilities.
# Details:
@@ -17,68 +17,33 @@ Build task expansion functionality including:
Test expanding various types of tasks into subtasks. Verify that subtasks are properly linked to parent tasks. Check that context is properly incorporated into generated subtasks.
# Subtasks:
## Subtask ID: 1
## Title: Design and Implement Subtask Generation Prompts
## Status: done
## Dependencies: None
## Description: Create optimized prompt templates for Claude to generate subtasks from parent tasks. Design the prompts to include task context, project information, and formatting instructions that ensure consistent, high-quality subtask generation. Implement a prompt template system that allows for dynamic insertion of task details, configurable number of subtasks, and additional context parameters.
## Acceptance Criteria:
- At least two prompt templates are created (standard and detailed)
- Prompts include clear instructions for formatting subtask output
- Prompts dynamically incorporate task title, description, details, and context
- Prompts include parameters for specifying the number of subtasks to generate
- Prompt system allows for easy modification and extension of templates
## 1. Design and Implement Subtask Generation Prompts [done]
### Dependencies: None
### Description: Create optimized prompt templates for Claude to generate subtasks from parent tasks. Design the prompts to include task context, project information, and formatting instructions that ensure consistent, high-quality subtask generation. Implement a prompt template system that allows for dynamic insertion of task details, configurable number of subtasks, and additional context parameters.
### Details:
## Subtask ID: 2
## Title: Develop Task Expansion Workflow and UI
## Status: done
## Dependencies: 7.5 ✅
## Description: Implement the command-line interface and workflow for expanding tasks into subtasks. Create a new command that allows users to select a task, specify the number of subtasks, and add optional context. Design the interaction flow to handle the API request, process the response, and update the tasks.json file with the newly generated subtasks.
## Acceptance Criteria:
- Command `node scripts/dev.js expand --id=<task_id> --count=<number>` is implemented
- Optional parameters for additional context (`--context="..."`) are supported
- User is shown progress indicators during API calls
- Generated subtasks are displayed for review before saving
- Command handles errors gracefully with helpful error messages
- Help documentation for the expand command is comprehensive
## Subtask ID: 3
## Title: Implement Context-Aware Expansion Capabilities
## Status: done
## Dependencies: 7.1 ✅
## Description: Enhance the task expansion functionality to incorporate project context when generating subtasks. Develop a system to gather relevant information from the project, such as related tasks, dependencies, and previously completed work. Implement logic to include this context in the Claude prompts to improve the relevance and quality of generated subtasks.
## Acceptance Criteria:
- System automatically gathers context from related tasks and dependencies
- Project metadata is incorporated into expansion prompts
- Implementation details from dependent tasks are included in context
- Context gathering is configurable (amount and type of context)
- Generated subtasks show awareness of existing project structure and patterns
- Context gathering has reasonable performance even with large task collections
## 2. Develop Task Expansion Workflow and UI [done]
### Dependencies: 5 (done)
### Description: Implement the command-line interface and workflow for expanding tasks into subtasks. Create a new command that allows users to select a task, specify the number of subtasks, and add optional context. Design the interaction flow to handle the API request, process the response, and update the tasks.json file with the newly generated subtasks.
### Details:
## 3. Implement Context-Aware Expansion Capabilities [done]
### Dependencies: 1 (done)
### Description: Enhance the task expansion functionality to incorporate project context when generating subtasks. Develop a system to gather relevant information from the project, such as related tasks, dependencies, and previously completed work. Implement logic to include this context in the Claude prompts to improve the relevance and quality of generated subtasks.
### Details:
## 4. Build Parent-Child Relationship Management [done]
### Dependencies: 3 (done)
### Description: Implement the data structure and operations for managing parent-child relationships between tasks and subtasks. Create functions to establish these relationships in the tasks.json file, update the task model to support subtask arrays, and develop utilities to navigate, filter, and display task hierarchies. Ensure all basic task operations (update, delete, etc.) properly handle subtask relationships.
### Details:
## 5. Implement Subtask Regeneration Mechanism [done]
### Dependencies: 1 (done), 2 (done), 4 (done)
### Description: Create functionality that allows users to regenerate unsatisfactory subtasks. Implement a command that can target specific subtasks for regeneration, preserve satisfactory subtasks, and incorporate feedback to improve the new generation. Design the system to maintain proper parent-child relationships and task IDs during regeneration.
### Details:
## Subtask ID: 4
## Title: Build Parent-Child Relationship Management
## Status: done
## Dependencies: 7.3 ✅
## Description: Implement the data structure and operations for managing parent-child relationships between tasks and subtasks. Create functions to establish these relationships in the tasks.json file, update the task model to support subtask arrays, and develop utilities to navigate, filter, and display task hierarchies. Ensure all basic task operations (update, delete, etc.) properly handle subtask relationships.
## Acceptance Criteria:
- Task model is updated to include subtasks array
- Subtasks have proper ID format (parent.sequence)
- Parent tasks track their subtasks with proper references
- Task listing command shows hierarchical structure
- Completing all subtasks automatically updates parent task status
- Deleting a parent task properly handles orphaned subtasks
- Task file generation includes subtask information
## Subtask ID: 5
## Title: Implement Subtask Regeneration Mechanism
## Status: done
## Dependencies: 7.1 ✅, 7.2 ✅, 7.4 ✅
## Description: Create functionality that allows users to regenerate unsatisfactory subtasks. Implement a command that can target specific subtasks for regeneration, preserve satisfactory subtasks, and incorporate feedback to improve the new generation. Design the system to maintain proper parent-child relationships and task IDs during regeneration.
## Acceptance Criteria:
- Command `node scripts/dev.js regenerate --id=<subtask_id>` is implemented
- Option to regenerate all subtasks for a parent (`--all`)
- Feedback parameter allows user to guide regeneration (`--feedback="..."`)
- Original subtask details are preserved in prompt context
- Regenerated subtasks maintain proper ID sequence
- Task relationships remain intact after regeneration
- Command provides clear before/after comparison of subtasks

View File

@@ -1,7 +1,7 @@
# Task ID: 8
# Title: Develop Implementation Drift Handling
# Status: done
# Dependencies: 3 ✅, 5 ✅, 7 ✅
# Dependencies: ✅ 3 (done), ✅ 5 (done), ✅ 7 (done)
# Priority: medium
# Description: Create system to handle changes in implementation that affect future tasks.
# Details:
@@ -16,69 +16,33 @@ Implement drift handling including:
Simulate implementation changes and test the system's ability to update future tasks appropriately. Verify that completed tasks remain unchanged while pending tasks are updated correctly.
# Subtasks:
## Subtask ID: 1
## Title: Create Task Update Mechanism Based on Completed Work
## Status: done
## Dependencies: None
## Description: Implement a system that can identify pending tasks affected by recently completed tasks and update them accordingly. This requires analyzing the dependency chain and determining which future tasks need modification based on implementation decisions made in completed tasks. Create a function that takes a completed task ID as input, identifies dependent tasks, and prepares them for potential updates.
## Acceptance Criteria:
- Function implemented to identify all pending tasks that depend on a specified completed task
- System can extract relevant implementation details from completed tasks
- Mechanism to flag tasks that need updates based on implementation changes
- Unit tests that verify the correct tasks are identified for updates
- Command-line interface to trigger the update analysis process
## 1. Create Task Update Mechanism Based on Completed Work [done]
### Dependencies: None
### Description: Implement a system that can identify pending tasks affected by recently completed tasks and update them accordingly. This requires analyzing the dependency chain and determining which future tasks need modification based on implementation decisions made in completed tasks. Create a function that takes a completed task ID as input, identifies dependent tasks, and prepares them for potential updates.
### Details:
## Subtask ID: 2
## Title: Implement AI-Powered Task Rewriting
## Status: done
## Dependencies: None
## Description: Develop functionality to use Claude API to rewrite pending tasks based on new implementation context. This involves creating specialized prompts that include the original task description, the implementation details of completed dependency tasks, and instructions to update the pending task to align with the actual implementation. The system should generate updated task descriptions, details, and test strategies.
## Acceptance Criteria:
- Specialized Claude prompt template for task rewriting
- Function to gather relevant context from completed dependency tasks
- Implementation of task rewriting logic that preserves task ID and dependencies
- Proper error handling for API failures
- Mechanism to preview changes before applying them
- Unit tests with mock API responses
## Subtask ID: 3
## Title: Build Dependency Chain Update System
## Status: done
## Dependencies: None
## Description: Create a system to update task dependencies when task implementations change. This includes adding new dependencies that weren't initially identified, removing dependencies that are no longer relevant, and reordering dependencies based on implementation decisions. The system should maintain the integrity of the dependency graph while reflecting the actual implementation requirements.
## Acceptance Criteria:
- Function to analyze and update the dependency graph
- Capability to add new dependencies to tasks
- Capability to remove obsolete dependencies
- Validation to prevent circular dependencies
- Preservation of dependency chain integrity
- CLI command to visualize dependency changes
- Unit tests for dependency graph modifications
## 2. Implement AI-Powered Task Rewriting [done]
### Dependencies: None
### Description: Develop functionality to use Claude API to rewrite pending tasks based on new implementation context. This involves creating specialized prompts that include the original task description, the implementation details of completed dependency tasks, and instructions to update the pending task to align with the actual implementation. The system should generate updated task descriptions, details, and test strategies.
### Details:
## 3. Build Dependency Chain Update System [done]
### Dependencies: None
### Description: Create a system to update task dependencies when task implementations change. This includes adding new dependencies that weren't initially identified, removing dependencies that are no longer relevant, and reordering dependencies based on implementation decisions. The system should maintain the integrity of the dependency graph while reflecting the actual implementation requirements.
### Details:
## 4. Implement Completed Work Preservation [done]
### Dependencies: 3 (done)
### Description: Develop a mechanism to ensure that updates to future tasks don't affect completed work. This includes creating a versioning system for tasks, tracking task history, and implementing safeguards to prevent modifications to completed tasks. The system should maintain a record of task changes while ensuring that completed work remains stable.
### Details:
## 5. Create Update Analysis and Suggestion Command [done]
### Dependencies: 3 (done)
### Description: Implement a CLI command that analyzes the current state of tasks, identifies potential drift between completed and pending tasks, and suggests updates. This command should provide a comprehensive report of potential inconsistencies and offer recommendations for task updates without automatically applying them. It should include options to apply all suggested changes, select specific changes to apply, or ignore suggestions.
### Details:
## Subtask ID: 4
## Title: Implement Completed Work Preservation
## Status: done
## Dependencies: 8.3 ✅
## Description: Develop a mechanism to ensure that updates to future tasks don't affect completed work. This includes creating a versioning system for tasks, tracking task history, and implementing safeguards to prevent modifications to completed tasks. The system should maintain a record of task changes while ensuring that completed work remains stable.
## Acceptance Criteria:
- Implementation of task versioning to track changes
- Safeguards that prevent modifications to tasks marked as "done"
- System to store and retrieve task history
- Clear visual indicators in the CLI for tasks that have been modified
- Ability to view the original version of a modified task
- Unit tests for completed work preservation
## Subtask ID: 5
## Title: Create Update Analysis and Suggestion Command
## Status: done
## Dependencies: 8.3 ✅
## Description: Implement a CLI command that analyzes the current state of tasks, identifies potential drift between completed and pending tasks, and suggests updates. This command should provide a comprehensive report of potential inconsistencies and offer recommendations for task updates without automatically applying them. It should include options to apply all suggested changes, select specific changes to apply, or ignore suggestions.
## Acceptance Criteria:
- New CLI command "analyze-drift" implemented
- Comprehensive analysis of potential implementation drift
- Detailed report of suggested task updates
- Interactive mode to select which suggestions to apply
- Batch mode to apply all suggested changes
- Option to export suggestions to a file for review
- Documentation of the command usage and options
- Integration tests that verify the end-to-end workflow

View File

@@ -1,7 +1,7 @@
# Task ID: 9
# Title: Integrate Perplexity API
# Status: done
# Dependencies: 5
# Dependencies: ✅ 5 (done)
# Priority: low
# Description: Add integration with Perplexity API for research-backed task generation.
# Details:
@@ -17,67 +17,33 @@ Implement Perplexity integration including:
Test connectivity to Perplexity API. Verify research-oriented prompts return useful information. Test fallback mechanism by simulating Perplexity API unavailability.
# Subtasks:
## Subtask ID: 1
## Title: Implement Perplexity API Authentication Module
## Status: done
## Dependencies: None
## Description: Create a dedicated module for authenticating with the Perplexity API using the OpenAI client library. This module should handle API key management, connection setup, and basic error handling. Implement environment variable support for the PERPLEXITY_API_KEY and PERPLEXITY_MODEL variables with appropriate defaults as specified in the PRD. Include a connection test function to verify API access.
## Acceptance Criteria:
- Authentication module successfully connects to Perplexity API using OpenAI client
- Environment variables for API key and model selection are properly handled
- Connection test function returns appropriate success/failure responses
- Basic error handling for authentication failures is implemented
- Documentation for required environment variables is added to .env.example
## 1. Implement Perplexity API Authentication Module [done]
### Dependencies: None
### Description: Create a dedicated module for authenticating with the Perplexity API using the OpenAI client library. This module should handle API key management, connection setup, and basic error handling. Implement environment variable support for the PERPLEXITY_API_KEY and PERPLEXITY_MODEL variables with appropriate defaults as specified in the PRD. Include a connection test function to verify API access.
### Details:
## Subtask ID: 2
## Title: Develop Research-Oriented Prompt Templates
## Status: done
## Dependencies: None
## Description: Design and implement specialized prompt templates optimized for research tasks with Perplexity. Create a template system that can generate contextually relevant research prompts based on task information. These templates should be structured to leverage Perplexity's online search capabilities and should follow the Research-Backed Expansion Prompt Structure defined in the PRD. Include mechanisms to control prompt length and focus.
## Acceptance Criteria:
- At least 3 different research-oriented prompt templates are implemented
- Templates can be dynamically populated with task context and parameters
- Prompts are optimized for Perplexity's capabilities and response format
- Template system is extensible to allow for future additions
- Templates include appropriate system instructions to guide Perplexity's responses
## Subtask ID: 3
## Title: Create Perplexity Response Handler
## Status: done
## Dependencies: None
## Description: Implement a specialized response handler for Perplexity API responses. This should parse and process the JSON responses from Perplexity, extract relevant information, and transform it into the task data structure format. Include validation to ensure responses meet quality standards and contain the expected information. Implement streaming response handling if supported by the API client.
## Acceptance Criteria:
- Response handler successfully parses Perplexity API responses
- Handler extracts structured task information from free-text responses
- Validation logic identifies and handles malformed or incomplete responses
- Response streaming is properly implemented if supported
- Handler includes appropriate error handling for various response scenarios
- Unit tests verify correct parsing of sample responses
## 2. Develop Research-Oriented Prompt Templates [done]
### Dependencies: None
### Description: Design and implement specialized prompt templates optimized for research tasks with Perplexity. Create a template system that can generate contextually relevant research prompts based on task information. These templates should be structured to leverage Perplexity's online search capabilities and should follow the Research-Backed Expansion Prompt Structure defined in the PRD. Include mechanisms to control prompt length and focus.
### Details:
## Subtask ID: 4
## Title: Implement Claude Fallback Mechanism
## Status: done
## Dependencies: None
## Description: Create a fallback system that automatically switches to the Claude API when Perplexity is unavailable or returns errors. This system should detect API failures, rate limiting, or quality issues with Perplexity responses and seamlessly transition to using Claude with appropriate prompt modifications. Implement retry logic with exponential backoff before falling back to Claude. Log all fallback events for monitoring.
## Acceptance Criteria:
- System correctly detects Perplexity API failures and availability issues
- Fallback to Claude is triggered automatically when needed
- Prompts are appropriately modified when switching to Claude
- Retry logic with exponential backoff is implemented before fallback
- All fallback events are logged with relevant details
- Configuration option allows setting the maximum number of retries
## Subtask ID: 5
## Title: Develop Response Quality Comparison and Model Selection
## Status: done
## Dependencies: None
## Description: Implement a system to compare response quality between Perplexity and Claude, and provide configuration options for model selection. Create metrics for evaluating response quality (e.g., specificity, relevance, actionability). Add configuration options that allow users to specify which model to use for different types of tasks. Implement a caching mechanism to reduce API calls and costs when appropriate.
## Acceptance Criteria:
- Quality comparison logic evaluates responses based on defined metrics
- Configuration system allows selection of preferred models for different operations
- Model selection can be controlled via environment variables and command-line options
- Response caching mechanism reduces duplicate API calls
- System logs quality metrics for later analysis
- Documentation clearly explains model selection options and quality metrics
## 3. Create Perplexity Response Handler [done]
### Dependencies: None
### Description: Implement a specialized response handler for Perplexity API responses. This should parse and process the JSON responses from Perplexity, extract relevant information, and transform it into the task data structure format. Include validation to ensure responses meet quality standards and contain the expected information. Implement streaming response handling if supported by the API client.
### Details:
## 4. Implement Claude Fallback Mechanism [done]
### Dependencies: None
### Description: Create a fallback system that automatically switches to the Claude API when Perplexity is unavailable or returns errors. This system should detect API failures, rate limiting, or quality issues with Perplexity responses and seamlessly transition to using Claude with appropriate prompt modifications. Implement retry logic with exponential backoff before falling back to Claude. Log all fallback events for monitoring.
### Details:
## 5. Develop Response Quality Comparison and Model Selection [done]
### Dependencies: None
### Description: Implement a system to compare response quality between Perplexity and Claude, and provide configuration options for model selection. Create metrics for evaluating response quality (e.g., specificity, relevance, actionability). Add configuration options that allow users to specify which model to use for different types of tasks. Implement a caching mechanism to reduce API calls and costs when appropriate.
### Details:
These subtasks provide a comprehensive breakdown of the Perplexity API integration task, covering all the required aspects mentioned in the original task description while ensuring each subtask is specific, actionable, and technically relevant.

View File

@@ -1,7 +1,7 @@
# Task ID: 10
# Title: Create Research-Backed Subtask Generation
# Status: done
# Dependencies: 7 ✅, 9 ✅
# Dependencies: ✅ 7 (done), ✅ 9 (done)
# Priority: low
# Description: Enhance subtask generation with research capabilities from Perplexity API.
# Details:
@@ -16,79 +16,39 @@ Implement research-backed generation including:
Compare subtasks generated with and without research backing. Verify that research-backed subtasks include more specific technical details and best practices.
# Subtasks:
## Subtask ID: 1
## Title: Design Domain-Specific Research Prompt Templates
## Status: done
## Dependencies: None
## Description: Create a set of specialized prompt templates for different software development domains (e.g., web development, mobile, data science, DevOps). Each template should be structured to extract relevant best practices, libraries, tools, and implementation patterns from Perplexity API. Implement a prompt template selection mechanism based on the task context and domain.
## Acceptance Criteria:
- At least 5 domain-specific prompt templates are created and stored in a dedicated templates directory
- Templates include specific sections for querying best practices, tools, libraries, and implementation patterns
- A prompt selection function is implemented that can determine the appropriate template based on task metadata
- Templates are parameterized to allow dynamic insertion of task details and context
- Documentation is added explaining each template's purpose and structure
## 1. Design Domain-Specific Research Prompt Templates [done]
### Dependencies: None
### Description: Create a set of specialized prompt templates for different software development domains (e.g., web development, mobile, data science, DevOps). Each template should be structured to extract relevant best practices, libraries, tools, and implementation patterns from Perplexity API. Implement a prompt template selection mechanism based on the task context and domain.
### Details:
## Subtask ID: 2
## Title: Implement Research Query Execution and Response Processing
## Status: done
## Dependencies: None
## Description: Build a module that executes research queries using the Perplexity API integration. This should include sending the domain-specific prompts, handling the API responses, and parsing the results into a structured format that can be used for context enrichment. Implement error handling, rate limiting, and fallback to Claude when Perplexity is unavailable.
## Acceptance Criteria:
- Function to execute research queries with proper error handling and retries
- Response parser that extracts structured data from Perplexity's responses
- Fallback mechanism that uses Claude when Perplexity fails or is unavailable
- Caching system to avoid redundant API calls for similar research queries
- Logging system for tracking API usage and response quality
- Unit tests verifying correct handling of successful and failed API calls
## Subtask ID: 3
## Title: Develop Context Enrichment Pipeline
## Status: done
## Dependencies: 10.2 ✅
## Description: Create a pipeline that processes research results and enriches the task context with relevant information. This should include filtering irrelevant information, organizing research findings by category (tools, libraries, best practices, etc.), and formatting the enriched context for use in subtask generation. Implement a scoring mechanism to prioritize the most relevant research findings.
## Acceptance Criteria:
- Context enrichment function that takes raw research results and task details as input
- Filtering system to remove irrelevant or low-quality information
- Categorization of research findings into distinct sections (tools, libraries, patterns, etc.)
- Relevance scoring algorithm to prioritize the most important findings
- Formatted output that can be directly used in subtask generation prompts
- Tests comparing enriched context quality against baseline
## 2. Implement Research Query Execution and Response Processing [done]
### Dependencies: None
### Description: Build a module that executes research queries using the Perplexity API integration. This should include sending the domain-specific prompts, handling the API responses, and parsing the results into a structured format that can be used for context enrichment. Implement error handling, rate limiting, and fallback to Claude when Perplexity is unavailable.
### Details:
## Subtask ID: 4
## Title: Implement Domain-Specific Knowledge Incorporation
## Status: done
## Dependencies: 10.3 ✅
## Description: Develop a system to incorporate domain-specific knowledge into the subtask generation process. This should include identifying key domain concepts, technical requirements, and industry standards from the research results. Create a knowledge base structure that organizes domain information and can be referenced during subtask generation.
## Acceptance Criteria:
- Domain knowledge extraction function that identifies key technical concepts
- Knowledge base structure for organizing domain-specific information
- Integration with the subtask generation prompt to incorporate relevant domain knowledge
- Support for technical terminology and concept explanation in generated subtasks
- Mechanism to link domain concepts to specific implementation recommendations
- Tests verifying improved technical accuracy in generated subtasks
## Subtask ID: 5
## Title: Enhance Subtask Generation with Technical Details
## Status: done
## Dependencies: 10.3 ✅, 10.4 ✅
## Description: Extend the existing subtask generation functionality to incorporate research findings and produce more technically detailed subtasks. This includes modifying the Claude prompt templates to leverage the enriched context, implementing specific sections for technical approach, implementation notes, and potential challenges. Ensure generated subtasks include concrete technical details rather than generic steps.
## Acceptance Criteria:
- Enhanced prompt templates for Claude that incorporate research-backed context
- Generated subtasks include specific technical approaches and implementation details
- Each subtask contains references to relevant tools, libraries, or frameworks
- Implementation notes section with code patterns or architectural recommendations
- Potential challenges and mitigation strategies are included where appropriate
- Comparative tests showing improvement over baseline subtask generation
## 3. Develop Context Enrichment Pipeline [done]
### Dependencies: 2 (done)
### Description: Create a pipeline that processes research results and enriches the task context with relevant information. This should include filtering irrelevant information, organizing research findings by category (tools, libraries, best practices, etc.), and formatting the enriched context for use in subtask generation. Implement a scoring mechanism to prioritize the most relevant research findings.
### Details:
## 4. Implement Domain-Specific Knowledge Incorporation [done]
### Dependencies: 3 (done)
### Description: Develop a system to incorporate domain-specific knowledge into the subtask generation process. This should include identifying key domain concepts, technical requirements, and industry standards from the research results. Create a knowledge base structure that organizes domain information and can be referenced during subtask generation.
### Details:
## 5. Enhance Subtask Generation with Technical Details [done]
### Dependencies: 3 (done), 4 (done)
### Description: Extend the existing subtask generation functionality to incorporate research findings and produce more technically detailed subtasks. This includes modifying the Claude prompt templates to leverage the enriched context, implementing specific sections for technical approach, implementation notes, and potential challenges. Ensure generated subtasks include concrete technical details rather than generic steps.
### Details:
## 6. Implement Reference and Resource Inclusion [done]
### Dependencies: 3 (done), 5 (done)
### Description: Create a system to include references to relevant libraries, tools, documentation, and other resources in generated subtasks. This should extract specific references from research results, validate their relevance, and format them as actionable links or citations within subtasks. Implement a verification step to ensure referenced resources are current and applicable.
### Details:
## Subtask ID: 6
## Title: Implement Reference and Resource Inclusion
## Status: done
## Dependencies: 10.3 ✅, 10.5 ✅
## Description: Create a system to include references to relevant libraries, tools, documentation, and other resources in generated subtasks. This should extract specific references from research results, validate their relevance, and format them as actionable links or citations within subtasks. Implement a verification step to ensure referenced resources are current and applicable.
## Acceptance Criteria:
- Reference extraction function that identifies tools, libraries, and resources from research
- Validation mechanism to verify reference relevance and currency
- Formatting system for including references in subtask descriptions
- Support for different reference types (GitHub repos, documentation, articles, etc.)
- Optional version specification for referenced libraries and tools
- Tests verifying that included references are relevant and accessible

View File

@@ -1,7 +1,7 @@
# Task ID: 11
# Title: Implement Batch Operations
# Status: done
# Dependencies: 3
# Dependencies: ✅ 3 (done)
# Priority: medium
# Description: Add functionality for performing operations on multiple tasks simultaneously.
# Details:
@@ -17,75 +17,33 @@ Create batch operations including:
Test batch operations with various filters and operations. Verify that operations are applied correctly to all matching tasks. Test with large task sets to ensure performance.
# Subtasks:
## Subtask ID: 1
## Title: Implement Multi-Task Status Update Functionality
## Status: done
## Dependencies: 11.3 ✅
## Description: Create a command-line interface command that allows users to update the status of multiple tasks simultaneously. Implement the backend logic to process batch status changes, validate the requested changes, and update the tasks.json file accordingly. The implementation should include options for filtering tasks by various criteria (ID ranges, status, priority, etc.) and applying status changes to the filtered set.
## Acceptance Criteria:
- Command accepts parameters for filtering tasks (e.g., `--status=pending`, `--priority=high`, `--id=1,2,3-5`)
- Command accepts a parameter for the new status value (e.g., `--new-status=done`)
- All matching tasks are updated in the tasks.json file
- Command provides a summary of changes made (e.g., "Updated 5 tasks from 'pending' to 'done'")
- Command handles errors gracefully (e.g., invalid status values, no matching tasks)
- Changes are persisted correctly to tasks.json
## 1. Implement Multi-Task Status Update Functionality [done]
### Dependencies: 3 (done)
### Description: Create a command-line interface command that allows users to update the status of multiple tasks simultaneously. Implement the backend logic to process batch status changes, validate the requested changes, and update the tasks.json file accordingly. The implementation should include options for filtering tasks by various criteria (ID ranges, status, priority, etc.) and applying status changes to the filtered set.
### Details:
## Subtask ID: 2
## Title: Develop Bulk Subtask Generation System
## Status: done
## Dependencies: 11.3 ✅, 11.4 ✅
## Description: Create functionality to generate multiple subtasks across several parent tasks at once. This should include a command-line interface that accepts filtering parameters to select parent tasks and either a template for subtasks or an AI-assisted generation option. The system should validate parent tasks, generate appropriate subtasks with proper ID assignments, and update the tasks.json file.
## Acceptance Criteria:
- Command accepts parameters for filtering parent tasks
- Command supports template-based subtask generation with variable substitution
- Command supports AI-assisted subtask generation using Claude API
- Generated subtasks have proper IDs following the parent.sequence format (e.g., 1.1, 1.2)
- Subtasks inherit appropriate properties from parent tasks (e.g., dependencies)
- Generated subtasks are added to the tasks.json file
- Task files are regenerated to include the new subtasks
- Command provides a summary of subtasks created
## Subtask ID: 3
## Title: Implement Advanced Task Filtering and Querying
## Status: done
## Dependencies: None
## Description: Create a robust filtering and querying system that can be used across all batch operations. Implement a query syntax that allows for complex filtering based on task properties, including status, priority, dependencies, ID ranges, and text search within titles and descriptions. Design the system to be reusable across different batch operation commands.
## Acceptance Criteria:
- Support for filtering by task properties (status, priority, dependencies)
- Support for ID-based filtering (individual IDs, ranges, exclusions)
- Support for text search within titles and descriptions
- Support for logical operators (AND, OR, NOT) in filters
- Query parser that converts command-line arguments to filter criteria
- Reusable filtering module that can be imported by other commands
- Comprehensive test cases covering various filtering scenarios
- Documentation of the query syntax for users
## 2. Develop Bulk Subtask Generation System [done]
### Dependencies: 3 (done), 4 (done)
### Description: Create functionality to generate multiple subtasks across several parent tasks at once. This should include a command-line interface that accepts filtering parameters to select parent tasks and either a template for subtasks or an AI-assisted generation option. The system should validate parent tasks, generate appropriate subtasks with proper ID assignments, and update the tasks.json file.
### Details:
## 3. Implement Advanced Task Filtering and Querying [done]
### Dependencies: None
### Description: Create a robust filtering and querying system that can be used across all batch operations. Implement a query syntax that allows for complex filtering based on task properties, including status, priority, dependencies, ID ranges, and text search within titles and descriptions. Design the system to be reusable across different batch operation commands.
### Details:
## 4. Create Advanced Dependency Management System [done]
### Dependencies: 3 (done)
### Description: Implement batch operations for managing dependencies between tasks. This includes commands for adding, removing, and updating dependencies across multiple tasks simultaneously. The system should validate dependency changes to prevent circular dependencies, update the tasks.json file, and regenerate task files to reflect the changes.
### Details:
## 5. Implement Batch Task Prioritization and Command System [done]
### Dependencies: 3 (done)
### Description: Create a system for batch prioritization of tasks and a command framework for operating on filtered task sets. This includes commands for changing priorities of multiple tasks at once and a generic command execution system that can apply custom operations to filtered task sets. The implementation should include a plugin architecture that allows for extending the system with new batch operations.
### Details:
## Subtask ID: 4
## Title: Create Advanced Dependency Management System
## Status: done
## Dependencies: 11.3 ✅
## Description: Implement batch operations for managing dependencies between tasks. This includes commands for adding, removing, and updating dependencies across multiple tasks simultaneously. The system should validate dependency changes to prevent circular dependencies, update the tasks.json file, and regenerate task files to reflect the changes.
## Acceptance Criteria:
- Command for adding dependencies to multiple tasks at once
- Command for removing dependencies from multiple tasks
- Command for replacing dependencies across multiple tasks
- Validation to prevent circular dependencies
- Validation to ensure referenced tasks exist
- Automatic update of affected task files
- Summary report of dependency changes made
- Error handling for invalid dependency operations
## Subtask ID: 5
## Title: Implement Batch Task Prioritization and Command System
## Status: done
## Dependencies: 11.3 ✅
## Description: Create a system for batch prioritization of tasks and a command framework for operating on filtered task sets. This includes commands for changing priorities of multiple tasks at once and a generic command execution system that can apply custom operations to filtered task sets. The implementation should include a plugin architecture that allows for extending the system with new batch operations.
## Acceptance Criteria:
- Command for changing priorities of multiple tasks at once
- Support for relative priority changes (e.g., increase/decrease priority)
- Generic command execution framework that works with the filtering system
- Plugin architecture for registering new batch operations
- At least three example plugins (e.g., batch tagging, batch assignment, batch export)
- Command for executing arbitrary operations on filtered task sets
- Documentation for creating new batch operation plugins
- Performance testing with large task sets (100+ tasks)

View File

@@ -1,7 +1,7 @@
# Task ID: 12
# Title: Develop Project Initialization System
# Status: done
# Dependencies: 1 ✅, 2 ✅, 3 ✅, 4 ✅, 6 ✅
# Dependencies: ✅ 1 (done), ✅ 2 (done), ✅ 3 (done), ✅ 4 (done), ✅ 6 (done)
# Priority: medium
# Description: Create functionality for initializing new projects with task structure and configuration.
# Details:
@@ -17,50 +17,39 @@ Implement project initialization including:
Test project initialization in empty directories. Verify that all required files and directories are created correctly. Test the interactive setup with various inputs.
# Subtasks:
## Subtask ID: 1
## Title: Create Project Template Structure
## Status: done
## Dependencies: 12.4 ✅
## Description: Design and implement a flexible project template system that will serve as the foundation for new project initialization. This should include creating a base directory structure, template files (e.g., default tasks.json, .env.example), and a configuration file to define customizable aspects of the template.
## Acceptance Criteria:
- A `templates` directory is created with at least one default project template
## 1. Create Project Template Structure [done]
### Dependencies: 4 (done)
### Description: Design and implement a flexible project template system that will serve as the foundation for new project initialization. This should include creating a base directory structure, template files (e.g., default tasks.json, .env.example), and a configuration file to define customizable aspects of the template.
### Details:
## Subtask ID: 2
## Title: Implement Interactive Setup Wizard
## Status: done
## Dependencies: 12.3 ✅
## Description: Develop an interactive command-line wizard using a library like Inquirer.js to guide users through the project initialization process. The wizard should prompt for project name, description, initial task structure, and other configurable options defined in the template configuration.
## Acceptance Criteria:
- Interactive wizard prompts for essential project information
## Subtask ID: 3
## Title: Generate Environment Configuration
## Status: done
## Dependencies: 12.2 ✅
## Description: Create functionality to generate environment-specific configuration files based on user input and template defaults. This includes creating a .env file with necessary API keys and configuration values, and updating the tasks.json file with project-specific metadata.
## Acceptance Criteria:
- .env file is generated with placeholders for required API keys
## 2. Implement Interactive Setup Wizard [done]
### Dependencies: 3 (done)
### Description: Develop an interactive command-line wizard using a library like Inquirer.js to guide users through the project initialization process. The wizard should prompt for project name, description, initial task structure, and other configurable options defined in the template configuration.
### Details:
## Subtask ID: 4
## Title: Implement Directory Structure Creation
## Status: done
## Dependencies: 12.1 ✅
## Description: Develop the logic to create the initial directory structure for new projects based on the selected template and user inputs. This should include creating necessary subdirectories (e.g., tasks/, scripts/, .cursor/rules/) and copying template files to appropriate locations.
## Acceptance Criteria:
- Directory structure is created according to the template specification
## Subtask ID: 5
## Title: Generate Example Tasks.json
## Status: done
## Dependencies: 12.6 ✅
## Description: Create functionality to generate an initial tasks.json file with example tasks based on the project template and user inputs from the setup wizard. This should include creating a set of starter tasks that demonstrate the task structure and provide a starting point for the project.
## Acceptance Criteria:
- An initial tasks.json file is generated with at least 3 example tasks
## 3. Generate Environment Configuration [done]
### Dependencies: 2 (done)
### Description: Create functionality to generate environment-specific configuration files based on user input and template defaults. This includes creating a .env file with necessary API keys and configuration values, and updating the tasks.json file with project-specific metadata.
### Details:
## 4. Implement Directory Structure Creation [done]
### Dependencies: 1 (done)
### Description: Develop the logic to create the initial directory structure for new projects based on the selected template and user inputs. This should include creating necessary subdirectories (e.g., tasks/, scripts/, .cursor/rules/) and copying template files to appropriate locations.
### Details:
## 5. Generate Example Tasks.json [done]
### Dependencies: 6 (done)
### Description: Create functionality to generate an initial tasks.json file with example tasks based on the project template and user inputs from the setup wizard. This should include creating a set of starter tasks that demonstrate the task structure and provide a starting point for the project.
### Details:
## 6. Implement Default Configuration Setup [done]
### Dependencies: None
### Description: Develop the system for setting up default configurations for the project, including initializing the .cursor/rules/ directory with dev_workflow.mdc, cursor_rules.mdc, and self_improve.mdc files. Also, create a default package.json with necessary dependencies and scripts for the project.
### Details:
## Subtask ID: 6
## Title: Implement Default Configuration Setup
## Status: done
## Dependencies: None
## Description: Develop the system for setting up default configurations for the project, including initializing the .cursor/rules/ directory with dev_workflow.mdc, cursor_rules.mdc, and self_improve.mdc files. Also, create a default package.json with necessary dependencies and scripts for the project.
## Acceptance Criteria:
- .cursor/rules/ directory is created with required .mdc files

View File

@@ -1,7 +1,7 @@
# Task ID: 13
# Title: Create Cursor Rules Implementation
# Status: done
# Dependencies: 1 ✅, 2 ✅, 3 ✅
# Dependencies: ✅ 1 (done), ✅ 2 (done), ✅ 3 (done)
# Priority: medium
# Description: Develop the Cursor AI integration rules and documentation.
# Details:
@@ -17,70 +17,33 @@ Implement Cursor rules including:
Review rules documentation for clarity and completeness. Test with Cursor AI to verify the rules are properly interpreted and followed.
# Subtasks:
## Subtask ID: 1
## Title: Set up .cursor Directory Structure
## Status: done
## Dependencies: None
## Description: Create the required directory structure for Cursor AI integration, including the .cursor folder and rules subfolder. This provides the foundation for storing all Cursor-related configuration files and rule documentation. Ensure proper permissions and gitignore settings are configured to maintain these files correctly.
## Acceptance Criteria:
- .cursor directory created at the project root
- .cursor/rules subdirectory created
- Directory structure matches the specification in the PRD
- Appropriate entries added to .gitignore to handle .cursor directory correctly
- README documentation updated to mention the .cursor directory purpose
## 1. Set up .cursor Directory Structure [done]
### Dependencies: None
### Description: Create the required directory structure for Cursor AI integration, including the .cursor folder and rules subfolder. This provides the foundation for storing all Cursor-related configuration files and rule documentation. Ensure proper permissions and gitignore settings are configured to maintain these files correctly.
### Details:
## Subtask ID: 2
## Title: Create dev_workflow.mdc Documentation
## Status: done
## Dependencies: 13.1 ✅
## Description: Develop the dev_workflow.mdc file that documents the development workflow for Cursor AI. This file should outline how Cursor AI should assist with task discovery, implementation, and verification within the project. Include specific examples of commands and interactions that demonstrate the optimal workflow.
## Acceptance Criteria:
- dev_workflow.mdc file created in .cursor/rules directory
- Document clearly explains the development workflow with Cursor AI
- Workflow documentation includes task discovery process
- Implementation guidance for Cursor AI is detailed
- Verification procedures are documented
- Examples of typical interactions are provided
## Subtask ID: 3
## Title: Implement cursor_rules.mdc
## Status: done
## Dependencies: 13.1 ✅
## Description: Create the cursor_rules.mdc file that defines specific rules and guidelines for how Cursor AI should interact with the codebase. This should include code style preferences, architectural patterns to follow, documentation requirements, and any project-specific conventions that Cursor AI should adhere to when generating or modifying code.
## Acceptance Criteria:
- cursor_rules.mdc file created in .cursor/rules directory
- Rules document clearly defines code style guidelines
- Architectural patterns and principles are specified
- Documentation requirements for generated code are outlined
- Project-specific naming conventions are documented
- Rules for handling dependencies and imports are defined
- Guidelines for test implementation are included
## 2. Create dev_workflow.mdc Documentation [done]
### Dependencies: 1 (done)
### Description: Develop the dev_workflow.mdc file that documents the development workflow for Cursor AI. This file should outline how Cursor AI should assist with task discovery, implementation, and verification within the project. Include specific examples of commands and interactions that demonstrate the optimal workflow.
### Details:
## 3. Implement cursor_rules.mdc [done]
### Dependencies: 1 (done)
### Description: Create the cursor_rules.mdc file that defines specific rules and guidelines for how Cursor AI should interact with the codebase. This should include code style preferences, architectural patterns to follow, documentation requirements, and any project-specific conventions that Cursor AI should adhere to when generating or modifying code.
### Details:
## 4. Add self_improve.mdc Documentation [done]
### Dependencies: 1 (done), 2 (done), 3 (done)
### Description: Develop the self_improve.mdc file that instructs Cursor AI on how to continuously improve its assistance capabilities within the project context. This document should outline how Cursor AI should learn from feedback, adapt to project evolution, and enhance its understanding of the codebase over time.
### Details:
## 5. Create Cursor AI Integration Documentation [done]
### Dependencies: 1 (done), 2 (done), 3 (done), 4 (done)
### Description: Develop comprehensive documentation on how Cursor AI integrates with the task management system. This should include detailed instructions on how Cursor AI should interpret tasks.json, individual task files, and how it should assist with implementation. Document the specific commands and workflows that Cursor AI should understand and support.
### Details:
## Subtask ID: 4
## Title: Add self_improve.mdc Documentation
## Status: done
## Dependencies: 13.1 ✅, 13.2 ✅, 13.3 ✅
## Description: Develop the self_improve.mdc file that instructs Cursor AI on how to continuously improve its assistance capabilities within the project context. This document should outline how Cursor AI should learn from feedback, adapt to project evolution, and enhance its understanding of the codebase over time.
## Acceptance Criteria:
- self_improve.mdc file created in .cursor/rules directory
- Document outlines feedback incorporation mechanisms
- Guidelines for adapting to project evolution are included
- Instructions for enhancing codebase understanding over time
- Strategies for improving code suggestions based on past interactions
- Methods for refining prompt responses based on user feedback
- Approach for maintaining consistency with evolving project patterns
## Subtask ID: 5
## Title: Create Cursor AI Integration Documentation
## Status: done
## Dependencies: 13.1 ✅, 13.2 ✅, 13.3 ✅, 13.4 ✅
## Description: Develop comprehensive documentation on how Cursor AI integrates with the task management system. This should include detailed instructions on how Cursor AI should interpret tasks.json, individual task files, and how it should assist with implementation. Document the specific commands and workflows that Cursor AI should understand and support.
## Acceptance Criteria:
- Integration documentation created and stored in an appropriate location
- Documentation explains how Cursor AI should interpret tasks.json structure
- Guidelines for Cursor AI to understand task dependencies and priorities
- Instructions for Cursor AI to assist with task implementation
- Documentation of specific commands Cursor AI should recognize
- Examples of effective prompts for working with the task system
- Troubleshooting section for common Cursor AI integration issues
- Documentation references all created rule files and explains their purpose

View File

@@ -1,7 +1,7 @@
# Task ID: 14
# Title: Develop Agent Workflow Guidelines
# Status: pending
# Dependencies: 13
# Status: done
# Dependencies: 13 (done)
# Priority: medium
# Description: Create comprehensive guidelines for how AI agents should interact with the task system.
# Details:
@@ -17,42 +17,33 @@ Create agent workflow guidelines including:
Review guidelines with actual AI agents to verify they can follow the procedures. Test various scenarios to ensure the guidelines cover all common workflows.
# Subtasks:
## Subtask ID: 1
## Title: Document Task Discovery Workflow
## Status: pending
## Dependencies: None
## Description: Create a comprehensive document outlining how AI agents should discover and interpret new tasks within the system. This should include steps for parsing the tasks.json file, interpreting task metadata, and understanding the relationships between tasks and subtasks. Implement example code snippets in Node.js demonstrating how to traverse the task structure and extract relevant information.
## Acceptance Criteria:
- Detailed markdown document explaining the task discovery process
## 1. Document Task Discovery Workflow [done]
### Dependencies: None
### Description: Create a comprehensive document outlining how AI agents should discover and interpret new tasks within the system. This should include steps for parsing the tasks.json file, interpreting task metadata, and understanding the relationships between tasks and subtasks. Implement example code snippets in Node.js demonstrating how to traverse the task structure and extract relevant information.
### Details:
## Subtask ID: 2
## Title: Implement Task Selection Algorithm
## Status: pending
## Dependencies: 14.1 ⏱️
## Description: Develop an algorithm for AI agents to select the most appropriate task to work on based on priority, dependencies, and current project status. This should include logic for evaluating task urgency, managing blocked tasks, and optimizing workflow efficiency. Implement the algorithm in JavaScript and integrate it with the existing task management system.
## Acceptance Criteria:
- JavaScript module implementing the task selection algorithm
## Subtask ID: 3
## Title: Create Implementation Guidance Generator
## Status: pending
## Dependencies: 14.5 ⏱️
## Description: Develop a system that generates detailed implementation guidance for AI agents based on task descriptions and project context. This should leverage the Anthropic Claude API to create step-by-step instructions, suggest relevant libraries or tools, and provide code snippets or pseudocode where appropriate. Implement caching to reduce API calls and improve performance.
## Acceptance Criteria:
- Node.js module for generating implementation guidance using Claude API
## 2. Implement Task Selection Algorithm [done]
### Dependencies: 1 (done)
### Description: Develop an algorithm for AI agents to select the most appropriate task to work on based on priority, dependencies, and current project status. This should include logic for evaluating task urgency, managing blocked tasks, and optimizing workflow efficiency. Implement the algorithm in JavaScript and integrate it with the existing task management system.
### Details:
## 3. Create Implementation Guidance Generator [done]
### Dependencies: 5 (done)
### Description: Develop a system that generates detailed implementation guidance for AI agents based on task descriptions and project context. This should leverage the Anthropic Claude API to create step-by-step instructions, suggest relevant libraries or tools, and provide code snippets or pseudocode where appropriate. Implement caching to reduce API calls and improve performance.
### Details:
## 4. Develop Verification Procedure Framework [done]
### Dependencies: 1 (done), 2 (done)
### Description: Create a flexible framework for defining and executing verification procedures for completed tasks. This should include a DSL (Domain Specific Language) for specifying acceptance criteria, automated test generation where possible, and integration with popular testing frameworks. Implement hooks for both automated and manual verification steps.
### Details:
## 5. Implement Dynamic Task Prioritization System [done]
### Dependencies: 1 (done), 2 (done), 3 (done)
### Description: Develop a system that dynamically adjusts task priorities based on project progress, dependencies, and external factors. This should include an algorithm for recalculating priorities, a mechanism for propagating priority changes through dependency chains, and an API for external systems to influence priorities. Implement this as a background process that periodically updates the tasks.json file.
### Details:
## Subtask ID: 4
## Title: Develop Verification Procedure Framework
## Status: pending
## Dependencies: 14.1 ⏱️, 14.2 ⏱️
## Description: Create a flexible framework for defining and executing verification procedures for completed tasks. This should include a DSL (Domain Specific Language) for specifying acceptance criteria, automated test generation where possible, and integration with popular testing frameworks. Implement hooks for both automated and manual verification steps.
## Acceptance Criteria:
- JavaScript module implementing the verification procedure framework
## Subtask ID: 5
## Title: Implement Dynamic Task Prioritization System
## Status: pending
## Dependencies: 14.1 ⏱️, 14.2 ⏱️, 14.3 ⏱️
## Description: Develop a system that dynamically adjusts task priorities based on project progress, dependencies, and external factors. This should include an algorithm for recalculating priorities, a mechanism for propagating priority changes through dependency chains, and an API for external systems to influence priorities. Implement this as a background process that periodically updates the tasks.json file.
## Acceptance Criteria:
- Node.js module implementing the dynamic prioritization system

View File

@@ -1,7 +1,7 @@
# Task ID: 15
# Title: Optimize Agent Integration with Cursor and dev.js Commands
# Status: pending
# Dependencies: 2, 14 ⏱️
# Status: done
# Dependencies: ✅ 2 (done), ✅ 14 (done)
# Priority: medium
# Description: Document and enhance existing agent interaction patterns through Cursor rules and dev.js commands.
# Details:
@@ -16,50 +16,39 @@ Optimize agent integration including:
Test the enhanced commands with AI agents to verify they can correctly interpret and use them. Verify that agents can effectively interact with the task system using the documented patterns in Cursor rules.
# Subtasks:
## Subtask ID: 1
## Title: Document Existing Agent Interaction Patterns
## Status: pending
## Dependencies: None
## Description: Review and document the current agent interaction patterns in Cursor rules (dev_workflow.mdc, cursor_rules.mdc). Create comprehensive documentation that explains how agents should interact with the task system using existing commands and patterns.
## Acceptance Criteria:
- Comprehensive documentation of existing agent interaction patterns in Cursor rules
## 1. Document Existing Agent Interaction Patterns [done]
### Dependencies: None
### Description: Review and document the current agent interaction patterns in Cursor rules (dev_workflow.mdc, cursor_rules.mdc). Create comprehensive documentation that explains how agents should interact with the task system using existing commands and patterns.
### Details:
## Subtask ID: 2
## Title: Enhance Integration Between Cursor Agents and dev.js Commands
## Status: pending
## Dependencies: None
## Description: Improve the integration between Cursor's built-in agent capabilities and the dev.js command system. Ensure that agents can effectively use all task management commands and that the command outputs are optimized for agent consumption.
## Acceptance Criteria:
- Enhanced integration between Cursor agents and dev.js commands
## Subtask ID: 3
## Title: Optimize Command Responses for Agent Consumption
## Status: pending
## Dependencies: 15.2 ⏱️
## Description: Refine the output format of existing commands to ensure they are easily parseable by AI agents. Focus on consistent, structured outputs that agents can reliably interpret without requiring a separate parsing system.
## Acceptance Criteria:
- Command outputs optimized for agent consumption
## 2. Enhance Integration Between Cursor Agents and dev.js Commands [done]
### Dependencies: None
### Description: Improve the integration between Cursor's built-in agent capabilities and the dev.js command system. Ensure that agents can effectively use all task management commands and that the command outputs are optimized for agent consumption.
### Details:
## Subtask ID: 4
## Title: Improve Agent Workflow Documentation in Cursor Rules
## Status: pending
## Dependencies: 15.1 ⏱️, 15.3 ⏱️
## Description: Enhance the agent workflow documentation in dev_workflow.mdc and cursor_rules.mdc to provide clear guidance on how agents should interact with the task system. Include example interactions and best practices for agents.
## Acceptance Criteria:
- Enhanced agent workflow documentation in Cursor rules
## Subtask ID: 5
## Title: Add Agent-Specific Features to Existing Commands
## Status: pending
## Dependencies: 15.2 ⏱️
## Description: Identify and implement any missing agent-specific features in the existing command system. This may include additional flags, parameters, or output formats that are particularly useful for agent interactions.
## Acceptance Criteria:
- Agent-specific features added to existing commands
## 3. Optimize Command Responses for Agent Consumption [done]
### Dependencies: 2 (done)
### Description: Refine the output format of existing commands to ensure they are easily parseable by AI agents. Focus on consistent, structured outputs that agents can reliably interpret without requiring a separate parsing system.
### Details:
## 4. Improve Agent Workflow Documentation in Cursor Rules [done]
### Dependencies: 1 (done), 3 (done)
### Description: Enhance the agent workflow documentation in dev_workflow.mdc and cursor_rules.mdc to provide clear guidance on how agents should interact with the task system. Include example interactions and best practices for agents.
### Details:
## 5. Add Agent-Specific Features to Existing Commands [done]
### Dependencies: 2 (done)
### Description: Identify and implement any missing agent-specific features in the existing command system. This may include additional flags, parameters, or output formats that are particularly useful for agent interactions.
### Details:
## 6. Create Agent Usage Examples and Patterns [done]
### Dependencies: 3 (done), 4 (done)
### Description: Develop a set of example interactions and usage patterns that demonstrate how agents should effectively use the task system. Include these examples in the documentation to guide future agent implementations.
### Details:
## Subtask ID: 6
## Title: Create Agent Usage Examples and Patterns
## Status: pending
## Dependencies: 15.3 ⏱️, 15.4 ⏱️
## Description: Develop a set of example interactions and usage patterns that demonstrate how agents should effectively use the task system. Include these examples in the documentation to guide future agent implementations.
## Acceptance Criteria:
- Comprehensive set of agent usage examples and patterns

View File

@@ -1,7 +1,7 @@
# Task ID: 16
# Title: Create Configuration Management System
# Status: done
# Dependencies: 1 ✅, 2 ✅
# Dependencies: ✅ 1 (done), ✅ 2 (done)
# Priority: high
# Description: Implement robust configuration handling with environment variables and .env files.
# Details:
@@ -18,77 +18,39 @@ Build configuration management including:
Test configuration loading from various sources (environment variables, .env files). Verify that validation correctly identifies invalid configurations. Test that defaults are applied when values are missing.
# Subtasks:
## Subtask ID: 1
## Title: Implement Environment Variable Loading
## Status: done
## Dependencies: None
## Description: Create a module that loads environment variables from process.env and makes them accessible throughout the application. Implement a hierarchical structure for configuration values with proper typing. Include support for required vs. optional variables and implement a validation mechanism to ensure critical environment variables are present.
## Acceptance Criteria:
- Function created to access environment variables with proper TypeScript typing
- Support for required variables with validation
- Default values provided for optional variables
- Error handling for missing required variables
- Unit tests verifying environment variable loading works correctly
## 1. Implement Environment Variable Loading [done]
### Dependencies: None
### Description: Create a module that loads environment variables from process.env and makes them accessible throughout the application. Implement a hierarchical structure for configuration values with proper typing. Include support for required vs. optional variables and implement a validation mechanism to ensure critical environment variables are present.
### Details:
## Subtask ID: 2
## Title: Implement .env File Support
## Status: done
## Dependencies: 16.1 ✅
## Description: Add support for loading configuration from .env files using dotenv or a similar library. Implement file detection, parsing, and merging with existing environment variables. Handle multiple environments (.env.development, .env.production, etc.) and implement proper error handling for file reading issues.
## Acceptance Criteria:
- Integration with dotenv or equivalent library
- Support for multiple environment-specific .env files (.env.development, .env.production)
- Proper error handling for missing or malformed .env files
- Priority order established (process.env overrides .env values)
- Unit tests verifying .env file loading and overriding behavior
## Subtask ID: 3
## Title: Implement Configuration Validation
## Status: done
## Dependencies: 16.1 ✅, 16.2 ✅
## Description: Create a validation system for configuration values using a schema validation library like Joi, Zod, or Ajv. Define schemas for all configuration categories (API keys, file paths, feature flags, etc.). Implement validation that runs at startup and provides clear error messages for invalid configurations.
## Acceptance Criteria:
- Schema validation implemented for all configuration values
- Type checking and format validation for different value types
- Comprehensive error messages that clearly identify validation failures
- Support for custom validation rules for complex configuration requirements
- Unit tests covering validation of valid and invalid configurations
## 2. Implement .env File Support [done]
### Dependencies: 1 (done)
### Description: Add support for loading configuration from .env files using dotenv or a similar library. Implement file detection, parsing, and merging with existing environment variables. Handle multiple environments (.env.development, .env.production, etc.) and implement proper error handling for file reading issues.
### Details:
## Subtask ID: 4
## Title: Create Configuration Defaults and Override System
## Status: done
## Dependencies: 16.1 ✅, 16.2 ✅, 16.3 ✅
## Description: Implement a system of sensible defaults for all configuration values with the ability to override them via environment variables or .env files. Create a unified configuration object that combines defaults, .env values, and environment variables with proper precedence. Implement a caching mechanism to avoid repeated environment lookups.
## Acceptance Criteria:
- Default configuration values defined for all settings
- Clear override precedence (env vars > .env files > defaults)
- Configuration object accessible throughout the application
- Caching mechanism to improve performance
- Unit tests verifying override behavior works correctly
## Subtask ID: 5
## Title: Create .env.example Template
## Status: done
## Dependencies: 16.1 ✅, 16.2 ✅, 16.3 ✅, 16.4 ✅
## Description: Generate a comprehensive .env.example file that documents all supported environment variables, their purpose, format, and default values. Include comments explaining the purpose of each variable and provide examples. Ensure sensitive values are not included but have clear placeholders.
## Acceptance Criteria:
- Complete .env.example file with all supported variables
- Detailed comments explaining each variable's purpose and format
- Clear placeholders for sensitive values (API_KEY=your-api-key-here)
- Categorization of variables by function (API, logging, features, etc.)
- Documentation on how to use the .env.example file
## 3. Implement Configuration Validation [done]
### Dependencies: 1 (done), 2 (done)
### Description: Create a validation system for configuration values using a schema validation library like Joi, Zod, or Ajv. Define schemas for all configuration categories (API keys, file paths, feature flags, etc.). Implement validation that runs at startup and provides clear error messages for invalid configurations.
### Details:
## 4. Create Configuration Defaults and Override System [done]
### Dependencies: 1 (done), 2 (done), 3 (done)
### Description: Implement a system of sensible defaults for all configuration values with the ability to override them via environment variables or .env files. Create a unified configuration object that combines defaults, .env values, and environment variables with proper precedence. Implement a caching mechanism to avoid repeated environment lookups.
### Details:
## 5. Create .env.example Template [done]
### Dependencies: 1 (done), 2 (done), 3 (done), 4 (done)
### Description: Generate a comprehensive .env.example file that documents all supported environment variables, their purpose, format, and default values. Include comments explaining the purpose of each variable and provide examples. Ensure sensitive values are not included but have clear placeholders.
### Details:
## 6. Implement Secure API Key Handling [done]
### Dependencies: 1 (done), 2 (done), 3 (done), 4 (done)
### Description: Create a secure mechanism for handling sensitive configuration values like API keys. Implement masking of sensitive values in logs and error messages. Add validation for API key formats and implement a mechanism to detect and warn about insecure storage of API keys (e.g., committed to git). Add support for key rotation and refresh.
### Details:
## Subtask ID: 6
## Title: Implement Secure API Key Handling
## Status: done
## Dependencies: 16.1 ✅, 16.2 ✅, 16.3 ✅, 16.4 ✅
## Description: Create a secure mechanism for handling sensitive configuration values like API keys. Implement masking of sensitive values in logs and error messages. Add validation for API key formats and implement a mechanism to detect and warn about insecure storage of API keys (e.g., committed to git). Add support for key rotation and refresh.
## Acceptance Criteria:
- Secure storage of API keys and sensitive configuration
- Masking of sensitive values in logs and error messages
- Validation of API key formats (length, character set, etc.)
- Warning system for potentially insecure configuration practices
- Support for key rotation without application restart
- Unit tests verifying secure handling of sensitive configuration
These subtasks provide a comprehensive approach to implementing the configuration management system with a focus on security, validation, and developer experience. The tasks are sequenced to build upon each other logically, starting with basic environment variable support and progressing to more advanced features like secure API key handling.

View File

@@ -1,7 +1,7 @@
# Task ID: 17
# Title: Implement Comprehensive Logging System
# Status: done
# Dependencies: 2 ✅, 16 ✅
# Dependencies: ✅ 2 (done), ✅ 16 (done)
# Priority: medium
# Description: Create a flexible logging system with configurable levels and output formats.
# Details:
@@ -18,68 +18,33 @@ Implement logging system including:
Test logging at different verbosity levels. Verify that logs contain appropriate information for debugging. Test log file rotation with large volumes of logs.
# Subtasks:
## Subtask ID: 1
## Title: Implement Core Logging Framework with Log Levels
## Status: done
## Dependencies: None
## Description: Create a modular logging framework that supports multiple log levels (debug, info, warn, error). Implement a Logger class that handles message formatting, timestamp addition, and log level filtering. The framework should allow for global log level configuration through the configuration system and provide a clean API for logging messages at different levels.
## Acceptance Criteria:
- Logger class with methods for each log level (debug, info, warn, error)
- Log level filtering based on configuration settings
- Consistent log message format including timestamp, level, and context
- Unit tests for each log level and filtering functionality
- Documentation for logger usage in different parts of the application
## 1. Implement Core Logging Framework with Log Levels [done]
### Dependencies: None
### Description: Create a modular logging framework that supports multiple log levels (debug, info, warn, error). Implement a Logger class that handles message formatting, timestamp addition, and log level filtering. The framework should allow for global log level configuration through the configuration system and provide a clean API for logging messages at different levels.
### Details:
## Subtask ID: 2
## Title: Implement Configurable Output Destinations
## Status: done
## Dependencies: 17.1 ✅
## Description: Extend the logging framework to support multiple output destinations simultaneously. Implement adapters for console output, file output, and potentially other destinations (like remote logging services). Create a configuration system that allows specifying which log levels go to which destinations. Ensure thread-safe writing to prevent log corruption.
## Acceptance Criteria:
- Abstract destination interface that can be implemented by different output types
- Console output adapter with color-coding based on log level
- File output adapter with proper file handling and path configuration
- Configuration options to route specific log levels to specific destinations
- Ability to add custom output destinations through the adapter pattern
- Tests verifying logs are correctly routed to configured destinations
## Subtask ID: 3
## Title: Implement Command and API Interaction Logging
## Status: done
## Dependencies: 17.1 ✅, 17.2 ✅
## Description: Create specialized logging functionality for command execution and API interactions. For commands, log the command name, arguments, options, and execution status. For API interactions, log request details (URL, method, headers), response status, and timing information. Implement sanitization to prevent logging sensitive data like API keys or passwords.
## Acceptance Criteria:
- Command logger that captures command execution details
- API logger that records request/response details with timing information
- Data sanitization to mask sensitive information in logs
- Configuration options to control verbosity of command and API logs
- Integration with existing command execution flow
- Tests verifying proper logging of commands and API calls
## 2. Implement Configurable Output Destinations [done]
### Dependencies: 1 (done)
### Description: Extend the logging framework to support multiple output destinations simultaneously. Implement adapters for console output, file output, and potentially other destinations (like remote logging services). Create a configuration system that allows specifying which log levels go to which destinations. Ensure thread-safe writing to prevent log corruption.
### Details:
## 3. Implement Command and API Interaction Logging [done]
### Dependencies: 1 (done), 2 (done)
### Description: Create specialized logging functionality for command execution and API interactions. For commands, log the command name, arguments, options, and execution status. For API interactions, log request details (URL, method, headers), response status, and timing information. Implement sanitization to prevent logging sensitive data like API keys or passwords.
### Details:
## 4. Implement Error Tracking and Performance Metrics [done]
### Dependencies: 1 (done)
### Description: Enhance the logging system to provide detailed error tracking and performance metrics. For errors, capture stack traces, error codes, and contextual information. For performance metrics, implement timing utilities to measure execution duration of key operations. Create a consistent format for these specialized log types to enable easier analysis.
### Details:
## 5. Implement Log File Rotation and Management [done]
### Dependencies: 2 (done)
### Description: Create a log file management system that handles rotation based on file size or time intervals. Implement compression of rotated logs, automatic cleanup of old logs, and configurable retention policies. Ensure that log rotation happens without disrupting the application and that no log messages are lost during rotation.
### Details:
## Subtask ID: 4
## Title: Implement Error Tracking and Performance Metrics
## Status: done
## Dependencies: 17.1 ✅
## Description: Enhance the logging system to provide detailed error tracking and performance metrics. For errors, capture stack traces, error codes, and contextual information. For performance metrics, implement timing utilities to measure execution duration of key operations. Create a consistent format for these specialized log types to enable easier analysis.
## Acceptance Criteria:
- Error logging with full stack trace capture and error context
- Performance timer utility for measuring operation duration
- Standard format for error and performance log entries
- Ability to track related errors through correlation IDs
- Configuration options for performance logging thresholds
- Unit tests for error tracking and performance measurement
## Subtask ID: 5
## Title: Implement Log File Rotation and Management
## Status: done
## Dependencies: 17.2 ✅
## Description: Create a log file management system that handles rotation based on file size or time intervals. Implement compression of rotated logs, automatic cleanup of old logs, and configurable retention policies. Ensure that log rotation happens without disrupting the application and that no log messages are lost during rotation.
## Acceptance Criteria:
- Log rotation based on configurable file size or time interval
- Compressed archive creation for rotated logs
- Configurable retention policy for log archives
- Zero message loss during rotation operations
- Proper file locking to prevent corruption during rotation
- Configuration options for rotation settings
- Tests verifying rotation functionality with large log volumes
- Documentation for log file location and naming conventions

View File

@@ -1,7 +1,7 @@
# Task ID: 18
# Title: Create Comprehensive User Documentation
# Status: done
# Dependencies: 1 ✅, 2 ✅, 3 ✅, 4 ✅, 5 ✅, 6 ✅, 7 ✅, 11 ✅, 12 ✅, 16 ✅
# Dependencies: ✅ 1 (done), ✅ 2 (done), ✅ 3 (done), ✅ 4 (done), ✅ 5 (done), ✅ 6 (done), ✅ 7 (done), ✅ 11 (done), ✅ 12 (done), ✅ 16 (done)
# Priority: medium
# Description: Develop complete user documentation including README, examples, and troubleshooting guides.
# Details:
@@ -19,80 +19,39 @@ Create user documentation including:
Review documentation for clarity and completeness. Have users unfamiliar with the system attempt to follow the documentation and note any confusion or issues.
# Subtasks:
## Subtask ID: 1
## Title: Create Detailed README with Installation and Usage Instructions
## Status: done
## Dependencies: 18.3 ✅
## Description: Develop a comprehensive README.md file that serves as the primary documentation entry point. Include project overview, installation steps for different environments, basic usage examples, and links to other documentation sections. Structure the README with clear headings, code blocks for commands, and screenshots where helpful.
## Acceptance Criteria:
- README includes project overview, features list, and system requirements
- Installation instructions cover all supported platforms with step-by-step commands
- Basic usage examples demonstrate core functionality with command syntax
- Configuration section explains environment variables and .env file usage
- Documentation includes badges for version, license, and build status
- All sections are properly formatted with Markdown for readability
## 1. Create Detailed README with Installation and Usage Instructions [done]
### Dependencies: 3 (done)
### Description: Develop a comprehensive README.md file that serves as the primary documentation entry point. Include project overview, installation steps for different environments, basic usage examples, and links to other documentation sections. Structure the README with clear headings, code blocks for commands, and screenshots where helpful.
### Details:
## Subtask ID: 2
## Title: Develop Command Reference Documentation
## Status: done
## Dependencies: 18.3 ✅
## Description: Create detailed documentation for all CLI commands, their options, arguments, and examples. Organize commands by functionality category, include syntax diagrams, and provide real-world examples for each command. Document all global options and environment variables that affect command behavior.
## Acceptance Criteria:
- All commands are documented with syntax, options, and arguments
- Each command includes at least 2 practical usage examples
- Commands are organized into logical categories (task management, AI integration, etc.)
- Global options are documented with their effects on command execution
- Exit codes and error messages are documented for troubleshooting
- Documentation includes command output examples
## Subtask ID: 3
## Title: Create Configuration and Environment Setup Guide
## Status: done
## Dependencies: None
## Description: Develop a comprehensive guide for configuring the application, including environment variables, .env file setup, API keys management, and configuration best practices. Include security considerations for API keys and sensitive information. Document all configuration options with their default values and effects.
## Acceptance Criteria:
- All environment variables are documented with purpose, format, and default values
- Step-by-step guide for setting up .env file with examples
- Security best practices for managing API keys
- Configuration troubleshooting section with common issues and solutions
- Documentation includes example configurations for different use cases
- Validation rules for configuration values are clearly explained
## 2. Develop Command Reference Documentation [done]
### Dependencies: 3 (done)
### Description: Create detailed documentation for all CLI commands, their options, arguments, and examples. Organize commands by functionality category, include syntax diagrams, and provide real-world examples for each command. Document all global options and environment variables that affect command behavior.
### Details:
## Subtask ID: 4
## Title: Develop Example Workflows and Use Cases
## Status: done
## Dependencies: 18.3 ✅, 18.6 ✅
## Description: Create detailed documentation of common workflows and use cases, showing how to use the tool effectively for different scenarios. Include step-by-step guides with command sequences, expected outputs, and explanations. Cover basic to advanced workflows, including PRD parsing, task expansion, and implementation drift handling.
## Acceptance Criteria:
- At least 5 complete workflow examples from initialization to completion
- Each workflow includes all commands in sequence with expected outputs
- Screenshots or terminal recordings illustrate the workflows
- Explanation of decision points and alternatives within workflows
- Advanced use cases demonstrate integration with development processes
- Examples show how to handle common edge cases and errors
## Subtask ID: 5
## Title: Create Troubleshooting Guide and FAQ
## Status: done
## Dependencies: 18.1 ✅, 18.2 ✅, 18.3 ✅
## Description: Develop a comprehensive troubleshooting guide that addresses common issues, error messages, and their solutions. Include a FAQ section covering common questions about usage, configuration, and best practices. Document known limitations and workarounds for edge cases.
## Acceptance Criteria:
- All error messages are documented with causes and solutions
- Common issues are organized by category (installation, configuration, execution)
- FAQ covers at least 15 common questions with detailed answers
- Troubleshooting decision trees help users diagnose complex issues
- Known limitations and edge cases are clearly documented
- Recovery procedures for data corruption or API failures are included
## 3. Create Configuration and Environment Setup Guide [done]
### Dependencies: None
### Description: Develop a comprehensive guide for configuring the application, including environment variables, .env file setup, API keys management, and configuration best practices. Include security considerations for API keys and sensitive information. Document all configuration options with their default values and effects.
### Details:
## 4. Develop Example Workflows and Use Cases [done]
### Dependencies: 3 (done), 6 (done)
### Description: Create detailed documentation of common workflows and use cases, showing how to use the tool effectively for different scenarios. Include step-by-step guides with command sequences, expected outputs, and explanations. Cover basic to advanced workflows, including PRD parsing, task expansion, and implementation drift handling.
### Details:
## 5. Create Troubleshooting Guide and FAQ [done]
### Dependencies: 1 (done), 2 (done), 3 (done)
### Description: Develop a comprehensive troubleshooting guide that addresses common issues, error messages, and their solutions. Include a FAQ section covering common questions about usage, configuration, and best practices. Document known limitations and workarounds for edge cases.
### Details:
## 6. Develop API Integration and Extension Documentation [done]
### Dependencies: 5 (done)
### Description: Create technical documentation for API integrations (Claude, Perplexity) and extension points. Include details on prompt templates, response handling, token optimization, and custom integrations. Document the internal architecture to help developers extend the tool with new features or integrations.
### Details:
## Subtask ID: 6
## Title: Develop API Integration and Extension Documentation
## Status: done
## Dependencies: 18.5 ✅
## Description: Create technical documentation for API integrations (Claude, Perplexity) and extension points. Include details on prompt templates, response handling, token optimization, and custom integrations. Document the internal architecture to help developers extend the tool with new features or integrations.
## Acceptance Criteria:
- Detailed documentation of all API integrations with authentication requirements
- Prompt templates are documented with variables and expected responses
- Token usage optimization strategies are explained
- Extension points are documented with examples
- Internal architecture diagrams show component relationships
- Custom integration guide includes step-by-step instructions and code examples

View File

@@ -1,7 +1,7 @@
# Task ID: 19
# Title: Implement Error Handling and Recovery
# Status: pending
# Dependencies: 1 ✅, 2 ✅, 3 ✅, 5 ✅, 9 ✅, 16 ✅, 17 ✅
# Status: done
# Dependencies: ✅ 1 (done), ✅ 2 (done), ✅ 3 (done), ✅ 5 (done), ✅ 9 (done), ✅ 16 (done), ✅ 17 (done)
# Priority: high
# Description: Create robust error handling throughout the system with helpful error messages and recovery options.
# Details:
@@ -18,50 +18,39 @@ Implement error handling including:
Deliberately trigger various error conditions and verify that the system handles them gracefully. Check that error messages are helpful and provide clear guidance on how to resolve issues.
# Subtasks:
## Subtask ID: 1
## Title: Define Error Message Format and Structure
## Status: pending
## Dependencies: None
## Description: Create a standardized error message format that includes error codes, descriptive messages, and recovery suggestions. Implement a centralized ErrorMessage class or module that enforces this structure across the application. This should include methods for generating consistent error messages and translating error codes to user-friendly descriptions.
## Acceptance Criteria:
- ErrorMessage class/module is implemented with methods for creating structured error messages
## 1. Define Error Message Format and Structure [done]
### Dependencies: None
### Description: Create a standardized error message format that includes error codes, descriptive messages, and recovery suggestions. Implement a centralized ErrorMessage class or module that enforces this structure across the application. This should include methods for generating consistent error messages and translating error codes to user-friendly descriptions.
### Details:
## Subtask ID: 2
## Title: Implement API Error Handling with Retry Logic
## Status: pending
## Dependencies: None
## Description: Develop a robust error handling system for API calls, including automatic retries with exponential backoff. Create a wrapper for API requests that catches common errors (e.g., network timeouts, rate limiting) and implements appropriate retry logic. This should be integrated with both the Claude and Perplexity API calls.
## Acceptance Criteria:
- API request wrapper is implemented with configurable retry logic
## Subtask ID: 3
## Title: Develop File System Error Recovery Mechanisms
## Status: pending
## Dependencies: 19.1 ⏱️
## Description: Implement error handling and recovery mechanisms for file system operations, focusing on tasks.json and individual task files. This should include handling of file not found errors, permission issues, and data corruption scenarios. Implement automatic backups and recovery procedures to ensure data integrity.
## Acceptance Criteria:
- File system operations are wrapped with comprehensive error handling
## 2. Implement API Error Handling with Retry Logic [done]
### Dependencies: None
### Description: Develop a robust error handling system for API calls, including automatic retries with exponential backoff. Create a wrapper for API requests that catches common errors (e.g., network timeouts, rate limiting) and implements appropriate retry logic. This should be integrated with both the Claude and Perplexity API calls.
### Details:
## Subtask ID: 4
## Title: Enhance Data Validation with Detailed Error Feedback
## Status: pending
## Dependencies: 19.1 ⏱️, 19.3 ⏱️
## Description: Improve the existing data validation system to provide more specific and actionable error messages. Implement detailed validation checks for all user inputs and task data, with clear error messages that pinpoint the exact issue and how to resolve it. This should cover task creation, updates, and any data imported from external sources.
## Acceptance Criteria:
- Enhanced validation checks are implemented for all task properties and user inputs
## Subtask ID: 5
## Title: Implement Command Syntax Error Handling and Guidance
## Status: pending
## Dependencies: 19.2 ⏱️
## Description: Enhance the CLI to provide more helpful error messages and guidance when users input invalid commands or options. Implement a "did you mean?" feature for close matches to valid commands, and provide context-sensitive help for command syntax errors. This should integrate with the existing Commander.js setup.
## Acceptance Criteria:
- Invalid commands trigger helpful error messages with suggestions for valid alternatives
## 3. Develop File System Error Recovery Mechanisms [done]
### Dependencies: 1 (done)
### Description: Implement error handling and recovery mechanisms for file system operations, focusing on tasks.json and individual task files. This should include handling of file not found errors, permission issues, and data corruption scenarios. Implement automatic backups and recovery procedures to ensure data integrity.
### Details:
## 4. Enhance Data Validation with Detailed Error Feedback [done]
### Dependencies: 1 (done), 3 (done)
### Description: Improve the existing data validation system to provide more specific and actionable error messages. Implement detailed validation checks for all user inputs and task data, with clear error messages that pinpoint the exact issue and how to resolve it. This should cover task creation, updates, and any data imported from external sources.
### Details:
## 5. Implement Command Syntax Error Handling and Guidance [done]
### Dependencies: 2 (done)
### Description: Enhance the CLI to provide more helpful error messages and guidance when users input invalid commands or options. Implement a "did you mean?" feature for close matches to valid commands, and provide context-sensitive help for command syntax errors. This should integrate with the existing Commander.js setup.
### Details:
## 6. Develop System State Recovery After Critical Failures [done]
### Dependencies: 1 (done), 3 (done)
### Description: Implement a system state recovery mechanism to handle critical failures that could leave the task management system in an inconsistent state. This should include creating periodic snapshots of the system state, implementing a recovery procedure to restore from these snapshots, and providing tools for manual intervention if automatic recovery fails.
### Details:
## Subtask ID: 6
## Title: Develop System State Recovery After Critical Failures
## Status: pending
## Dependencies: 19.1 ⏱️, 19.3 ⏱️
## Description: Implement a system state recovery mechanism to handle critical failures that could leave the task management system in an inconsistent state. This should include creating periodic snapshots of the system state, implementing a recovery procedure to restore from these snapshots, and providing tools for manual intervention if automatic recovery fails.
## Acceptance Criteria:
- Periodic snapshots of the tasks.json and related state are automatically created

View File

@@ -1,7 +1,7 @@
# Task ID: 20
# Title: Create Token Usage Tracking and Cost Management
# Status: pending
# Dependencies: 5 ✅, 9 ✅, 17 ✅
# Status: done
# Dependencies: ✅ 5 (done), ✅ 9 (done), ✅ 17 (done)
# Priority: medium
# Description: Implement system for tracking API token usage and managing costs.
# Details:
@@ -18,42 +18,33 @@ Implement token tracking including:
Track token usage across various operations and verify accuracy. Test that limits properly prevent excessive usage. Verify that caching reduces token consumption for repeated operations.
# Subtasks:
## Subtask ID: 1
## Title: Implement Token Usage Tracking for API Calls
## Status: pending
## Dependencies: 20.5 ⏱️
## Description: Create a middleware or wrapper function that intercepts all API calls to OpenAI, Anthropic, and Perplexity. This function should count the number of tokens used in both the request and response, storing this information in a persistent data store (e.g., SQLite database). Implement a caching mechanism to reduce redundant API calls and token usage.
## Acceptance Criteria:
- Token usage is accurately tracked for all API calls
## 1. Implement Token Usage Tracking for API Calls [done]
### Dependencies: 5 (done)
### Description: Create a middleware or wrapper function that intercepts all API calls to OpenAI, Anthropic, and Perplexity. This function should count the number of tokens used in both the request and response, storing this information in a persistent data store (e.g., SQLite database). Implement a caching mechanism to reduce redundant API calls and token usage.
### Details:
## Subtask ID: 2
## Title: Develop Configurable Usage Limits
## Status: pending
## Dependencies: None
## Description: Create a configuration system that allows setting token usage limits at the project, user, and API level. Implement a mechanism to enforce these limits by checking the current usage against the configured limits before making API calls. Add the ability to set different limit types (e.g., daily, weekly, monthly) and actions to take when limits are reached (e.g., block calls, send notifications).
## Acceptance Criteria:
- Configuration file or database table for storing usage limits
## Subtask ID: 3
## Title: Implement Token Usage Reporting and Cost Estimation
## Status: pending
## Dependencies: 20.1 ⏱️, 20.2 ⏱️
## Description: Develop a reporting module that generates detailed token usage reports. Include breakdowns by API, user, and time period. Implement cost estimation features by integrating current pricing information for each API. Create both command-line and programmatic interfaces for generating reports and estimates.
## Acceptance Criteria:
- CLI command for generating usage reports with various filters
## 2. Develop Configurable Usage Limits [done]
### Dependencies: None
### Description: Create a configuration system that allows setting token usage limits at the project, user, and API level. Implement a mechanism to enforce these limits by checking the current usage against the configured limits before making API calls. Add the ability to set different limit types (e.g., daily, weekly, monthly) and actions to take when limits are reached (e.g., block calls, send notifications).
### Details:
## 3. Implement Token Usage Reporting and Cost Estimation [done]
### Dependencies: 1 (done), 2 (done)
### Description: Develop a reporting module that generates detailed token usage reports. Include breakdowns by API, user, and time period. Implement cost estimation features by integrating current pricing information for each API. Create both command-line and programmatic interfaces for generating reports and estimates.
### Details:
## 4. Optimize Token Usage in Prompts [done]
### Dependencies: None
### Description: Implement a prompt optimization system that analyzes and refines prompts to reduce token usage while maintaining effectiveness. Use techniques such as prompt compression, removing redundant information, and leveraging efficient prompting patterns. Integrate this system into the existing prompt generation and API call processes.
### Details:
## 5. Develop Token Usage Alert System [done]
### Dependencies: 2 (done), 3 (done)
### Description: Create an alert system that monitors token usage in real-time and sends notifications when usage approaches or exceeds defined thresholds. Implement multiple notification channels (e.g., email, Slack, system logs) and allow for customizable alert rules. Integrate this system with the existing logging and reporting modules.
### Details:
## Subtask ID: 4
## Title: Optimize Token Usage in Prompts
## Status: pending
## Dependencies: None
## Description: Implement a prompt optimization system that analyzes and refines prompts to reduce token usage while maintaining effectiveness. Use techniques such as prompt compression, removing redundant information, and leveraging efficient prompting patterns. Integrate this system into the existing prompt generation and API call processes.
## Acceptance Criteria:
- Prompt optimization function reduces average token usage by at least 10%
## Subtask ID: 5
## Title: Develop Token Usage Alert System
## Status: pending
## Dependencies: 20.2 ⏱️, 20.3 ⏱️
## Description: Create an alert system that monitors token usage in real-time and sends notifications when usage approaches or exceeds defined thresholds. Implement multiple notification channels (e.g., email, Slack, system logs) and allow for customizable alert rules. Integrate this system with the existing logging and reporting modules.
## Acceptance Criteria:
- Real-time monitoring of token usage against configured limits

View File

@@ -1,7 +1,7 @@
# Task ID: 21
# Title: Refactor dev.js into Modular Components
# Status: pending
# Dependencies: 3 ✅, 16 ✅, 17 ✅
# Status: done
# Dependencies: ✅ 3 (done), ✅ 16 (done), ✅ 17 (done)
# Priority: high
# Description: Restructure the monolithic dev.js file into separate modular components to improve code maintainability, readability, and testability while preserving all existing functionality.
# Details:
@@ -58,42 +58,33 @@ Testing should verify that functionality remains identical after refactoring:
- Ensure README is updated if necessary to reflect architectural changes
# Subtasks:
## Subtask ID: 1
## Title: Analyze Current dev.js Structure and Plan Module Boundaries
## Status: pending
## Dependencies: None
## Description: Perform a comprehensive analysis of the existing dev.js file to identify logical boundaries for the new modules. Create a detailed mapping document that outlines which functions, variables, and code blocks will move to which module files. Identify shared dependencies, potential circular references, and determine the appropriate interfaces between modules.
## Acceptance Criteria:
- Complete inventory of all functions, variables, and code blocks in dev.js
## 1. Analyze Current dev.js Structure and Plan Module Boundaries [done]
### Dependencies: None
### Description: Perform a comprehensive analysis of the existing dev.js file to identify logical boundaries for the new modules. Create a detailed mapping document that outlines which functions, variables, and code blocks will move to which module files. Identify shared dependencies, potential circular references, and determine the appropriate interfaces between modules.
### Details:
## Subtask ID: 2
## Title: Create Core Module Structure and Entry Point Refactoring
## Status: pending
## Dependencies: 21.1 ⏱️
## Description: Create the skeleton structure for all module files (commands.js, ai-services.js, task-manager.js, ui.js, utils.js) with proper export statements. Refactor dev.js to serve as the entry point that imports and orchestrates these modules. Implement the basic initialization flow and command-line argument parsing in the new structure.
## Acceptance Criteria:
- All module files created with appropriate JSDoc headers explaining purpose
## Subtask ID: 3
## Title: Implement Core Module Functionality with Dependency Injection
## Status: pending
## Dependencies: 21.2 ⏱️
## Description: Migrate the core functionality from dev.js into the appropriate modules following the mapping document. Implement proper dependency injection to avoid circular dependencies. Ensure each module has a clear API and properly encapsulates its internal state. Focus on the critical path functionality first.
## Acceptance Criteria:
- All core functionality migrated to appropriate modules
## 2. Create Core Module Structure and Entry Point Refactoring [done]
### Dependencies: 1 (done)
### Description: Create the skeleton structure for all module files (commands.js, ai-services.js, task-manager.js, ui.js, utils.js) with proper export statements. Refactor dev.js to serve as the entry point that imports and orchestrates these modules. Implement the basic initialization flow and command-line argument parsing in the new structure.
### Details:
## 3. Implement Core Module Functionality with Dependency Injection [done]
### Dependencies: 2 (done)
### Description: Migrate the core functionality from dev.js into the appropriate modules following the mapping document. Implement proper dependency injection to avoid circular dependencies. Ensure each module has a clear API and properly encapsulates its internal state. Focus on the critical path functionality first.
### Details:
## 4. Implement Error Handling and Complete Module Migration [done]
### Dependencies: 3 (done)
### Description: Establish a consistent error handling pattern across all modules. Complete the migration of remaining functionality from dev.js to the appropriate modules. Ensure all edge cases, error scenarios, and helper functions are properly moved and integrated. Update all import/export statements throughout the codebase to reference the new module structure.
### Details:
## 5. Test, Document, and Finalize Modular Structure [done]
### Dependencies: 21.4
### Description: Perform comprehensive testing of the refactored codebase to ensure all functionality works as expected. Add detailed JSDoc comments to all modules, functions, and significant code blocks. Create or update developer documentation explaining the new modular structure, module responsibilities, and how they interact. Perform a final code review to ensure code quality, consistency, and adherence to best practices.
### Details:
## Subtask ID: 4
## Title: Implement Error Handling and Complete Module Migration
## Status: pending
## Dependencies: 21.3 ⏱️
## Description: Establish a consistent error handling pattern across all modules. Complete the migration of remaining functionality from dev.js to the appropriate modules. Ensure all edge cases, error scenarios, and helper functions are properly moved and integrated. Update all import/export statements throughout the codebase to reference the new module structure.
## Acceptance Criteria:
- Consistent error handling pattern implemented across all modules
## Subtask ID: 5
## Title: Test, Document, and Finalize Modular Structure
## Status: pending
## Dependencies: 21.4 ⏱️
## Description: Perform comprehensive testing of the refactored codebase to ensure all functionality works as expected. Add detailed JSDoc comments to all modules, functions, and significant code blocks. Create or update developer documentation explaining the new modular structure, module responsibilities, and how they interact. Perform a final code review to ensure code quality, consistency, and adherence to best practices.
## Acceptance Criteria:
- All existing functionality works exactly as before

View File

@@ -1,9 +1,9 @@
# Task ID: 22
# Title: Create Comprehensive Test Suite for Claude Task Master CLI
# Title: Create Comprehensive Test Suite for Task Master CLI
# Status: pending
# Dependencies: 21 ⏱️
# Dependencies: 21 (done)
# Priority: high
# Description: Develop a complete testing infrastructure for the Claude Task Master CLI that includes unit, integration, and end-to-end tests to verify all core functionality and error handling.
# Description: Develop a complete testing infrastructure for the Task Master CLI that includes unit, integration, and end-to-end tests to verify all core functionality and error handling.
# Details:
Implement a comprehensive test suite using Jest as the testing framework. The test suite should be organized into three main categories:
@@ -57,26 +57,21 @@ Verification will involve:
The task will be considered complete when all tests pass consistently, coverage meets targets, and the test suite can detect intentionally introduced bugs.
# Subtasks:
## Subtask ID: 1
## Title: Set Up Jest Testing Environment
## Status: pending
## Dependencies: None
## Description: Configure Jest for the project, including setting up the jest.config.js file, adding necessary dependencies, and creating the initial test directory structure. Implement proper mocking for Claude API interactions, file system operations, and user input/output. Set up test coverage reporting and configure it to run in the CI pipeline.
## Acceptance Criteria:
- jest.config.js is properly configured for the project
## 1. Set Up Jest Testing Environment [pending]
### Dependencies: None
### Description: Configure Jest for the project, including setting up the jest.config.js file, adding necessary dependencies, and creating the initial test directory structure. Implement proper mocking for Claude API interactions, file system operations, and user input/output. Set up test coverage reporting and configure it to run in the CI pipeline.
### Details:
## 2. Implement Unit Tests for Core Components [pending]
### Dependencies: 1 (pending)
### Description: Create a comprehensive set of unit tests for all utility functions, core logic components, and individual modules of the Task Master CLI. This includes tests for task creation, parsing, manipulation, data storage, retrieval, and formatting functions. Ensure all edge cases and error scenarios are covered.
### Details:
## 3. Develop Integration and End-to-End Tests [pending]
### Dependencies: 1 (pending), 2 (pending)
### Description: Create integration tests that verify the correct interaction between different components of the CLI, including command execution, option parsing, and data flow. Implement end-to-end tests that simulate complete user workflows, such as creating a task, expanding it, and updating its status. Include tests for error scenarios, recovery processes, and handling large numbers of tasks.
### Details:
## Subtask ID: 2
## Title: Implement Unit Tests for Core Components
## Status: pending
## Dependencies: 22.1 ⏱️
## Description: Create a comprehensive set of unit tests for all utility functions, core logic components, and individual modules of the Claude Task Master CLI. This includes tests for task creation, parsing, manipulation, data storage, retrieval, and formatting functions. Ensure all edge cases and error scenarios are covered.
## Acceptance Criteria:
- Unit tests are implemented for all utility functions in the project
## Subtask ID: 3
## Title: Develop Integration and End-to-End Tests
## Status: pending
## Dependencies: 22.1 ⏱️, 22.2 ⏱️
## Description: Create integration tests that verify the correct interaction between different components of the CLI, including command execution, option parsing, and data flow. Implement end-to-end tests that simulate complete user workflows, such as creating a task, expanding it, and updating its status. Include tests for error scenarios, recovery processes, and handling large numbers of tasks.
## Acceptance Criteria:
- Integration tests cover all CLI commands (create, expand, update, list, etc.)

58
tasks/task_023.txt Normal file
View File

@@ -0,0 +1,58 @@
# Task ID: 23
# Title: Implement MCP (Model Context Protocol) Server Functionality for Task Master
# Status: pending
# Dependencies: ⏱️ 22 (pending)
# Priority: medium
# Description: Extend Task Master to function as an MCP server, allowing it to provide context management services to other applications following the Model Context Protocol specification.
# Details:
This task involves implementing the Model Context Protocol server capabilities within Task Master. The implementation should:
1. Create a new module `mcp-server.js` that implements the core MCP server functionality
2. Implement the required MCP endpoints:
- `/context` - For retrieving and updating context
- `/models` - For listing available models
- `/execute` - For executing operations with context
3. Develop a context management system that can:
- Store and retrieve context data efficiently
- Handle context windowing and truncation when limits are reached
- Support context metadata and tagging
4. Add authentication and authorization mechanisms for MCP clients
5. Implement proper error handling and response formatting according to MCP specifications
6. Create configuration options in Task Master to enable/disable the MCP server functionality
7. Add documentation for how to use Task Master as an MCP server
8. Ensure the implementation is compatible with existing MCP clients
9. Optimize for performance, especially for context retrieval operations
10. Add logging for MCP server operations
The implementation should follow RESTful API design principles and should be able to handle concurrent requests from multiple clients.
# Test Strategy:
Testing for the MCP server functionality should include:
1. Unit tests:
- Test each MCP endpoint handler function independently
- Verify context storage and retrieval mechanisms
- Test authentication and authorization logic
- Validate error handling for various failure scenarios
2. Integration tests:
- Set up a test MCP server instance
- Test complete request/response cycles for each endpoint
- Verify context persistence across multiple requests
- Test with various payload sizes and content types
3. Compatibility tests:
- Test with existing MCP client libraries
- Verify compliance with the MCP specification
- Ensure backward compatibility with any MCP versions supported
4. Performance tests:
- Measure response times for context operations with various context sizes
- Test concurrent request handling
- Verify memory usage remains within acceptable limits during extended operation
5. Security tests:
- Verify authentication mechanisms cannot be bypassed
- Test for common API vulnerabilities (injection, CSRF, etc.)
All tests should be automated and included in the CI/CD pipeline. Documentation should include examples of how to test the MCP server functionality manually using tools like curl or Postman.

101
tasks/task_024.txt Normal file
View File

@@ -0,0 +1,101 @@
# Task ID: 24
# Title: Implement AI-Powered Test Generation Command
# Status: pending
# Dependencies: ⏱️ 22 (pending)
# Priority: high
# Description: Create a new 'generate-test' command that leverages AI to automatically produce Jest test files for tasks based on their descriptions and subtasks.
# Details:
Implement a new command in the Task Master CLI that generates comprehensive Jest test files for tasks. The command should be callable as 'task-master generate-test --id=1' and should:
1. Accept a task ID parameter to identify which task to generate tests for
2. Retrieve the task and its subtasks from the task store
3. Analyze the task description, details, and subtasks to understand implementation requirements
4. Construct an appropriate prompt for an AI service (e.g., OpenAI API) that requests generation of Jest tests
5. Process the AI response to create a well-formatted test file named 'task_XXX.test.js' where XXX is the zero-padded task ID
6. Include appropriate test cases that cover the main functionality described in the task
7. Generate mocks for external dependencies identified in the task description
8. Create assertions that validate the expected behavior
9. Handle both parent tasks and subtasks appropriately (for subtasks, name the file 'task_XXX_YYY.test.js' where YYY is the subtask ID)
10. Include error handling for API failures, invalid task IDs, etc.
11. Add appropriate documentation for the command in the help system
The implementation should utilize the existing AI service integration in the codebase and maintain consistency with the current command structure and error handling patterns.
# Test Strategy:
Testing for this feature should include:
1. Unit tests for the command handler function to verify it correctly processes arguments and options
2. Mock tests for the AI service integration to ensure proper prompt construction and response handling
3. Integration tests that verify the end-to-end flow using a mock AI response
4. Tests for error conditions including:
- Invalid task IDs
- Network failures when contacting the AI service
- Malformed AI responses
- File system permission issues
5. Verification that generated test files follow Jest conventions and can be executed
6. Tests for both parent task and subtask handling
7. Manual verification of the quality of generated tests by running them against actual task implementations
Create a test fixture with sample tasks of varying complexity to evaluate the test generation capabilities across different scenarios. The tests should verify that the command outputs appropriate success/error messages to the console and creates files in the expected location with proper content structure.
# Subtasks:
## 1. Create command structure for 'generate-test' [pending]
### Dependencies: None
### Description: Implement the basic structure for the 'generate-test' command, including command registration, parameter validation, and help documentation
### Details:
Implementation steps:
1. Create a new file `src/commands/generate-test.js`
2. Implement the command structure following the pattern of existing commands
3. Register the new command in the CLI framework
4. Add command options for task ID (--id=X) parameter
5. Implement parameter validation to ensure a valid task ID is provided
6. Add help documentation for the command
7. Create the basic command flow that retrieves the task from the task store
8. Implement error handling for invalid task IDs and other basic errors
Testing approach:
- Test command registration
- Test parameter validation (missing ID, invalid ID format)
- Test error handling for non-existent task IDs
- Test basic command flow with a mock task store
## 2. Implement AI prompt construction and API integration [pending]
### Dependencies: 1 (pending)
### Description: Develop the logic to analyze tasks, construct appropriate AI prompts, and interact with the AI service to generate test content
### Details:
Implementation steps:
1. Create a utility function to analyze task descriptions and subtasks for test requirements
2. Implement a prompt builder that formats task information into an effective AI prompt
3. The prompt should request Jest test generation with specifics about mocking dependencies and creating assertions
4. Integrate with the existing AI service in the codebase to send the prompt
5. Process the AI response to extract the generated test code
6. Implement error handling for API failures, rate limits, and malformed responses
7. Add appropriate logging for the AI interaction process
Testing approach:
- Test prompt construction with various task types
- Test AI service integration with mocked responses
- Test error handling for API failures
- Test response processing with sample AI outputs
## 3. Implement test file generation and output [pending]
### Dependencies: 2 (pending)
### Description: Create functionality to format AI-generated tests into proper Jest test files and save them to the appropriate location
### Details:
Implementation steps:
1. Create a utility to format the AI response into a well-structured Jest test file
2. Implement naming logic for test files (task_XXX.test.js for parent tasks, task_XXX_YYY.test.js for subtasks)
3. Add logic to determine the appropriate file path for saving the test
4. Implement file system operations to write the test file
5. Add validation to ensure the generated test follows Jest conventions
6. Implement formatting of the test file for consistency with project coding standards
7. Add user feedback about successful test generation and file location
8. Implement handling for both parent tasks and subtasks
Testing approach:
- Test file naming logic for various task/subtask combinations
- Test file content formatting with sample AI outputs
- Test file system operations with mocked fs module
- Test the complete flow from command input to file output
- Verify generated tests can be executed by Jest

View File

@@ -900,7 +900,7 @@
"id": 14,
"title": "Develop Agent Workflow Guidelines",
"description": "Create comprehensive guidelines for how AI agents should interact with the task system.",
"status": "pending",
"status": "done",
"dependencies": [
13
],
@@ -912,7 +912,7 @@
"id": 1,
"title": "Document Task Discovery Workflow",
"description": "Create a comprehensive document outlining how AI agents should discover and interpret new tasks within the system. This should include steps for parsing the tasks.json file, interpreting task metadata, and understanding the relationships between tasks and subtasks. Implement example code snippets in Node.js demonstrating how to traverse the task structure and extract relevant information.",
"status": "pending",
"status": "done",
"dependencies": [],
"acceptanceCriteria": "- Detailed markdown document explaining the task discovery process"
},
@@ -920,7 +920,7 @@
"id": 2,
"title": "Implement Task Selection Algorithm",
"description": "Develop an algorithm for AI agents to select the most appropriate task to work on based on priority, dependencies, and current project status. This should include logic for evaluating task urgency, managing blocked tasks, and optimizing workflow efficiency. Implement the algorithm in JavaScript and integrate it with the existing task management system.",
"status": "pending",
"status": "done",
"dependencies": [
1
],
@@ -930,7 +930,7 @@
"id": 3,
"title": "Create Implementation Guidance Generator",
"description": "Develop a system that generates detailed implementation guidance for AI agents based on task descriptions and project context. This should leverage the Anthropic Claude API to create step-by-step instructions, suggest relevant libraries or tools, and provide code snippets or pseudocode where appropriate. Implement caching to reduce API calls and improve performance.",
"status": "pending",
"status": "done",
"dependencies": [
5
],
@@ -940,7 +940,7 @@
"id": 4,
"title": "Develop Verification Procedure Framework",
"description": "Create a flexible framework for defining and executing verification procedures for completed tasks. This should include a DSL (Domain Specific Language) for specifying acceptance criteria, automated test generation where possible, and integration with popular testing frameworks. Implement hooks for both automated and manual verification steps.",
"status": "pending",
"status": "done",
"dependencies": [
1,
2
@@ -951,7 +951,7 @@
"id": 5,
"title": "Implement Dynamic Task Prioritization System",
"description": "Develop a system that dynamically adjusts task priorities based on project progress, dependencies, and external factors. This should include an algorithm for recalculating priorities, a mechanism for propagating priority changes through dependency chains, and an API for external systems to influence priorities. Implement this as a background process that periodically updates the tasks.json file.",
"status": "pending",
"status": "done",
"dependencies": [
1,
2,
@@ -965,7 +965,7 @@
"id": 15,
"title": "Optimize Agent Integration with Cursor and dev.js Commands",
"description": "Document and enhance existing agent interaction patterns through Cursor rules and dev.js commands.",
"status": "pending",
"status": "done",
"dependencies": [
2,
14
@@ -978,7 +978,7 @@
"id": 1,
"title": "Document Existing Agent Interaction Patterns",
"description": "Review and document the current agent interaction patterns in Cursor rules (dev_workflow.mdc, cursor_rules.mdc). Create comprehensive documentation that explains how agents should interact with the task system using existing commands and patterns.",
"status": "pending",
"status": "done",
"dependencies": [],
"acceptanceCriteria": "- Comprehensive documentation of existing agent interaction patterns in Cursor rules"
},
@@ -986,7 +986,7 @@
"id": 2,
"title": "Enhance Integration Between Cursor Agents and dev.js Commands",
"description": "Improve the integration between Cursor's built-in agent capabilities and the dev.js command system. Ensure that agents can effectively use all task management commands and that the command outputs are optimized for agent consumption.",
"status": "pending",
"status": "done",
"dependencies": [],
"acceptanceCriteria": "- Enhanced integration between Cursor agents and dev.js commands"
},
@@ -994,7 +994,7 @@
"id": 3,
"title": "Optimize Command Responses for Agent Consumption",
"description": "Refine the output format of existing commands to ensure they are easily parseable by AI agents. Focus on consistent, structured outputs that agents can reliably interpret without requiring a separate parsing system.",
"status": "pending",
"status": "done",
"dependencies": [
2
],
@@ -1004,7 +1004,7 @@
"id": 4,
"title": "Improve Agent Workflow Documentation in Cursor Rules",
"description": "Enhance the agent workflow documentation in dev_workflow.mdc and cursor_rules.mdc to provide clear guidance on how agents should interact with the task system. Include example interactions and best practices for agents.",
"status": "pending",
"status": "done",
"dependencies": [
1,
3
@@ -1015,7 +1015,7 @@
"id": 5,
"title": "Add Agent-Specific Features to Existing Commands",
"description": "Identify and implement any missing agent-specific features in the existing command system. This may include additional flags, parameters, or output formats that are particularly useful for agent interactions.",
"status": "pending",
"status": "done",
"dependencies": [
2
],
@@ -1025,7 +1025,7 @@
"id": 6,
"title": "Create Agent Usage Examples and Patterns",
"description": "Develop a set of example interactions and usage patterns that demonstrate how agents should effectively use the task system. Include these examples in the documentation to guide future agent implementations.",
"status": "pending",
"status": "done",
"dependencies": [
3,
4
@@ -1268,7 +1268,7 @@
"id": 19,
"title": "Implement Error Handling and Recovery",
"description": "Create robust error handling throughout the system with helpful error messages and recovery options.",
"status": "pending",
"status": "done",
"dependencies": [
1,
2,
@@ -1286,7 +1286,7 @@
"id": 1,
"title": "Define Error Message Format and Structure",
"description": "Create a standardized error message format that includes error codes, descriptive messages, and recovery suggestions. Implement a centralized ErrorMessage class or module that enforces this structure across the application. This should include methods for generating consistent error messages and translating error codes to user-friendly descriptions.",
"status": "pending",
"status": "done",
"dependencies": [],
"acceptanceCriteria": "- ErrorMessage class/module is implemented with methods for creating structured error messages"
},
@@ -1294,7 +1294,7 @@
"id": 2,
"title": "Implement API Error Handling with Retry Logic",
"description": "Develop a robust error handling system for API calls, including automatic retries with exponential backoff. Create a wrapper for API requests that catches common errors (e.g., network timeouts, rate limiting) and implements appropriate retry logic. This should be integrated with both the Claude and Perplexity API calls.",
"status": "pending",
"status": "done",
"dependencies": [],
"acceptanceCriteria": "- API request wrapper is implemented with configurable retry logic"
},
@@ -1302,7 +1302,7 @@
"id": 3,
"title": "Develop File System Error Recovery Mechanisms",
"description": "Implement error handling and recovery mechanisms for file system operations, focusing on tasks.json and individual task files. This should include handling of file not found errors, permission issues, and data corruption scenarios. Implement automatic backups and recovery procedures to ensure data integrity.",
"status": "pending",
"status": "done",
"dependencies": [
1
],
@@ -1312,7 +1312,7 @@
"id": 4,
"title": "Enhance Data Validation with Detailed Error Feedback",
"description": "Improve the existing data validation system to provide more specific and actionable error messages. Implement detailed validation checks for all user inputs and task data, with clear error messages that pinpoint the exact issue and how to resolve it. This should cover task creation, updates, and any data imported from external sources.",
"status": "pending",
"status": "done",
"dependencies": [
1,
3
@@ -1323,7 +1323,7 @@
"id": 5,
"title": "Implement Command Syntax Error Handling and Guidance",
"description": "Enhance the CLI to provide more helpful error messages and guidance when users input invalid commands or options. Implement a \"did you mean?\" feature for close matches to valid commands, and provide context-sensitive help for command syntax errors. This should integrate with the existing Commander.js setup.",
"status": "pending",
"status": "done",
"dependencies": [
2
],
@@ -1333,7 +1333,7 @@
"id": 6,
"title": "Develop System State Recovery After Critical Failures",
"description": "Implement a system state recovery mechanism to handle critical failures that could leave the task management system in an inconsistent state. This should include creating periodic snapshots of the system state, implementing a recovery procedure to restore from these snapshots, and providing tools for manual intervention if automatic recovery fails.",
"status": "pending",
"status": "done",
"dependencies": [
1,
3
@@ -1346,7 +1346,7 @@
"id": 20,
"title": "Create Token Usage Tracking and Cost Management",
"description": "Implement system for tracking API token usage and managing costs.",
"status": "pending",
"status": "done",
"dependencies": [
5,
9,
@@ -1360,7 +1360,7 @@
"id": 1,
"title": "Implement Token Usage Tracking for API Calls",
"description": "Create a middleware or wrapper function that intercepts all API calls to OpenAI, Anthropic, and Perplexity. This function should count the number of tokens used in both the request and response, storing this information in a persistent data store (e.g., SQLite database). Implement a caching mechanism to reduce redundant API calls and token usage.",
"status": "pending",
"status": "done",
"dependencies": [
5
],
@@ -1370,7 +1370,7 @@
"id": 2,
"title": "Develop Configurable Usage Limits",
"description": "Create a configuration system that allows setting token usage limits at the project, user, and API level. Implement a mechanism to enforce these limits by checking the current usage against the configured limits before making API calls. Add the ability to set different limit types (e.g., daily, weekly, monthly) and actions to take when limits are reached (e.g., block calls, send notifications).",
"status": "pending",
"status": "done",
"dependencies": [],
"acceptanceCriteria": "- Configuration file or database table for storing usage limits"
},
@@ -1378,7 +1378,7 @@
"id": 3,
"title": "Implement Token Usage Reporting and Cost Estimation",
"description": "Develop a reporting module that generates detailed token usage reports. Include breakdowns by API, user, and time period. Implement cost estimation features by integrating current pricing information for each API. Create both command-line and programmatic interfaces for generating reports and estimates.",
"status": "pending",
"status": "done",
"dependencies": [
1,
2
@@ -1389,7 +1389,7 @@
"id": 4,
"title": "Optimize Token Usage in Prompts",
"description": "Implement a prompt optimization system that analyzes and refines prompts to reduce token usage while maintaining effectiveness. Use techniques such as prompt compression, removing redundant information, and leveraging efficient prompting patterns. Integrate this system into the existing prompt generation and API call processes.",
"status": "pending",
"status": "done",
"dependencies": [],
"acceptanceCriteria": "- Prompt optimization function reduces average token usage by at least 10%"
},
@@ -1397,7 +1397,7 @@
"id": 5,
"title": "Develop Token Usage Alert System",
"description": "Create an alert system that monitors token usage in real-time and sends notifications when usage approaches or exceeds defined thresholds. Implement multiple notification channels (e.g., email, Slack, system logs) and allow for customizable alert rules. Integrate this system with the existing logging and reporting modules.",
"status": "pending",
"status": "done",
"dependencies": [
2,
3
@@ -1410,7 +1410,7 @@
"id": 21,
"title": "Refactor dev.js into Modular Components",
"description": "Restructure the monolithic dev.js file into separate modular components to improve code maintainability, readability, and testability while preserving all existing functionality.",
"status": "pending",
"status": "done",
"dependencies": [
3,
16,
@@ -1424,7 +1424,7 @@
"id": 1,
"title": "Analyze Current dev.js Structure and Plan Module Boundaries",
"description": "Perform a comprehensive analysis of the existing dev.js file to identify logical boundaries for the new modules. Create a detailed mapping document that outlines which functions, variables, and code blocks will move to which module files. Identify shared dependencies, potential circular references, and determine the appropriate interfaces between modules.",
"status": "pending",
"status": "done",
"dependencies": [],
"acceptanceCriteria": "- Complete inventory of all functions, variables, and code blocks in dev.js"
},
@@ -1432,7 +1432,7 @@
"id": 2,
"title": "Create Core Module Structure and Entry Point Refactoring",
"description": "Create the skeleton structure for all module files (commands.js, ai-services.js, task-manager.js, ui.js, utils.js) with proper export statements. Refactor dev.js to serve as the entry point that imports and orchestrates these modules. Implement the basic initialization flow and command-line argument parsing in the new structure.",
"status": "pending",
"status": "done",
"dependencies": [
1
],
@@ -1442,7 +1442,7 @@
"id": 3,
"title": "Implement Core Module Functionality with Dependency Injection",
"description": "Migrate the core functionality from dev.js into the appropriate modules following the mapping document. Implement proper dependency injection to avoid circular dependencies. Ensure each module has a clear API and properly encapsulates its internal state. Focus on the critical path functionality first.",
"status": "pending",
"status": "done",
"dependencies": [
2
],
@@ -1452,7 +1452,7 @@
"id": 4,
"title": "Implement Error Handling and Complete Module Migration",
"description": "Establish a consistent error handling pattern across all modules. Complete the migration of remaining functionality from dev.js to the appropriate modules. Ensure all edge cases, error scenarios, and helper functions are properly moved and integrated. Update all import/export statements throughout the codebase to reference the new module structure.",
"status": "pending",
"status": "done",
"dependencies": [
3
],
@@ -1462,7 +1462,7 @@
"id": 5,
"title": "Test, Document, and Finalize Modular Structure",
"description": "Perform comprehensive testing of the refactored codebase to ensure all functionality works as expected. Add detailed JSDoc comments to all modules, functions, and significant code blocks. Create or update developer documentation explaining the new modular structure, module responsibilities, and how they interact. Perform a final code review to ensure code quality, consistency, and adherence to best practices.",
"status": "pending",
"status": "done",
"dependencies": [
"21.4"
],
@@ -1512,6 +1512,63 @@
"acceptanceCriteria": "- Integration tests cover all CLI commands (create, expand, update, list, etc.)"
}
]
},
{
"id": 23,
"title": "Implement MCP (Model Context Protocol) Server Functionality for Task Master",
"description": "Extend Task Master to function as an MCP server, allowing it to provide context management services to other applications following the Model Context Protocol specification.",
"status": "pending",
"dependencies": [
"22"
],
"priority": "medium",
"details": "This task involves implementing the Model Context Protocol server capabilities within Task Master. The implementation should:\n\n1. Create a new module `mcp-server.js` that implements the core MCP server functionality\n2. Implement the required MCP endpoints:\n - `/context` - For retrieving and updating context\n - `/models` - For listing available models\n - `/execute` - For executing operations with context\n3. Develop a context management system that can:\n - Store and retrieve context data efficiently\n - Handle context windowing and truncation when limits are reached\n - Support context metadata and tagging\n4. Add authentication and authorization mechanisms for MCP clients\n5. Implement proper error handling and response formatting according to MCP specifications\n6. Create configuration options in Task Master to enable/disable the MCP server functionality\n7. Add documentation for how to use Task Master as an MCP server\n8. Ensure the implementation is compatible with existing MCP clients\n9. Optimize for performance, especially for context retrieval operations\n10. Add logging for MCP server operations\n\nThe implementation should follow RESTful API design principles and should be able to handle concurrent requests from multiple clients.",
"testStrategy": "Testing for the MCP server functionality should include:\n\n1. Unit tests:\n - Test each MCP endpoint handler function independently\n - Verify context storage and retrieval mechanisms\n - Test authentication and authorization logic\n - Validate error handling for various failure scenarios\n\n2. Integration tests:\n - Set up a test MCP server instance\n - Test complete request/response cycles for each endpoint\n - Verify context persistence across multiple requests\n - Test with various payload sizes and content types\n\n3. Compatibility tests:\n - Test with existing MCP client libraries\n - Verify compliance with the MCP specification\n - Ensure backward compatibility with any MCP versions supported\n\n4. Performance tests:\n - Measure response times for context operations with various context sizes\n - Test concurrent request handling\n - Verify memory usage remains within acceptable limits during extended operation\n\n5. Security tests:\n - Verify authentication mechanisms cannot be bypassed\n - Test for common API vulnerabilities (injection, CSRF, etc.)\n\nAll tests should be automated and included in the CI/CD pipeline. Documentation should include examples of how to test the MCP server functionality manually using tools like curl or Postman."
},
{
"id": 24,
"title": "Implement AI-Powered Test Generation Command",
"description": "Create a new 'generate-test' command that leverages AI to automatically produce Jest test files for tasks based on their descriptions and subtasks.",
"status": "pending",
"dependencies": [
"22"
],
"priority": "high",
"details": "Implement a new command in the Task Master CLI that generates comprehensive Jest test files for tasks. The command should be callable as 'task-master generate-test --id=1' and should:\n\n1. Accept a task ID parameter to identify which task to generate tests for\n2. Retrieve the task and its subtasks from the task store\n3. Analyze the task description, details, and subtasks to understand implementation requirements\n4. Construct an appropriate prompt for an AI service (e.g., OpenAI API) that requests generation of Jest tests\n5. Process the AI response to create a well-formatted test file named 'task_XXX.test.js' where XXX is the zero-padded task ID\n6. Include appropriate test cases that cover the main functionality described in the task\n7. Generate mocks for external dependencies identified in the task description\n8. Create assertions that validate the expected behavior\n9. Handle both parent tasks and subtasks appropriately (for subtasks, name the file 'task_XXX_YYY.test.js' where YYY is the subtask ID)\n10. Include error handling for API failures, invalid task IDs, etc.\n11. Add appropriate documentation for the command in the help system\n\nThe implementation should utilize the existing AI service integration in the codebase and maintain consistency with the current command structure and error handling patterns.",
"testStrategy": "Testing for this feature should include:\n\n1. Unit tests for the command handler function to verify it correctly processes arguments and options\n2. Mock tests for the AI service integration to ensure proper prompt construction and response handling\n3. Integration tests that verify the end-to-end flow using a mock AI response\n4. Tests for error conditions including:\n - Invalid task IDs\n - Network failures when contacting the AI service\n - Malformed AI responses\n - File system permission issues\n5. Verification that generated test files follow Jest conventions and can be executed\n6. Tests for both parent task and subtask handling\n7. Manual verification of the quality of generated tests by running them against actual task implementations\n\nCreate a test fixture with sample tasks of varying complexity to evaluate the test generation capabilities across different scenarios. The tests should verify that the command outputs appropriate success/error messages to the console and creates files in the expected location with proper content structure.",
"subtasks": [
{
"id": 1,
"title": "Create command structure for 'generate-test'",
"description": "Implement the basic structure for the 'generate-test' command, including command registration, parameter validation, and help documentation",
"dependencies": [],
"details": "Implementation steps:\n1. Create a new file `src/commands/generate-test.js`\n2. Implement the command structure following the pattern of existing commands\n3. Register the new command in the CLI framework\n4. Add command options for task ID (--id=X) parameter\n5. Implement parameter validation to ensure a valid task ID is provided\n6. Add help documentation for the command\n7. Create the basic command flow that retrieves the task from the task store\n8. Implement error handling for invalid task IDs and other basic errors\n\nTesting approach:\n- Test command registration\n- Test parameter validation (missing ID, invalid ID format)\n- Test error handling for non-existent task IDs\n- Test basic command flow with a mock task store",
"status": "pending",
"parentTaskId": 24
},
{
"id": 2,
"title": "Implement AI prompt construction and API integration",
"description": "Develop the logic to analyze tasks, construct appropriate AI prompts, and interact with the AI service to generate test content",
"dependencies": [
1
],
"details": "Implementation steps:\n1. Create a utility function to analyze task descriptions and subtasks for test requirements\n2. Implement a prompt builder that formats task information into an effective AI prompt\n3. The prompt should request Jest test generation with specifics about mocking dependencies and creating assertions\n4. Integrate with the existing AI service in the codebase to send the prompt\n5. Process the AI response to extract the generated test code\n6. Implement error handling for API failures, rate limits, and malformed responses\n7. Add appropriate logging for the AI interaction process\n\nTesting approach:\n- Test prompt construction with various task types\n- Test AI service integration with mocked responses\n- Test error handling for API failures\n- Test response processing with sample AI outputs",
"status": "pending",
"parentTaskId": 24
},
{
"id": 3,
"title": "Implement test file generation and output",
"description": "Create functionality to format AI-generated tests into proper Jest test files and save them to the appropriate location",
"dependencies": [
2
],
"details": "Implementation steps:\n1. Create a utility to format the AI response into a well-structured Jest test file\n2. Implement naming logic for test files (task_XXX.test.js for parent tasks, task_XXX_YYY.test.js for subtasks)\n3. Add logic to determine the appropriate file path for saving the test\n4. Implement file system operations to write the test file\n5. Add validation to ensure the generated test follows Jest conventions\n6. Implement formatting of the test file for consistency with project coding standards\n7. Add user feedback about successful test generation and file location\n8. Implement handling for both parent tasks and subtasks\n\nTesting approach:\n- Test file naming logic for various task/subtask combinations\n- Test file content formatting with sample AI outputs\n- Test file system operations with mocked fs module\n- Test the complete flow from command input to file output\n- Verify generated tests can be executed by Jest",
"status": "pending",
"parentTaskId": 24
}
]
}
]
}