Skip to content

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

feat(cli): implement loop command (#1571)

Ralph Khreishc2d6c18a96fc
diff --git a/.changeset/tiny-clocks-report.md b/.changeset/tiny-clocks-report.md
new file mode 100644
index 00000000..337f65c1
--- /dev/null
+++ b/.changeset/tiny-clocks-report.md
@@ -0,0 +1,17 @@
+---
+"task-master-ai": minor
+---
+
+Add loop command for automated task execution with Claude Code
+
+**New Features:**
+- `task-master loop` command that runs Claude Code in a Docker sandbox, executing one task per iteration based on the selected tag
+- Built-in presets for different workflows:
+ - `default` - General task completion from the Task Master backlog
+ - `test-coverage` - Find uncovered code and write meaningful tests
+ - `linting` - Fix lint errors and type errors one by one
+ - `duplication` - Find duplicated code and refactor into shared utilities
+ - `entropy` - Find code smells and clean them up
+- Progress file tracking to maintain context across iterations (inside `.taskmaster/loop-progress.txt`)
+ - Remember to delete this file between loops to not pollute the agent with bad context
+- Automatic completion detection via `<loop-complete>` and `<loop-blocked>` markers
diff --git a/.taskmaster/CLAUDE.md b/.taskmaster/CLAUDE.md
index a625746e..c2af2f4c 100644
--- a/.taskmaster/CLAUDE.md
+++ b/.taskmaster/CLAUDE.md
@@ -115,7 +115,7 @@ Task Master uses tiered tool loading to optimize context window usage:
|------|-------|----------|
| `core` | 7 | Minimal daily workflow tools (default) |
| `standard` | 14 | Common task management |
-| `all` | 44+ | Full suite with research, autopilot, dependencies |
+| `all` | 42+ | Full suite with research, autopilot, dependencies |
**Core tools (7):** `get_tasks`, `next_task`, `get_task`, `set_task_status`, `update_subtask`, `parse_prd`, `expand_task`
diff --git a/.taskmaster/config.json b/.taskmaster/config.json
index 7db58de1..698de60d 100644
--- a/.taskmaster/config.json
+++ b/.taskmaster/config.json
@@ -2,8 +2,8 @@
"models": {
"main": {
"provider": "claude-code",
- "modelId": "haiku",
- "maxTokens": 200000,
+ "modelId": "opus",
+ "maxTokens": 32000,
"temperature": 0.2
},
"research": {
diff --git a/.taskmaster/docs/loop-prd.md b/.taskmaster/docs/loop-prd.md
new file mode 100644
index 00000000..72dc6fcc
--- /dev/null
+++ b/.taskmaster/docs/loop-prd.md
@@ -0,0 +1,425 @@
+# PRD: Task Master Loop (`tm loop`)
+
+## Overview
+
+**Task Master Loop** implements the "Ralph Wiggum" pattern (credited to Jeffrey Huntley, popularized by Matt Pocock) - a simple, loop-based approach to running coding agents that work through a task backlog one task at a time, with fresh context per iteration.
+
+Unlike complex agent orchestration systems, Loop's power lies in its simplicity: a for loop that spawns a new agent session for each iteration, letting it pick the next task, complete it, commit, and exit. The fresh context window each iteration prevents context degradation and produces higher quality code.
+
+## Problem Statement
+
+Users currently run Task Master in two ways:
+
+1. **Manual "next, next, next"** - Running `task-master next` repeatedly in the same session, which works but degrades context quality over time
+2. **Autopilot TDD workflow** - A structured RED/GREEN/COMMIT cycle that's powerful but opinionated and complex for simple task completion
+
+There's no middle ground: a simple loop that spawns fresh agent sessions, completes one task per iteration, and automatically stops when all tasks are done.
+
+## Goals
+
+1. **Simple loop execution** - Run Claude Code in a loop, one task per iteration, fresh context each time
+2. **Automatic task selection** - Use `task-master next` or intelligent task selection to pick what to work on
+3. **Clear completion criteria** - Stop when all tasks are done (or max iterations reached)
+4. **Progress tracking** - Maintain a progress log across iterations for agent memory
+5. **Built-in presets** - Provide ready-to-use workflow presets (test coverage, linting, duplication, entropy)
+6. **Custom prompts** - Allow users to provide custom prompt files for domain-specific workflows
+
+## Non-Goals
+
+- Replacing the existing autopilot TDD workflow
+- Complex agent orchestration or multi-agent coordination
+- Real-time human-in-the-loop interaction (that's what manual `next` is for)
+- Multi-agent support (v2 consideration: codex, aider, etc.)
+- Programmatic enforcement of quality gates (the prompt is the source of truth - modern models follow instructions)
+
+## User Stories
+
+### US-1: Basic Loop
+
+As a developer, I want to run `task-master loop --iterations 10` and have it automatically work through my pending tasks, one per iteration, stopping when all tasks are done or iterations exhausted.
+
+### US-2: Preset Workflows
+
+As a developer, I want to use built-in presets (`--prompt test-coverage`, `--prompt linting`, etc.) for common workflows without writing custom prompts.
+
+### US-3: Custom Prompts
+
+As a developer, I want to provide a custom prompt file (`--prompt ./my-prompt.md`) for domain-specific workflows not covered by presets.
+
+### US-4: Progress Persistence
+
+As a developer, I want the loop to maintain a progress.txt file that persists learnings across iterations, so each fresh agent session has context about what was already done.
+
+### US-5: Completion Notification
+
+As a developer, I want the loop to notify me when complete (stdout message, optional webhook/command).
+
+## Technical Design
+
+### Architecture
+
+Loop will be implemented as:
+
+1. **CLI Command** (`apps/cli/src/commands/loop.command.ts`) - Thin presentation layer
+2. **Core Logic** (`packages/tm-core/src/modules/loop/`) - Business logic for task selection, progress tracking, prompt generation, preset resolution
+
+### Command Interface
+
+```bash
+# Basic usage - run up to 10 iterations with default preset
+task-master loop --iterations 10
+
+# Built-in presets
+task-master loop -n 10 --prompt test-coverage # Write tests for uncovered code
+task-master loop -n 10 --prompt linting # Fix lint/type errors
+task-master loop -n 10 --prompt duplication # Refactor duplicated code
+task-master loop -n 10 --prompt entropy # Clean up code smells
+
+# Custom prompt file (detected by path-like string or file extension)
+task-master loop -n 10 --prompt .taskmaster/prompts/my-workflow.md
+
+# With completion command (runs when done)
+task-master loop -n 10 --on-complete "notify-send 'Loop complete'"
+
+# Filter by tag
+task-master loop -n 5 --tag backend
+```
+
+### Options
+
+| Option | Type | Default | Description |
+| ------ | ---- | ------- | ----------- |
+| `--iterations, -n` | number | 10 | Maximum iterations before stopping |
+| `--prompt, -p` | string | "default" | Preset name (`default`, `test-coverage`, `linting`, `duplication`, `entropy`) or path to custom prompt file |
+| `--progress-file` | string | `.taskmaster/loop-progress.txt` | Path to progress log |
+| `--sleep` | number | 5 | Seconds to sleep between iterations |
+| `--on-complete` | string | - | Command to run when all tasks complete |
+| `--tag` | string | - | Only work on tasks with this tag |
+| `--status` | string | "pending" | Only work on tasks with this status |
+
+### Built-in Presets
+
+Presets are bundled markdown files that define the workflow for each iteration. The `--prompt` flag accepts either a preset name or a file path (detected by presence of `/`, `\`, or file extension).
+
+| Preset | Description | Completion Criteria |
+| ------ | ----------- | ------------------- |
+| `default` | Standard task completion from Task Master backlog | All tasks done |
+| `test-coverage` | Find uncovered lines, write meaningful tests | Coverage target reached |
+| `linting` | Fix lint errors and type errors one by one | Zero lint errors |
+| `duplication` | Hook into jscpd, refactor clones into shared utilities | No duplicates above threshold |
+| `entropy` | Scan for code smells, clean them up | Entropy score below threshold |
+
+#### Preset: `default`
+
+```markdown
+# Task Master Loop - Default Task Completion
+
+You are completing tasks from a Task Master backlog. Complete ONE task per session.
+
+## Files Available
+
+- @.taskmaster/tasks/tasks.json - Your task backlog
+- @.taskmaster/loop-progress.txt - Progress log from previous iterations
+
+## Process
+
+1. Run `task-master next` to get the highest priority available task
+2. Read the task details carefully with `task-master show <id>`
+3. Implement the task, focusing on the smallest possible change
+4. Ensure quality:
+ - Run tests if they exist
+ - Run type check if applicable
+ - Verify the implementation works as expected
+5. Update the task status: `task-master set-status --id=<id> --status=done`
+6. Commit your work with a descriptive message referencing the task ID
+7. Append a brief note to the progress file about what was done
+
+## Important
+
+- Complete ONLY ONE task per session
+- Keep changes small and focused
+- Do NOT start another task after completing one
+- If all tasks are complete, output: <loop-complete>ALL_TASKS_DONE</loop-complete>
+- If you cannot complete the task, output: <loop-blocked>REASON</loop-blocked>
+```
+
+#### Preset: `test-coverage`
+
+```markdown
+# Task Master Loop - Test Coverage
+
+Find uncovered code and write meaningful tests. ONE test per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (coverage %, what was tested)
+
+## What Makes a Great Test
+
+A great test covers behavior users depend on. It tests a feature that, if broken,
+would frustrate or block users. It validates real workflows - not implementation details.
+
+Do NOT write tests just to increase coverage. Use coverage as a guide to find
+UNTESTED USER-FACING BEHAVIOR. If code is not worth testing (boilerplate, unreachable
+branches, internal plumbing), add ignore comments instead of low-value tests.
+
+## Process
+
+1. Run coverage command (`pnpm coverage`, `npm run coverage`, etc.)
+2. Identify the most important USER-FACING FEATURE that lacks tests
+ - Prioritize: error handling users hit, CLI commands, API endpoints, file parsing
+ - Deprioritize: internal utilities, edge cases users won't encounter, boilerplate
+3. Write ONE meaningful test that validates the feature works correctly
+4. Run coverage again - it should increase as a side effect of testing real behavior
+5. Commit with message: `test(<file>): <describe the user behavior being tested>`
+6. Append to progress file: what you tested, new coverage %, learnings
+
+## Completion Criteria
+
+- If coverage reaches target (or 100%), output: <loop-complete>COVERAGE_TARGET</loop-complete>
+- Only write ONE test per iteration
+```
+
+#### Preset: `linting`
+
+```markdown
+# Task Master Loop - Linting
+
+Fix lint errors and type errors one by one. ONE fix per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (errors fixed, remaining count)
+
+## Process
+
+1. Run lint command (`pnpm lint`, `npm run lint`, `eslint .`, etc.)
+2. Run type check (`pnpm typecheck`, `tsc --noEmit`, etc.)
+3. Pick ONE error to fix - prioritize:
+ - Type errors (breaks builds)
+ - Security-related lint errors
+ - Errors in frequently-changed files
+4. Fix the error with minimal changes - don't refactor surrounding code
+5. Run lint/typecheck again to verify the fix doesn't introduce new errors
+6. Commit with message: `fix(<file>): <describe the lint/type error fixed>`
+7. Append to progress file: error fixed, remaining error count
+
+## Completion Criteria
+
+- If zero lint errors and zero type errors, output: <loop-complete>ZERO_ERRORS</loop-complete>
+- Only fix ONE error per iteration
+```
+
+#### Preset: `duplication`
+
+```markdown
+# Task Master Loop - Duplication
+
+Find duplicated code and refactor into shared utilities. ONE refactor per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (clones refactored, duplication %)
+
+## Process
+
+1. Run duplication detection (`npx jscpd .`, or similar tool)
+2. Review the report and pick ONE clone to refactor - prioritize:
+ - Larger clones (more lines = more maintenance burden)
+ - Clones in frequently-changed files
+ - Clones with slight variations (consolidate logic)
+3. Extract the duplicated code into a shared utility/function
+4. Update all clone locations to use the shared utility
+5. Run tests to ensure behavior is preserved
+6. Commit with message: `refactor(<file>): extract <utility> to reduce duplication`
+7. Append to progress file: what was refactored, new duplication %
+
+## Completion Criteria
+
+- If duplication below threshold (e.g., <3%), output: <loop-complete>LOW_DUPLICATION</loop-complete>
+- Only refactor ONE clone per iteration
+```
+
+#### Preset: `entropy`
+
+```markdown
+# Task Master Loop - Entropy (Code Smells)
+
+Find code smells and clean them up. ONE cleanup per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (smells fixed, areas cleaned)
+
+## Code Smells to Target
+
+- Long functions (>60 lines) - extract into smaller functions
+- Deep nesting (>3 levels) - use early returns, extract conditions
+- Large files (>500 lines) - split into focused modules
+- Magic numbers - extract into named constants
+- Complex conditionals - extract into well-named functions
+- God classes - split responsibilities
+
+## Process
+
+1. Scan the codebase for code smells (use your judgment or tools like `complexity-report`)
+2. Pick ONE smell to fix - prioritize:
+ - Smells in frequently-changed files
+ - Smells that hurt readability the most
+ - Smells in critical paths (authentication, payments, etc.)
+3. Refactor with minimal changes - don't over-engineer
+4. Run tests to ensure behavior is preserved
+5. Commit with message: `refactor(<file>): <describe the cleanup>`
+6. Append to progress file: what was cleaned, smell type
+
+## Completion Criteria
+
+- If no significant smells remain, output: <loop-complete>LOW_ENTROPY</loop-complete>
+- Only fix ONE smell per iteration
+```
+
+### Core Logic (tm-core)
+
+```typescript
+// packages/tm-core/src/modules/loop/types.ts
+export type LoopPreset = 'default' | 'test-coverage' | 'linting' | 'duplication' | 'entropy';
+
+export interface LoopConfig {
+ iterations: number;
+ prompt: LoopPreset | string; // Preset name or file path
+ progressFile: string;
+ sleepSeconds: number;
+ onComplete?: string;
+ tag?: string;
+ status?: string;
+}
+
+export interface LoopIteration {
+ iteration: number;
+ taskId?: string;
+ status: 'success' | 'blocked' | 'error' | 'complete';
+ message?: string;
+ duration?: number;
+}
+
+export interface LoopResult {
+ iterations: LoopIteration[];
+ totalIterations: number;
+ tasksCompleted: number;
+ finalStatus: 'all_complete' | 'max_iterations' | 'blocked' | 'error';
+}
+```
+
+```typescript
+// packages/tm-core/src/modules/loop/loop.service.ts
+export class LoopService {
+ // Resolve preset name to prompt content, or read custom file
+ async resolvePrompt(prompt: LoopPreset | string): Promise<string>;
+
+ // Check if string is a preset name or file path
+ isPreset(prompt: string): prompt is LoopPreset;
+
+ async generatePrompt(config: LoopConfig): Promise<string>;
+ async appendProgress(progressFile: string, note: string): Promise<void>;
+ async checkAllTasksComplete(options: { tag?: string; status?: string }): Promise<boolean>;
+ async getClaudeCommand(prompt: string): Promise<string>;
+}
+```
+
+### CLI Flow
+
+```typescript
+// Pseudocode for loop.command.ts
+async execute(options: LoopOptions) {
+ const tmCore = await createTmCore({ projectPath });
+
+ for (let i = 1; i <= options.iterations; i++) {
+ // Check if all tasks are done before starting (for default preset)
+ if (options.prompt === 'default' && await tmCore.loop.checkAllTasksComplete({ tag: options.tag })) {
+ console.log('All tasks complete!');
+ if (options.onComplete) await exec(options.onComplete);
+ return;
+ }
+
+ // Resolve preset or custom prompt
+ const promptContent = await tmCore.loop.resolvePrompt(options.prompt);
+
+ // Generate full prompt with context
+ const prompt = await tmCore.loop.generatePrompt({ ...options, promptContent });
+
+ // Run Claude Code
+ const cmd = await tmCore.loop.getClaudeCommand(prompt);
+ const result = await exec(cmd); // claude -p "<prompt>"
+
+ // Check for completion markers in output
+ if (result.includes('<loop-complete>')) {
+ console.log('Loop complete!');
+ if (options.onComplete) await exec(options.onComplete);
+ return;
+ }
+
+ // Sleep between iterations
+ await sleep(options.sleepSeconds * 1000);
+ }
+
+ console.log(`Max iterations (${options.iterations}) reached`);
+}
+```
+
+### Claude Code Integration
+
+Loop runs Claude Code via CLI:
+
+```bash
+claude -p "<prompt>"
+```
+
+The prompt includes file references using `@` syntax so Claude Code loads the progress file and relevant context into context.
+
+## Testing Strategy
+
+### Unit Tests
+
+1. **Preset resolution** - Verify preset names resolve to correct bundled prompts
+2. **Custom prompt loading** - Verify file paths are read correctly
+3. **Prompt detection** - Test `isPreset()` correctly distinguishes presets from file paths
+4. **Progress file handling** - Test append operations, file creation if missing
+5. **Task completion detection** - Test parsing of completion markers (`<loop-complete>`, `<loop-blocked>`)
+6. **Claude command generation** - Verify correct command string formatting
+
+### Integration Tests
+
+1. **Full loop with mock agent** - Test iteration logic with mocked Claude responses
+2. **Progress persistence** - Verify progress file survives across iterations
+3. **Preset workflows** - Verify each preset generates expected prompt structure
+
+### E2E Tests
+
+1. **Real agent execution** (manual/CI) - Run loop with Claude Code on a test project
+2. **Completion detection** - Verify loop stops when completion marker detected
+
+## Success Metrics
+
+1. Users can run loop with a single command
+2. Built-in presets provide immediate value without configuration
+3. Loop correctly identifies when tasks/goals are complete
+4. Progress is maintained across iterations
+5. Custom prompts work for domain-specific workflows
+6. Integration with existing Task Master commands (next, show, set-status)
+
+## Future Enhancements (v2)
+
+1. **Multi-agent support** - Add codex, opencode, and custom agent support
+2. **Sandbox mode** (`--sandbox`) - Run Claude Code inside a Docker container for isolation (e.g., `docker sandbox run claude -p "<prompt>"`)
+3. **Structured activity log** - Replace progress.txt with `.taskmaster/activity.jsonl` or global `~/.taskmaster/workspaces/<project>/activity.jsonl` for structured logging across iterations
+4. **Parallel Loop** - Run multiple loop instances on different task tags
+5. **Terminal UI integration** - Monitor loop progress from Task Master terminal UI
+6. **Slack/Discord notifications** - Notify channels on completion
+7. **Custom preset registration** - Allow users to register their own presets globally
+
+## References
+
+- [Matt Pocock's Ralph Wiggum video](https://www.youtube.com/watch?v=example)
+- [Jeffrey Huntley's original Ralph pattern](https://jeffreyhuntley.com/ralph-wiggum)
+- [Anthropic: Effective Harnesses for Long-Running Agents](https://www.anthropic.com/research/swe-bench-sonnet)
+- [AI Hero](https://www.aihero.dev/)
diff --git a/.taskmaster/loop-progress.txt b/.taskmaster/loop-progress.txt
new file mode 100644
index 00000000..bd457df1
--- /dev/null
+++ b/.taskmaster/loop-progress.txt
@@ -0,0 +1,7 @@
+# Loop Feature Progress
+
+## 2026-01-08
+- 1.1: Created loop module directory and types.ts. All types already implemented: LoopPreset, LoopConfig, LoopIteration, LoopResult, LoopCompletionMarker. index.ts barrel export also present.
+- 1.2: Added types.spec.ts with compile-time type tests. LoopPreset/LoopConfig were already in types.ts from 1.1. tsc --noEmit passes. Native rollup module issue in env blocked vitest but types are correct.
+- 1.3: LoopIteration and LoopResult interfaces already defined in types.ts (lines 38-63) from 1.1. Tests present in types.spec.ts (lines 69-129). tsc --noEmit passes. Marked done.
+- 1.4: LoopCompletionMarker already defined in types.ts (lines 65-73) from 1.1. Tests in types.spec.ts (lines 131-149). tsc --noEmit passes. Marked done.
diff --git a/.taskmaster/reports/task-complexity-report_loop.json b/.taskmaster/reports/task-complexity-report_loop.json
new file mode 100644
index 00000000..8e1c7dc9
--- /dev/null
+++ b/.taskmaster/reports/task-complexity-report_loop.json
@@ -0,0 +1,157 @@
+{
+ "meta": {
+ "generatedAt": "2026-01-08T18:01:42.102Z",
+ "tasksAnalyzed": 18,
+ "totalTasks": 18,
+ "analysisCount": 18,
+ "thresholdScore": 5,
+ "projectName": "Taskmaster",
+ "usedResearch": false
+ },
+ "complexityAnalysis": [
+ {
+ "taskId": 1,
+ "taskTitle": "Define Loop Module Types and Interfaces",
+ "complexityScore": 2,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a straightforward type definition task.",
+ "reasoning": "Very straightforward task following established patterns in workflow/types.ts and execution/types.ts. The types are already well-defined in the task details. Simply creating a single types.ts file with type/interface definitions. No business logic, no dependencies, just TypeScript type exports. The test strategy (compile-time checks) is also minimal."
+ },
+ {
+ "taskId": 2,
+ "taskTitle": "Create Preset Markdown Files",
+ "complexityScore": 4,
+ "recommendedSubtasks": 3,
+ "expansionPrompt": "Break down into: 1) Create preset directory structure and index.ts export file, 2) Write the 5 markdown preset files (default, test-coverage, linting, duplication, entropy) with proper completion markers and @ syntax, 3) Write snapshot tests to verify preset structure and required markers",
+ "reasoning": "Content creation task requiring 5 markdown files with specific format requirements (completion markers, @ file references, numbered steps). Each preset needs careful design to work correctly with Claude. The index.ts export file is simple. Testing is straightforward with snapshot tests. Moderate complexity due to content design requirements rather than code complexity."
+ },
+ {
+ "taskId": 3,
+ "taskTitle": "Implement Preset Resolution Service",
+ "complexityScore": 4,
+ "recommendedSubtasks": 2,
+ "expansionPrompt": "Break down into: 1) Implement LoopPresetService with isPreset(), isFilePath(), and resolvePrompt() methods including error handling, 2) Write comprehensive unit tests for all methods including edge cases (paths with spaces, various extensions, missing files)",
+ "reasoning": "Service follows existing patterns from workflow/services/. Core logic is simple (string matching, file reading) with clear implementation provided. Main complexity is in edge case handling and proper error messages. Dependencies on Task 1 (types) and Task 2 (presets) must be complete first. Testing is important but straightforward."
+ },
+ {
+ "taskId": 4,
+ "taskTitle": "Implement Progress File Service",
+ "complexityScore": 3,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a focused file I/O service with clear implementation.",
+ "reasoning": "Simple file I/O service using node:fs/promises. Implementation is largely provided in the task details. Methods are straightforward (initializeProgressFile, appendProgress, readProgress, exists). Error handling is simple (file not found returns empty string). No complex business logic. Testing with mock filesystem is standard practice. Very similar to existing file services in the codebase."
+ },
+ {
+ "taskId": 5,
+ "taskTitle": "Implement Loop Completion Detection",
+ "complexityScore": 3,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a focused regex parsing service with clear implementation.",
+ "reasoning": "Simple regex-based parsing service. Two patterns to match (<loop-complete>, <loop-blocked>). Implementation is fully provided in task details. Edge cases (multiple markers, malformed markers, case insensitivity) are well-defined. Testing is comprehensive but straightforward with clear test cases listed."
+ },
+ {
+ "taskId": 6,
+ "taskTitle": "Implement Loop Prompt Generator",
+ "complexityScore": 3,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a straightforward string composition service.",
+ "reasoning": "String composition service that combines preset content with context header. Dependencies on LoopPresetService (Task 3) for resolving presets. Implementation is provided. No complex logic - just building a formatted string with iteration number, file references, and optional tag. Testing includes snapshot tests for generated prompts."
+ },
+ {
+ "taskId": 7,
+ "taskTitle": "Implement Loop Executor Service",
+ "complexityScore": 6,
+ "recommendedSubtasks": 4,
+ "expansionPrompt": "Break down into: 1) Implement basic spawn mechanism with stdio handling following claude-executor.ts patterns, 2) Implement output capture and completion detection integration, 3) Implement process lifecycle management (stop, error handling, cleanup), 4) Write unit tests with mocked spawn for all scenarios (success, completion markers, errors, timeouts)",
+ "reasoning": "Most complex service in the loop module. Involves child process spawning with spawn(), stdout/stderr handling, process lifecycle management, and integration with LoopCompletionService. Follows patterns from packages/tm-core/src/modules/execution/executors/claude-executor.ts. Needs proper async handling, error recovery, and cleanup. Testing with mocked spawn requires careful setup."
+ },
+ {
+ "taskId": 8,
+ "taskTitle": "Implement Loop Service (Main Orchestrator)",
+ "complexityScore": 7,
+ "recommendedSubtasks": 4,
+ "expansionPrompt": "Break down into: 1) Implement service constructor with DI for all sub-services, 2) Implement main run() loop with iteration tracking and completion detection, 3) Implement stop() functionality and sleep mechanism, 4) Write integration tests with mocked executor covering all termination scenarios (completion marker, blocked marker, max iterations, error)",
+ "reasoning": "Main orchestration service coordinating all other services. Has 6 dependencies (presets, progress, completion, prompt, executor). Complex state management across iterations. Needs to handle async operations, sleep between iterations, early termination conditions, and proper cleanup. Testing requires careful mocking of multiple services. Similar complexity to WorkflowService in the codebase."
+ },
+ {
+ "taskId": 9,
+ "taskTitle": "Create Loop Domain Facade",
+ "complexityScore": 4,
+ "recommendedSubtasks": 2,
+ "expansionPrompt": "Break down into: 1) Implement LoopDomain class with config building, preset operations, and task completion checking, 2) Create index.ts exports and write unit/integration tests for domain facade",
+ "reasoning": "Follows established pattern from WorkflowDomain (157 lines). Thin facade over LoopService with config building, preset exposure, and TasksDomain integration. Dependency injection for TasksDomain via setTasksDomain(). Implementation details provided. Moderate complexity due to cross-domain integration requirements."
+ },
+ {
+ "taskId": 10,
+ "taskTitle": "Integrate Loop Domain into TmCore",
+ "complexityScore": 2,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a straightforward integration task following existing patterns.",
+ "reasoning": "Very simple integration task. TmCore.ts shows exact pattern to follow (import, private property, getter, initialize in initialize()). Only requires: 1 import, 1 private property, 1 getter, ~3 lines in initialize(), and export updates in index.ts. Testing verifies domain is accessible. No complex logic."
+ },
+ {
+ "taskId": 11,
+ "taskTitle": "Implement Loop CLI Command",
+ "complexityScore": 5,
+ "recommendedSubtasks": 3,
+ "expansionPrompt": "Break down into: 1) Implement LoopCommand class extending Commander.Command with all options, 2) Implement executeLoop() with display logic and on-complete command execution, 3) Write unit tests for option parsing/validation and integration tests with mocked TmCore",
+ "reasoning": "CLI command following NextCommand pattern (264 lines). Multiple options to parse (-n, -p, --progress-file, --sleep, --on-complete, -t, --status, --project, --json). Needs display methods for different output formats. On-complete command execution with execAsync. Follows established CLI patterns but has more options than most commands."
+ },
+ {
+ "taskId": 12,
+ "taskTitle": "Register Loop Command in CLI",
+ "complexityScore": 1,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a trivial registration task.",
+ "reasoning": "Trivial task. Add 1 import and 1 entry to the commands array in command-registry.ts (~8 lines). Add 1 export to index.ts. Verify with task-master --help. Pattern is clearly established with 15+ existing commands in the registry."
+ },
+ {
+ "taskId": 13,
+ "taskTitle": "Add Loop MCP Tool",
+ "complexityScore": 4,
+ "recommendedSubtasks": 2,
+ "expansionPrompt": "Break down into: 1) Implement loop_start and loop_presets tools following autopilot tool patterns with Zod schemas, 2) Register tools in MCP server and write unit tests with mocked TmCore",
+ "reasoning": "MCP tools follow clear pattern from apps/mcp/src/tools/autopilot/start.tool.ts. Two tools (loop_start, loop_presets). Zod schema definition, withToolContext wrapper, handleApiResult pattern. Registration in tool registry. Testing with mocked TmCore follows existing patterns."
+ },
+ {
+ "taskId": 14,
+ "taskTitle": "Write Unit Tests for Loop Module",
+ "complexityScore": 5,
+ "recommendedSubtasks": 5,
+ "expansionPrompt": "Break down into: 1) Write tests for loop-preset.service.spec.ts, 2) Write tests for loop-progress.service.spec.ts, 3) Write tests for loop-completion.service.spec.ts, 4) Write tests for loop-prompt.service.spec.ts, 5) Write tests for loop.service.spec.ts with mocked sub-services",
+ "reasoning": "Comprehensive test suite for 5 services. Each service needs its own spec file. Testing patterns established in packages/tm-core/src/modules/**/*.spec.ts. Requires mocking filesystem operations, external processes, and coordinating mocks for the main orchestrator test. Target >80% coverage. Natural parallelism in writing tests for each service."
+ },
+ {
+ "taskId": 15,
+ "taskTitle": "Write Integration Tests for Loop CLI",
+ "complexityScore": 4,
+ "recommendedSubtasks": 2,
+ "expansionPrompt": "Break down into: 1) Set up test infrastructure following apps/cli/tests/integration patterns with temp directory setup and CLI execution helpers, 2) Write integration tests for help, preset listing, and basic loop execution scenarios",
+ "reasoning": "Integration tests follow clear pattern from apps/cli/tests/integration/commands/next.command.test.ts. Setup with temp directories, beforeEach/afterEach hooks, execSync for CLI execution. Main challenge is mocking Claude Code execution for CI. Limited scope due to external dependency on Claude."
+ },
+ {
+ "taskId": 16,
+ "taskTitle": "Add Documentation for Loop Command",
+ "complexityScore": 3,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a focused documentation task with clear structure.",
+ "reasoning": "Documentation following existing mdx patterns in apps/docs/. Clear sections defined: overview, examples, options table, presets, custom prompt guide, progress file format. Low technical complexity but requires clear writing. Examples should match actual implementation. Can reference existing docs for style."
+ },
+ {
+ "taskId": 17,
+ "taskTitle": "Bundle Presets with Package Distribution",
+ "complexityScore": 5,
+ "recommendedSubtasks": 3,
+ "expansionPrompt": "Break down into: 1) Investigate current build setup (tsdown config, package.json files) and determine best bundling approach, 2) Implement chosen approach (either copy assets or inline content), 3) Test that presets are accessible in both development and after npm pack",
+ "reasoning": "Build configuration task with investigation required. Current package.json shows 'files': ['src', 'README.md', 'CHANGELOG.md']. Need to either: add presets to files array and update service to handle bundled paths, OR inline preset content as string constants. Requires understanding of how the monorepo builds and distributes packages. Testing must verify both dev and production paths work."
+ },
+ {
+ "taskId": 18,
+ "taskTitle": "Add Loop Tool to MCP Tool Tiers",
+ "complexityScore": 2,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a straightforward configuration update.",
+ "reasoning": "Simple configuration task. Add tool names to the TOOL_TIERS constant (likely in mcp-server/src/tools/). Update CLAUDE.md documentation table. Test with MCP inspector. Pattern is clearly established for existing tools. Minimal code changes."
+ }
+ ]
+}
diff --git a/.taskmaster/state.json b/.taskmaster/state.json
index 91b3027e..742c427c 100644
--- a/.taskmaster/state.json
+++ b/.taskmaster/state.json
@@ -1,5 +1,5 @@
{
- "currentTag": "tm-core-phase-1",
+ "currentTag": "loop",
"lastUpdated": "2025-11-28T02:21:32.160Z",
"metadata": {
"upgradePrompts": {
@@ -55,5 +55,7 @@
}
}
},
- "migrationNoticeShown": true
+ "migrationNoticeShown": true,
+ "lastSwitched": "2026-01-08T17:48:52.356Z",
+ "branchTagMapping": {}
}
diff --git a/.taskmaster/tasks/tasks.json b/.taskmaster/tasks/tasks.json
index a8e96b66..06f0df05 100644
--- a/.taskmaster/tasks/tasks.json
+++ b/.taskmaster/tasks/tasks.json
@@ -27,7 +27,9 @@
"title": "Implement Basic Task Operations",
"description": "Create core functionality for managing tasks including listing, creating, updating, and deleting tasks.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"priority": "high",
"details": "Implement the following task operations:\n- List tasks with filtering options\n- Create new tasks with required fields\n- Update existing task properties\n- Delete tasks\n- Change task status (pending/done/deferred)\n- Handle dependencies between tasks\n- Manage task priorities",
"testStrategy": "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."
@@ -37,7 +39,10 @@
"title": "Create Task File Generation System",
"description": "Implement the system for generating individual task files from the tasks.json data structure.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"priority": "medium",
"details": "Build the task file generation system including:\n- Create task file templates\n- Implement generation of task files from tasks.json\n- Add bi-directional synchronization between task files and tasks.json\n- Implement proper file naming and organization\n- Handle updates to task files reflecting back to tasks.json",
"testStrategy": "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.",
@@ -55,7 +60,9 @@
"title": "Implement Task File Generation Logic",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Successfully reads tasks from tasks.json\n- Correctly applies template to each task's data\n- Generates files with proper naming convention (e.g., task_001.txt)\n- Creates the tasks directory if it doesn't exist\n- Handles errors gracefully (file not found, permission issues, etc.)\n- Validates task data before generation to prevent errors\n- Logs generation process with appropriate verbosity levels"
},
{
@@ -63,7 +70,9 @@
"title": "Implement File Naming and Organization System",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Generates consistent filenames based on task IDs with proper zero-padding\n- Creates and maintains the correct directory structure as specified in the PRD\n- Handles special characters or edge cases in task IDs appropriately\n- Prevents filename collisions between different tasks\n- Provides utility functions for converting between task IDs and filenames\n- Maintains backward compatibility if the naming scheme needs to evolve"
},
{
@@ -71,7 +80,10 @@
"title": "Implement Task File to JSON Synchronization",
"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.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Successfully parses task files to extract structured data\n- Validates parsed data against the task model schema\n- Updates tasks.json with changes from task files\n- Handles conflicts when the same task is modified in both places\n- Preserves task relationships and dependencies during synchronization\n- Provides clear error messages for parsing or validation failures\n- Updates the \"updatedAt\" timestamp in tasks.json metadata"
},
{
@@ -79,7 +91,11 @@
"title": "Implement Change Detection and Update Handling",
"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.",
"status": "done",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"acceptanceCriteria": "- Detects changes in both task files and tasks.json\n- Determines which version is newer based on modification timestamps or content\n- Applies changes in the appropriate direction (file to JSON or JSON to file)\n- Handles edge cases like deleted files, new tasks, and renamed tasks\n- Provides options for manual conflict resolution when necessary\n- Maintains data integrity during the synchronization process\n- Includes a command to force synchronization in either direction\n- Logs all synchronization activities for troubleshooting\n\nEach 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.",
"details": "\n\n<info added on 2025-05-01T21:59:10.551Z>\n{\n \"id\": 5,\n \"title\": \"Implement Change Detection and Update Handling\",\n \"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.\",\n \"status\": \"done\",\n \"dependencies\": [\n 1,\n 3,\n 4,\n 2\n ],\n \"acceptanceCriteria\": \"- Detects changes in both task files and tasks.json\\n- Determines which version is newer based on modification timestamps or content\\n- Applies changes in the appropriate direction (file to JSON or JSON to file)\\n- Handles edge cases like deleted files, new tasks, and renamed tasks\\n- Provides options for manual conflict resolution when necessary\\n- Maintains data integrity during the synchronization process\\n- Includes a command to force synchronization in either direction\\n- Logs all synchronization activities for troubleshooting\\n\\nEach 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.\",\n \"details\": \"[2025-05-01 21:59:07] Adding another note via MCP test.\"\n}\n</info added on 2025-05-01T21:59:10.551Z>"
}
@@ -90,7 +106,9 @@
"title": "Integrate Anthropic Claude API",
"description": "Set up the integration with Claude API for AI-powered task generation and expansion.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"priority": "high",
"details": "Implement Claude API integration including:\n- API authentication using environment variables\n- Create prompt templates for various operations\n- Implement response handling and parsing\n- Add error management with retries and exponential backoff\n- Implement token usage tracking\n- Create configurable model parameters",
"testStrategy": "Test API connectivity with sample prompts. Verify authentication works correctly with different API keys. Test error handling by simulating API failures.",
@@ -108,7 +126,9 @@
"title": "Develop Prompt Template System",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- PromptTemplate class supports variable substitution\n- System and user message separation is properly implemented\n- Templates exist for all required operations (task generation, expansion, etc.)\n- Templates include appropriate constraints and formatting instructions\n- Template system is unit tested with various inputs"
},
{
@@ -116,7 +136,9 @@
"title": "Implement Response Handling and Parsing",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Response parsing functions handle both JSON and text formats\n- Error detection identifies malformed or unexpected responses\n- Utility functions transform responses into task data structures\n- Validation ensures responses meet expected schemas\n- Edge cases like empty or partial responses are handled gracefully"
},
{
@@ -124,7 +146,10 @@
"title": "Build Error Management with Retry Logic",
"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.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- All API errors are caught and handled appropriately\n- Exponential backoff retry logic is implemented\n- Retry limits and timeouts are configurable\n- Detailed error logging provides actionable information\n- System degrades gracefully when API is unavailable\n- Unit tests verify retry behavior with mocked API failures"
},
{
@@ -132,7 +157,10 @@
"title": "Implement Token Usage Tracking",
"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.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Token counting functions accurately estimate usage\n- Usage logging records tokens per operation type\n- Reporting functions show usage statistics and estimated costs\n- Configurable limits can prevent excessive API usage\n- Warning system alerts when approaching usage thresholds\n- Token tracking data is persisted between application runs"
},
{
@@ -140,7 +168,9 @@
"title": "Create Model Parameter Configuration System",
"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.).",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Configuration module manages all Claude model parameters\n- Parameter customization functions exist for different operations\n- Validation ensures parameters are within acceptable ranges\n- Preset configurations exist for different use cases\n- Parameters can be overridden at runtime when needed\n- Documentation explains parameter effects and recommended values\n- Unit tests verify parameter validation and configuration loading"
}
]
@@ -150,7 +180,9 @@
"title": "Build PRD Parsing System",
"description": "Create the system for parsing Product Requirements Documents into structured task lists.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"priority": "high",
"details": "Implement PRD parsing functionality including:\n- PRD file reading from specified path\n- Prompt engineering for effective PRD parsing\n- Convert PRD content to task structure via Claude API\n- Implement intelligent dependency inference\n- Add priority assignment logic\n- Handle large PRDs by chunking if necessary",
"testStrategy": "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.",
@@ -176,7 +208,9 @@
"title": "Implement PRD to Task Conversion System",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Successfully sends PRD content to Claude API with appropriate prompts\n- Parses Claude's response into structured task objects\n- Validates generated tasks against the task model schema\n- Handles API errors and response parsing failures gracefully\n- Generates unique and sequential task IDs"
},
{
@@ -184,7 +218,10 @@
"title": "Build Intelligent Dependency Inference System",
"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).",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Correctly identifies explicit dependencies mentioned in task descriptions\n- Infers implicit dependencies based on task context and relationships\n- Prevents circular dependencies in the task graph\n- Provides confidence scores for inferred dependencies\n- Allows for manual override/adjustment of detected dependencies"
},
{
@@ -192,7 +229,10 @@
"title": "Implement Priority Assignment Logic",
"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.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Assigns priorities based on multiple factors (dependencies, critical path, risk)\n- Identifies foundation/infrastructure tasks as high priority\n- Balances priorities across the project (not everything is high priority)\n- Provides justification for priority assignments\n- Allows for manual adjustment of priorities"
},
{
@@ -200,7 +240,10 @@
"title": "Implement PRD Chunking for Large Documents",
"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.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Successfully processes PRDs larger than Claude's context window\n- Intelligently splits documents at logical boundaries (sections, chapters)\n- Preserves context when processing individual chunks\n- Reassembles tasks from multiple chunks into a coherent task list\n- Detects and resolves duplicate or overlapping tasks\n- Maintains correct dependency relationships across chunks"
}
]
@@ -210,7 +253,9 @@
"title": "Implement Task Expansion with Claude",
"description": "Create functionality to expand tasks into subtasks using Claude's AI capabilities.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"priority": "medium",
"details": "Build task expansion functionality including:\n- Create subtask generation prompts\n- Implement workflow for expanding a task into subtasks\n- Add context-aware expansion capabilities\n- Implement parent-child relationship management\n- Allow specification of number of subtasks to generate\n- Provide mechanism to regenerate unsatisfactory subtasks",
"testStrategy": "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.",
@@ -236,7 +281,9 @@
"title": "Implement Context-Aware Expansion Capabilities",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- System automatically gathers context from related tasks and dependencies\n- Project metadata is incorporated into expansion prompts\n- Implementation details from dependent tasks are included in context\n- Context gathering is configurable (amount and type of context)\n- Generated subtasks show awareness of existing project structure and patterns\n- Context gathering has reasonable performance even with large task collections"
},
{
@@ -244,7 +291,9 @@
"title": "Build Parent-Child Relationship Management",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Task model is updated to include subtasks array\n- Subtasks have proper ID format (parent.sequence)\n- Parent tasks track their subtasks with proper references\n- Task listing command shows hierarchical structure\n- Completing all subtasks automatically updates parent task status\n- Deleting a parent task properly handles orphaned subtasks\n- Task file generation includes subtask information"
},
{
@@ -252,7 +301,10 @@
"title": "Implement Subtask Regeneration Mechanism",
"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.",
"status": "done",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"acceptanceCriteria": "- Command `node scripts/dev.js regenerate --id=<subtask_id>` is implemented\n- Option to regenerate all subtasks for a parent (`--all`)\n- Feedback parameter allows user to guide regeneration (`--feedback=\"...\"`)\n- Original subtask details are preserved in prompt context\n- Regenerated subtasks maintain proper ID sequence\n- Task relationships remain intact after regeneration\n- Command provides clear before/after comparison of subtasks"
}
]
@@ -262,7 +314,10 @@
"title": "Develop Implementation Drift Handling",
"description": "Create system to handle changes in implementation that affect future tasks.",
"status": "done",
- "dependencies": [3, 7],
+ "dependencies": [
+ 3,
+ 7
+ ],
"priority": "medium",
"details": "Implement drift handling including:\n- Add capability to update future tasks based on completed work\n- Implement task rewriting based on new context\n- Create dependency chain updates when tasks change\n- Preserve completed work while updating future tasks\n- Add command to analyze and suggest updates to future tasks",
"testStrategy": "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.",
@@ -296,7 +351,9 @@
"title": "Implement Completed Work Preservation",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Implementation of task versioning to track changes\n- Safeguards that prevent modifications to tasks marked as \"done\"\n- System to store and retrieve task history\n- Clear visual indicators in the CLI for tasks that have been modified\n- Ability to view the original version of a modified task\n- Unit tests for completed work preservation"
},
{
@@ -304,7 +361,9 @@
"title": "Create Update Analysis and Suggestion Command",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- New CLI command \"analyze-drift\" implemented\n- Comprehensive analysis of potential implementation drift\n- Detailed report of suggested task updates\n- Interactive mode to select which suggestions to apply\n- Batch mode to apply all suggested changes\n- Option to export suggestions to a file for review\n- Documentation of the command usage and options\n- Integration tests that verify the end-to-end workflow"
}
]
@@ -366,7 +425,9 @@
"title": "Create Research-Backed Subtask Generation",
"description": "Enhance subtask generation with research capabilities from Perplexity API.",
"status": "done",
- "dependencies": [7],
+ "dependencies": [
+ 7
+ ],
"priority": "low",
"details": "Implement research-backed generation including:\n- Create specialized research prompts for different domains\n- Implement context enrichment from research results\n- Add domain-specific knowledge incorporation\n- Create more detailed subtask generation with best practices\n- Include references to relevant libraries and tools",
"testStrategy": "Compare subtasks generated with and without research backing. Verify that research-backed subtasks include more specific technical details and best practices.",
@@ -400,7 +461,9 @@
"title": "Implement Domain-Specific Knowledge Incorporation",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Domain knowledge extraction function that identifies key technical concepts\n- Knowledge base structure for organizing domain-specific information\n- Integration with the subtask generation prompt to incorporate relevant domain knowledge\n- Support for technical terminology and concept explanation in generated subtasks\n- Mechanism to link domain concepts to specific implementation recommendations\n- Tests verifying improved technical accuracy in generated subtasks"
},
{
@@ -408,7 +471,10 @@
"title": "Enhance Subtask Generation with Technical Details",
"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.",
"status": "done",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"acceptanceCriteria": "- Enhanced prompt templates for Claude that incorporate research-backed context\n- Generated subtasks include specific technical approaches and implementation details\n- Each subtask contains references to relevant tools, libraries, or frameworks\n- Implementation notes section with code patterns or architectural recommendations\n- Potential challenges and mitigation strategies are included where appropriate\n- Comparative tests showing improvement over baseline subtask generation"
},
{
@@ -416,7 +482,9 @@
"title": "Implement Reference and Resource Inclusion",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Reference extraction function that identifies tools, libraries, and resources from research\n- Validation mechanism to verify reference relevance and currency\n- Formatting system for including references in subtask descriptions\n- Support for different reference types (GitHub repos, documentation, articles, etc.)\n- Optional version specification for referenced libraries and tools\n- Tests verifying that included references are relevant and accessible"
}
]
@@ -426,7 +494,9 @@
"title": "Implement Batch Operations",
"description": "Add functionality for performing operations on multiple tasks simultaneously.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"priority": "medium",
"details": "Create batch operations including:\n- Implement multi-task status updates\n- Add bulk subtask generation\n- Create task filtering and querying capabilities\n- Implement advanced dependency management\n- Add batch prioritization\n- Create commands for operating on filtered task sets",
"testStrategy": "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.",
@@ -436,7 +506,9 @@
"title": "Implement Multi-Task Status Update Functionality",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Command accepts parameters for filtering tasks (e.g., `--status=pending`, `--priority=high`, `--id=1,2,3-5`)\n- Command accepts a parameter for the new status value (e.g., `--new-status=done`)\n- All matching tasks are updated in the tasks.json file\n- Command provides a summary of changes made (e.g., \"Updated 5 tasks from 'pending' to 'done'\")\n- Command handles errors gracefully (e.g., invalid status values, no matching tasks)\n- Changes are persisted correctly to tasks.json"
},
{
@@ -444,7 +516,10 @@
"title": "Develop Bulk Subtask Generation System",
"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.",
"status": "done",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"acceptanceCriteria": "- Command accepts parameters for filtering parent tasks\n- Command supports template-based subtask generation with variable substitution\n- Command supports AI-assisted subtask generation using Claude API\n- Generated subtasks have proper IDs following the parent.sequence format (e.g., 1.1, 1.2)\n- Subtasks inherit appropriate properties from parent tasks (e.g., dependencies)\n- Generated subtasks are added to the tasks.json file\n- Task files are regenerated to include the new subtasks\n- Command provides a summary of subtasks created"
},
{
@@ -460,7 +535,9 @@
"title": "Create Advanced Dependency Management System",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Command for adding dependencies to multiple tasks at once\n- Command for removing dependencies from multiple tasks\n- Command for replacing dependencies across multiple tasks\n- Validation to prevent circular dependencies\n- Validation to ensure referenced tasks exist\n- Automatic update of affected task files\n- Summary report of dependency changes made\n- Error handling for invalid dependency operations"
},
{
@@ -468,7 +545,9 @@
"title": "Implement Batch Task Prioritization and Command System",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Command for changing priorities of multiple tasks at once\n- Support for relative priority changes (e.g., increase/decrease priority)\n- Generic command execution framework that works with the filtering system\n- Plugin architecture for registering new batch operations\n- At least three example plugins (e.g., batch tagging, batch assignment, batch export)\n- Command for executing arbitrary operations on filtered task sets\n- Documentation for creating new batch operation plugins\n- Performance testing with large task sets (100+ tasks)"
}
]
@@ -478,7 +557,11 @@
"title": "Develop Project Initialization System",
"description": "Create functionality for initializing new projects with task structure and configuration.",
"status": "done",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"priority": "medium",
"details": "Implement project initialization including:\n- Create project templating system\n- Implement interactive setup wizard\n- Add environment configuration generation\n- Create initial directory structure\n- Generate example tasks.json\n- Set up default configuration",
"testStrategy": "Test project initialization in empty directories. Verify that all required files and directories are created correctly. Test the interactive setup with various inputs.",
@@ -488,7 +571,9 @@
"title": "Create Project Template Structure",
"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.",
"status": "done",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"acceptanceCriteria": "- A `templates` directory is created with at least one default project template"
},
{
@@ -496,7 +581,9 @@
"title": "Implement Interactive Setup Wizard",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Interactive wizard prompts for essential project information"
},
{
@@ -512,7 +599,9 @@
"title": "Implement Directory Structure Creation",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Directory structure is created according to the template specification"
},
{
@@ -538,7 +627,10 @@
"title": "Create Cursor Rules Implementation",
"description": "Develop the Cursor AI integration rules and documentation.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"priority": "medium",
"details": "Implement Cursor rules including:\n- Create dev_workflow.mdc documentation\n- Implement cursor_rules.mdc\n- Add self_improve.mdc\n- Design rule integration documentation\n- Set up .cursor directory structure\n- Document how Cursor AI should interact with the system",
"testStrategy": "Review rules documentation for clarity and completeness. Test with Cursor AI to verify the rules are properly interpreted and followed.",
@@ -556,7 +648,9 @@
"title": "Create dev_workflow.mdc Documentation",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- dev_workflow.mdc file created in .cursor/rules directory\n- Document clearly explains the development workflow with Cursor AI\n- Workflow documentation includes task discovery process\n- Implementation guidance for Cursor AI is detailed\n- Verification procedures are documented\n- Examples of typical interactions are provided"
},
{
@@ -564,7 +658,9 @@
"title": "Implement cursor_rules.mdc",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- cursor_rules.mdc file created in .cursor/rules directory\n- Rules document clearly defines code style guidelines\n- Architectural patterns and principles are specified\n- Documentation requirements for generated code are outlined\n- Project-specific naming conventions are documented\n- Rules for handling dependencies and imports are defined\n- Guidelines for test implementation are included"
},
{
@@ -572,7 +668,10 @@
"title": "Add self_improve.mdc Documentation",
"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.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- self_improve.mdc file created in .cursor/rules directory\n- Document outlines feedback incorporation mechanisms\n- Guidelines for adapting to project evolution are included\n- Instructions for enhancing codebase understanding over time\n- Strategies for improving code suggestions based on past interactions\n- Methods for refining prompt responses based on user feedback\n- Approach for maintaining consistency with evolving project patterns"
},
{
@@ -580,7 +679,11 @@
"title": "Create Cursor AI Integration Documentation",
"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.",
"status": "done",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"acceptanceCriteria": "- Integration documentation created and stored in an appropriate location\n- Documentation explains how Cursor AI should interpret tasks.json structure\n- Guidelines for Cursor AI to understand task dependencies and priorities\n- Instructions for Cursor AI to assist with task implementation\n- Documentation of specific commands Cursor AI should recognize\n- Examples of effective prompts for working with the task system\n- Troubleshooting section for common Cursor AI integration issues\n- Documentation references all created rule files and explains their purpose"
}
]
@@ -590,7 +693,9 @@
"title": "Develop Agent Workflow Guidelines",
"description": "Create comprehensive guidelines for how AI agents should interact with the task system.",
"status": "done",
- "dependencies": [13],
+ "dependencies": [
+ 13
+ ],
"priority": "medium",
"details": "Create agent workflow guidelines including:\n- Document task discovery workflow\n- Create task selection guidelines\n- Implement implementation guidance\n- Add verification procedures\n- Define how agents should prioritize work\n- Create guidelines for handling dependencies",
"testStrategy": "Review guidelines with actual AI agents to verify they can follow the procedures. Test various scenarios to ensure the guidelines cover all common workflows.",
@@ -608,7 +713,9 @@
"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": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- JavaScript module implementing the task selection algorithm"
},
{
@@ -624,7 +731,9 @@
"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": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- JavaScript module implementing the verification procedure framework"
},
{
@@ -632,7 +741,10 @@
"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": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Node.js module implementing the dynamic prioritization system"
}
]
@@ -642,7 +754,9 @@
"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": "done",
- "dependencies": [14],
+ "dependencies": [
+ 14
+ ],
"priority": "medium",
"details": "Optimize agent integration including:\n- Document and improve existing agent interaction patterns in Cursor rules\n- Enhance integration between Cursor agent capabilities and dev.js commands\n- Improve agent workflow documentation in cursor rules (dev_workflow.mdc, cursor_rules.mdc)\n- Add missing agent-specific features to existing commands\n- Leverage existing infrastructure rather than building a separate system",
"testStrategy": "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.",
@@ -676,7 +790,10 @@
"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": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Enhanced agent workflow documentation in Cursor rules"
},
{
@@ -692,7 +809,10 @@
"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": "done",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"acceptanceCriteria": "- Comprehensive set of agent usage examples and patterns"
}
]
@@ -702,7 +822,9 @@
"title": "Create Configuration Management System",
"description": "Implement robust configuration handling with environment variables and .env files.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"priority": "high",
"details": "Build configuration management including:\n- Environment variable handling\n- .env file support\n- Configuration validation\n- Sensible defaults with overrides\n- Create .env.example template\n- Add configuration documentation\n- Implement secure handling of API keys",
"testStrategy": "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.",
@@ -720,7 +842,9 @@
"title": "Implement .env File Support",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Integration with dotenv or equivalent library\n- Support for multiple environment-specific .env files (.env.development, .env.production)\n- Proper error handling for missing or malformed .env files\n- Priority order established (process.env overrides .env values)\n- Unit tests verifying .env file loading and overriding behavior"
},
{
@@ -728,7 +852,9 @@
"title": "Implement Configuration Validation",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Schema validation implemented for all configuration values\n- Type checking and format validation for different value types\n- Comprehensive error messages that clearly identify validation failures\n- Support for custom validation rules for complex configuration requirements\n- Unit tests covering validation of valid and invalid configurations"
},
{
@@ -736,7 +862,10 @@
"title": "Create Configuration Defaults and Override System",
"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.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Default configuration values defined for all settings\n- Clear override precedence (env vars > .env files > defaults)\n- Configuration object accessible throughout the application\n- Caching mechanism to improve performance\n- Unit tests verifying override behavior works correctly"
},
{
@@ -744,7 +873,11 @@
"title": "Create .env.example Template",
"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.",
"status": "done",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"acceptanceCriteria": "- Complete .env.example file with all supported variables\n- Detailed comments explaining each variable's purpose and format\n- Clear placeholders for sensitive values (API_KEY=your-api-key-here)\n- Categorization of variables by function (API, logging, features, etc.)\n- Documentation on how to use the .env.example file"
},
{
@@ -752,7 +885,11 @@
"title": "Implement Secure API Key Handling",
"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.",
"status": "done",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"acceptanceCriteria": "- Secure storage of API keys and sensitive configuration\n- Masking of sensitive values in logs and error messages\n- Validation of API key formats (length, character set, etc.)\n- Warning system for potentially insecure configuration practices\n- Support for key rotation without application restart\n- Unit tests verifying secure handling of sensitive configuration\n\nThese 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."
}
]
@@ -762,7 +899,9 @@
"title": "Implement Comprehensive Logging System",
"description": "Create a flexible logging system with configurable levels and output formats.",
"status": "done",
- "dependencies": [16],
+ "dependencies": [
+ 16
+ ],
"priority": "medium",
"details": "Implement logging system including:\n- Multiple log levels (debug, info, warn, error)\n- Configurable output destinations\n- Command execution logging\n- API interaction logging\n- Error tracking\n- Performance metrics\n- Log file rotation",
"testStrategy": "Test logging at different verbosity levels. Verify that logs contain appropriate information for debugging. Test log file rotation with large volumes of logs.",
@@ -780,7 +919,9 @@
"title": "Implement Configurable Output Destinations",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Abstract destination interface that can be implemented by different output types\n- Console output adapter with color-coding based on log level\n- File output adapter with proper file handling and path configuration\n- Configuration options to route specific log levels to specific destinations\n- Ability to add custom output destinations through the adapter pattern\n- Tests verifying logs are correctly routed to configured destinations"
},
{
@@ -788,7 +929,9 @@
"title": "Implement Command and API Interaction Logging",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Command logger that captures command execution details\n- API logger that records request/response details with timing information\n- Data sanitization to mask sensitive information in logs\n- Configuration options to control verbosity of command and API logs\n- Integration with existing command execution flow\n- Tests verifying proper logging of commands and API calls"
},
{
@@ -796,7 +939,9 @@
"title": "Implement Error Tracking and Performance Metrics",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Error logging with full stack trace capture and error context\n- Performance timer utility for measuring operation duration\n- Standard format for error and performance log entries\n- Ability to track related errors through correlation IDs\n- Configuration options for performance logging thresholds\n- Unit tests for error tracking and performance measurement"
},
{
@@ -814,7 +959,15 @@
"title": "Create Comprehensive User Documentation",
"description": "Develop complete user documentation including README, examples, and troubleshooting guides.",
"status": "done",
- "dependencies": [1, 3, 4, 7, 11, 12, 16],
+ "dependencies": [
+ 1,
+ 3,
+ 4,
+ 7,
+ 11,
+ 12,
+ 16
+ ],
"priority": "medium",
"details": "Create user documentation including:\n- Detailed README with installation and usage instructions\n- Command reference documentation\n- Configuration guide\n- Example workflows\n- Troubleshooting guides\n- API integration documentation\n- Best practices\n- Advanced usage scenarios",
"testStrategy": "Review documentation for clarity and completeness. Have users unfamiliar with the system attempt to follow the documentation and note any confusion or issues.",
@@ -824,7 +977,9 @@
"title": "Create Detailed README with Installation and Usage Instructions",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- README includes project overview, features list, and system requirements\n- Installation instructions cover all supported platforms with step-by-step commands\n- Basic usage examples demonstrate core functionality with command syntax\n- Configuration section explains environment variables and .env file usage\n- Documentation includes badges for version, license, and build status\n- All sections are properly formatted with Markdown for readability"
},
{
@@ -832,7 +987,9 @@
"title": "Develop Command Reference Documentation",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- All commands are documented with syntax, options, and arguments\n- Each command includes at least 2 practical usage examples\n- Commands are organized into logical categories (task management, AI integration, etc.)\n- Global options are documented with their effects on command execution\n- Exit codes and error messages are documented for troubleshooting\n- Documentation includes command output examples"
},
{
@@ -848,7 +1005,9 @@
"title": "Develop Example Workflows and Use Cases",
"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.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- At least 5 complete workflow examples from initialization to completion\n- Each workflow includes all commands in sequence with expected outputs\n- Screenshots or terminal recordings illustrate the workflows\n- Explanation of decision points and alternatives within workflows\n- Advanced use cases demonstrate integration with development processes\n- Examples show how to handle common edge cases and errors"
},
{
@@ -856,7 +1015,10 @@
"title": "Create Troubleshooting Guide and FAQ",
"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.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- All error messages are documented with causes and solutions\n- Common issues are organized by category (installation, configuration, execution)\n- FAQ covers at least 15 common questions with detailed answers\n- Troubleshooting decision trees help users diagnose complex issues\n- Known limitations and edge cases are clearly documented\n- Recovery procedures for data corruption or API failures are included"
},
{
@@ -874,7 +1036,12 @@
"title": "Implement Error Handling and Recovery",
"description": "Create robust error handling throughout the system with helpful error messages and recovery options.",
"status": "done",
- "dependencies": [1, 3, 16, 17],
+ "dependencies": [
+ 1,
+ 3,
+ 16,
+ 17
+ ],
"priority": "high",
"details": "Implement error handling including:\n- Consistent error message format\n- Helpful error messages with recovery suggestions\n- API error handling with retries\n- File system error recovery\n- Data validation errors with specific feedback\n- Command syntax error guidance\n- System state recovery after failures",
"testStrategy": "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.",
@@ -900,7 +1067,9 @@
"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": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- File system operations are wrapped with comprehensive error handling"
},
{
@@ -908,7 +1077,10 @@
"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": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Enhanced validation checks are implemented for all task properties and user inputs"
},
{
@@ -924,7 +1096,10 @@
"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": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"acceptanceCriteria": "- Periodic snapshots of the tasks.json and related state are automatically created"
}
]
@@ -934,7 +1109,9 @@
"title": "Create Token Usage Tracking and Cost Management",
"description": "Implement system for tracking API token usage and managing costs.",
"status": "done",
- "dependencies": [17],
+ "dependencies": [
+ 17
+ ],
"priority": "medium",
"details": "Implement token tracking including:\n- Track token usage for all API calls\n- Implement configurable usage limits\n- Add reporting on token consumption\n- Create cost estimation features\n- Implement caching to reduce API calls\n- Add token optimization for prompts\n- Create usage alerts when approaching limits",
"testStrategy": "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.",
@@ -960,7 +1137,9 @@
"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": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- CLI command for generating usage reports with various filters"
},
{
@@ -976,7 +1155,9 @@
"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": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Real-time monitoring of token usage against configured limits"
}
]
@@ -986,7 +1167,11 @@
"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": "done",
- "dependencies": [3, 16, 17],
+ "dependencies": [
+ 3,
+ 16,
+ 17
+ ],
"priority": "high",
"details": "This task involves breaking down the current dev.js file into logical modules with clear responsibilities:\n\n1. Create the following module files:\n - commands.js: Handle all CLI command definitions and execution logic\n - ai-services.js: Encapsulate all AI service interactions (OpenAI, etc.)\n - task-manager.js: Manage task operations (create, read, update, delete)\n - ui.js: Handle all console output formatting, colors, and user interaction\n - utils.js: Contain helper functions, utilities, and shared code\n\n2. Refactor dev.js to serve as the entry point that:\n - Imports and initializes all modules\n - Handles command-line argument parsing\n - Sets up the execution environment\n - Orchestrates the flow between modules\n\n3. Ensure proper dependency injection between modules to avoid circular dependencies\n\n4. Maintain consistent error handling across modules\n\n5. Update import/export statements throughout the codebase\n\n6. Document each module with clear JSDoc comments explaining purpose and usage\n\n7. Ensure configuration and logging systems are properly integrated into each module\n\nThe refactoring should not change any existing functionality - this is purely a code organization task.",
"testStrategy": "Testing should verify that functionality remains identical after refactoring:\n\n1. Automated Testing:\n - Create unit tests for each new module to verify individual functionality\n - Implement integration tests that verify modules work together correctly\n - Test each command to ensure it works exactly as before\n\n2. Manual Testing:\n - Execute all existing CLI commands and verify outputs match pre-refactoring behavior\n - Test edge cases like error handling and invalid inputs\n - Verify that configuration options still work as expected\n\n3. Code Quality Verification:\n - Run linting tools to ensure code quality standards are maintained\n - Check for any circular dependencies between modules\n - Verify that each module has a single, clear responsibility\n\n4. Performance Testing:\n - Compare execution time before and after refactoring to ensure no performance regression\n\n5. Documentation Check:\n - Verify that each module has proper documentation\n - Ensure README is updated if necessary to reflect architectural changes",
@@ -1004,7 +1189,9 @@
"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": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- All module files created with appropriate JSDoc headers explaining purpose"
},
{
@@ -1020,7 +1207,9 @@
"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": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"acceptanceCriteria": "- Consistent error handling pattern implemented across all modules"
},
{
@@ -1028,7 +1217,9 @@
"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": "done",
- "dependencies": ["21.4"],
+ "dependencies": [
+ "21.4"
+ ],
"acceptanceCriteria": "- All existing functionality works exactly as before"
}
]
@@ -1038,7 +1229,9 @@
"title": "Create Comprehensive Test Suite for Task Master CLI",
"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.",
"status": "done",
- "dependencies": [21],
+ "dependencies": [
+ 21
+ ],
"priority": "high",
"details": "Implement a comprehensive test suite using Jest as the testing framework. The test suite should be organized into three main categories:\n\n1. Unit Tests:\n - Create tests for all utility functions and core logic components\n - Test task creation, parsing, and manipulation functions\n - Test data storage and retrieval functions\n - Test formatting and display functions\n\n2. Integration Tests:\n - Test all CLI commands (create, expand, update, list, etc.)\n - Verify command options and parameters work correctly\n - Test interactions between different components\n - Test configuration loading and application settings\n\n3. End-to-End Tests:\n - Test complete workflows (e.g., creating a task, expanding it, updating status)\n - Test error scenarios and recovery\n - Test edge cases like handling large numbers of tasks\n\nImplement proper mocking for:\n- Claude API interactions (using Jest mock functions)\n- File system operations (using mock-fs or similar)\n- User input/output (using mock stdin/stdout)\n\nEnsure tests cover both successful operations and error handling paths. Set up continuous integration to run tests automatically. Create fixtures for common test data and scenarios. Include test coverage reporting to identify untested code paths.",
"testStrategy": "Verification will involve:\n\n1. Code Review:\n - Verify test organization follows the unit/integration/end-to-end structure\n - Check that all major functions have corresponding tests\n - Verify mocks are properly implemented for external dependencies\n\n2. Test Coverage Analysis:\n - Run test coverage tools to ensure at least 80% code coverage\n - Verify critical paths have 100% coverage\n - Identify any untested code paths\n\n3. Test Quality Verification:\n - Manually review test cases to ensure they test meaningful behavior\n - Verify both positive and negative test cases exist\n - Check that tests are deterministic and don't have false positives/negatives\n\n4. CI Integration:\n - Verify tests run successfully in the CI environment\n - Ensure tests run in a reasonable amount of time\n - Check that test failures provide clear, actionable information\n\nThe task will be considered complete when all tests pass consistently, coverage meets targets, and the test suite can detect intentionally introduced bugs.",
@@ -1056,7 +1249,9 @@
"title": "Implement Unit Tests for Core Components",
"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.",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Unit tests are implemented for all utility functions in the project"
},
{
@@ -1064,7 +1259,9 @@
"title": "Develop Integration and End-to-End Tests",
"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.",
"status": "deferred",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"acceptanceCriteria": "- Integration tests cover all CLI commands (create, expand, update, list, etc.)"
}
]
@@ -1074,7 +1271,9 @@
"title": "Complete MCP Server Implementation for Task Master using FastMCP",
"description": "Finalize the MCP server functionality for Task Master by leveraging FastMCP's capabilities, transitioning from CLI-based execution to direct function imports, and optimizing performance, authentication, and context management. Ensure the server integrates seamlessly with Cursor via `mcp.json` and supports proper tool registration, efficient context handling, and transport type handling (focusing on stdio). Additionally, ensure the server can be instantiated properly when installed via `npx` or `npm i -g`. Evaluate and address gaps in the current implementation, including function imports, context management, caching, tool registration, and adherence to FastMCP best practices.",
"status": "done",
- "dependencies": [22],
+ "dependencies": [
+ 22
+ ],
"priority": "medium",
"details": "This task involves completing the Model Context Protocol (MCP) server implementation for Task Master using FastMCP. Key updates include:\n\n1. Transition from CLI-based execution (currently using `child_process.spawnSync`) to direct Task Master function imports for improved performance and reliability.\n2. Implement caching mechanisms for frequently accessed contexts to enhance performance, leveraging FastMCP's efficient transport mechanisms (e.g., stdio).\n3. Refactor context management to align with best practices for handling large context windows, metadata, and tagging.\n4. Refactor tool registration in `tools/index.js` to include clear descriptions and parameter definitions, leveraging FastMCP's decorator-based patterns for better integration.\n5. Enhance transport type handling to ensure proper stdio communication and compatibility with FastMCP.\n6. Ensure the MCP server can be instantiated and run correctly when installed globally via `npx` or `npm i -g`.\n7. Integrate the ModelContextProtocol SDK directly to streamline resource and tool registration, ensuring compatibility with FastMCP's transport mechanisms.\n8. Identify and address missing components or functionalities to meet FastMCP best practices, such as robust error handling, monitoring endpoints, and concurrency support.\n9. Update documentation to include examples of using the MCP server with FastMCP, detailed setup instructions, and client integration guides.\n10. Organize direct function implementations in a modular structure within the mcp-server/src/core/direct-functions/ directory for improved maintainability and organization.\n11. Follow consistent naming conventions: file names use kebab-case (like-this.js), direct functions use camelCase with Direct suffix (functionNameDirect), tool registration functions use camelCase with Tool suffix (registerToolNameTool), and MCP tool names exposed to clients use snake_case (tool_name).\n\nThe implementation must ensure compatibility with existing MCP clients and follow RESTful API design principles, while supporting concurrent requests and maintaining robust error handling.",
"testStrategy": "Testing for the MCP server implementation will follow a comprehensive approach based on our established testing guidelines:\n\n## Test Organization\n\n1. **Unit Tests** (`tests/unit/mcp-server/`):\n - Test individual MCP server components in isolation\n - Mock all external dependencies including FastMCP SDK\n - Test each tool implementation separately\n - Test each direct function implementation in the direct-functions directory\n - Verify direct function imports work correctly\n - Test context management and caching mechanisms\n - Example files: `context-manager.test.js`, `tool-registration.test.js`, `direct-functions/list-tasks.test.js`\n\n2. **Integration Tests** (`tests/integration/mcp-server/`):\n - Test interactions between MCP server components\n - Verify proper tool registration with FastMCP\n - Test context flow between components\n - Validate error handling across module boundaries\n - Test the integration between direct functions and their corresponding MCP tools\n - Example files: `server-tool-integration.test.js`, `context-flow.test.js`\n\n3. **End-to-End Tests** (`tests/e2e/mcp-server/`):\n - Test complete MCP server workflows\n - Verify server instantiation via different methods (direct, npx, global install)\n - Test actual stdio communication with mock clients\n - Example files: `server-startup.e2e.test.js`, `client-communication.e2e.test.js`\n\n4. **Test Fixtures** (`tests/fixtures/mcp-server/`):\n - Sample context data\n - Mock tool definitions\n - Sample MCP requests and responses\n\n## Testing Approach\n\n### Module Mocking Strategy\n```javascript\n// Mock the FastMCP SDK\njest.mock('@model-context-protocol/sdk', () => ({\n MCPServer: jest.fn().mockImplementation(() => ({\n registerTool: jest.fn(),\n registerResource: jest.fn(),\n start: jest.fn().mockResolvedValue(undefined),\n stop: jest.fn().mockResolvedValue(undefined)\n })),\n MCPError: jest.fn().mockImplementation(function(message, code) {\n this.message = message;\n this.code = code;\n })\n}));\n\n// Import modules after mocks\nimport { MCPServer, MCPError } from '@model-context-protocol/sdk';\nimport { initMCPServer } from '../../scripts/mcp-server.js';\n```\n\n### Direct Function Testing\n- Test each direct function in isolation\n- Verify proper error handling and return formats\n- Test with various input parameters and edge cases\n- Verify integration with the task-master-core.js export hub\n\n### Context Management Testing\n- Test context creation, retrieval, and manipulation\n- Verify caching mechanisms work correctly\n- Test context windowing and metadata handling\n- Validate context persistence across server restarts\n\n### Direct Function Import Testing\n- Verify Task Master functions are imported correctly\n- Test performance improvements compared to CLI execution\n- Validate error handling with direct imports\n\n### Tool Registration Testing\n- Verify tools are registered with proper descriptions and parameters\n- Test decorator-based registration patterns\n- Validate tool execution with different input types\n\n### Error Handling Testing\n- Test all error paths with appropriate MCPError types\n- Verify error propagation to clients\n- Test recovery from various error conditions\n\n### Performance Testing\n- Benchmark response times with and without caching\n- Test memory usage under load\n- Verify concurrent request handling\n\n## Test Quality Guidelines\n\n- Follow TDD approach when possible\n- Maintain test independence and isolation\n- Use descriptive test names explaining expected behavior\n- Aim for 80%+ code coverage, with critical paths at 100%\n- Follow the mock-first-then-import pattern for all Jest mocks\n- Avoid testing implementation details that might change\n- Ensure tests don't depend on execution order\n\n## Specific Test Cases\n\n1. **Server Initialization**\n - Test server creation with various configuration options\n - Verify proper tool and resource registration\n - Test server startup and shutdown procedures\n\n2. **Context Operations**\n - Test context creation, retrieval, update, and deletion\n - Verify context windowing and truncation\n - Test context metadata and tagging\n\n3. **Tool Execution**\n - Test each tool with various input parameters\n - Verify proper error handling for invalid inputs\n - Test tool execution performance\n\n4. **MCP.json Integration**\n - Test creation and updating of .cursor/mcp.json\n - Verify proper server registration in mcp.json\n - Test handling of existing mcp.json files\n\n5. **Transport Handling**\n - Test stdio communication\n - Verify proper message formatting\n - Test error handling in transport layer\n\n6. **Direct Function Structure**\n - Test the modular organization of direct functions\n - Verify proper import/export through task-master-core.js\n - Test utility functions in the utils directory\n\nAll tests will be automated and integrated into the CI/CD pipeline to ensure consistent quality.",
@@ -1092,7 +1291,9 @@
"id": 2,
"title": "Implement Context Management System",
"description": "Develop a robust context management system that can efficiently store, retrieve, and manipulate context data according to the MCP specification.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implementation steps:\n1. Design and implement data structures for context storage\n2. Create methods for context creation, retrieval, updating, and deletion\n3. Implement context windowing and truncation algorithms for handling size limits\n4. Add support for context metadata and tagging\n5. Create utilities for context serialization and deserialization\n6. Implement efficient indexing for quick context lookups\n7. Add support for context versioning and history\n8. Develop mechanisms for context persistence (in-memory, disk-based, or database)\n\nTesting approach:\n- Unit tests for all context operations (CRUD)\n- Performance tests for context retrieval with various sizes\n- Test context windowing and truncation with edge cases\n- Verify metadata handling and tagging functionality\n- Test persistence mechanisms with simulated failures",
"status": "done",
"parentTaskId": 23
@@ -1101,7 +1302,9 @@
"id": 3,
"title": "Implement MCP Endpoints and API Handlers",
"description": "Develop the complete API handlers for all required MCP endpoints, ensuring they follow the protocol specification and integrate with the context management system.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implementation steps:\n1. Implement the `/context` endpoint for:\n - GET: retrieving existing context\n - POST: creating new context\n - PUT: updating existing context\n - DELETE: removing context\n2. Implement the `/models` endpoint to list available models\n3. Develop the `/execute` endpoint for performing operations with context\n4. Create request validators for each endpoint\n5. Implement response formatters according to MCP specifications\n6. Add detailed error handling for each endpoint\n7. Set up proper HTTP status codes for different scenarios\n8. Implement pagination for endpoints that return lists\n\nTesting approach:\n- Unit tests for each endpoint handler\n- Integration tests with mock context data\n- Test various request formats and edge cases\n- Verify response formats match MCP specifications\n- Test error handling with invalid inputs\n- Benchmark endpoint performance",
"status": "done",
"parentTaskId": 23
@@ -1110,7 +1313,10 @@
"id": 6,
"title": "Refactor MCP Server to Leverage ModelContextProtocol SDK",
"description": "Integrate the ModelContextProtocol SDK directly into the MCP server implementation to streamline tool registration and resource handling.",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Implementation steps:\n1. Replace manual tool registration with ModelContextProtocol SDK methods.\n2. Use SDK utilities to simplify resource and template management.\n3. Ensure compatibility with FastMCP's transport mechanisms.\n4. Update server initialization to include SDK-based configurations.\n\nTesting approach:\n- Verify SDK integration with all MCP endpoints.\n- Test resource and template registration using SDK methods.\n- Validate compatibility with existing MCP clients.\n- Benchmark performance improvements from SDK integration.\n\n<info added on 2025-03-31T18:49:14.439Z>\nThe subtask is being cancelled because FastMCP already serves as a higher-level abstraction over the Model Context Protocol SDK. Direct integration with the MCP SDK would be redundant and potentially counterproductive since:\n\n1. FastMCP already encapsulates the necessary SDK functionality for tool registration and resource handling\n2. The existing FastMCP abstractions provide a more streamlined developer experience\n3. Adding another layer of SDK integration would increase complexity without clear benefits\n4. The transport mechanisms in FastMCP are already optimized for the current architecture\n\nInstead, we should focus on extending and enhancing the existing FastMCP abstractions where needed, rather than attempting to bypass them with direct SDK integration.\n</info added on 2025-03-31T18:49:14.439Z>",
"status": "done",
"parentTaskId": 23
@@ -1119,7 +1325,9 @@
"id": 8,
"title": "Implement Direct Function Imports and Replace CLI-based Execution",
"description": "Refactor the MCP server implementation to use direct Task Master function imports instead of the current CLI-based execution using child_process.spawnSync. This will improve performance, reliability, and enable better error handling.",
- "dependencies": ["23.13"],
+ "dependencies": [
+ "23.13"
+ ],
"details": "\n\n<info added on 2025-03-30T00:14:10.040Z>\n```\n# Refactoring Strategy for Direct Function Imports\n\n## Core Approach\n1. Create a clear separation between data retrieval/processing and presentation logic\n2. Modify function signatures to accept `outputFormat` parameter ('cli'|'json', default: 'cli')\n3. Implement early returns for JSON format to bypass CLI-specific code\n\n## Implementation Details for `listTasks`\n```javascript\nfunction listTasks(tasksPath, statusFilter, withSubtasks = false, outputFormat = 'cli') {\n try {\n // Existing data retrieval logic\n const filteredTasks = /* ... */;\n \n // Early return for JSON format\n if (outputFormat === 'json') return filteredTasks;\n \n // Existing CLI output logic\n } catch (error) {\n if (outputFormat === 'json') {\n throw {\n code: 'TASK_LIST_ERROR',\n message: error.message,\n details: error.stack\n };\n } else {\n console.error(error);\n process.exit(1);\n }\n }\n}\n```\n\n## Testing Strategy\n- Create integration tests in `tests/integration/mcp-server/`\n- Use FastMCP InMemoryTransport for direct client-server testing\n- Test both JSON and CLI output formats\n- Verify structure consistency with schema validation\n\n## Additional Considerations\n- Update JSDoc comments to document new parameters and return types\n- Ensure backward compatibility with default CLI behavior\n- Add JSON schema validation for consistent output structure\n- Apply similar pattern to other core functions (expandTask, updateTaskById, etc.)\n\n## Error Handling Improvements\n- Standardize error format for JSON returns:\n```javascript\n{\n code: 'ERROR_CODE',\n message: 'Human-readable message',\n details: {}, // Additional context when available\n stack: process.env.NODE_ENV === 'development' ? error.stack : undefined\n}\n```\n- Enrich JSON errors with error codes and debug info\n- Ensure validation failures return proper objects in JSON mode\n```\n</info added on 2025-03-30T00:14:10.040Z>",
"status": "done",
"parentTaskId": 23
@@ -1128,7 +1336,9 @@
"id": 9,
"title": "Implement Context Management and Caching Mechanisms",
"description": "Enhance the MCP server with proper context management and caching to improve performance and user experience, especially for frequently accessed data and contexts.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "1. Implement a context manager class that leverages FastMCP's Context object\n2. Add caching for frequently accessed task data with configurable TTL settings\n3. Implement context tagging for better organization of context data\n4. Add methods to efficiently handle large context windows\n5. Create helper functions for storing and retrieving context data\n6. Implement cache invalidation strategies for task updates\n7. Add cache statistics for monitoring performance\n8. Create unit tests for context management and caching functionality",
"status": "done",
"parentTaskId": 23
@@ -1137,7 +1347,10 @@
"id": 10,
"title": "Enhance Tool Registration and Resource Management",
"description": "Refactor tool registration to follow FastMCP best practices, using decorators and improving the overall structure. Implement proper resource management for task templates and other shared resources.",
- "dependencies": [1, "23.8"],
+ "dependencies": [
+ 1,
+ "23.8"
+ ],
"details": "1. Update registerTaskMasterTools function to use FastMCP's decorator pattern\n2. Implement @mcp.tool() decorators for all existing tools\n3. Add proper type annotations and documentation for all tools\n4. Create resource handlers for task templates using @mcp.resource()\n5. Implement resource templates for common task patterns\n6. Update the server initialization to properly register all tools and resources\n7. Add validation for tool inputs using FastMCP's built-in validation\n8. Create comprehensive tests for tool registration and resource access\n\n<info added on 2025-03-31T18:35:21.513Z>\nHere is additional information to enhance the subtask regarding resources and resource templates in FastMCP:\n\nResources in FastMCP are used to expose static or dynamic data to LLM clients. For the Task Master MCP server, we should implement resources to provide:\n\n1. Task templates: Predefined task structures that can be used as starting points\n2. Workflow definitions: Reusable workflow patterns for common task sequences\n3. User preferences: Stored user settings for task management\n4. Project metadata: Information about active projects and their attributes\n\nResource implementation should follow this structure:\n\n```python\[email protected](\"tasks://templates/{template_id}\")\ndef get_task_template(template_id: str) -> dict:\n # Fetch and return the specified task template\n ...\n\[email protected](\"workflows://definitions/{workflow_id}\")\ndef get_workflow_definition(workflow_id: str) -> dict:\n # Fetch and return the specified workflow definition\n ...\n\[email protected](\"users://{user_id}/preferences\")\ndef get_user_preferences(user_id: str) -> dict:\n # Fetch and return user preferences\n ...\n\[email protected](\"projects://metadata\")\ndef get_project_metadata() -> List[dict]:\n # Fetch and return metadata for all active projects\n ...\n```\n\nResource templates in FastMCP allow for dynamic generation of resources based on patterns. For Task Master, we can implement:\n\n1. Dynamic task creation templates\n2. Customizable workflow templates\n3. User-specific resource views\n\nExample implementation:\n\n```python\[email protected](\"tasks://create/{task_type}\")\ndef get_task_creation_template(task_type: str) -> dict:\n # Generate and return a task creation template based on task_type\n ...\n\[email protected](\"workflows://custom/{user_id}/{workflow_name}\")\ndef get_custom_workflow_template(user_id: str, workflow_name: str) -> dict:\n # Generate and return a custom workflow template for the user\n ...\n\[email protected](\"users://{user_id}/dashboard\")\ndef get_user_dashboard(user_id: str) -> dict:\n # Generate and return a personalized dashboard view for the user\n ...\n```\n\nBest practices for integrating resources with Task Master functionality:\n\n1. Use resources to provide context and data for tools\n2. Implement caching for frequently accessed resources\n3. Ensure proper error handling and not-found cases for all resources\n4. Use resource templates to generate dynamic, personalized views of data\n5. Implement access control to ensure users only access authorized resources\n\nBy properly implementing these resources and resource templates, we can provide rich, contextual data to LLM clients, enhancing the Task Master's capabilities and user experience.\n</info added on 2025-03-31T18:35:21.513Z>",
"status": "done",
"parentTaskId": 23
@@ -1148,7 +1361,10 @@
"description": "Implement robust error handling using FastMCP's MCPError, including custom error types for different categories and standardized error responses.",
"details": "1. Create custom error types extending MCPError for different categories (validation, auth, etc.)\\n2. Implement standardized error responses following MCP protocol\\n3. Add error handling middleware for all MCP endpoints\\n4. Ensure proper error propagation from tools to client\\n5. Add debug mode with detailed error information\\n6. Document error types and handling patterns",
"status": "done",
- "dependencies": ["23.1", "23.3"],
+ "dependencies": [
+ "23.1",
+ "23.3"
+ ],
"parentTaskId": 23
},
{
@@ -1157,7 +1373,10 @@
"description": "Implement a comprehensive logging system for the MCP server with different log levels, structured logging format, and request/response tracking.",
"details": "1. Design structured log format for consistent parsing\\n2. Implement different log levels (debug, info, warn, error)\\n3. Add request/response logging middleware\\n4. Implement correlation IDs for request tracking\\n5. Add performance metrics logging\\n6. Configure log output destinations (console, file)\\n7. Document logging patterns and usage",
"status": "done",
- "dependencies": ["23.1", "23.3"],
+ "dependencies": [
+ "23.1",
+ "23.3"
+ ],
"parentTaskId": 23
},
{
@@ -1166,7 +1385,10 @@
"description": "Implement a comprehensive testing framework for the MCP server, including unit tests, integration tests, and end-to-end tests.",
"details": "1. Set up Jest testing framework with proper configuration\\n2. Create MCPTestClient for testing FastMCP server interaction\\n3. Implement unit tests for individual tool functions\\n4. Create integration tests for end-to-end request/response cycles\\n5. Set up test fixtures and mock data\\n6. Implement test coverage reporting\\n7. Document testing guidelines and examples",
"status": "done",
- "dependencies": ["23.1", "23.3"],
+ "dependencies": [
+ "23.1",
+ "23.3"
+ ],
"parentTaskId": 23
},
{
@@ -1175,7 +1397,10 @@
"description": "Implement functionality to create or update .cursor/mcp.json during project initialization, handling cases where: 1) If there's no mcp.json, create it with the appropriate configuration; 2) If there is an mcp.json, intelligently append to it without syntax errors like trailing commas",
"details": "1. Create functionality to detect if .cursor/mcp.json exists in the project\\n2. Implement logic to create a new mcp.json file with proper structure if it doesn't exist\\n3. Add functionality to read and parse existing mcp.json if it exists\\n4. Create method to add a new taskmaster-ai server entry to the mcpServers object\\n5. Implement intelligent JSON merging that avoids trailing commas and syntax errors\\n6. Ensure proper formatting and indentation in the generated/updated JSON\\n7. Add validation to verify the updated configuration is valid JSON\\n8. Include this functionality in the init workflow\\n9. Add error handling for file system operations and JSON parsing\\n10. Document the mcp.json structure and integration process",
"status": "done",
- "dependencies": ["23.1", "23.3"],
+ "dependencies": [
+ "23.1",
+ "23.3"
+ ],
"parentTaskId": 23
},
{
@@ -1184,7 +1409,11 @@
"description": "Add Server-Sent Events (SSE) capabilities to the MCP server to enable real-time updates and streaming of task execution progress, logs, and status changes to clients",
"details": "1. Research and implement SSE protocol for the MCP server\\n2. Create dedicated SSE endpoints for event streaming\\n3. Implement event emitter pattern for internal event management\\n4. Add support for different event types (task status, logs, errors)\\n5. Implement client connection management with proper keep-alive handling\\n6. Add filtering capabilities to allow subscribing to specific event types\\n7. Create in-memory event buffer for clients reconnecting\\n8. Document SSE endpoint usage and client implementation examples\\n9. Add robust error handling for dropped connections\\n10. Implement rate limiting and backpressure mechanisms\\n11. Add authentication for SSE connections",
"status": "done",
- "dependencies": ["23.1", "23.3", "23.11"],
+ "dependencies": [
+ "23.1",
+ "23.3",
+ "23.11"
+ ],
"parentTaskId": 23
},
{
@@ -1337,7 +1566,9 @@
"description": "Move existing direct function implementations from task-master-core.js to individual files in the new directory structure.",
"details": "1. Identify all existing direct functions in task-master-core.js\n2. Create individual files for each function in mcp-server/src/core/direct-functions/\n3. Move the implementation to the new files, ensuring consistent error handling\n4. Update imports/exports in task-master-core.js\n5. Create unit tests for each individual function file\n6. Update documentation to reflect the new structure\n7. Ensure all MCP tools reference the functions through task-master-core.js\n8. Verify backward compatibility with existing code",
"status": "done",
- "dependencies": ["23.31"],
+ "dependencies": [
+ "23.31"
+ ],
"parentTaskId": 23
},
{
@@ -1400,7 +1631,9 @@
"description": "Create MCP tool implementation for the add-dependency command",
"details": "",
"status": "done",
- "dependencies": ["23.31"],
+ "dependencies": [
+ "23.31"
+ ],
"parentTaskId": 23
},
{
@@ -1409,7 +1642,9 @@
"description": "Create MCP tool implementation for the remove-dependency command",
"details": "",
"status": "done",
- "dependencies": ["23.31"],
+ "dependencies": [
+ "23.31"
+ ],
"parentTaskId": 23
},
{
@@ -1418,7 +1653,11 @@
"description": "Create MCP tool implementation for the validate-dependencies command",
"details": "",
"status": "done",
- "dependencies": ["23.31", "23.39", "23.40"],
+ "dependencies": [
+ "23.31",
+ "23.39",
+ "23.40"
+ ],
"parentTaskId": 23
},
{
@@ -1427,7 +1666,10 @@
"description": "Create MCP tool implementation for the fix-dependencies command",
"details": "",
"status": "done",
- "dependencies": ["23.31", "23.41"],
+ "dependencies": [
+ "23.31",
+ "23.41"
+ ],
"parentTaskId": 23
},
{
@@ -1436,7 +1678,9 @@
"description": "Create MCP tool implementation for the complexity-report command",
"details": "",
"status": "done",
- "dependencies": ["23.31"],
+ "dependencies": [
+ "23.31"
+ ],
"parentTaskId": 23
},
{
@@ -1473,7 +1717,9 @@
"title": "Implement AI-Powered Test Generation Command",
"description": "Create a new 'generate-test' command in Task Master that leverages AI to automatically produce Jest test files for tasks based on their descriptions and subtasks, utilizing Claude API for AI integration.",
"status": "pending",
- "dependencies": [22],
+ "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 the AI service using Claude API\n5. Process the AI response to create a well-formatted test file named 'task_XXX.test.ts' 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.ts' 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 Claude API for AI service integration and maintain consistency with the current command structure and error handling patterns. Consider using TypeScript for better type safety and integration with the Claude API.",
"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 Claude API integration to ensure proper prompt construction and response handling\n3. Integration tests that verify the end-to-end flow using a mock Claude API 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.",
@@ -1491,7 +1737,9 @@
"id": 2,
"title": "Implement AI prompt construction and FastMCP integration",
"description": "Develop the logic to analyze tasks, construct appropriate AI prompts, and interact with the AI service using FastMCP to generate test content.",
- "dependencies": [1],
+ "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. Use FastMCP to send the prompt and receive the response\n4. Process the FastMCP response to extract the generated test code\n5. Implement error handling for FastMCP failures, rate limits, and malformed responses\n6. Add appropriate logging for the FastMCP interaction process\n\nTesting approach:\n- Test prompt construction with various task types\n- Test FastMCP integration with mocked responses\n- Test error handling for FastMCP failures\n- Test response processing with sample FastMCP outputs\n<info added on 2025-05-23T21:04:33.890Z>\n## AI Integration Implementation\n\n### AI Service Integration\n- Use the unified AI service layer, not FastMCP directly\n- Implement with `generateObjectService` from '../ai-services-unified.js'\n- Define Zod schema for structured test generation output:\n - testContent: Complete Jest test file content\n - fileName: Suggested filename for the test file\n - mockRequirements: External dependencies that need mocking\n\n### Prompt Construction\n- Create system prompt defining AI's role as test generator\n- Build user prompt with task context (ID, title, description, details)\n- Include test strategy and subtasks context in the prompt\n- Follow patterns from add-task.js for prompt structure\n\n### Task Analysis\n- Retrieve task data using `findTaskById()` from utils.js\n- Build context by analyzing task description, details, and testStrategy\n- Examine project structure for import patterns\n- Parse specific testing requirements from task.testStrategy field\n\n### File System Operations\n- Determine output path in same directory as tasks.json\n- Generate standardized filename based on task ID\n- Use fs.writeFileSync for writing test content to file\n\n### Error Handling & UI\n- Implement try/catch blocks for AI service calls\n- Display user-friendly error messages with chalk\n- Use loading indicators during AI processing\n- Support both research and main AI models\n\n### Telemetry\n- Pass through telemetryData from AI service response\n- Display AI usage summary for CLI output\n\n### Required Dependencies\n- generateObjectService from ai-services-unified.js\n- UI components (loading indicators, display functions)\n- Zod for schema validation\n- Chalk for formatted console output\n</info added on 2025-05-23T21:04:33.890Z>",
"status": "pending",
"parentTaskId": 24
@@ -1511,7 +1759,9 @@
"description": "Create MCP server tool support for the generate-test command to enable integration with Claude Code and other MCP clients.",
"details": "Implementation steps:\n1. Create direct function wrapper in mcp-server/src/core/direct-functions/\n2. Create MCP tool registration in mcp-server/src/tools/\n3. Add tool to the main tools index\n4. Implement proper parameter validation and error handling\n5. Ensure telemetry data is properly passed through\n6. Add tool to MCP server registration\n\nThe MCP tool should support the same parameters as the CLI command:\n- id: Task ID to generate tests for\n- file: Path to tasks.json file\n- research: Whether to use research model\n- prompt: Additional context for test generation\n\nFollow the existing pattern from other MCP tools like add-task.js and expand-task.js.",
"status": "pending",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"parentTaskId": 24
},
{
@@ -1520,7 +1770,9 @@
"description": "Enhance the init.js process to let users choose their preferred testing framework (Jest, Mocha, Vitest, etc.) and store this choice in .taskmasterconfig for use by the generate-test command.",
"details": "Implementation requirements:\n\n1. **Add Testing Framework Prompt to init.js**:\n - Add interactive prompt asking users to choose testing framework\n - Support Jest (default), Mocha + Chai, Vitest, Ava, Jasmine\n - Include brief descriptions of each framework\n - Allow --testing-framework flag for non-interactive mode\n\n2. **Update .taskmasterconfig Template**:\n - Add testingFramework field to configuration file\n - Include default dependencies for each framework\n - Store framework-specific configuration options\n\n3. **Framework-Specific Setup**:\n - Generate appropriate config files (jest.config.js, vitest.config.ts, etc.)\n - Add framework dependencies to package.json suggestions\n - Create sample test file for the chosen framework\n\n4. **Integration Points**:\n - Ensure generate-test command reads testingFramework from config\n - Add validation to prevent conflicts between framework choices\n - Support switching frameworks later via models command or separate config command\n\nThis makes the generate-test command truly framework-agnostic and sets up the foundation for --with-test flags in other commands.\n<info added on 2025-05-23T21:22:02.048Z>\n# Implementation Plan for Testing Framework Integration\n\n## Code Structure\n\n### 1. Update init.js\n- Add testing framework prompt after addAliases prompt\n- Implement framework selection with descriptions\n- Support non-interactive mode with --testing-framework flag\n- Create setupTestingFramework() function to handle framework-specific setup\n\n### 2. Create New Module Files\n- Create `scripts/modules/testing-frameworks.js` for framework templates and setup\n- Add sample test generators for each supported framework\n- Implement config file generation for each framework\n\n### 3. Update Configuration Templates\n- Modify `assets/.taskmasterconfig` to include testing fields:\n ```json\n \"testingFramework\": \"{{testingFramework}}\",\n \"testingConfig\": {\n \"framework\": \"{{testingFramework}}\",\n \"setupFiles\": [],\n \"testDirectory\": \"tests\",\n \"testPattern\": \"**/*.test.js\",\n \"coverage\": {\n \"enabled\": false,\n \"threshold\": 80\n }\n }\n ```\n\n### 4. Create Framework-Specific Templates\n- `assets/jest.config.template.js`\n- `assets/vitest.config.template.ts`\n- `assets/.mocharc.template.json`\n- `assets/ava.config.template.js`\n- `assets/jasmine.json.template`\n\n### 5. Update commands.js\n- Add `--testing-framework <framework>` option to init command\n- Add validation for supported frameworks\n\n## Error Handling\n- Validate selected framework against supported list\n- Handle existing config files gracefully with warning/overwrite prompt\n- Provide recovery options if framework setup fails\n- Add conflict detection for multiple testing frameworks\n\n## Integration Points\n- Ensure generate-test command reads testingFramework from config\n- Prepare for future --with-test flag in other commands\n- Support framework switching via config command\n\n## Testing Requirements\n- Unit tests for framework selection logic\n- Integration tests for config file generation\n- Validation tests for each supported framework\n</info added on 2025-05-23T21:22:02.048Z>",
"status": "pending",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"parentTaskId": 24
}
]
@@ -1530,7 +1782,9 @@
"title": "Implement 'add-subtask' Command for Task Hierarchy Management",
"description": "Create a command-line interface command that allows users to manually add subtasks to existing tasks, establishing a parent-child relationship between tasks.",
"status": "done",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"priority": "medium",
"details": "Implement the 'add-subtask' command that enables users to create hierarchical relationships between tasks. The command should:\n\n1. Accept parameters for the parent task ID and either the details for a new subtask or the ID of an existing task to convert to a subtask\n2. Validate that the parent task exists before proceeding\n3. If creating a new subtask, collect all necessary task information (title, description, due date, etc.)\n4. If converting an existing task, ensure it's not already a subtask of another task\n5. Update the data model to support parent-child relationships between tasks\n6. Modify the task storage mechanism to persist these relationships\n7. Ensure that when a parent task is marked complete, there's appropriate handling of subtasks (prompt user or provide options)\n8. Update the task listing functionality to display subtasks with appropriate indentation or visual hierarchy\n9. Implement proper error handling for cases like circular dependencies (a task cannot be a subtask of its own subtask)\n10. Document the command syntax and options in the help system",
"testStrategy": "Testing should verify both the functionality and edge cases of the subtask implementation:\n\n1. Unit tests:\n - Test adding a new subtask to an existing task\n - Test converting an existing task to a subtask\n - Test validation logic for parent task existence\n - Test prevention of circular dependencies\n - Test error handling for invalid inputs\n\n2. Integration tests:\n - Verify subtask relationships are correctly persisted to storage\n - Verify subtasks appear correctly in task listings\n - Test the complete workflow from adding a subtask to viewing it in listings\n\n3. Edge cases:\n - Attempt to add a subtask to a non-existent parent\n - Attempt to make a task a subtask of itself\n - Attempt to create circular dependencies (A → B → A)\n - Test with a deep hierarchy of subtasks (A → B → C → D)\n - Test handling of subtasks when parent tasks are deleted\n - Verify behavior when marking parent tasks as complete\n\n4. Manual testing:\n - Verify command usability and clarity of error messages\n - Test the command with various parameter combinations",
@@ -1548,7 +1802,9 @@
"id": 2,
"title": "Implement Core addSubtask Function in task-manager.js",
"description": "Create the core function that handles adding subtasks to parent tasks",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "1. Create a new addSubtask function in scripts/modules/task-manager.js\n2. Implement logic to validate that the parent task exists\n3. Add functionality to handle both creating new subtasks and converting existing tasks\n4. For new subtasks: collect task information and create a new task with parentId set\n5. For existing tasks: validate it's not already a subtask and update its parentId\n6. Add validation to prevent circular dependencies (a task cannot be a subtask of its own subtask)\n7. Update the parent task's subtasks array\n8. Ensure proper error handling with descriptive error messages\n9. Export the function for use by the command handler\n10. Write unit tests to verify all scenarios (new subtask, converting task, error cases)",
"status": "done",
"parentTaskId": 25
@@ -1566,7 +1822,9 @@
"id": 4,
"title": "Create Unit Test for add-subtask",
"description": "Develop comprehensive unit tests for the add-subtask functionality",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "1. Create a test file in tests/unit/ directory for the add-subtask functionality\n2. Write tests for the addSubtask function in task-manager.js\n3. Test all key scenarios: adding new subtasks, converting existing tasks to subtasks\n4. Test error cases: non-existent parent task, circular dependencies, invalid input\n5. Use Jest mocks to isolate the function from file system operations\n6. Test the command handler in isolation using mock functions\n7. Ensure test coverage for all branches and edge cases\n8. Document the testing approach for future reference",
"status": "done",
"parentTaskId": 25
@@ -1575,7 +1833,9 @@
"id": 5,
"title": "Implement remove-subtask Command",
"description": "Create functionality to remove a subtask from its parent, following the same approach as add-subtask",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "1. Create a removeSubtask function in scripts/modules/task-manager.js\n2. Implement logic to validate the subtask exists and is actually a subtask\n3. Add options to either delete the subtask completely or convert it to a standalone task\n4. Update the parent task's subtasks array to remove the reference\n5. If converting to standalone task, clear the parentId reference\n6. Implement the remove-subtask command in scripts/modules/commands.js following patterns from add-subtask\n7. Add appropriate validation and error messages\n8. Document the command in the help system\n9. Export the function in task-manager.js\n10. Ensure proper error handling for all scenarios",
"status": "done",
"parentTaskId": 25
@@ -1587,7 +1847,9 @@
"title": "Implement Context Foundation for AI Operations",
"description": "Implement the foundation for context integration in Task Master, enabling AI operations to leverage file-based context, cursor rules, and basic code context to improve generated outputs.",
"status": "pending",
- "dependencies": [7],
+ "dependencies": [
+ 7
+ ],
"priority": "high",
"details": "Create a Phase 1 foundation for context integration in Task Master that provides immediate practical value:\n\n1. Add `--context-file` Flag to AI Commands:\n - Add a consistent `--context-file <file>` option to all AI-related commands (expand, update, add-task, etc.)\n - Implement file reading functionality that loads content from the specified file\n - Add content integration into Claude API prompts with appropriate formatting\n - Handle error conditions such as file not found gracefully\n - Update help documentation to explain the new option\n\n2. Implement Cursor Rules Integration for Context:\n - Create a `--context-rules <rules>` option for all AI commands\n - Implement functionality to extract content from specified .cursor/rules/*.mdc files\n - Support comma-separated lists of rule names and \"all\" option\n - Add validation and error handling for non-existent rules\n - Include helpful examples in command help output\n\n3. Implement Basic Context File Extraction Utility:\n - Create utility functions in utils.js for reading context from files\n - Add proper error handling and logging\n - Implement content validation to ensure reasonable size limits\n - Add content truncation if files exceed token limits\n - Create helper functions for formatting context additions properly\n\n4. Update Command Handler Logic:\n - Modify command handlers to support the new context options\n - Update prompt construction to incorporate context content\n - Ensure backwards compatibility with existing commands\n - Add logging for context inclusion to aid troubleshooting\n\nThe focus of this phase is to provide immediate value with straightforward implementations that enable users to include relevant context in their AI operations.",
"testStrategy": "Testing should verify that the context foundation works as expected and adds value:\n\n1. Functional Tests:\n - Verify `--context-file` flag correctly reads and includes content from specified files\n - Test that `--context-rules` correctly extracts and formats content from cursor rules\n - Test with both existing and non-existent files/rules to verify error handling\n - Verify content truncation works appropriately for large files\n\n2. Integration Tests:\n - Test each AI-related command with context options\n - Verify context is properly included in API calls to Claude\n - Test combinations of multiple context options\n - Verify help documentation includes the new options\n\n3. Usability Testing:\n - Create test scenarios that show clear improvement in AI output quality with context\n - Compare outputs with and without context to measure impact\n - Document examples of effective context usage for the user documentation\n\n4. Error Handling:\n - Test invalid file paths and rule names\n - Test oversized context files\n - Verify appropriate error messages guide users to correct usage\n\nThe testing focus should be on proving immediate value to users while ensuring robust error handling.",
@@ -1635,7 +1897,9 @@
"title": "Implement Context Enhancements for AI Operations",
"description": "Enhance the basic context integration with more sophisticated code context extraction, task history awareness, and PRD integration to provide richer context for AI operations.",
"status": "pending",
- "dependencies": [26],
+ "dependencies": [
+ 26
+ ],
"priority": "high",
"details": "Building upon the foundational context implementation in Task #26, implement Phase 2 context enhancements:\n\n1. Add Code Context Extraction Feature:\n - Create a `--context-code <pattern>` option for all AI commands\n - Implement glob-based file matching to extract code from specified patterns\n - Create intelligent code parsing to extract most relevant sections (function signatures, classes, exports)\n - Implement token usage optimization by selecting key structural elements\n - Add formatting for code context with proper file paths and syntax indicators\n\n2. Implement Task History Context:\n - Add a `--context-tasks <ids>` option for AI commands\n - Support comma-separated task IDs and a \"similar\" option to find related tasks\n - Create functions to extract context from specified tasks or find similar tasks\n - Implement formatting for task context with clear section markers\n - Add validation and error handling for non-existent task IDs\n\n3. Add PRD Context Integration:\n - Create a `--context-prd <file>` option for AI commands\n - Implement PRD text extraction and intelligent summarization\n - Add formatting for PRD context with appropriate section markers\n - Integrate with the existing PRD parsing functionality from Task #6\n\n4. Improve Context Formatting and Integration:\n - Create a standardized context formatting system\n - Implement type-based sectioning for different context sources\n - Add token estimation for different context types to manage total prompt size\n - Enhance prompt templates to better integrate various context types\n\nThese enhancements will provide significantly richer context for AI operations, resulting in more accurate and relevant outputs while remaining practical to implement.",
"testStrategy": "Testing should verify the enhanced context functionality:\n\n1. Code Context Testing:\n - Verify pattern matching works for different glob patterns\n - Test code extraction with various file types and sizes\n - Verify intelligent parsing correctly identifies important code elements\n - Test token optimization by comparing full file extraction vs. optimized extraction\n - Check code formatting in prompts sent to Claude API\n\n2. Task History Testing:\n - Test with different combinations of task IDs\n - Verify \"similar\" option correctly identifies relevant tasks\n - Test with non-existent task IDs to ensure proper error handling\n - Verify formatting and integration in prompts\n\n3. PRD Context Testing:\n - Test with various PRD files of different sizes\n - Verify summarization functions correctly when PRDs are too large\n - Test integration with prompts and formatting\n\n4. Performance Testing:\n - Measure the impact of context enrichment on command execution time\n - Test with large code bases to ensure reasonable performance\n - Verify token counting and optimization functions work as expected\n\n5. Quality Assessment:\n - Compare AI outputs with Phase 1 vs. Phase 2 context to measure improvements\n - Create test cases that specifically benefit from code context\n - Create test cases that benefit from task history context\n\nFocus testing on practical use cases that demonstrate clear improvements in AI-generated outputs.",
@@ -1683,7 +1947,10 @@
"title": "Implement Advanced ContextManager System",
"description": "Create a comprehensive ContextManager class to unify context handling with advanced features like context optimization, prioritization, and intelligent context selection.",
"status": "pending",
- "dependencies": [26, 27],
+ "dependencies": [
+ 26,
+ 27
+ ],
"priority": "high",
"details": "Building on Phase 1 and Phase 2 context implementations, develop Phase 3 advanced context management:\n\n1. Implement the ContextManager Class:\n - Create a unified `ContextManager` class that encapsulates all context functionality\n - Implement methods for gathering context from all supported sources\n - Create a configurable context priority system to favor more relevant context types\n - Add token management to ensure context fits within API limits\n - Implement caching for frequently used context to improve performance\n\n2. Create Context Optimization Pipeline:\n - Develop intelligent context optimization algorithms\n - Implement type-based truncation strategies (code vs. text)\n - Create relevance scoring to prioritize most useful context portions\n - Add token budget allocation that divides available tokens among context types\n - Implement dynamic optimization based on operation type\n\n3. Add Command Interface Enhancements:\n - Create the `--context-all` flag to include all available context\n - Add the `--context-max-tokens <tokens>` option to control token allocation\n - Implement unified context options across all AI commands\n - Add intelligent default values for different command types\n\n4. Integrate with AI Services:\n - Update the AI service integration to use the ContextManager\n - Create specialized context assembly for different AI operations\n - Add post-processing to capture new context from AI responses\n - Implement adaptive context selection based on operation success\n\n5. Add Performance Monitoring:\n - Create context usage statistics tracking\n - Implement logging for context selection decisions\n - Add warnings for context token limits\n - Create troubleshooting utilities for context-related issues\n\nThe ContextManager system should provide a powerful but easy-to-use interface for both users and developers, maintaining backward compatibility with earlier phases while adding substantial new capabilities.",
"testStrategy": "Testing should verify both the functionality and performance of the advanced context management:\n\n1. Unit Testing:\n - Test all ContextManager class methods with various inputs\n - Verify optimization algorithms maintain critical information\n - Test caching mechanisms for correctness and efficiency\n - Verify token allocation and budgeting functions\n - Test each context source integration separately\n\n2. Integration Testing:\n - Verify ContextManager integration with AI services\n - Test with all AI-related commands\n - Verify backward compatibility with existing context options\n - Test context prioritization across multiple context types\n - Verify logging and error handling\n\n3. Performance Testing:\n - Benchmark context gathering and optimization times\n - Test with large and complex context sources\n - Measure impact of caching on repeated operations\n - Verify memory usage remains acceptable\n - Test with token limits of different sizes\n\n4. Quality Assessment:\n - Compare AI outputs using Phase 3 vs. earlier context handling\n - Measure improvements in context relevance and quality\n - Test complex scenarios requiring multiple context types\n - Quantify the impact on token efficiency\n\n5. User Experience Testing:\n - Verify CLI options are intuitive and well-documented\n - Test error messages are helpful for troubleshooting\n - Ensure log output provides useful insights\n - Test all convenience options like `--context-all`\n\nCreate automated test suites for regression testing of the complete context system.",
@@ -1915,7 +2182,9 @@
"id": 2,
"title": "Implement updateTask command in commands.js",
"description": "Create a new command called 'updateTask' in commands.js that leverages the updateTaskById function to update a specific task by ID.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implementation steps:\n1. Create a new command object for 'updateTask' in commands.js following the Command pattern\n2. Define command parameters including a required taskId parameter\n3. Support all options from the existing update command:\n - Research flag for Perplexity integration\n - Formatting and refinement options\n - Task context options\n4. Implement the command handler function that calls the updateTaskById function from task-manager.js\n5. Add appropriate error handling to catch and display user-friendly error messages\n6. Ensure the command follows the same pattern as other commands in the codebase\n7. Implement proper validation of input parameters\n8. Format and return appropriate success/failure messages to the user\n\nTesting approach:\n- Unit test the command handler with various input combinations\n- Test error handling scenarios\n- Verify command options are correctly passed to the updateTaskById function",
"status": "done",
"parentTaskId": 34
@@ -1924,7 +2193,9 @@
"id": 3,
"title": "Add comprehensive error handling and validation",
"description": "Implement robust error handling and validation for the updateTask command to ensure proper user feedback and system stability.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implementation steps:\n1. Create custom error types for different failure scenarios (TaskNotFoundError, ValidationError, etc.)\n2. Implement input validation for the taskId parameter and all options\n3. Add proper error handling for AI service failures with appropriate fallback mechanisms\n4. Implement concurrency handling to prevent conflicts when multiple updates occur simultaneously\n5. Add comprehensive logging for debugging and auditing purposes\n6. Ensure all error messages are user-friendly and actionable\n7. Implement proper HTTP status codes for API responses if applicable\n8. Add validation to ensure the task exists before attempting updates\n\nTesting approach:\n- Test various error scenarios including invalid inputs, non-existent tasks, and API failures\n- Verify error messages are clear and helpful\n- Test concurrency scenarios with multiple simultaneous updates\n- Verify logging captures appropriate information for troubleshooting",
"status": "done",
"parentTaskId": 34
@@ -1933,7 +2204,10 @@
"id": 4,
"title": "Write comprehensive tests for updateTask command",
"description": "Create a comprehensive test suite for the updateTask command to ensure it works correctly in all scenarios and maintains backward compatibility.",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Implementation steps:\n1. Create unit tests for the updateTaskById function in task-manager.js\n - Test finding and updating tasks with various IDs\n - Test preservation of completed subtasks\n - Test different update options combinations\n - Test error handling for non-existent tasks\n2. Create unit tests for the updateTask command in commands.js\n - Test command parameter parsing\n - Test option handling\n - Test error scenarios and messages\n3. Create integration tests that verify the end-to-end flow\n - Test the command with actual AI service integration\n - Test with mock AI responses for predictable testing\n4. Implement test fixtures and mocks for consistent testing\n5. Add performance tests to ensure the command is efficient\n6. Test edge cases such as empty tasks, tasks with many subtasks, etc.\n\nTesting approach:\n- Use Jest or similar testing framework\n- Implement mocks for external dependencies like AI services\n- Create test fixtures for consistent test data\n- Use snapshot testing for command output verification",
"status": "done",
"parentTaskId": 34
@@ -2012,7 +2286,9 @@
"id": 2,
"title": "Update Source Code License Headers and Package Metadata",
"description": "Add appropriate dual license headers to all source code files and update package metadata to reflect the new licensing structure.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implementation steps:\n1. Create a template for the new license header that references the dual license structure (BSL 1.1 / Apache 2.0).\n2. Systematically update all source code files to include the new license header, replacing any existing MIT headers.\n3. Update the license field in package.json to \"BSL 1.1 / Apache 2.0\".\n4. Update any other metadata files (composer.json, setup.py, etc.) that contain license information.\n5. Verify that any build scripts or tools that reference licensing information are updated.\n\nTesting approach:\n- Write a script to verify that all source files contain the new license header\n- Validate package.json and other metadata files have the correct license field\n- Ensure any build processes that depend on license information still function correctly\n- Run a sample build to confirm license information is properly included in any generated artifacts",
"status": "done",
"parentTaskId": 39
@@ -2021,7 +2297,9 @@
"id": 3,
"title": "Update Documentation and Create License Explanation",
"description": "Update project documentation to clearly explain the dual license structure and create comprehensive licensing guidance.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implementation steps:\n1. Update the README.md with a clear, concise explanation of the licensing terms:\n - Summary of what users can and cannot do with the code\n - Who holds commercial rights (Ralph & Eyal)\n - How to obtain commercial use permission\n - Links to the full license texts\n2. Create a dedicated LICENSING.md or similar document with detailed explanations of:\n - The rationale behind the dual licensing approach\n - Detailed examples of what constitutes commercial vs. non-commercial use\n - FAQs addressing common licensing questions\n3. Update any other documentation references to licensing throughout the project.\n4. Create visual aids (if appropriate) to help users understand the licensing structure.\n5. Ensure all documentation links to licensing information are updated.\n\nTesting approach:\n- Have non-technical stakeholders review the documentation for clarity and understanding\n- Verify all links to license files work correctly\n- Ensure the explanation is comprehensive but concise enough for users to understand quickly\n- Check that the documentation correctly addresses the most common use cases and questions",
"status": "done",
"parentTaskId": 39
@@ -2050,7 +2328,9 @@
"id": 2,
"title": "Generate Implementation Plan with AI",
"description": "Use an AI model (Claude or Perplexity) to generate an implementation plan based on the retrieved task content. The plan should outline the steps required to complete the task.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement logic to switch between Claude and Perplexity APIs. Handle API authentication and rate limiting. Prompt the AI model with the task content and request a detailed implementation plan.",
"status": "pending"
},
@@ -2066,7 +2346,9 @@
"id": 4,
"title": "Error Handling and Output",
"description": "Implement error handling for all steps, including API failures and XML formatting errors. Output the formatted XML plan to the console or a file.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Add try-except blocks to handle potential exceptions. Log errors for debugging. Provide informative error messages to the user. Output the XML plan in a user-friendly format.",
"status": "pending"
}
@@ -2094,7 +2376,9 @@
"id": 2,
"title": "Graph Layout Algorithms",
"description": "Develop or integrate algorithms to compute optimal node and edge placement for clear and readable graph layouts in a terminal environment.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Consider topological sorting, hierarchical, and force-directed layouts suitable for ASCII/Unicode rendering.\n<info added on 2025-05-23T21:02:49.434Z>\nCreate a new diagram-generator.js module in the scripts/modules/ directory following Task Master's module architecture pattern. The module should include:\n\n1. Core functions for generating Mermaid diagrams:\n - generateDependencyGraph(tasks, options) - creates flowchart showing task dependencies\n - generateSubtaskDiagram(task, options) - creates hierarchy diagram for subtasks\n - generateProjectFlow(tasks, options) - creates overall project workflow\n - generateGanttChart(tasks, options) - creates timeline visualization\n\n2. Integration with existing Task Master data structures:\n - Use the same task object format from task-manager.js\n - Leverage dependency analysis from dependency-manager.js\n - Support complexity scores from analyze-complexity functionality\n - Handle both main tasks and subtasks with proper ID notation (parentId.subtaskId)\n\n3. Layout algorithm considerations for Mermaid:\n - Topological sorting for dependency flows\n - Hierarchical layouts for subtask trees\n - Circular dependency detection and highlighting\n - Terminal width-aware formatting for ASCII fallback\n\n4. Export functions following the existing module pattern at the bottom of the file\n</info added on 2025-05-23T21:02:49.434Z>",
"status": "pending"
},
@@ -2110,7 +2394,9 @@
"id": 4,
"title": "Color Coding Support",
"description": "Add color coding to nodes and edges to visually distinguish types, statuses, or other attributes in the graph.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Use ANSI escape codes for color; provide options for colorblind-friendly palettes.\n<info added on 2025-05-23T21:03:35.762Z>\nIntegrate color coding with Task Master's existing status system:\n\n1. Extend getStatusWithColor() in ui.js to support diagram contexts:\n - Add 'diagram' parameter to determine rendering context\n - Modify color intensity for better visibility in graph elements\n\n2. Implement Task Master's established color scheme using ANSI codes:\n - Green (\\x1b[32m) for 'done'/'completed' tasks\n - Yellow (\\x1b[33m) for 'pending' tasks\n - Orange (\\x1b[38;5;208m) for 'in-progress' tasks\n - Red (\\x1b[31m) for 'blocked' tasks\n - Gray (\\x1b[90m) for 'deferred'/'cancelled' tasks\n - Magenta (\\x1b[35m) for 'review' tasks\n\n3. Create diagram-specific color functions:\n - getDependencyLineColor(fromTaskStatus, toTaskStatus) - color dependency arrows based on relationship status\n - getNodeBorderColor(task) - style node borders using priority/complexity indicators\n - getSubtaskGroupColor(parentTask) - visually group related subtasks\n\n4. Integrate complexity visualization:\n - Use getComplexityWithColor() for node background or border thickness\n - Map complexity scores to visual weight in the graph\n\n5. Ensure accessibility:\n - Add text-based indicators (symbols like ✓, ⚠, ⏳) alongside colors\n - Implement colorblind-friendly palettes as user-selectable option\n - Include shape variations for different statuses\n\n6. Follow existing ANSI patterns:\n - Maintain consistency with terminal UI color usage\n - Reuse color constants from the codebase\n\n7. Support graceful degradation:\n - Check terminal capabilities using existing detection\n - Provide monochrome fallbacks with distinctive patterns\n - Use bold/underline as alternatives when colors unavailable\n</info added on 2025-05-23T21:03:35.762Z>",
"status": "pending"
},
@@ -2126,7 +2412,9 @@
"id": 6,
"title": "Filtering and Search Functionality",
"description": "Enable users to filter nodes and edges by criteria such as name, type, or dependency depth.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Support command-line flags for filtering and interactive search if feasible.\n<info added on 2025-05-23T21:04:57.811Z>\nImplement MCP tool integration for task dependency visualization:\n\n1. Create task_diagram.js in mcp-server/src/tools/ following existing tool patterns\n2. Implement taskDiagramDirect.js in mcp-server/src/core/direct-functions/\n3. Use Zod schema for parameter validation:\n - diagramType (dependencies, subtasks, flow, gantt)\n - taskId (optional string)\n - format (mermaid, text, json)\n - includeComplexity (boolean)\n\n4. Structure response data with:\n - mermaidCode for client-side rendering\n - metadata (nodeCount, edgeCount, cycleWarnings)\n - support for both task-specific and project-wide diagrams\n\n5. Integrate with session management and project root handling\n6. Implement error handling using handleApiResult pattern\n7. Register the tool in tools/index.js\n\nMaintain compatibility with existing command-line flags for filtering and interactive search.\n</info added on 2025-05-23T21:04:57.811Z>",
"status": "pending"
},
@@ -2134,7 +2422,10 @@
"id": 7,
"title": "Accessibility Features",
"description": "Ensure the tool is accessible, including support for screen readers, high-contrast modes, and keyboard navigation.",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Provide alternative text output and ensure color is not the sole means of conveying information.\n<info added on 2025-05-23T21:05:54.584Z>\n# Accessibility and Export Integration\n\n## Accessibility Features\n- Provide alternative text output for visual elements\n- Ensure color is not the sole means of conveying information\n- Support keyboard navigation through the dependency graph\n- Add screen reader compatible node descriptions\n\n## Export Integration\n- Extend generateTaskFiles function in task-manager.js to include Mermaid diagram sections\n- Add Mermaid code blocks to task markdown files under ## Diagrams header\n- Follow existing task file generation patterns and markdown structure\n- Support multiple diagram types per task file:\n * Task dependencies (prerequisite relationships)\n * Subtask hierarchy visualization\n * Task flow context in project workflow\n- Integrate with existing fs module file writing operations\n- Add diagram export options to the generate command in commands.js\n- Support SVG and PNG export using Mermaid CLI when available\n- Implement error handling for diagram generation failures\n- Reference exported diagrams in task markdown with proper paths\n- Update CLI generate command with options like --include-diagrams\n</info added on 2025-05-23T21:05:54.584Z>",
"status": "pending"
},
@@ -2142,7 +2433,10 @@
"id": 8,
"title": "Performance Optimization",
"description": "Profile and optimize the tool for large graphs to ensure responsive rendering and low memory usage.",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Implement lazy loading, efficient data structures, and parallel processing where appropriate.\n<info added on 2025-05-23T21:06:14.533Z>\n# Mermaid Library Integration and Terminal-Specific Handling\n\n## Package Dependencies\n- Add mermaid package as an optional dependency in package.json for generating raw Mermaid diagram code\n- Consider mermaid-cli for SVG/PNG conversion capabilities\n- Evaluate terminal-image or similar libraries for terminals with image support\n- Explore ascii-art-ansi or box-drawing character libraries for text-only terminals\n\n## Terminal Capability Detection\n- Leverage existing terminal detection from ui.js to assess rendering capabilities\n- Implement detection for:\n - iTerm2 and other terminals with image protocol support\n - Terminals with Unicode/extended character support\n - Basic terminals requiring pure ASCII output\n\n## Rendering Strategy with Fallbacks\n1. Primary: Generate raw Mermaid code for user copy/paste\n2. Secondary: Render simplified ASCII tree/flow representation using box characters\n3. Tertiary: Present dependencies in tabular format for minimal terminals\n\n## Implementation Approach\n- Use dynamic imports for optional rendering libraries to maintain lightweight core\n- Implement graceful degradation when optional packages aren't available\n- Follow Task Master's philosophy of minimal dependencies\n- Ensure performance optimization through lazy loading where appropriate\n- Design modular rendering components that can be swapped based on terminal capabilities\n</info added on 2025-05-23T21:06:14.533Z>",
"status": "pending"
},
@@ -2150,7 +2444,12 @@
"id": 9,
"title": "Documentation",
"description": "Write comprehensive user and developer documentation covering installation, usage, configuration, and extension.",
- "dependencies": [1, 3, 4, 7],
+ "dependencies": [
+ 1,
+ 3,
+ 4,
+ 7
+ ],
"details": "Include examples, troubleshooting, and contribution guidelines.",
"status": "pending"
},
@@ -2158,7 +2457,12 @@
"id": 10,
"title": "Testing and Validation",
"description": "Develop automated tests for all major features, including CLI parsing, layout correctness, rendering, color coding, filtering, and cycle detection.",
- "dependencies": [1, 3, 4, 7],
+ "dependencies": [
+ 1,
+ 3,
+ 4,
+ 7
+ ],
"details": "Include unit, integration, and regression tests; validate accessibility and performance claims.\n<info added on 2025-05-23T21:08:36.329Z>\n# Documentation Tasks for Visual Task Dependency Graph\n\n## User Documentation\n1. Update README.md with diagram command documentation following existing command reference format\n2. Add examples to CLI command help text in commands.js matching patterns from other commands\n3. Create docs/diagrams.md with detailed usage guide including:\n - Command examples for each diagram type\n - Mermaid code samples and output\n - Terminal compatibility notes\n - Integration with task workflow examples\n - Troubleshooting section for common diagram rendering issues\n - Accessibility features and terminal fallback options\n\n## Developer Documentation\n1. Update MCP tool documentation to include the new task_diagram tool\n2. Add JSDoc comments to all new functions following existing code standards\n3. Create contributor documentation for extending diagram types\n4. Update API documentation for any new MCP interface endpoints\n\n## Integration Documentation\n1. Document integration with existing commands (analyze-complexity, generate, etc.)\n2. Provide examples showing how diagrams complement other Task Master features\n</info added on 2025-05-23T21:08:36.329Z>",
"status": "pending"
}
@@ -2248,7 +2552,9 @@
"id": 2,
"title": "Implement webhook authentication and security measures",
"description": "Develop security mechanisms for webhook verification and payload signing",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement signature verification using HMAC, rate limiting to prevent abuse, IP whitelisting options, and webhook secret management. Create a secure token system for webhook verification and implement TLS for all webhook communications.",
"status": "pending"
},
@@ -2264,7 +2570,10 @@
"id": 4,
"title": "Build event processing and queuing system",
"description": "Implement a robust system for processing and queuing events before webhook delivery",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Create an event queue using a message broker (like RabbitMQ or Kafka) to handle high volumes of events. Implement event deduplication, prioritization, and persistence to ensure reliable delivery even during system failures.",
"status": "pending"
},
@@ -2272,7 +2581,9 @@
"id": 5,
"title": "Develop webhook delivery and retry mechanism",
"description": "Create a reliable system for webhook delivery with retry logic and failure handling",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Implement exponential backoff retry logic, configurable retry attempts, and dead letter queues for failed deliveries. Add monitoring for webhook delivery success rates and performance metrics. Include timeout handling for unresponsive webhook endpoints.",
"status": "pending"
},
@@ -2288,7 +2599,9 @@
"id": 7,
"title": "Create webhook testing and simulation tools",
"description": "Develop tools for testing webhook integrations and simulating event triggers",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Build a webhook testing console that allows manual triggering of events, viewing delivery history, and replaying failed webhooks. Create a webhook simulator for developers to test their endpoint implementations without generating real system events.",
"status": "pending"
}
@@ -2299,7 +2612,9 @@
"title": "Implement GitHub Issue Import Feature",
"description": "Implement a comprehensive LLM-powered 'import_task' command that can intelligently import tasks from GitHub Issues and Discussions. The system uses our existing ContextGatherer.js infrastructure to analyze the full context of GitHub content and automatically generate well-structured tasks with appropriate subtasks, priorities, and implementation details. This feature works in conjunction with the GitHub export feature (Task #97) to provide bidirectional linking between Task Master tasks and GitHub issues.",
"status": "pending",
- "dependencies": [97],
+ "dependencies": [
+ 97
+ ],
"priority": "medium",
"details": "Implement a new 'import_task' command that leverages LLM-powered analysis to create comprehensive tasks from GitHub Issues and Discussions. The system should be designed as an extensible import framework that can support multiple platforms in the future.\n\nCore functionality:\n1. **New Command Structure**: Create 'import_task' command with source-specific subcommands:\n - 'taskmaster import_task github <URL>' for GitHub imports\n - Future: 'taskmaster import_task gitlab <URL>', 'taskmaster import_task linear <URL>', etc.\n\n2. **Multi-Source GitHub Support**: Automatically detect and handle:\n - GitHub Issues: https://github.com/owner/repo/issues/123\n - GitHub Discussions: https://github.com/owner/repo/discussions/456\n - Auto-detect URL type and use appropriate API endpoints\n\n3. **LLM-Powered Context Analysis**: Integrate with ContextGatherer.js to:\n - Fetch complete GitHub content (main post + all comments/replies)\n - Analyze discussion threads and extract key insights\n - Identify references to our project components and codebase\n - Generate comprehensive task descriptions based on full context\n - Automatically create relevant subtasks from complex discussions\n - Determine appropriate priority levels based on content analysis\n - Suggest dependencies based on mentioned components/features\n\n4. **Smart Content Processing**: The LLM should:\n - Parse markdown content and preserve important formatting\n - Extract actionable items from discussion threads\n - Identify implementation requirements and technical details\n - Convert complex discussions into structured task breakdowns\n - Generate appropriate test strategies based on the scope\n - Preserve important context while creating focused task descriptions\n\n5. **Enhanced GitHub API Integration**:\n - Support GITHUB_API_KEY environment variable for authentication\n - Handle both public and private repository access\n - Fetch issue/discussion metadata (labels, assignees, status)\n - Retrieve complete comment threads with proper threading\n - Implement rate limiting and error handling\n\n6. **Rich Metadata Storage**:\n - Source platform and original URL\n - Import timestamp and LLM model version used\n - Content hash for change detection and sync capabilities\n - Participant information and discussion context\n - GitHub-specific metadata (labels, assignees, status)\n - **Use consistent metadata schema with export feature (Task #97)**\n\n7. **Future-Proof Architecture**:\n - Modular design supporting multiple import sources\n - Plugin-style architecture for new platforms\n - Extensible content type handling (issues, PRs, discussions, etc.)\n - Configurable LLM prompts for different content types\n\n8. **Bidirectional Integration**:\n - Maintain compatibility with GitHub export feature\n - Enable round-trip workflows (import → modify → export)\n - Preserve source linking for synchronization capabilities\n - Support identification of imported vs. native tasks\n\n9. **Error Handling and Validation**:\n - Validate GitHub URLs and accessibility\n - Handle API rate limiting gracefully\n - Provide meaningful error messages for various failure scenarios\n - Implement retry logic for transient failures\n - Validate LLM responses and handle generation errors\n\n10. **Configuration and Customization**:\n - Allow users to customize LLM prompts for task generation\n - Support different import strategies (full vs. summary)\n - Enable filtering of comments by date, author, or relevance\n - Provide options for manual review before task creation",
"testStrategy": "Testing should cover the comprehensive LLM-powered import system:\n\n1. **Unit Tests**:\n - Test URL parsing for GitHub Issues and Discussions\n - Test GitHub API client with mocked responses\n - Test LLM integration with ContextGatherer.js\n - Test metadata schema consistency with export feature\n - Test content processing and task generation logic\n - Test error handling for various failure scenarios\n\n2. **Integration Tests**:\n - Test with real GitHub Issues and Discussions (public repos)\n - Test LLM-powered analysis with various content types\n - Test ContextGatherer integration with GitHub content\n - Test bidirectional compatibility with export feature\n - Test metadata structure and storage\n - Test with different GitHub content complexities\n\n3. **LLM and Context Analysis Tests**:\n - Test task generation quality with various GitHub content types\n - Test subtask creation from complex discussions\n - Test priority and dependency inference\n - Test handling of code references and technical discussions\n - Test content summarization and structure preservation\n - Validate LLM prompt effectiveness and response quality\n\n4. **Error Case Tests**:\n - Invalid or malformed GitHub URLs\n - Non-existent repositories or issues/discussions\n - API rate limit handling\n - Authentication failures for private repos\n - LLM service unavailability or errors\n - Network connectivity issues\n - Malformed or incomplete GitHub content\n\n5. **End-to-End Tests**:\n - Complete import workflow from GitHub URL to created task\n - Verify task quality and completeness\n - Test metadata preservation and linking\n - Test compatibility with existing task management features\n - Verify bidirectional workflow with export feature\n\n6. **Performance and Scalability Tests**:\n - Test with large GitHub discussions (many comments)\n - Test LLM processing time and resource usage\n - Test API rate limiting behavior\n - Test concurrent import operations\n\n7. **Future Platform Preparation Tests**:\n - Test modular architecture extensibility\n - Verify plugin-style platform addition capability\n - Test configuration system flexibility\n\nCreate comprehensive mock data for GitHub API responses including various issue/discussion types, comment structures, and edge cases. Use environment variables for test credentials and LLM service configuration.",
@@ -2316,7 +2631,9 @@
"id": 2,
"title": "Implement GitHub URL parsing and validation",
"description": "Create a module to parse and validate GitHub issue URLs, extracting repository owner, repository name, and issue number.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Handle various GitHub URL formats (e.g., github.com/owner/repo/issues/123, github.com/owner/repo/pull/123). Implement validation to ensure the URL points to a valid issue or pull request. Return structured data with owner, repo, and issue number for valid URLs.",
"status": "pending"
},
@@ -2324,7 +2641,9 @@
"id": 3,
"title": "Develop GitHub API client for issue fetching",
"description": "Create a service to authenticate with GitHub and fetch issue details using the GitHub REST API.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement authentication using GitHub Personal Access Tokens or OAuth. Handle API responses, including error cases (rate limiting, authentication failures, not found). Extract relevant issue data: title, description, labels, assignees, and comments.",
"status": "pending"
},
@@ -2332,7 +2651,9 @@
"id": 4,
"title": "Create task formatter for GitHub issues",
"description": "Develop a formatter to convert GitHub issue data into the application's task format.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Map GitHub issue fields to task fields (title, description, etc.). Convert GitHub markdown to the application's supported format. Handle special GitHub features like issue references and user mentions. Generate appropriate tags based on GitHub labels.",
"status": "pending"
},
@@ -2340,7 +2661,9 @@
"id": 5,
"title": "Implement end-to-end import flow with UI",
"description": "Create the user interface and workflow for importing GitHub issues, including progress indicators and error handling.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Design and implement UI for URL input and import confirmation. Show loading states during API calls. Display meaningful error messages for various failure scenarios. Allow users to review and modify imported task details before saving. Add automated tests for the entire import flow.",
"status": "pending"
},
@@ -2380,7 +2703,9 @@
"id": 10,
"title": "Implement comprehensive GitHub API client",
"description": "Create enhanced GitHub API client supporting both Issues and Discussions APIs with complete content fetching.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Extend existing API client to support GitHub Discussions API. Implement complete content fetching including all comments and replies. Add support for GITHUB_API_KEY environment variable. Handle threaded discussions and comment hierarchies. Implement robust error handling and rate limiting for both API types.",
"status": "pending"
},
@@ -2396,7 +2721,9 @@
"id": 12,
"title": "Implement LLM-powered task generation",
"description": "Create the core LLM integration that analyzes GitHub content and generates comprehensive tasks with subtasks.",
- "dependencies": [11],
+ "dependencies": [
+ 11
+ ],
"details": "Design LLM prompts for task generation from GitHub content. Implement automatic subtask creation from complex discussions. Add priority and dependency inference based on content analysis. Create test strategy generation from technical discussions. Implement quality validation for LLM-generated content. Add fallback mechanisms for LLM failures.",
"status": "pending"
},
@@ -2404,7 +2731,9 @@
"id": 13,
"title": "Enhance metadata system for rich import context",
"description": "Extend the metadata schema to store comprehensive import context and enable advanced features.",
- "dependencies": [12],
+ "dependencies": [
+ 12
+ ],
"details": "Extend existing metadata schema with import-specific fields. Add source platform, import timestamp, and LLM model tracking. Implement content hash storage for change detection. Store participant information and discussion context. Add support for custom metadata per platform type. Ensure backward compatibility with existing export feature metadata.",
"status": "pending"
},
@@ -2412,7 +2741,10 @@
"id": 14,
"title": "Implement import_task command interface",
"description": "Create the user-facing command interface for the new import_task system with GitHub support.",
- "dependencies": [12, 13],
+ "dependencies": [
+ 12,
+ 13
+ ],
"details": "Implement the main import_task command with GitHub subcommand. Add command-line argument parsing and validation. Create progress indicators for LLM processing. Implement user review and confirmation workflow. Add verbose output options for debugging. Create help documentation and usage examples.",
"status": "pending"
},
@@ -2420,7 +2752,9 @@
"id": 15,
"title": "Add comprehensive testing and validation",
"description": "Implement comprehensive testing suite covering all aspects of the LLM-powered import system.",
- "dependencies": [14],
+ "dependencies": [
+ 14
+ ],
"details": "Create unit tests for all new components. Implement integration tests with real GitHub content. Add LLM response validation and quality tests. Create performance tests for large discussions. Implement end-to-end workflow testing. Add mock data for consistent testing. Test bidirectional compatibility with export feature.",
"status": "pending"
}
@@ -2448,7 +2782,9 @@
"id": 2,
"title": "Implement AI integration for ICE scoring",
"description": "Develop the AI component that will analyze tasks and generate ICE scores",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create prompts for the AI to evaluate Impact, Confidence, and Ease. Implement error handling for AI responses. Add caching to prevent redundant AI calls. Ensure the AI provides justification for each score component. Test with various task types to ensure consistent scoring.",
"status": "pending"
},
@@ -2464,7 +2800,9 @@
"id": 4,
"title": "Implement CLI rendering for ICE analysis",
"description": "Develop the command-line interface for displaying ICE analysis results",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Design a tabular format for displaying ICE scores in the terminal. Use color coding to highlight high/medium/low priority tasks. Implement filtering options (by score range, task type, etc.). Add sorting capabilities. Create a summary view that shows top N tasks by ICE score.",
"status": "pending"
},
@@ -2472,7 +2810,10 @@
"id": 5,
"title": "Integrate with existing complexity reports",
"description": "Connect the ICE analysis functionality with the existing complexity reporting system",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Modify the existing complexity report to include ICE scores. Ensure consistent formatting between complexity and ICE reports. Add cross-referencing between reports. Update the command-line help documentation. Test the integrated system with various project sizes and configurations.",
"status": "pending"
}
@@ -2500,7 +2841,9 @@
"id": 2,
"title": "Implement State Management for Task Expansion",
"description": "Develop the state management logic to handle expanded task states, subtask creation, and context additions.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create state handlers for expanded/collapsed states, subtask array management, and context data. Implement proper validation for user inputs and error handling. Ensure state persistence across user sessions and synchronization with backend services.",
"status": "pending"
},
@@ -2524,7 +2867,10 @@
"id": 5,
"title": "Integrate with Existing Task Systems",
"description": "Ensure the enhanced actions card workflow integrates seamlessly with existing task management functionality.",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Connect the new UI components to existing backend APIs. Update data models if necessary to support new features. Ensure compatibility with existing task filters, search, and reporting features. Implement data migration plan for existing tasks if needed.",
"status": "pending"
},
@@ -2560,7 +2906,9 @@
"id": 2,
"title": "Extract prompts into individual files",
"description": "Identify all hardcoded prompts in the codebase and extract them into individual files in the prompts directory",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Search through the codebase for all hardcoded prompt strings. For each prompt, create a new file in the appropriate subdirectory with a descriptive name (e.g., 'taskBreakdownPrompt.js'). Format each file to export the prompt string as a constant. Add JSDoc comments to document the purpose and expected usage of each prompt.",
"status": "pending"
},
@@ -2568,7 +2916,9 @@
"id": 3,
"title": "Update functions to import prompts",
"description": "Modify all functions that use hardcoded prompts to import them from the centralized structure",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "For each function that previously used a hardcoded prompt, add an import statement to pull in the prompt from the centralized structure. Test each function after modification to ensure it still works correctly. Update any tests that might be affected by the refactoring. Create a pull request with the changes and document the new prompt structure in the project documentation.",
"status": "pending"
}
@@ -2596,7 +2946,9 @@
"id": 2,
"title": "Implement best practice verification",
"description": "Build verification checks against established coding standards and best practices",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create a framework to compare code against established best practices for the specific language/framework. Include checks for naming conventions, function length, complexity metrics, comment coverage, and other industry-standard quality indicators.",
"status": "pending"
},
@@ -2604,7 +2956,9 @@
"id": 3,
"title": "Develop AI integration for code analysis",
"description": "Integrate AI capabilities to enhance code analysis and provide intelligent recommendations",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Connect to AI services (like OpenAI) to analyze code beyond rule-based checks. Configure the AI to understand context, project-specific patterns, and provide nuanced analysis that rule-based systems might miss.",
"status": "pending"
},
@@ -2612,7 +2966,9 @@
"id": 4,
"title": "Create recommendation generation system",
"description": "Build a system to generate actionable improvement recommendations based on analysis results",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Develop algorithms to transform analysis results into specific, actionable recommendations. Include priority levels, effort estimates, and potential impact assessments for each recommendation.",
"status": "pending"
},
@@ -2620,7 +2976,9 @@
"id": 5,
"title": "Implement task creation functionality",
"description": "Add capability to automatically create tasks from code quality recommendations",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Build functionality to convert recommendations into tasks in the project management system. Include appropriate metadata, assignee suggestions based on code ownership, and integration with existing workflow systems.",
"status": "pending"
},
@@ -2628,7 +2986,9 @@
"id": 6,
"title": "Create comprehensive reporting interface",
"description": "Develop a user interface to display analysis results and recommendations",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Build a dashboard showing code quality metrics, identified patterns, recommendations, and created tasks. Include filtering options, trend analysis over time, and the ability to drill down into specific issues with code snippets and explanations.",
"status": "pending"
}
@@ -2657,7 +3017,9 @@
"id": 2,
"title": "Develop coverage report parser and adapter system",
"description": "Create a framework-agnostic system that can parse coverage reports from various testing tools and convert them to the standardized task-based format in tests.json.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "1. Research and document output formats for major coverage tools (Istanbul/nyc, Jest, Pytest, JaCoCo).\n2. Design a normalized intermediate coverage format that any test tool can map to.\n3. Implement adapter classes for each major testing framework that convert their reports to the intermediate format.\n4. Create a parser registry that can automatically detect and use the appropriate parser based on input format.\n5. Develop a mapping algorithm that associates coverage data with specific tasks based on file paths and code blocks.\n6. Implement file path normalization to handle different operating systems and environments.\n7. Add error handling for malformed or incomplete coverage reports.\n8. Create unit tests for each adapter using sample coverage reports.\n9. Implement a command-line interface for manual parsing and testing.\n10. Document the extension points for adding custom coverage tool adapters.",
"status": "pending",
"parentTaskId": 50
@@ -2666,7 +3028,9 @@
"id": 3,
"title": "Build coverage tracking and update generator",
"description": "Create a system that processes code coverage reports, maps them to tasks, and updates the tests.json file to maintain accurate coverage tracking over time.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "1. Implement a coverage processor that takes parsed coverage data and maps it to task IDs.\n2. Create algorithms to calculate aggregate coverage metrics at the task and subtask levels.\n3. Develop a change detection system that identifies when tests or code have changed and require updates.\n4. Implement incremental update logic to avoid reprocessing unchanged tests.\n5. Create a task-code association system that maps specific code blocks to tasks for granular tracking.\n6. Add historical tracking to monitor coverage trends over time.\n7. Implement hooks for CI/CD integration to automatically update coverage after test runs.\n8. Create a conflict resolution strategy for when multiple tests cover the same code areas.\n9. Add performance optimizations for large codebases and test suites.\n10. Develop unit tests that verify correct aggregation and mapping of coverage data.\n11. Document the update workflow with sequence diagrams and examples.",
"status": "pending",
"parentTaskId": 50
@@ -2675,7 +3039,10 @@
"id": 4,
"title": "Implement CLI commands for coverage operations",
"description": "Create a set of command-line interface tools that allow developers to view, analyze, and manage test coverage at the task level.",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "1. Design a cohesive CLI command structure with subcommands for different coverage operations.\n2. Implement 'coverage show' command to display test coverage for a specific task/subtask.\n3. Create 'coverage gaps' command to identify untested code related to a particular task.\n4. Develop 'coverage history' command to show how coverage has changed over time.\n5. Implement 'coverage generate' command that uses LLMs to suggest tests for uncovered code.\n6. Add filtering options to focus on specific test types or coverage thresholds.\n7. Create formatted output options (JSON, CSV, markdown tables) for integration with other tools.\n8. Implement colorized terminal output for better readability of coverage reports.\n9. Add batch processing capabilities for running operations across multiple tasks.\n10. Create comprehensive help documentation and examples for each command.\n11. Develop unit and integration tests for CLI commands.\n12. Document command usage patterns and example workflows.",
"status": "pending",
"parentTaskId": 50
@@ -2684,7 +3051,11 @@
"id": 5,
"title": "Develop AI-powered test generation system",
"description": "Create an intelligent system that uses LLMs to generate targeted tests for uncovered code sections within tasks, integrating with the existing task management workflow.",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"details": "1. Design prompt templates for different test types (unit, integration, E2E) that incorporate task descriptions and code context.\n2. Implement code analysis to extract relevant context from uncovered code sections.\n3. Create a test generation pipeline that combines task metadata, code context, and coverage gaps.\n4. Develop strategies for maintaining test context across task changes and updates.\n5. Implement test quality evaluation to ensure generated tests are meaningful and effective.\n6. Create a feedback mechanism to improve prompts based on acceptance or rejection of generated tests.\n7. Add support for different testing frameworks and languages through templating.\n8. Implement caching to avoid regenerating similar tests.\n9. Create a workflow that integrates with the task management system to suggest tests alongside implementation requirements.\n10. Develop specialized generation modes for edge cases, regression tests, and performance tests.\n11. Add configuration options for controlling test generation style and coverage goals.\n12. Create comprehensive documentation on how to use and extend the test generation system.\n13. Implement evaluation metrics to track the effectiveness of AI-generated tests.",
"status": "pending",
"parentTaskId": 50
@@ -2723,7 +3094,9 @@
"id": 3,
"title": "Build Research Command CLI Interface",
"description": "Implement the Commander.js command structure for the 'research' command with all required options and parameters.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implementation details:\n1. Create a new command file `commands/research.js`\n2. Set up the Commander.js command structure with the following options:\n - Required search query parameter\n - `--task` or `-t` option for task/subtask ID\n - `--prompt` or `-p` option for custom research prompt\n - `--save` or `-s` option to save results to a file\n - `--copy` or `-c` option to copy results to clipboard\n - `--summary` or `-m` option to generate a summary\n - `--detail` or `-d` option to set research depth (default: medium)\n3. Implement command validation logic\n4. Connect the command to the Perplexity service created in subtask 1\n5. Integrate the context extraction logic from subtask 2\n6. Register the command in the main CLI application\n7. Add help text and examples\n\nTesting approach:\n- Test command registration and option parsing\n- Verify command validation logic works correctly\n- Test with various combinations of options\n- Ensure proper error messages for invalid inputs\n<info added on 2025-05-23T21:09:08.478Z>\nImplementation details:\n1. Create a new module `repl/research-chat.js` for the interactive research experience\n2. Implement REPL-style chat interface using inquirer with:\n - Persistent conversation history management\n - Context-aware prompting system\n - Command parsing for special instructions\n3. Implement REPL commands:\n - `/save` - Save conversation to file\n - `/task` - Associate with or load context from a task\n - `/help` - Show available commands and usage\n - `/exit` - End the research session\n - `/copy` - Copy last response to clipboard\n - `/summary` - Generate summary of conversation\n - `/detail` - Adjust research depth level\n4. Create context initialization system:\n - Task/subtask context loading\n - File content integration\n - System prompt configuration\n5. Integrate with ai-services-unified.js research mode\n6. Implement conversation state management:\n - Track message history\n - Maintain context window\n - Handle context pruning for long conversations\n7. Design consistent UI patterns using ui.js library\n8. Add entry point in main CLI application\n\nTesting approach:\n- Test REPL command parsing and execution\n- Verify context initialization with various inputs\n- Test conversation state management\n- Ensure proper error handling and recovery\n- Validate UI consistency across different terminal environments\n</info added on 2025-05-23T21:09:08.478Z>",
"status": "pending",
"parentTaskId": 51
@@ -2732,7 +3105,10 @@
"id": 4,
"title": "Implement Results Processing and Output Formatting",
"description": "Create functionality to process, format, and display research results in the terminal with options for saving, copying, and summarizing.",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Implementation details:\n1. Create a new module `utils/researchFormatter.js`\n2. Implement terminal output formatting with:\n - Color-coded sections for better readability\n - Proper text wrapping for terminal width\n - Highlighting of key points\n3. Add functionality to save results to a file:\n - Create a `research-results` directory if it doesn't exist\n - Save results with timestamp and query in filename\n - Support multiple formats (text, markdown, JSON)\n4. Implement clipboard copying using a library like `clipboardy`\n5. Create a summarization function that extracts key points from research results\n6. Add progress indicators during API calls\n7. Implement pagination for long results\n\nTesting approach:\n- Test output formatting with various result lengths and content types\n- Verify file saving functionality creates proper files with correct content\n- Test clipboard functionality\n- Verify summarization produces useful results\n<info added on 2025-05-23T21:10:00.181Z>\nImplementation details:\n1. Create a new module `utils/chatFormatter.js` for REPL interface formatting\n2. Implement terminal output formatting for conversational display:\n - Color-coded messages distinguishing user inputs and AI responses\n - Proper text wrapping and indentation for readability\n - Support for markdown rendering in terminal\n - Visual indicators for system messages and status updates\n3. Implement streaming/progressive display of AI responses:\n - Character-by-character or chunk-by-chunk display\n - Cursor animations during response generation\n - Ability to interrupt long responses\n4. Design chat history visualization:\n - Scrollable history with clear message boundaries\n - Timestamp display options\n - Session identification\n5. Create specialized formatters for different content types:\n - Code blocks with syntax highlighting\n - Bulleted and numbered lists\n - Tables and structured data\n - Citations and references\n6. Implement export functionality:\n - Save conversations to markdown or text files\n - Export individual responses\n - Copy responses to clipboard\n7. Adapt existing ui.js patterns for conversational context:\n - Maintain consistent styling while supporting chat flow\n - Handle multi-turn context appropriately\n\nTesting approach:\n- Test streaming display with various response lengths and speeds\n- Verify markdown rendering accuracy for complex formatting\n- Test history navigation and scrolling functionality\n- Verify export features create properly formatted files\n- Test display on various terminal sizes and configurations\n- Verify handling of special characters and unicode\n</info added on 2025-05-23T21:10:00.181Z>",
"status": "pending",
"parentTaskId": 51
@@ -2741,7 +3117,10 @@
"id": 5,
"title": "Implement Caching and Results Management System",
"description": "Create a persistent caching system for research results and implement functionality to manage, retrieve, and reference previous research.",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"details": "Implementation details:\n1. Create a research results database using a simple JSON file or SQLite:\n - Store queries, timestamps, and results\n - Index by query and related task IDs\n2. Implement cache retrieval and validation:\n - Check for cached results before making API calls\n - Validate cache freshness with configurable TTL\n3. Add commands to manage research history:\n - List recent research queries\n - Retrieve past research by ID or search term\n - Clear cache or delete specific entries\n4. Create functionality to associate research results with tasks:\n - Add metadata linking research to specific tasks\n - Implement command to show all research related to a task\n5. Add configuration options for cache behavior in user settings\n6. Implement export/import functionality for research data\n\nTesting approach:\n- Test cache storage and retrieval with various queries\n- Verify cache invalidation works correctly\n- Test history management commands\n- Verify task association functionality\n- Test with large cache sizes to ensure performance\n<info added on 2025-05-23T21:10:28.544Z>\nImplementation details:\n1. Create a session management system for the REPL experience:\n - Generate and track unique session IDs\n - Store conversation history with timestamps\n - Maintain context and state between interactions\n2. Implement session persistence:\n - Save sessions to disk automatically\n - Load previous sessions on startup\n - Handle graceful recovery from crashes\n3. Build session browser and selector:\n - List available sessions with preview\n - Filter sessions by date, topic, or content\n - Enable quick switching between sessions\n4. Implement conversation state serialization:\n - Capture full conversation context\n - Preserve user preferences per session\n - Handle state migration during updates\n5. Add session sharing capabilities:\n - Export sessions to portable formats\n - Import sessions from files\n - Generate shareable links (if applicable)\n6. Create session management commands:\n - Create new sessions\n - Clone existing sessions\n - Archive or delete old sessions\n\nTesting approach:\n- Verify session persistence across application restarts\n- Test session recovery from simulated crashes\n- Validate state serialization with complex conversations\n- Ensure session switching maintains proper context\n- Test session import/export functionality\n- Verify performance with large conversation histories\n</info added on 2025-05-23T21:10:28.544Z>",
"status": "cancelled",
"parentTaskId": 51
@@ -2759,7 +3138,9 @@
"id": 7,
"title": "Create REPL Command System",
"description": "Implement a flexible command system for the research REPL that allows users to control the conversation flow, manage sessions, and access additional functionality.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Implementation details:\n1. Create a new module `repl/commands.js` for REPL command handling\n2. Implement a command parser that:\n - Detects commands starting with `/`\n - Parses arguments and options\n - Handles quoted strings and special characters\n3. Create a command registry system:\n - Register command handlers with descriptions\n - Support command aliases\n - Enable command discovery and help\n4. Implement core commands:\n - `/save [filename]` - Save conversation\n - `/task <taskId>` - Load task context\n - `/file <path>` - Include file content\n - `/help [command]` - Show help\n - `/exit` - End session\n - `/copy [n]` - Copy nth response\n - `/summary` - Generate conversation summary\n - `/detail <level>` - Set detail level\n - `/clear` - Clear conversation\n - `/project` - Refresh project context\n - `/session <id|new>` - Switch/create session\n5. Add command completion and suggestions\n6. Implement error handling for invalid commands\n7. Create a help system with examples\n\nTesting approach:\n- Test command parsing with various inputs\n- Verify command execution and error handling\n- Test command completion functionality\n- Verify help system provides useful information\n- Test with complex command sequences",
"status": "pending",
"parentTaskId": 51
@@ -2768,7 +3149,10 @@
"id": 8,
"title": "Integrate with AI Services Unified",
"description": "Integrate the research REPL with the existing ai-services-unified.js to leverage the unified AI service architecture with research mode.",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Implementation details:\n1. Update `repl/research-chat.js` to integrate with ai-services-unified.js\n2. Configure research mode in AI service:\n - Set appropriate system prompts\n - Configure temperature and other parameters\n - Enable streaming responses\n3. Implement context management:\n - Format conversation history for AI context\n - Include task and project context\n - Handle context window limitations\n4. Add support for different research styles:\n - Exploratory research with broader context\n - Focused research with specific questions\n - Comparative analysis between concepts\n5. Implement response handling:\n - Process streaming chunks\n - Format and display responses\n - Handle errors and retries\n6. Add configuration options for AI service selection\n7. Implement fallback mechanisms for service unavailability\n\nTesting approach:\n- Test integration with mocked AI services\n- Verify context formatting and management\n- Test streaming response handling\n- Verify error handling and recovery\n- Test with various research styles and queries",
"status": "pending",
"parentTaskId": 51
@@ -2797,7 +3181,9 @@
"id": 2,
"title": "Implement AI integration for task suggestions",
"description": "Develop the core functionality to generate task suggestions using AI based on existing tasks",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create an AI prompt template that effectively communicates the existing task context and request for suggestions. Implement error handling for API failures, rate limiting, and malformed responses. Include parameters for controlling suggestion quantity and specificity.",
"status": "pending"
},
@@ -2813,7 +3199,9 @@
"id": 4,
"title": "Implement suggestion selection and task creation",
"description": "Allow users to interactively select suggestions to convert into actual tasks",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Create an interactive selection interface where users can review suggestions, select which ones to create as tasks, and optionally modify them before creation. Implement batch creation capabilities and validation to ensure new tasks meet system requirements.",
"status": "pending"
},
@@ -2821,7 +3209,10 @@
"id": 5,
"title": "Add configuration options and flag handling",
"description": "Implement various configuration options and command flags for customizing suggestion behavior",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Create a comprehensive set of command flags for controlling suggestion quantity, specificity, format, and other parameters. Implement persistent configuration options that users can set as defaults. Document all available options and provide examples of common usage patterns.",
"status": "pending"
}
@@ -2849,7 +3240,9 @@
"id": 2,
"title": "Build context gathering mechanism",
"description": "Develop a system to collect relevant context from parent task and existing subtasks",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create functions to extract information from the parent task including title, description, and metadata. Also gather information about any existing subtasks to provide context for AI suggestions. Format this data appropriately for the AI prompt.",
"status": "pending"
},
@@ -2865,7 +3258,9 @@
"id": 4,
"title": "Create interactive CLI interface",
"description": "Build a user-friendly command-line interface for the subtask suggestion feature",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Develop CLI commands and options for requesting subtask suggestions. Include interactive elements for selecting, modifying, or rejecting suggested subtasks. Ensure clear user feedback throughout the process.",
"status": "pending"
},
@@ -2873,7 +3268,9 @@
"id": 5,
"title": "Implement subtask linking functionality",
"description": "Create system to properly link suggested subtasks to their parent task",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Develop the database operations to save accepted subtasks and link them to the parent task. Include functionality for setting dependencies between subtasks. Ensure proper transaction handling to maintain data integrity.",
"status": "pending"
},
@@ -2919,7 +3316,9 @@
"id": 2,
"title": "Design positional argument specification format",
"description": "Create a specification for how positional arguments will be defined in command definitions, including their order, required/optional status, and type validation.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Define a clear syntax for specifying positional arguments in command definitions. Consider how to handle mixed positional and named arguments, default values, and type constraints. Document the specification with examples for different command types.",
"status": "pending"
},
@@ -2927,7 +3326,9 @@
"id": 3,
"title": "Implement core positional argument parsing logic",
"description": "Modify the argument parser to recognize and process positional arguments according to the specification, while maintaining compatibility with existing named arguments.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Update the parser to identify arguments without flags as positional, map them to the correct parameter based on order, and apply appropriate validation. Ensure the implementation handles missing required positional arguments and provides helpful error messages.",
"status": "pending"
},
@@ -2935,7 +3336,9 @@
"id": 4,
"title": "Handle edge cases and error conditions",
"description": "Implement robust handling for edge cases such as too many/few arguments, type mismatches, and ambiguous situations between positional and named arguments.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Create comprehensive error handling for scenarios like: providing both positional and named version of the same argument, incorrect argument types, missing required positional arguments, and excess positional arguments. Ensure error messages are clear and actionable for users.",
"status": "pending"
},
@@ -2943,7 +3346,10 @@
"id": 5,
"title": "Update documentation and create usage examples",
"description": "Update CLI documentation to explain positional argument support and provide clear examples showing how to use positional arguments with different commands.",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Revise user documentation to include positional argument syntax, update command reference with positional argument information, and create example command snippets showing both positional and named argument usage. Include a migration guide for users transitioning from named-only to positional arguments.",
"status": "pending"
}
@@ -3013,7 +3419,9 @@
"id": 6,
"title": "Create Help System and Interactive Documentation",
"description": "Develop an in-CLI help system with examples and contextual assistance",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Implement a comprehensive help command with examples for each feature. Add contextual help that suggests relevant commands based on user actions. Create interactive tutorials for new users. Include command auto-completion suggestions and syntax highlighting for command examples.",
"status": "pending"
}
@@ -3051,7 +3459,9 @@
"id": 2,
"title": "Remove Manual Dependency Modifications",
"description": "Eliminate any custom scripts or manual steps that alter dependencies outside of npm's standard workflow.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Refactor or delete code that manually installs, updates, or modifies dependencies, ensuring all dependency management is handled via npm.",
"status": "done"
},
@@ -3067,7 +3477,9 @@
"id": 4,
"title": "Update Initialization and Installation Commands",
"description": "Revise project setup scripts and documentation to reflect the new npm-based dependency management approach.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Ensure that all initialization commands (e.g., npm install) are up-to-date and remove references to deprecated manual steps.",
"status": "done"
},
@@ -3075,7 +3487,9 @@
"id": 5,
"title": "Update Documentation",
"description": "Revise project documentation to describe the new dependency management process and provide clear setup instructions.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Update README, onboarding guides, and any developer documentation to align with npm best practices.",
"status": "done"
},
@@ -3111,7 +3525,9 @@
"id": 2,
"title": "Implement Mentor Profile Management",
"description": "Develop the functionality for creating, editing, and managing mentor profiles in the system.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Build UI components for mentor profile creation and editing. Implement backend APIs for profile CRUD operations. Create expertise tagging system and availability calendar. Add profile verification and approval workflows for quality control.",
"status": "pending"
},
@@ -3119,7 +3535,9 @@
"id": 3,
"title": "Develop Round-Table Discussion Framework",
"description": "Create the core framework for hosting and managing round-table discussions between mentors and users.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Design the discussion room data model and state management. Implement discussion scheduling and participant management. Create discussion topic and agenda setting functionality. Develop discussion moderation tools and rules enforcement mechanisms.",
"status": "pending"
},
@@ -3127,7 +3545,9 @@
"id": 4,
"title": "Implement LLM Integration for AI Mentors",
"description": "Integrate LLM capabilities to simulate AI mentors that can participate in round-table discussions.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Select appropriate LLM models for mentor simulation. Develop prompt engineering templates for different mentor personas and expertise areas. Implement context management to maintain conversation coherence. Create fallback mechanisms for handling edge cases in discussions.",
"status": "pending"
},
@@ -3135,7 +3555,10 @@
"id": 5,
"title": "Build Discussion Output Formatter",
"description": "Create a system to format and present round-table discussion outputs in a structured, readable format.",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Design templates for discussion summaries and transcripts. Implement real-time formatting of ongoing discussions. Create exportable formats for discussion outcomes (PDF, markdown, etc.). Develop highlighting and annotation features for key insights.",
"status": "pending"
},
@@ -3143,7 +3566,9 @@
"id": 6,
"title": "Integrate Mentor System with Task Management",
"description": "Connect the mentor system with the existing task management functionality to enable task-specific mentoring.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Create APIs to link tasks with relevant mentors based on expertise. Implement functionality to initiate discussions around specific tasks. Develop mechanisms for mentors to provide feedback and guidance on tasks. Build notification system for task-related mentor interactions.",
"status": "pending"
},
@@ -3151,7 +3576,9 @@
"id": 7,
"title": "Test and Optimize Round-Table Discussions",
"description": "Conduct comprehensive testing of the round-table discussion feature and optimize for performance and user experience.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Perform load testing with multiple concurrent discussions. Test AI mentor responses for quality and relevance. Optimize LLM usage for cost efficiency. Conduct user testing sessions and gather feedback. Implement performance monitoring and analytics for ongoing optimization.",
"status": "pending"
}
@@ -3180,7 +3607,9 @@
"id": 2,
"title": "Implement CLI Command Parser for Model Management",
"description": "Extend the CLI command parser to handle the new 'models' command and associated flags for model management.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "1. Update the CLI command parser to recognize the 'models' command\n2. Add support for '--set-main' and '--set-research' flags\n3. Implement validation for command arguments\n4. Create help text and usage examples for the models command\n5. Add error handling for invalid command usage\n6. Connect CLI parser to the configuration manager\n7. Implement command output formatting for model listings\n8. Testing approach: Create integration tests that verify CLI commands correctly interact with the configuration manager",
"status": "done",
"parentTaskId": 61
@@ -3189,7 +3618,9 @@
"id": 3,
"title": "Integrate Vercel AI SDK and Create Client Factory",
"description": "Set up Vercel AI SDK integration and implement a client factory pattern to create and manage AI model clients.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "1. Install Vercel AI SDK: `npm install @vercel/ai`\n2. Create an `ai-client-factory.js` module that implements the Factory pattern\n3. Define client creation functions for each supported model (Claude, OpenAI, Ollama, Gemini, OpenRouter, Perplexity, Grok)\n4. Implement error handling for missing API keys or configuration issues\n5. Add caching mechanism to reuse existing clients\n6. Create a unified interface for all clients regardless of the underlying model\n7. Implement client validation to ensure proper initialization\n8. Testing approach: Mock API responses to test client creation and error handling\n\n<info added on 2025-04-14T23:02:30.519Z>\nHere's additional information for the client factory implementation:\n\nFor the client factory implementation:\n\n1. Structure the factory with a modular approach:\n```javascript\n// ai-client-factory.js\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createAnthropic } from '@ai-sdk/anthropic';\nimport { createGoogle } from '@ai-sdk/google';\nimport { createPerplexity } from '@ai-sdk/perplexity';\n\nconst clientCache = new Map();\n\nexport function createClientInstance(providerName, options = {}) {\n // Implementation details below\n}\n```\n\n2. For OpenAI-compatible providers (Ollama), implement specific configuration:\n```javascript\ncase 'ollama':\n const ollamaBaseUrl = process.env.OLLAMA_BASE_URL || 'http://localhost:11434';\n return createOpenAI({\n baseURL: ollamaBaseUrl,\n apiKey: 'ollama', // Ollama doesn't require a real API key\n ...options\n });\n```\n\n3. Add provider-specific model mapping:\n```javascript\n// Model mapping helper\nconst getModelForProvider = (provider, requestedModel) => {\n const modelMappings = {\n openai: {\n default: 'gpt-3.5-turbo',\n // Add other mappings\n },\n anthropic: {\n default: 'claude-3-opus-20240229',\n // Add other mappings\n },\n // Add mappings for other providers\n };\n \n return (modelMappings[provider] && modelMappings[provider][requestedModel]) \n || modelMappings[provider]?.default \n || requestedModel;\n};\n```\n\n4. Implement caching with provider+model as key:\n```javascript\nexport function getClient(providerName, model) {\n const cacheKey = `${providerName}:${model || 'default'}`;\n \n if (clientCache.has(cacheKey)) {\n return clientCache.get(cacheKey);\n }\n \n const modelName = getModelForProvider(providerName, model);\n const client = createClientInstance(providerName, { model: modelName });\n clientCache.set(cacheKey, client);\n \n return client;\n}\n```\n\n5. Add detailed environment variable validation:\n```javascript\nfunction validateEnvironment(provider) {\n const requirements = {\n openai: ['OPENAI_API_KEY'],\n anthropic: ['ANTHROPIC_API_KEY'],\n google: ['GOOGLE_API_KEY'],\n perplexity: ['PERPLEXITY_API_KEY'],\n openrouter: ['OPENROUTER_API_KEY'],\n ollama: ['OLLAMA_BASE_URL'],\n xai: ['XAI_API_KEY']\n };\n \n const missing = requirements[provider]?.filter(env => !process.env[env]) || [];\n \n if (missing.length > 0) {\n throw new Error(`Missing environment variables for ${provider}: ${missing.join(', ')}`);\n }\n}\n```\n\n6. Add Jest test examples:\n```javascript\n// ai-client-factory.test.js\ndescribe('AI Client Factory', () => {\n beforeEach(() => {\n // Mock environment variables\n process.env.OPENAI_API_KEY = 'test-openai-key';\n process.env.ANTHROPIC_API_KEY = 'test-anthropic-key';\n // Add other mocks\n });\n \n test('creates OpenAI client with correct configuration', () => {\n const client = getClient('openai');\n expect(client).toBeDefined();\n // Add assertions for client configuration\n });\n \n test('throws error when environment variables are missing', () => {\n delete process.env.OPENAI_API_KEY;\n expect(() => getClient('openai')).toThrow(/Missing environment variables/);\n });\n \n // Add tests for other providers\n});\n```\n</info added on 2025-04-14T23:02:30.519Z>",
"status": "done",
"parentTaskId": 61
@@ -3198,7 +3629,9 @@
"id": 4,
"title": "Develop Centralized AI Services Module",
"description": "Create a centralized AI services module that abstracts all AI interactions through a unified interface, using the Decorator pattern for adding functionality like logging and retries.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "1. Create `ai-services.js` module to consolidate all AI model interactions\n2. Implement wrapper functions for text generation and streaming\n3. Add retry mechanisms for handling API rate limits and transient errors\n4. Implement logging for all AI interactions for observability\n5. Create model-specific adapters to normalize responses across different providers\n6. Add caching layer for frequently used responses to optimize performance\n7. Implement graceful fallback mechanisms when primary models fail\n8. Testing approach: Create unit tests with mocked responses to verify service behavior\n\n<info added on 2025-04-19T23:51:22.219Z>\nBased on the exploration findings, here's additional information for the AI services module refactoring:\n\nThe existing `ai-services.js` should be refactored to:\n\n1. Leverage the `ai-client-factory.js` for model instantiation while providing a higher-level service abstraction\n2. Implement a layered architecture:\n - Base service layer handling common functionality (retries, logging, caching)\n - Model-specific service implementations extending the base\n - Facade pattern to provide a unified API for all consumers\n\n3. Integration points:\n - Replace direct OpenAI client usage with factory-provided clients\n - Maintain backward compatibility with existing service consumers\n - Add service registration mechanism for new AI providers\n\n4. Performance considerations:\n - Implement request batching for high-volume operations\n - Add request priority queuing for critical vs non-critical operations\n - Implement circuit breaker pattern to prevent cascading failures\n\n5. Monitoring enhancements:\n - Add detailed telemetry for response times, token usage, and costs\n - Implement standardized error classification for better diagnostics\n\n6. Implementation sequence:\n - Start with abstract base service class\n - Refactor existing OpenAI implementations\n - Add adapter layer for new providers\n - Implement the unified facade\n</info added on 2025-04-19T23:51:22.219Z>",
"status": "done",
"parentTaskId": 61
@@ -3207,7 +3640,10 @@
"id": 5,
"title": "Implement Environment Variable Management",
"description": "Update environment variable handling to support multiple AI models and create documentation for configuration options.",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "1. Update `.env.example` with all required API keys for supported models\n2. Implement environment variable validation on startup\n3. Create clear error messages for missing or invalid environment variables\n4. Add support for model-specific configuration options\n5. Document all environment variables and their purposes\n6. Implement a check to ensure required API keys are present for selected models\n7. Add support for optional configuration parameters for each model\n8. Testing approach: Create tests that verify environment variable validation logic",
"status": "done",
"parentTaskId": 61
@@ -3216,7 +3652,10 @@
"id": 6,
"title": "Implement Model Listing Command",
"description": "Implement the 'task-master models' command to display currently configured models and available options.",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"details": "1. Create handler for the models command without flags\n2. Implement formatted output showing current model configuration\n3. Add color-coding for better readability using a library like chalk\n4. Include version information for each configured model\n5. Show API status indicators (connected/disconnected)\n6. Display usage examples for changing models\n7. Add support for verbose output with additional details\n8. Testing approach: Create integration tests that verify correct output formatting and content",
"status": "done",
"parentTaskId": 61
@@ -3225,7 +3664,10 @@
"id": 7,
"title": "Implement Model Setting Commands",
"description": "Implement the commands to set main and research models with proper validation and feedback.",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"details": "1. Create handlers for '--set-main' and '--set-research' flags\n2. Implement validation logic for model names\n3. Add clear error messages for invalid model selections\n4. Implement confirmation messages for successful model changes\n5. Add support for setting both models in a single command\n6. Implement dry-run option to validate without making changes\n7. Add verbose output option for debugging\n8. Testing approach: Create integration tests that verify model setting functionality with various inputs",
"status": "done",
"parentTaskId": 61
@@ -3234,7 +3676,10 @@
"id": 8,
"title": "Update Main Task Processing Logic",
"description": "Refactor the main task processing logic to use the new AI services module and support dynamic model selection.",
- "dependencies": [4, "61.18"],
+ "dependencies": [
+ 4,
+ "61.18"
+ ],
"details": "1. Update task processing functions to use the centralized AI services\n2. Implement dynamic model selection based on configuration\n3. Add error handling for model-specific failures\n4. Implement graceful degradation when preferred models are unavailable\n5. Update prompts to be model-agnostic where possible\n6. Add telemetry for model performance monitoring\n7. Implement response validation to ensure quality across different models\n8. Testing approach: Create integration tests that verify task processing with different model configurations\n\n<info added on 2025-04-20T03:55:56.310Z>\nWhen updating the main task processing logic, implement the following changes to align with the new configuration system:\n\n1. Replace direct environment variable access with calls to the configuration manager:\n ```javascript\n // Before\n const apiKey = process.env.OPENAI_API_KEY;\n const modelId = process.env.MAIN_MODEL || \"gpt-4\";\n \n // After\n import { getMainProvider, getMainModelId, getMainMaxTokens, getMainTemperature } from './config-manager.js';\n \n const provider = getMainProvider();\n const modelId = getMainModelId();\n const maxTokens = getMainMaxTokens();\n const temperature = getMainTemperature();\n ```\n\n2. Implement model fallback logic using the configuration hierarchy:\n ```javascript\n async function processTaskWithFallback(task) {\n try {\n return await processWithModel(task, getMainModelId());\n } catch (error) {\n logger.warn(`Primary model failed: ${error.message}`);\n const fallbackModel = getMainFallbackModelId();\n if (fallbackModel) {\n return await processWithModel(task, fallbackModel);\n }\n throw error;\n }\n }\n ```\n\n3. Add configuration-aware telemetry points to track model usage and performance:\n ```javascript\n function trackModelPerformance(modelId, startTime, success) {\n const duration = Date.now() - startTime;\n telemetry.trackEvent('model_usage', {\n modelId,\n provider: getMainProvider(),\n duration,\n success,\n configVersion: getConfigVersion()\n });\n }\n ```\n\n4. Ensure all prompt templates are loaded through the configuration system rather than hardcoded:\n ```javascript\n const promptTemplate = getPromptTemplate('task_processing');\n const prompt = formatPrompt(promptTemplate, { task: taskData });\n ```\n</info added on 2025-04-20T03:55:56.310Z>",
"status": "done",
"parentTaskId": 61
@@ -3243,7 +3688,10 @@
"id": 9,
"title": "Update Research Processing Logic",
"description": "Refactor the research processing logic to use the new AI services module and support dynamic model selection for research operations.",
- "dependencies": [4, "61.18"],
+ "dependencies": [
+ 4,
+ "61.18"
+ ],
"details": "1. Update research functions to use the centralized AI services\n2. Implement dynamic model selection for research operations\n3. Add specialized error handling for research-specific issues\n4. Optimize prompts for research-focused models\n5. Implement result caching for research operations\n6. Add support for model-specific research parameters\n7. Create fallback mechanisms for research operations\n8. Testing approach: Create integration tests that verify research functionality with different model configurations\n\n<info added on 2025-04-20T03:55:39.633Z>\nWhen implementing the refactored research processing logic, ensure the following:\n\n1. Replace direct environment variable access with the new configuration system:\n ```javascript\n // Old approach\n const apiKey = process.env.OPENAI_API_KEY;\n const model = \"gpt-4\";\n \n // New approach\n import { getResearchProvider, getResearchModelId, getResearchMaxTokens, \n getResearchTemperature } from './config-manager.js';\n \n const provider = getResearchProvider();\n const modelId = getResearchModelId();\n const maxTokens = getResearchMaxTokens();\n const temperature = getResearchTemperature();\n ```\n\n2. Implement model fallback chains using the configuration system:\n ```javascript\n async function performResearch(query) {\n try {\n return await callAIService({\n provider: getResearchProvider(),\n modelId: getResearchModelId(),\n maxTokens: getResearchMaxTokens(),\n temperature: getResearchTemperature()\n });\n } catch (error) {\n logger.warn(`Primary research model failed: ${error.message}`);\n return await callAIService({\n provider: getResearchProvider('fallback'),\n modelId: getResearchModelId('fallback'),\n maxTokens: getResearchMaxTokens('fallback'),\n temperature: getResearchTemperature('fallback')\n });\n }\n }\n ```\n\n3. Add support for dynamic parameter adjustment based on research type:\n ```javascript\n function getResearchParameters(researchType) {\n // Get base parameters\n const baseParams = {\n provider: getResearchProvider(),\n modelId: getResearchModelId(),\n maxTokens: getResearchMaxTokens(),\n temperature: getResearchTemperature()\n };\n \n // Adjust based on research type\n switch(researchType) {\n case 'deep':\n return {...baseParams, maxTokens: baseParams.maxTokens * 1.5};\n case 'creative':\n return {...baseParams, temperature: Math.min(baseParams.temperature + 0.2, 1.0)};\n case 'factual':\n return {...baseParams, temperature: Math.max(baseParams.temperature - 0.2, 0)};\n default:\n return baseParams;\n }\n }\n ```\n\n4. Ensure the caching mechanism uses configuration-based TTL settings:\n ```javascript\n const researchCache = new Cache({\n ttl: getResearchCacheTTL(),\n maxSize: getResearchCacheMaxSize()\n });\n ```\n</info added on 2025-04-20T03:55:39.633Z>",
"status": "done",
"parentTaskId": 61
@@ -3252,7 +3700,9 @@
"id": 10,
"title": "Create Comprehensive Documentation and Examples",
"description": "Develop comprehensive documentation for the new model management features, including examples, troubleshooting guides, and best practices.",
- "dependencies": [7],
+ "dependencies": [
+ 7
+ ],
"details": "1. Update README.md with new model management commands\n2. Create usage examples for all supported models\n3. Document environment variable requirements for each model\n4. Create troubleshooting guide for common issues\n5. Add performance considerations and best practices\n6. Document API key acquisition process for each supported service\n7. Create comparison chart of model capabilities and limitations\n8. Testing approach: Conduct user testing with the documentation to ensure clarity and completeness\n\n<info added on 2025-04-20T03:55:20.433Z>\n## Documentation Update for Configuration System Refactoring\n\n### Configuration System Architecture\n- Document the separation between environment variables and configuration file:\n - API keys: Sourced exclusively from environment variables (process.env or session.env)\n - All other settings: Centralized in `.taskmasterconfig` JSON file\n\n### `.taskmasterconfig` Structure\n```json\n{\n \"models\": {\n \"completion\": \"gpt-3.5-turbo\",\n \"chat\": \"gpt-4\",\n \"embedding\": \"text-embedding-ada-002\"\n },\n \"parameters\": {\n \"temperature\": 0.7,\n \"maxTokens\": 2000,\n \"topP\": 1\n },\n \"logging\": {\n \"enabled\": true,\n \"level\": \"info\"\n },\n \"defaults\": {\n \"outputFormat\": \"markdown\"\n }\n}\n```\n\n### Configuration Access Patterns\n- Document the getter functions in `config-manager.js`:\n - `getModelForRole(role)`: Returns configured model for a specific role\n - `getParameter(name)`: Retrieves model parameters\n - `getLoggingConfig()`: Access logging settings\n - Example usage: `const completionModel = getModelForRole('completion')`\n\n### Environment Variable Resolution\n- Explain the `resolveEnvVariable(key)` function:\n - Checks both process.env and session.env\n - Prioritizes session variables over process variables\n - Returns null if variable not found\n\n### Configuration Precedence\n- Document the order of precedence:\n 1. Command-line arguments (highest priority)\n 2. Session environment variables\n 3. Process environment variables\n 4. `.taskmasterconfig` settings\n 5. Hardcoded defaults (lowest priority)\n\n### Migration Guide\n- Steps for users to migrate from previous configuration approach\n- How to verify configuration is correctly loaded\n</info added on 2025-04-20T03:55:20.433Z>",
"status": "done",
"parentTaskId": 61
@@ -3263,7 +3713,9 @@
"description": "Update PRD processing logic (callClaude, processClaudeResponse, handleStreamingRequest in ai-services.js) to use the new `generateObjectService` from `ai-services-unified.js` with an appropriate Zod schema.",
"details": "\n\n<info added on 2025-04-20T03:55:01.707Z>\nThe PRD parsing refactoring should align with the new configuration system architecture. When implementing this change:\n\n1. Replace direct environment variable access with `resolveEnvVariable` calls for API keys.\n\n2. Remove any hardcoded model names or parameters in the PRD processing functions. Instead, use the config-manager.js getters:\n - `getModelForRole('prd')` to determine the appropriate model\n - `getModelParameters('prd')` to retrieve temperature, maxTokens, etc.\n\n3. When constructing the generateObjectService call, ensure parameters are sourced from config:\n```javascript\nconst modelConfig = getModelParameters('prd');\nconst model = getModelForRole('prd');\n\nconst result = await generateObjectService({\n model,\n temperature: modelConfig.temperature,\n maxTokens: modelConfig.maxTokens,\n // other parameters as needed\n schema: prdSchema,\n // existing prompt/context parameters\n});\n```\n\n4. Update any logging to respect the logging configuration from config-manager (e.g., `isLoggingEnabled('ai')`)\n\n5. Ensure any default values previously hardcoded are now retrieved from the configuration system.\n</info added on 2025-04-20T03:55:01.707Z>",
"status": "done",
- "dependencies": ["61.23"],
+ "dependencies": [
+ "61.23"
+ ],
"parentTaskId": 61
},
{
@@ -3272,7 +3724,9 @@
"description": "Update the `generateSubtasks` function in `ai-services.js` to use the new `generateObjectService` from `ai-services-unified.js` with a Zod schema for the subtask array.",
"details": "\n\n<info added on 2025-04-20T03:54:45.542Z>\nThe refactoring should leverage the new configuration system:\n\n1. Replace direct model references with calls to config-manager.js getters:\n ```javascript\n const { getModelForRole, getModelParams } = require('./config-manager');\n \n // Instead of hardcoded models/parameters:\n const model = getModelForRole('subtask-generator');\n const modelParams = getModelParams('subtask-generator');\n ```\n\n2. Update API key handling to use the resolveEnvVariable pattern:\n ```javascript\n const { resolveEnvVariable } = require('./utils');\n const apiKey = resolveEnvVariable('OPENAI_API_KEY');\n ```\n\n3. When calling generateObjectService, pass the configuration parameters:\n ```javascript\n const result = await generateObjectService({\n schema: subtasksArraySchema,\n prompt: subtaskPrompt,\n model: model,\n temperature: modelParams.temperature,\n maxTokens: modelParams.maxTokens,\n // Other parameters from config\n });\n ```\n\n4. Add error handling that respects logging configuration:\n ```javascript\n const { isLoggingEnabled } = require('./config-manager');\n \n try {\n // Generation code\n } catch (error) {\n if (isLoggingEnabled('errors')) {\n console.error('Subtask generation error:', error);\n }\n throw error;\n }\n ```\n</info added on 2025-04-20T03:54:45.542Z>",
"status": "done",
- "dependencies": ["61.23"],
+ "dependencies": [
+ "61.23"
+ ],
"parentTaskId": 61
},
{
@@ -3281,7 +3735,9 @@
"description": "Update the `generateSubtasksWithPerplexity` function in `ai-services.js` to first perform research (potentially keeping the Perplexity call separate or adapting it) and then use `generateObjectService` from `ai-services-unified.js` with research results included in the prompt.",
"details": "\n\n<info added on 2025-04-20T03:54:26.882Z>\nThe refactoring should align with the new configuration system by:\n\n1. Replace direct environment variable access with `resolveEnvVariable` for API keys\n2. Use the config-manager.js getters to retrieve model parameters:\n - Replace hardcoded model names with `getModelForRole('research')`\n - Use `getParametersForRole('research')` to get temperature, maxTokens, etc.\n3. Implement proper error handling that respects the `getLoggingConfig()` settings\n4. Example implementation pattern:\n```javascript\nconst { getModelForRole, getParametersForRole, getLoggingConfig } = require('./config-manager');\nconst { resolveEnvVariable } = require('./environment-utils');\n\n// In the refactored function:\nconst researchModel = getModelForRole('research');\nconst { temperature, maxTokens } = getParametersForRole('research');\nconst apiKey = resolveEnvVariable('PERPLEXITY_API_KEY');\nconst { verbose } = getLoggingConfig();\n\n// Then use these variables in the API call configuration\n```\n5. Ensure the transition to generateObjectService maintains all existing functionality while leveraging the new configuration system\n</info added on 2025-04-20T03:54:26.882Z>",
"status": "done",
- "dependencies": ["61.23"],
+ "dependencies": [
+ "61.23"
+ ],
"parentTaskId": 61
},
{
@@ -3290,7 +3746,9 @@
"description": "Update the `generateTaskDescriptionWithPerplexity` function in `ai-services.js` to first perform research and then use `generateObjectService` from `ai-services-unified.js` to generate the structured task description.",
"details": "\n\n<info added on 2025-04-20T03:54:04.420Z>\nThe refactoring should incorporate the new configuration management system:\n\n1. Update imports to include the config-manager:\n```javascript\nconst { getModelForRole, getParametersForRole } = require('./config-manager');\n```\n\n2. Replace any hardcoded model selections or parameters with config-manager calls:\n```javascript\n// Replace direct model references like:\n// const model = \"perplexity-model-7b-online\" \n// With:\nconst model = getModelForRole('research');\nconst parameters = getParametersForRole('research');\n```\n\n3. For API key handling, use the resolveEnvVariable pattern:\n```javascript\nconst apiKey = resolveEnvVariable('PERPLEXITY_API_KEY');\n```\n\n4. When calling generateObjectService, pass the configuration-derived parameters:\n```javascript\nreturn generateObjectService({\n prompt: researchResults,\n schema: taskDescriptionSchema,\n role: 'taskDescription',\n // Config-driven parameters will be applied within generateObjectService\n});\n```\n\n5. Remove any hardcoded configuration values, ensuring all settings are retrieved from the centralized configuration system.\n</info added on 2025-04-20T03:54:04.420Z>",
"status": "done",
- "dependencies": ["61.23"],
+ "dependencies": [
+ "61.23"
+ ],
"parentTaskId": 61
},
{
@@ -3299,7 +3757,9 @@
"description": "Update the logic that calls the AI after using `generateComplexityAnalysisPrompt` in `ai-services.js` to use the new `generateObjectService` from `ai-services-unified.js` with a Zod schema for the complexity report.",
"details": "\n\n<info added on 2025-04-20T03:53:46.120Z>\nThe complexity analysis AI call should be updated to align with the new configuration system architecture. When refactoring to use `generateObjectService`, implement the following changes:\n\n1. Replace direct model references with calls to the appropriate config getter:\n ```javascript\n const modelName = getComplexityAnalysisModel(); // Use the specific getter from config-manager.js\n ```\n\n2. Retrieve AI parameters from the config system:\n ```javascript\n const temperature = getAITemperature('complexityAnalysis');\n const maxTokens = getAIMaxTokens('complexityAnalysis');\n ```\n\n3. When constructing the call to `generateObjectService`, pass these configuration values:\n ```javascript\n const result = await generateObjectService({\n prompt,\n schema: complexityReportSchema,\n modelName,\n temperature,\n maxTokens,\n sessionEnv: session?.env\n });\n ```\n\n4. Ensure API key resolution uses the `resolveEnvVariable` helper:\n ```javascript\n // Don't hardcode API keys or directly access process.env\n // The generateObjectService should handle this internally with resolveEnvVariable\n ```\n\n5. Add logging configuration based on settings:\n ```javascript\n const enableLogging = getAILoggingEnabled('complexityAnalysis');\n if (enableLogging) {\n // Use the logging mechanism defined in the configuration\n }\n ```\n</info added on 2025-04-20T03:53:46.120Z>",
"status": "done",
- "dependencies": ["61.23"],
+ "dependencies": [
+ "61.23"
+ ],
"parentTaskId": 61
},
{
@@ -3308,7 +3768,9 @@
"description": "Update the logic that calls the AI after using `_buildAddTaskPrompt` in `ai-services.js` to use the new `generateObjectService` from `ai-services-unified.js` with a Zod schema for the single task object.",
"details": "\n\n<info added on 2025-04-20T03:53:27.455Z>\nTo implement this refactoring, you'll need to:\n\n1. Replace direct AI calls with the new `generateObjectService` approach:\n ```javascript\n // OLD approach\n const aiResponse = await callLLM(prompt, modelName, temperature, maxTokens);\n const task = parseAIResponseToTask(aiResponse);\n \n // NEW approach using generateObjectService with config-manager\n import { generateObjectService } from '../services/ai-services-unified.js';\n import { getAIModelForRole, getAITemperature, getAIMaxTokens } from '../config/config-manager.js';\n import { taskSchema } from '../schemas/task-schema.js'; // Create this Zod schema for a single task\n \n const modelName = getAIModelForRole('taskCreation');\n const temperature = getAITemperature('taskCreation');\n const maxTokens = getAIMaxTokens('taskCreation');\n \n const task = await generateObjectService({\n prompt: _buildAddTaskPrompt(...),\n schema: taskSchema,\n modelName,\n temperature,\n maxTokens\n });\n ```\n\n2. Create a Zod schema for the task object in a new file `schemas/task-schema.js` that defines the expected structure.\n\n3. Ensure API key resolution uses the new pattern:\n ```javascript\n // This happens inside generateObjectService, but verify it uses:\n import { resolveEnvVariable } from '../config/config-manager.js';\n // Instead of direct process.env access\n ```\n\n4. Update any error handling to match the new service's error patterns.\n</info added on 2025-04-20T03:53:27.455Z>",
"status": "done",
- "dependencies": ["61.23"],
+ "dependencies": [
+ "61.23"
+ ],
"parentTaskId": 61
},
{
@@ -3317,7 +3779,9 @@
"description": "Refactor functions like `sendChatWithContext` (and potentially related task update functions in `task-manager.js` if they make direct AI calls) to use `streamTextService` or `generateTextService` from `ai-services-unified.js`.",
"details": "\n\n<info added on 2025-04-20T03:53:03.709Z>\nWhen refactoring `sendChatWithContext` and related functions, ensure they align with the new configuration system:\n\n1. Replace direct model references with config getter calls:\n ```javascript\n // Before\n const model = \"gpt-4\";\n \n // After\n import { getModelForRole } from './config-manager.js';\n const model = getModelForRole('chat'); // or appropriate role\n ```\n\n2. Extract AI parameters from config rather than hardcoding:\n ```javascript\n import { getAIParameters } from './config-manager.js';\n const { temperature, maxTokens } = getAIParameters('chat');\n ```\n\n3. When calling `streamTextService` or `generateTextService`, pass parameters from config:\n ```javascript\n await streamTextService({\n messages,\n model: getModelForRole('chat'),\n temperature: getAIParameters('chat').temperature,\n // other parameters as needed\n });\n ```\n\n4. For logging control, check config settings:\n ```javascript\n import { isLoggingEnabled } from './config-manager.js';\n \n if (isLoggingEnabled('aiCalls')) {\n console.log('AI request:', messages);\n }\n ```\n\n5. Ensure any default behaviors respect configuration defaults rather than hardcoded values.\n</info added on 2025-04-20T03:53:03.709Z>",
"status": "done",
- "dependencies": ["61.23"],
+ "dependencies": [
+ "61.23"
+ ],
"parentTaskId": 61
},
{
@@ -3335,7 +3799,9 @@
"description": "Refactor the AI call within `updateSubtaskById` in `task-manager.js` (which generates additional information based on a prompt) to use the appropriate unified service function (e.g., `generateTextService`) from `ai-services-unified.js`.",
"details": "\n\n<info added on 2025-04-20T03:52:28.196Z>\nThe `updateSubtaskById` function currently makes direct AI calls with hardcoded parameters. When refactoring to use the unified service:\n\n1. Replace direct OpenAI calls with `generateTextService` from `ai-services-unified.js`\n2. Use configuration parameters from `config-manager.js`:\n - Replace hardcoded model with `getMainModel()`\n - Use `getMainMaxTokens()` for token limits\n - Apply `getMainTemperature()` for response randomness\n3. Ensure prompt construction remains consistent but passes these dynamic parameters\n4. Handle API key resolution through the unified service (which uses `resolveEnvVariable`)\n5. Update error handling to work with the unified service response format\n6. If the function uses any logging, ensure it respects `getLoggingEnabled()` setting\n\nExample refactoring pattern:\n```javascript\n// Before\nconst completion = await openai.chat.completions.create({\n model: \"gpt-4\",\n temperature: 0.7,\n max_tokens: 1000,\n messages: [/* prompt messages */]\n});\n\n// After\nconst completion = await generateTextService({\n model: getMainModel(),\n temperature: getMainTemperature(),\n max_tokens: getMainMaxTokens(),\n messages: [/* prompt messages */]\n});\n```\n</info added on 2025-04-20T03:52:28.196Z>\n\n<info added on 2025-04-22T06:05:42.437Z>\n- When testing the non-streaming `generateTextService` call within `updateSubtaskById`, ensure that the function awaits the full response before proceeding with subtask updates. This allows you to validate that the unified service returns the expected structure (e.g., `completion.choices.message.content`) and that error handling logic correctly interprets any error objects or status codes returned by the service.\n\n- Mock or stub the `generateTextService` in unit tests to simulate both successful and failed completions. For example, verify that when the service returns a valid completion, the subtask is updated with the generated content, and when an error is returned, the error handling path is triggered and logged appropriately.\n\n- Confirm that the non-streaming mode does not emit partial results or require event-based handling; the function should only process the final, complete response.\n\n- Example test assertion:\n ```javascript\n // Mocked response from generateTextService\n const mockCompletion = {\n choices: [{ message: { content: \"Generated subtask details.\" } }]\n };\n generateTextService.mockResolvedValue(mockCompletion);\n\n // Call updateSubtaskById and assert the subtask is updated\n await updateSubtaskById(...);\n expect(subtask.details).toBe(\"Generated subtask details.\");\n ```\n\n- If the unified service supports both streaming and non-streaming modes, explicitly set or verify the `stream` parameter is `false` (or omitted) to ensure non-streaming behavior during these tests.\n</info added on 2025-04-22T06:05:42.437Z>\n\n<info added on 2025-04-22T06:20:19.747Z>\nWhen testing the non-streaming `generateTextService` call in `updateSubtaskById`, implement these verification steps:\n\n1. Add unit tests that verify proper parameter transformation between the old and new implementation:\n ```javascript\n test('should correctly transform parameters when calling generateTextService', async () => {\n // Setup mocks for config values\n jest.spyOn(configManager, 'getMainModel').mockReturnValue('gpt-4');\n jest.spyOn(configManager, 'getMainTemperature').mockReturnValue(0.7);\n jest.spyOn(configManager, 'getMainMaxTokens').mockReturnValue(1000);\n \n const generateTextServiceSpy = jest.spyOn(aiServices, 'generateTextService')\n .mockResolvedValue({ choices: [{ message: { content: 'test content' } }] });\n \n await updateSubtaskById(/* params */);\n \n // Verify the service was called with correct transformed parameters\n expect(generateTextServiceSpy).toHaveBeenCalledWith({\n model: 'gpt-4',\n temperature: 0.7,\n max_tokens: 1000,\n messages: expect.any(Array)\n });\n });\n ```\n\n2. Implement response validation to ensure the subtask content is properly extracted:\n ```javascript\n // In updateSubtaskById function\n try {\n const completion = await generateTextService({\n // parameters\n });\n \n // Validate response structure before using\n if (!completion?.choices?.[0]?.message?.content) {\n throw new Error('Invalid response structure from AI service');\n }\n \n // Continue with updating subtask\n } catch (error) {\n // Enhanced error handling\n }\n ```\n\n3. Add integration tests that verify the end-to-end flow with actual configuration values.\n</info added on 2025-04-22T06:20:19.747Z>\n\n<info added on 2025-04-22T06:23:23.247Z>\n<info added on 2025-04-22T06:35:14.892Z>\nWhen testing the non-streaming `generateTextService` call in `updateSubtaskById`, implement these specific verification steps:\n\n1. Create a dedicated test fixture that isolates the AI service interaction:\n ```javascript\n describe('updateSubtaskById AI integration', () => {\n beforeEach(() => {\n // Reset all mocks and spies\n jest.clearAllMocks();\n // Setup environment with controlled config values\n process.env.OPENAI_API_KEY = 'test-key';\n });\n \n // Test cases follow...\n });\n ```\n\n2. Test error propagation from the unified service:\n ```javascript\n test('should properly handle AI service errors', async () => {\n const mockError = new Error('Service unavailable');\n mockError.status = 503;\n jest.spyOn(aiServices, 'generateTextService').mockRejectedValue(mockError);\n \n // Capture console errors if needed\n const consoleSpy = jest.spyOn(console, 'error').mockImplementation();\n \n // Execute with error expectation\n await expect(updateSubtaskById(1, { prompt: 'test' })).rejects.toThrow();\n \n // Verify error was logged with appropriate context\n expect(consoleSpy).toHaveBeenCalledWith(\n expect.stringContaining('AI service error'),\n expect.objectContaining({ status: 503 })\n );\n });\n ```\n\n3. Verify that the function correctly preserves existing subtask content when appending new AI-generated information:\n ```javascript\n test('should preserve existing content when appending AI-generated details', async () => {\n // Setup mock subtask with existing content\n const mockSubtask = {\n id: 1,\n details: 'Existing details.\\n\\n'\n };\n \n // Mock database retrieval\n getSubtaskById.mockResolvedValue(mockSubtask);\n \n // Mock AI response\n generateTextService.mockResolvedValue({\n choices: [{ message: { content: 'New AI content.' } }]\n });\n \n await updateSubtaskById(1, { prompt: 'Enhance this subtask' });\n \n // Verify the update preserves existing content\n expect(updateSubtaskInDb).toHaveBeenCalledWith(\n 1,\n expect.objectContaining({\n details: expect.stringContaining('Existing details.\\n\\n<info added on')\n })\n );\n \n // Verify the new content was added\n expect(updateSubtaskInDb).toHaveBeenCalledWith(\n 1,\n expect.objectContaining({\n details: expect.stringContaining('New AI content.')\n })\n );\n });\n ```\n\n4. Test that the function correctly formats the timestamp and wraps the AI-generated content:\n ```javascript\n test('should format timestamp and wrap content correctly', async () => {\n // Mock date for consistent testing\n const mockDate = new Date('2025-04-22T10:00:00Z');\n jest.spyOn(global, 'Date').mockImplementation(() => mockDate);\n \n // Setup and execute test\n // ...\n \n // Verify correct formatting\n expect(updateSubtaskInDb).toHaveBeenCalledWith(\n expect.any(Number),\n expect.objectContaining({\n details: expect.stringMatching(\n /<info added on 2025-04-22T10:00:00\\.000Z>\\n.*\\n<\\/info added on 2025-04-22T10:00:00\\.000Z>/s\n )\n })\n );\n });\n ```\n\n5. Verify that the function correctly handles the case when no existing details are present:\n ```javascript\n test('should handle subtasks with no existing details', async () => {\n // Setup mock subtask with no details\n const mockSubtask = { id: 1 };\n getSubtaskById.mockResolvedValue(mockSubtask);\n \n // Execute test\n // ...\n \n // Verify details were initialized properly\n expect(updateSubtaskInDb).toHaveBeenCalledWith(\n 1,\n expect.objectContaining({\n details: expect.stringMatching(/^<info added on/)\n })\n );\n });\n ```\n</info added on 2025-04-22T06:35:14.892Z>\n</info added on 2025-04-22T06:23:23.247Z>",
"status": "done",
- "dependencies": ["61.23"],
+ "dependencies": [
+ "61.23"
+ ],
"parentTaskId": 61
},
{
@@ -3442,7 +3908,9 @@
"title": "Implement Integration Tests for Unified AI Service",
"description": "Implement integration tests for `ai-services-unified.js`. These tests should verify the correct routing to different provider modules based on configuration and ensure the unified service functions (`generateTextService`, `generateObjectService`, etc.) work correctly when called from modules like `task-manager.js`. [Updated: 5/2/2025] [Updated: 5/2/2025] [Updated: 5/2/2025] [Updated: 5/2/2025]",
"status": "done",
- "dependencies": ["61.18"],
+ "dependencies": [
+ "61.18"
+ ],
"details": "\n\n<info added on 2025-04-20T03:51:23.368Z>\nFor the integration tests of the Unified AI Service, consider the following implementation details:\n\n1. Setup test fixtures:\n - Create a mock `.taskmasterconfig` file with different provider configurations\n - Define test cases with various model selections and parameter settings\n - Use environment variable mocks only for API keys (e.g., `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`)\n\n2. Test configuration resolution:\n - Verify that `ai-services-unified.js` correctly retrieves settings from `config-manager.js`\n - Test that model selection follows the hierarchy defined in `.taskmasterconfig`\n - Ensure fallback mechanisms work when primary providers are unavailable\n\n3. Mock the provider modules:\n ```javascript\n jest.mock('../services/openai-service.js');\n jest.mock('../services/anthropic-service.js');\n ```\n\n4. Test specific scenarios:\n - Provider selection based on configured preferences\n - Parameter inheritance from config (temperature, maxTokens)\n - Error handling when API keys are missing\n - Proper routing when specific models are requested\n\n5. Verify integration with task-manager:\n ```javascript\n test('task-manager correctly uses unified AI service with config-based settings', async () => {\n // Setup mock config with specific settings\n mockConfigManager.getAIProviderPreference.mockReturnValue(['openai', 'anthropic']);\n mockConfigManager.getModelForRole.mockReturnValue('gpt-4');\n mockConfigManager.getParametersForModel.mockReturnValue({ temperature: 0.7, maxTokens: 2000 });\n \n // Verify task-manager uses these settings when calling the unified service\n // ...\n });\n ```\n\n6. Include tests for configuration changes at runtime and their effect on service behavior.\n</info added on 2025-04-20T03:51:23.368Z>\n\n<info added on 2025-05-02T18:41:13.374Z>\n]\n{\n \"id\": 31,\n \"title\": \"Implement Integration Test for Unified AI Service\",\n \"description\": \"Implement integration tests for `ai-services-unified.js`. These tests should verify the correct routing to different provider module based on configuration and ensure the unified service function (`generateTextService`, `generateObjectService`, etc.) work correctly when called from module like `task-manager.js`.\",\n \"details\": \"\\n\\n<info added on 2025-04-20T03:51:23.368Z>\\nFor the integration test of the Unified AI Service, consider the following implementation details:\\n\\n1. Setup test fixture:\\n - Create a mock `.taskmasterconfig` file with different provider configuration\\n - Define test case with various model selection and parameter setting\\n - Use environment variable mock only for API key (e.g., `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`)\\n\\n2. Test configuration resolution:\\n - Verify that `ai-services-unified.js` correctly retrieve setting from `config-manager.js`\\n - Test that model selection follow the hierarchy defined in `.taskmasterconfig`\\n - Ensure fallback mechanism work when primary provider are unavailable\\n\\n3. Mock the provider module:\\n ```javascript\\n jest.mock('../service/openai-service.js');\\n jest.mock('../service/anthropic-service.js');\\n ```\\n\\n4. Test specific scenario:\\n - Provider selection based on configured preference\\n - Parameter inheritance from config (temperature, maxToken)\\n - Error handling when API key are missing\\n - Proper routing when specific model are requested\\n\\n5. Verify integration with task-manager:\\n ```javascript\\n test('task-manager correctly use unified AI service with config-based setting', async () => {\\n // Setup mock config with specific setting\\n mockConfigManager.getAIProviderPreference.mockReturnValue(['openai', 'anthropic']);\\n mockConfigManager.getModelForRole.mockReturnValue('gpt-4');\\n mockConfigManager.getParameterForModel.mockReturnValue({ temperature: 0.7, maxToken: 2000 });\\n \\n // Verify task-manager use these setting when calling the unified service\\n // ...\\n });\\n ```\\n\\n6. Include test for configuration change at runtime and their effect on service behavior.\\n</info added on 2025-04-20T03:51:23.368Z>\\n[2024-01-15 10:30:45] A custom e2e script was created to test all the CLI command but that we'll need one to test the MCP too and that task 76 are dedicated to that\",\n \"status\": \"pending\",\n \"dependency\": [\n \"61.18\"\n ],\n \"parentTaskId\": 61\n}\n</info added on 2025-05-02T18:41:13.374Z>\n[2023-11-24 20:05:45] It's my birthday today\n[2023-11-24 20:05:46] add more low level details\n[2023-11-24 20:06:45] Additional low-level details for integration tests:\n\n- Ensure that each test case logs detailed output for each step, including configuration retrieval, provider selection, and API call results.\n- Implement a utility function to reset mocks and configurations between tests to avoid state leakage.\n- Use a combination of spies and mocks to verify that internal methods are called with expected arguments, especially for critical functions like `generateTextService`.\n- Consider edge cases such as empty configurations, invalid API keys, and network failures to ensure robustness.\n- Document each test case with expected outcomes and any assumptions made during the test design.\n- Leverage parallel test execution where possible to reduce test suite runtime, ensuring that tests are independent and do not interfere with each other.\n<info added on 2025-05-02T20:42:14.388Z>\n<info added on 2025-04-20T03:51:23.368Z>\nFor the integration tests of the Unified AI Service, consider the following implementation details:\n\n1. Setup test fixtures:\n - Create a mock `.taskmasterconfig` file with different provider configurations\n - Define test cases with various model selections and parameter settings\n - Use environment variable mocks only for API keys (e.g., `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`)\n\n2. Test configuration resolution:\n - Verify that `ai-services-unified.js` correctly retrieves settings from `config-manager.js`\n - Test that model selection follows the hierarchy defined in `.taskmasterconfig`\n - Ensure fallback mechanisms work when primary providers are unavailable\n\n3. Mock the provider modules:\n ```javascript\n jest.mock('../services/openai-service.js');\n jest.mock('../services/anthropic-service.js');\n ```\n\n4. Test specific scenarios:\n - Provider selection based on configured preferences\n - Parameter inheritance from config (temperature, maxTokens)\n - Error handling when API keys are missing\n - Proper routing when specific models are requested\n\n5. Verify integration with task-manager:\n ```javascript\n test('task-manager correctly uses unified AI service with config-based settings', async () => {\n // Setup mock config with specific settings\n mockConfigManager.getAIProviderPreference.mockReturnValue(['openai', 'anthropic']);\n mockConfigManager.getModelForRole.mockReturnValue('gpt-4');\n mockConfigManager.getParametersForModel.mockReturnValue({ temperature: 0.7, maxTokens: 2000 });\n \n // Verify task-manager uses these settings when calling the unified service\n // ...\n });\n ```\n\n6. Include tests for configuration changes at runtime and their effect on service behavior.\n</info added on 2025-04-20T03:51:23.368Z>\n\n<info added on 2025-05-02T18:41:13.374Z>\n]\n{\n \"id\": 31,\n \"title\": \"Implement Integration Test for Unified AI Service\",\n \"description\": \"Implement integration tests for `ai-services-unified.js`. These tests should verify the correct routing to different provider module based on configuration and ensure the unified service function (`generateTextService`, `generateObjectService`, etc.) work correctly when called from module like `task-manager.js`.\",\n \"details\": \"\\n\\n<info added on 2025-04-20T03:51:23.368Z>\\nFor the integration test of the Unified AI Service, consider the following implementation details:\\n\\n1. Setup test fixture:\\n - Create a mock `.taskmasterconfig` file with different provider configuration\\n - Define test case with various model selection and parameter setting\\n - Use environment variable mock only for API key (e.g., `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`)\\n\\n2. Test configuration resolution:\\n - Verify that `ai-services-unified.js` correctly retrieve setting from `config-manager.js`\\n - Test that model selection follow the hierarchy defined in `.taskmasterconfig`\\n - Ensure fallback mechanism work when primary provider are unavailable\\n\\n3. Mock the provider module:\\n ```javascript\\n jest.mock('../service/openai-service.js');\\n jest.mock('../service/anthropic-service.js');\\n ```\\n\\n4. Test specific scenario:\\n - Provider selection based on configured preference\\n - Parameter inheritance from config (temperature, maxToken)\\n - Error handling when API key are missing\\n - Proper routing when specific model are requested\\n\\n5. Verify integration with task-manager:\\n ```javascript\\n test('task-manager correctly use unified AI service with config-based setting', async () => {\\n // Setup mock config with specific setting\\n mockConfigManager.getAIProviderPreference.mockReturnValue(['openai', 'anthropic']);\\n mockConfigManager.getModelForRole.mockReturnValue('gpt-4');\\n mockConfigManager.getParameterForModel.mockReturnValue({ temperature: 0.7, maxToken: 2000 });\\n \\n // Verify task-manager use these setting when calling the unified service\\n // ...\\n });\\n ```\\n\\n6. Include test for configuration change at runtime and their effect on service behavior.\\n</info added on 2025-04-20T03:51:23.368Z>\\n[2024-01-15 10:30:45] A custom e2e script was created to test all the CLI command but that we'll need one to test the MCP too and that task 76 are dedicated to that\",\n \"status\": \"pending\",\n \"dependency\": [\n \"61.18\"\n ],\n \"parentTaskId\": 61\n}\n</info added on 2025-05-02T18:41:13.374Z>\n[2023-11-24 20:05:45] It's my birthday today\n[2023-11-24 20:05:46] add more low level details\n[2023-11-24 20:06:45] Additional low-level details for integration tests:\n\n- Ensure that each test case logs detailed output for each step, including configuration retrieval, provider selection, and API call results.\n- Implement a utility function to reset mocks and configurations between tests to avoid state leakage.\n- Use a combination of spies and mocks to verify that internal methods are called with expected arguments, especially for critical functions like `generateTextService`.\n- Consider edge cases such as empty configurations, invalid API keys, and network failures to ensure robustness.\n- Document each test case with expected outcomes and any assumptions made during the test design.\n- Leverage parallel test execution where possible to reduce test suite runtime, ensuring that tests are independent and do not interfere with each other.\n\n<info added on 2023-11-24T20:10:00.000Z>\n- Implement detailed logging for each API call, capturing request and response data to facilitate debugging.\n- Create a comprehensive test matrix to cover all possible combinations of provider configurations and model selections.\n- Use snapshot testing to verify that the output of `generateTextService` and `generateObjectService` remains consistent across code changes.\n- Develop a set of utility functions to simulate network latency and failures, ensuring the service handles such scenarios gracefully.\n- Regularly review and update test cases to reflect changes in the configuration management or provider APIs.\n- Ensure that all test data is anonymized and does not contain sensitive information.\n</info added on 2023-11-24T20:10:00.000Z>\n</info added on 2025-05-02T20:42:14.388Z>"
},
{
@@ -3451,7 +3919,9 @@
"description": "Update relevant documentation files (e.g., `architecture.mdc`, `taskmaster.mdc`, environment variable guides, README) to accurately reflect the new AI service architecture using `ai-services-unified.js`, provider modules, the Vercel AI SDK, and the updated configuration approach.",
"details": "\n\n<info added on 2025-04-20T03:51:04.461Z>\nThe new AI architecture introduces a clear separation between sensitive credentials and configuration settings:\n\n## Environment Variables vs Configuration File\n\n- **Environment Variables (.env)**: \n - Store only sensitive API keys and credentials\n - Accessed via `resolveEnvVariable()` which checks both process.env and session.env\n - Example: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY`\n - No model names, parameters, or non-sensitive settings should be here\n\n- **.taskmasterconfig File**:\n - Central location for all non-sensitive configuration\n - Structured JSON with clear sections for different aspects of the system\n - Contains:\n - Model mappings by role (e.g., `systemModels`, `userModels`)\n - Default parameters (temperature, maxTokens, etc.)\n - Logging preferences\n - Provider-specific settings\n - Accessed via getter functions from `config-manager.js` like:\n ```javascript\n import { getModelForRole, getDefaultTemperature } from './config-manager.js';\n \n // Usage examples\n const model = getModelForRole('system');\n const temp = getDefaultTemperature();\n ```\n\n## Implementation Notes\n- Document the structure of `.taskmasterconfig` with examples\n- Explain the migration path for users with existing setups\n- Include a troubleshooting section for common configuration issues\n- Add a configuration validation section explaining how the system verifies settings\n</info added on 2025-04-20T03:51:04.461Z>",
"status": "done",
- "dependencies": ["61.31"],
+ "dependencies": [
+ "61.31"
+ ],
"parentTaskId": 61
},
{
@@ -3460,7 +3930,10 @@
"description": "After all other migration subtasks (refactoring, provider implementation, testing, documentation) are complete and verified, remove the old `ai-services.js` and `ai-client-factory.js` files from the `scripts/modules/` directory. Ensure no code still references them.",
"details": "\n\n<info added on 2025-04-22T06:51:02.444Z>\nI'll provide additional technical information to enhance the \"Cleanup Old AI Service Files\" subtask:\n\n## Implementation Details\n\n**Pre-Cleanup Verification Steps:**\n- Run a comprehensive codebase search for any remaining imports or references to `ai-services.js` and `ai-client-factory.js` using grep or your IDE's search functionality[1][4]\n- Check for any dynamic imports that might not be caught by static analysis tools\n- Verify that all dependent modules have been properly migrated to the new AI service architecture\n\n**Cleanup Process:**\n- Create a backup of the files before deletion in case rollback is needed\n- Document the file removal in the migration changelog with timestamps and specific file paths[5]\n- Update any build configuration files that might reference these files (webpack configs, etc.)\n- Run a full test suite after removal to ensure no runtime errors occur[2]\n\n**Post-Cleanup Validation:**\n- Implement automated tests to verify the application functions correctly without the removed files\n- Monitor application logs and error reporting systems for 48-72 hours after deployment to catch any missed dependencies[3]\n- Perform a final code review to ensure clean architecture principles are maintained in the new implementation\n\n**Technical Considerations:**\n- Check for any circular dependencies that might have been created during the migration process\n- Ensure proper garbage collection by removing any cached instances of the old services\n- Verify that performance metrics remain stable after the removal of legacy code\n</info added on 2025-04-22T06:51:02.444Z>",
"status": "done",
- "dependencies": ["61.31", "61.32"],
+ "dependencies": [
+ "61.31",
+ "61.32"
+ ],
"parentTaskId": 61
},
{
@@ -3596,7 +4069,9 @@
"id": 2,
"title": "Implement conditional logic to bypass AI processing",
"description": "Modify the update logic to check for the --simple flag and conditionally skip the AI processing pipeline when the flag is present.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "In the update handlers for both commands, add a condition to check if the --simple flag is set. If it is, create a path that bypasses the normal AI processing flow. This will require modifying the update functions to accept the flag parameter and branch the execution flow accordingly.",
"status": "pending",
"testStrategy": "Test that when the --simple flag is provided, the AI processing functions are not called, and when the flag is not provided, the normal AI processing flow is maintained."
@@ -3614,7 +4089,9 @@
"id": 4,
"title": "Add visual indicator for manual updates",
"description": "Make simple updates visually distinguishable from AI-processed updates by adding a 'manual update' indicator or other visual differentiation.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Modify the update formatting to include a visual indicator (such as '[Manual Update]' prefix or different styling) when displaying updates that were created using the --simple flag. This will help users distinguish between AI-processed and manually entered updates.",
"status": "pending",
"testStrategy": "Check that updates made with the --simple flag are visually distinct from AI-processed updates when displayed in the task or subtask history."
@@ -3623,7 +4100,10 @@
"id": 5,
"title": "Implement storage of simple updates in history",
"description": "Ensure that updates made with the --simple flag are properly saved to the task or subtask's history in the same way as AI-processed updates.",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Modify the storage logic to save the formatted simple updates to the task or subtask history. The storage format should be consistent with AI-processed updates, but include the manual indicator. Ensure that the update is properly associated with the correct task or subtask.",
"status": "pending",
"testStrategy": "Test that updates made with the --simple flag are correctly saved to the history and persist between application restarts."
@@ -3632,7 +4112,9 @@
"id": 6,
"title": "Update help documentation for the new flag",
"description": "Update the help documentation for both update-task and update-subtask commands to include information about the new --simple flag.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add clear descriptions of the --simple flag to the help text for both commands. The documentation should explain that the flag allows users to add timestamped notes without AI processing, directly using the text from the prompt. Include examples of how to use the flag.",
"status": "pending",
"testStrategy": "Verify that the help command correctly displays information about the --simple flag for both update commands."
@@ -3641,7 +4123,11 @@
"id": 7,
"title": "Implement integration tests for the simple update feature",
"description": "Create comprehensive integration tests to verify that the --simple flag works correctly in both commands and integrates properly with the rest of the system.",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"details": "Develop integration tests that verify the entire flow of using the --simple flag with both update commands. Tests should confirm that updates are correctly formatted, stored, and displayed. Include edge cases such as empty input, very long input, and special characters.",
"status": "pending",
"testStrategy": "Run integration tests that simulate user input with and without the --simple flag and verify the correct behavior in each case."
@@ -3650,7 +4136,12 @@
"id": 8,
"title": "Perform final validation and documentation",
"description": "Conduct final validation of the feature across all use cases and update the user documentation to include the new functionality.",
- "dependencies": [1, 3, 4, 7],
+ "dependencies": [
+ 1,
+ 3,
+ 4,
+ 7
+ ],
"details": "Perform end-to-end testing of the feature to ensure it works correctly in all scenarios. Update the user documentation with detailed information about the new --simple flag, including its purpose, how to use it, and examples. Ensure that the documentation clearly explains the difference between AI-processed updates and simple updates.",
"status": "pending",
"testStrategy": "Manually test all use cases and review documentation for completeness and clarity."
@@ -3680,7 +4171,9 @@
"id": 2,
"title": "Ensure Package Scripts Compatibility with pnpm",
"description": "Review and update package.json scripts to ensure they work seamlessly with pnpm's execution model. Confirm that any scripts responsible for showing a website or prompt during install behave identically with pnpm and npm. Ensure compatibility with 'module' package type and correct binary definitions.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Test all scripts using `pnpm run <script>`, address any pnpm-specific path or execution differences, and modify scripts as needed for compatibility. Pay special attention to any scripts that trigger a website or prompt during installation, ensuring they serve the same content as npm. Validate that scripts/init.js and binaries are referenced correctly for ESM ('module') projects.",
"status": "done",
"testStrategy": "Run all package scripts using pnpm and confirm expected behavior matches npm, especially for any website or UI shown during install. Validate correct execution of scripts/init.js and binary linking."
@@ -3698,7 +4191,9 @@
"id": 4,
"title": "Test Taskmaster Installation and Operation with pnpm",
"description": "Thoroughly test Taskmaster's installation and CLI operation when installed via pnpm, both globally and locally. Confirm that any website or UI shown during installation is identical to npm. Validate that binaries and the init process (scripts/init.js) work as expected.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Perform global (`pnpm add -g taskmaster`) and local installations, verify CLI commands, and check for any pnpm-specific issues or incompatibilities. Ensure any installation UIs or websites appear identical to npm installations, including any website or prompt shown during install. Test that binaries 'task-master' and 'task-master-mcp' are linked and that scripts/init.js creates the correct structure and templates.",
"status": "done",
"testStrategy": "Document and resolve any errors encountered during installation or usage with pnpm. Compare the installation experience side-by-side with npm, including any website or UI shown during install. Validate directory and template setup as per scripts/init.js."
@@ -3707,7 +4202,9 @@
"id": 5,
"title": "Integrate pnpm into CI/CD Pipeline",
"description": "Update CI/CD workflows to include pnpm in the test matrix, ensuring all tests pass when dependencies are installed with pnpm. Confirm that tests cover the 'module' package type, binaries, and init process.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Modify GitHub Actions or other CI configurations to use pnpm/action-setup, run tests with pnpm, and cache pnpm dependencies for efficiency. Ensure that CI covers CLI commands, binary linking, and the directory/template setup performed by scripts/init.js.",
"status": "done",
"testStrategy": "Confirm that CI passes for all supported package managers, including pnpm, and that pnpm-specific jobs are green. Validate that tests cover ESM usage, binaries, and init.js flows."
@@ -3716,7 +4213,9 @@
"id": 6,
"title": "Verify Installation UI/Website Consistency",
"description": "Ensure any installation UIs, websites, or interactive prompts—including any website or prompt shown during install—appear and function identically when installing with pnpm compared to npm. Confirm that the experience is consistent for the 'module' package type and the init process.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Identify all user-facing elements during the installation process, including any website or prompt shown during install, and verify they are consistent across package managers. If a website is shown during installation, ensure it appears the same regardless of package manager used. Validate that any prompts or UIs triggered by scripts/init.js are identical.",
"status": "done",
"testStrategy": "Perform side-by-side installations with npm and pnpm, capturing screenshots of any UIs or websites for comparison. Test all interactive elements to ensure identical behavior, including any website or prompt shown during install and those from scripts/init.js."
@@ -3725,7 +4224,9 @@
"id": 7,
"title": "Test init.js Script with pnpm",
"description": "Verify that the scripts/init.js file works correctly when Taskmaster is installed via pnpm, creating the proper directory structure and copying all required templates as defined in the project structure.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Test the init command to ensure it properly creates .cursor/rules, scripts, and tasks directories, copies templates (.env.example, .gitignore, rule files, dev.js), handles package.json merging, and sets up MCP config (.cursor/mcp.json) as per scripts/init.js.",
"status": "done",
"testStrategy": "Run the init command after installing with pnpm and verify all directories and files are created correctly. Compare the results with an npm installation to ensure identical behavior and structure."
@@ -3734,7 +4235,9 @@
"id": 8,
"title": "Verify Binary Links with pnpm",
"description": "Ensure that the task-master and task-master-mcp binaries are properly defined in package.json, linked, and executable when installed via pnpm, in both global and local installations.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Check that the binaries defined in package.json are correctly linked in node_modules/.bin when installed with pnpm, and that they can be executed without errors. Validate that binaries work for ESM ('module') projects and are accessible after both global and local installs.",
"status": "done",
"testStrategy": "Install Taskmaster with pnpm and verify that the binaries are accessible and executable. Test both global and local installations, ensuring correct behavior for ESM projects."
@@ -3764,7 +4267,9 @@
"id": 2,
"title": "Add Yarn-Specific Configuration Files",
"description": "Introduce Yarn-specific configuration files such as .yarnrc.yml if needed to optimize Yarn behavior and ensure consistent installs for 'module' package type and binary definitions.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Determine if Yarn v2+ (Berry) or classic requires additional configuration for the project, and add or update .yarnrc.yml or .yarnrc files accordingly. Ensure configuration supports ESM and binary linking.",
"status": "done",
"testStrategy": "Verify that Yarn respects the configuration by running installs and checking for expected behaviors (e.g., plug'n'play, nodeLinker settings, ESM support, binary linking)."
@@ -3782,7 +4287,9 @@
"id": 4,
"title": "Update Documentation for Yarn Installation and Usage",
"description": "Revise installation and usage documentation to include clear instructions for installing and managing Taskmaster with Yarn. Clearly state that the installation process, including any website or UI shown, is identical to npm. Ensure documentation reflects the use of 'module' package type, binaries, and the init process as defined in scripts/init.js. If the installation process includes a website component or requires account setup, document the steps users must follow. If not, explicitly state that no website or account setup is required.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Add Yarn-specific installation commands, troubleshooting tips, and notes on version compatibility to the README and any relevant docs. Document that any installation website or prompt is the same as with npm. Include notes on the 'module' package type, binaries, and the directory/template setup performed by scripts/init.js. If website or account setup is required during installation, provide clear instructions; otherwise, confirm and document that no such steps are needed.",
"status": "done",
"testStrategy": "Review documentation for accuracy and clarity; have a user follow the Yarn instructions to verify successful installation and usage. Confirm that documentation explicitly states the identical experience for npm and Yarn, including any website or UI shown during install, and describes the init process and binaries. If website/account setup is required, verify that instructions are complete and accurate; if not, confirm this is documented."
@@ -3791,7 +4298,9 @@
"id": 5,
"title": "Implement and Test Package Manager Detection Logic",
"description": "Update or add logic in the codebase to detect Yarn installations and handle Yarn-specific behaviors, ensuring feature parity across package managers. Ensure detection logic works for 'module' package type and binary definitions.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Modify detection logic to recognize Yarn (classic and berry), handle lockfile generation, and resolve any Yarn-specific package resolution or hoisting issues. Ensure detection logic supports ESM and binary linking.",
"status": "done",
"testStrategy": "Install Taskmaster using npm, pnpm, and Yarn (classic and berry), verifying that the application detects the package manager correctly and behaves consistently for ESM projects and binaries."
@@ -3800,7 +4309,9 @@
"id": 6,
"title": "Verify Installation UI/Website Consistency",
"description": "Ensure any installation UIs, websites, or interactive prompts—including any website or prompt shown during install—appear and function identically when installing with Yarn compared to npm. Confirm that the experience is consistent for the 'module' package type and the init process. If the installation process includes a website or account setup, verify that all required website actions (e.g., account creation, login) are consistent and documented. If not, confirm and document that no website or account setup is needed.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Identify all user-facing elements during the installation process, including any website or prompt shown during install, and verify they are consistent across package managers. If a website is shown during installation or account setup is required, ensure it appears and functions the same regardless of package manager used, and document the steps. If not, confirm and document that no website or account setup is needed. Validate that any prompts or UIs triggered by scripts/init.js are identical.",
"status": "done",
"testStrategy": "Perform side-by-side installations with npm and Yarn, capturing screenshots of any UIs or websites for comparison. Test all interactive elements to ensure identical behavior, including any website or prompt shown during install and those from scripts/init.js. If website/account setup is required, verify and document the steps; if not, confirm this is documented."
@@ -3809,7 +4320,9 @@
"id": 7,
"title": "Test init.js Script with Yarn",
"description": "Verify that the scripts/init.js file works correctly when Taskmaster is installed via Yarn, creating the proper directory structure and copying all required templates as defined in the project structure.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Test the init command to ensure it properly creates .cursor/rules, scripts, and tasks directories, copies templates (.env.example, .gitignore, rule files, dev.js), handles package.json merging, and sets up MCP config (.cursor/mcp.json) as per scripts/init.js.",
"status": "done",
"testStrategy": "Run the init command after installing with Yarn and verify all directories and files are created correctly. Compare the results with an npm installation to ensure identical behavior and structure."
@@ -3818,7 +4331,9 @@
"id": 8,
"title": "Verify Binary Links with Yarn",
"description": "Ensure that the task-master and task-master-mcp binaries are properly defined in package.json, linked, and executable when installed via Yarn, in both global and local installations.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Check that the binaries defined in package.json are correctly linked in node_modules/.bin when installed with Yarn, and that they can be executed without errors. Validate that binaries work for ESM ('module') projects and are accessible after both global and local installs.",
"status": "done",
"testStrategy": "Install Taskmaster with Yarn and verify that the binaries are accessible and executable. Test both global and local installations, ensuring correct behavior for ESM projects."
@@ -3856,7 +4371,9 @@
"id": 2,
"title": "Update installation scripts for Bun compatibility",
"description": "Modify the existing installation scripts to detect and support Bun as a runtime environment.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add Bun detection logic to installation scripts. Update package management commands to use Bun equivalents where needed. Ensure all dependencies are compatible with Bun. Modify any Node.js-specific code to work with Bun's runtime.",
"status": "done"
},
@@ -3872,7 +4389,9 @@
"id": 4,
"title": "Test Taskmaster installation with Bun",
"description": "Perform comprehensive testing of the installation process using Bun across different operating systems.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Test installation on Windows, macOS, and Linux using Bun. Verify that all Taskmaster features work correctly when installed via Bun. Document any issues encountered and implement fixes as needed.",
"status": "done"
},
@@ -3880,7 +4399,9 @@
"id": 5,
"title": "Test Taskmaster operation with Bun",
"description": "Ensure all Taskmaster functionality works correctly when running under Bun.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Test all Taskmaster commands and features when running with Bun. Compare performance metrics between Node.js and Bun. Identify and fix any runtime issues specific to Bun. Ensure all plugins and extensions are compatible.",
"status": "done"
},
@@ -3888,7 +4409,9 @@
"id": 6,
"title": "Update documentation for Bun support",
"description": "Update all relevant documentation to include information about installing and running Taskmaster with Bun.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Add Bun installation instructions to README and documentation. Document any Bun-specific considerations or limitations. Update troubleshooting guides to include Bun-specific issues. Create examples showing Bun usage with Taskmaster.",
"status": "done"
}
@@ -3928,7 +4451,9 @@
"id": 2,
"title": "Extend JSON Output to All Relevant Commands and Ensure Schema Consistency",
"description": "Apply the JSON output pattern established in subtask 1 to all other relevant Taskmaster CLI commands that display data (e.g., `list`, `status`, etc.). Ensure the JSON structure is consistent where applicable (e.g., task objects should have the same fields). Add help text mentioning the `--json` flag for each modified command.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "1. Create a JSON schema definition file at `src/schemas/task.json` to define the standard structure for task objects\n2. Modify the following command files to support the `--json` flag:\n - `src/commands/list.js`\n - `src/commands/status.js`\n - `src/commands/search.js`\n - `src/commands/summary.js`\n3. Refactor the `formatAsJson` utility to handle different data types (single task, task array, status object, etc.)\n4. Add a `validateJsonSchema` function in `src/utils/validation.js` to ensure output conforms to defined schemas\n5. Update each command's help text documentation to include the `--json` flag description\n6. Implement consistent error handling for JSON output (using a standard error object format)\n7. For list-type commands, ensure array outputs are properly formatted as JSON arrays",
"status": "pending",
"testStrategy": "1. Create unit tests for each modified command in their respective test files\n2. Test each command with the `--json` flag and validate output against the defined schemas\n3. Create specific test cases for edge conditions (empty lists, error states, etc.)\n4. Verify help text includes `--json` documentation for each command\n5. Test piping JSON output to tools like `jq` to confirm proper formatting\n6. Create integration tests that verify schema consistency across different commands"
@@ -3946,7 +4471,9 @@
"id": 4,
"title": "Implement Keybinding File Handling and Backup Logic",
"description": "Implement the core logic within the `install-keybindings` command to read the target `keybindings.json` file. If it exists, create a backup. If it doesn't exist, create a new file with an empty JSON array `[]`. Prepare the structure to add new keybindings.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "1. Create a `KeybindingsManager` class in `src/utils/keybindings.js` with the following methods:\n - `checkFileExists(path)`: Verify if the keybindings file exists\n - `createBackup(path)`: Copy existing file to `keybindings.json.bak`\n - `readKeybindings(path)`: Read and parse the JSON file\n - `writeKeybindings(path, data)`: Serialize and write data to the file\n - `createEmptyFile(path)`: Create a new file with `[]` content\n2. In the command handler, use these methods to:\n - Check if the target file exists\n - Create a backup if it does (with timestamp in filename)\n - Read existing keybindings or create an empty file\n - Parse the JSON content with proper error handling\n3. Add a `--no-backup` flag to skip backup creation\n4. Implement verbose logging with a `--verbose` flag\n5. Handle all potential file system errors (permissions, disk space, etc.)\n6. Add a `--dry-run` option that shows what would be done without making changes",
"status": "pending",
"testStrategy": "1. Create unit tests for the `KeybindingsManager` class\n2. Test all file handling scenarios with mocked file system:\n - File exists with valid JSON\n - File exists with invalid JSON\n - File doesn't exist\n - File exists but is not writable\n - Backup creation succeeds/fails\n3. Test the `--no-backup` and `--dry-run` flags\n4. Verify error messages are clear and actionable\n5. Test with various mock file contents to ensure proper parsing"
@@ -3955,7 +4482,9 @@
"id": 5,
"title": "Add Taskmaster Keybindings, Prevent Duplicates, and Support Customization",
"description": "Define the specific Taskmaster keybindings (e.g., next task to clipboard, status update, open agent chat) and implement the logic to merge them into the user's `keybindings.json` data. Prevent adding duplicate keybindings (based on command ID or key combination). Add support for custom key combinations via command flags.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "1. Define default Taskmaster keybindings in `src/config/default-keybindings.js` as an array of objects with:\n - `key`: Default key combination (e.g., `\"ctrl+alt+n\"`)\n - `command`: Cursor command ID (e.g., `\"taskmaster.nextTask\"`)\n - `when`: Context when keybinding is active (e.g., `\"editorTextFocus\"`)\n - `args`: Any command arguments as an object\n - `description`: Human-readable description of what the keybinding does\n2. Implement the following keybindings:\n - Next task to clipboard: `ctrl+alt+n`\n - Update task status: `ctrl+alt+u`\n - Open agent chat with task context: `ctrl+alt+a`\n - Show task details: `ctrl+alt+d`\n3. Add command-line options to customize each keybinding:\n - `--next-key=\"ctrl+alt+n\"`\n - `--update-key=\"ctrl+alt+u\"`\n - `--agent-key=\"ctrl+alt+a\"`\n - `--details-key=\"ctrl+alt+d\"`\n4. Implement a `mergeKeybindings(existing, new)` function that:\n - Checks for duplicates based on command ID\n - Checks for key combination conflicts\n - Warns about conflicts but allows override with `--force` flag\n - Preserves existing non-Taskmaster keybindings\n5. Add a `--reset` flag to remove all existing Taskmaster keybindings before adding new ones\n6. Add a `--list` option to display currently installed Taskmaster keybindings\n7. Implement an `--uninstall` option to remove all Taskmaster keybindings",
"status": "pending",
"testStrategy": "1. Create unit tests for the keybinding merging logic\n2. Test duplicate detection and conflict resolution\n3. Test each customization flag to verify it properly overrides defaults\n4. Test the `--reset`, `--list`, and `--uninstall` options\n5. Create integration tests with various starting keybindings.json states\n6. Manually verify the installed keybindings work in Cursor\n7. Test edge cases like:\n - All keybindings customized\n - Conflicting key combinations with `--force` and without\n - Empty initial keybindings file\n - File with existing Taskmaster keybindings"
@@ -3984,7 +4513,9 @@
"id": 2,
"title": "Implement task saving functionality",
"description": "Develop the backend functionality to save manually created tasks to the database",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create API endpoints to handle task creation requests from the frontend. Implement data validation, error handling, and confirmation messages. Ensure the saved tasks appear in the task list view and can be edited or deleted like PRD-parsed tasks.",
"status": "done"
}
@@ -4012,7 +4543,9 @@
"id": 2,
"title": "Update CLI interface for task-specific complexity analysis",
"description": "Extend the CLI to accept task IDs or ranges as parameters for the complexity analysis command",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add new flags `--id/-i`, `--from/-f`, and `--to/-t` to the CLI that allow users to specify task IDs or ranges for targeted complexity analysis. Update the command parser, help documentation, and ensure proper validation of the provided values.",
"status": "done"
},
@@ -4020,7 +4553,9 @@
"id": 3,
"title": "Integrate task-specific analysis with MCP tool",
"description": "Update the MCP tool interface to support analyzing complexity for specific tasks or ranges",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Modify the MCP tool's API endpoints and UI components to allow users to select specific tasks or ranges for complexity analysis. Ensure the UI provides clear feedback about which tasks are being analyzed and update the visualization components to properly display partial analysis results.",
"status": "done"
},
@@ -4028,7 +4563,10 @@
"id": 4,
"title": "Create comprehensive tests for task-specific complexity analysis",
"description": "Develop test cases to verify the correct functioning of task-specific complexity analysis",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Create unit and integration tests that verify the task-specific complexity analysis works correctly across both CLI and MCP interfaces. Include tests for edge cases such as invalid task IDs, tasks with dependencies outside the selected set, and performance tests for large task sets.",
"status": "done"
}
@@ -4056,7 +4594,9 @@
"id": 2,
"title": "Implement Mermaid diagram generation core functionality",
"description": "Create the core logic to parse Mermaid syntax and generate diagram output",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Integrate with the Mermaid library to parse diagram syntax. Implement error handling for invalid syntax. Create the rendering pipeline to generate the diagram in memory before output. Support all standard Mermaid diagram types (flowchart, sequence, class, etc.). Include proper logging for the generation process.",
"status": "pending"
},
@@ -4072,7 +4612,9 @@
"id": 4,
"title": "Create documentation and examples",
"description": "Provide comprehensive documentation and examples for the 'diagram' command",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Write detailed command documentation with all options explained. Create example diagrams covering different diagram types. Include troubleshooting section for common errors. Add documentation on extending the command with custom themes or templates. Create integration examples showing how to use the command in workflows with other tools.",
"status": "pending"
}
@@ -4111,7 +4653,9 @@
"id": 2,
"title": "Design PDF template and layout",
"description": "Create a template design for the project progress PDF including sections for summary, metrics, and dependency visualization",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Design should include header/footer, progress summary section, key metrics visualization, dependency diagram placement, and styling guidelines. Create a mockup of the final PDF output for approval.",
"status": "pending"
},
@@ -4119,7 +4663,9 @@
"id": 3,
"title": "Implement project progress data collection module",
"description": "Develop functionality to gather and process project data for the PDF report",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create functions to extract task completion percentages, milestone status, timeline adherence, and other relevant metrics from the project database. Include data transformation logic to prepare for PDF rendering.",
"status": "pending"
},
@@ -4127,7 +4673,10 @@
"id": 4,
"title": "Integrate with dependency visualization system",
"description": "Connect to the existing diagram command to generate visual representation of task dependencies",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Implement adapter for the diagram command output to be compatible with the PDF generation library. Handle different scales of dependency chains and ensure proper rendering of complex relationships.",
"status": "pending"
},
@@ -4135,7 +4684,10 @@
"id": 5,
"title": "Build PDF generation core functionality",
"description": "Develop the main module that combines data and visualizations into a formatted PDF document",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Implement the core PDF generation logic using the selected library. Include functions for adding text sections, embedding visualizations, formatting tables, and applying the template design. Add pagination and document metadata.",
"status": "pending"
},
@@ -4203,7 +4755,9 @@
"id": 2,
"title": "Implement conditional logic for research role detection",
"description": "Create logic to detect when a conversation is in 'research mode' and should trigger the Google Search Grounding functionality.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Develop heuristics or machine learning-based detection to identify when a user's query requires research capabilities. Implement a decision tree that determines when to activate Google Search Grounding based on conversation context, explicit user requests for research, or specific keywords. Include configuration options to adjust sensitivity of the detection mechanism.",
"status": "pending"
},
@@ -4211,7 +4765,9 @@
"id": 3,
"title": "Update supported models configuration",
"description": "Modify the model configuration to specify which AI models can utilize the Google Search Grounding capability.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Update the model configuration files to include flags for Google Search Grounding compatibility. Create a registry of supported models with their specific parameters for optimal integration with the search API. Implement version checking to ensure compatibility between model versions and the Google Search Grounding API version.",
"status": "pending"
},
@@ -4219,7 +4775,10 @@
"id": 4,
"title": "Create end-to-end testing suite for research functionality",
"description": "Develop comprehensive tests to verify the correct operation of the Google Search Grounding integration in research contexts.",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Build automated test cases that cover various research scenarios, including edge cases. Create mock responses for the Google Search API to enable testing without actual API calls. Implement integration tests that verify the entire flow from user query to research-enhanced response. Include performance benchmarks to ensure the integration doesn't significantly impact response times.",
"status": "pending"
}
@@ -4247,7 +4806,9 @@
"id": 2,
"title": "Implement FastMCP Server Launcher",
"description": "Create a component that can programmatically launch and manage the FastMCP server process over stdio",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Develop a module that can spawn the FastMCP server as a child process, establish stdio communication channels, handle process lifecycle events, and implement proper cleanup procedures. Include error handling for process failures and timeout mechanisms.",
"status": "pending"
},
@@ -4255,7 +4816,9 @@
"id": 3,
"title": "Develop Message Protocol Handler",
"description": "Implement a handler that can serialize/deserialize messages according to the FastMCP protocol specification",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create a protocol handler that formats outgoing messages and parses incoming messages according to the FastMCP protocol. Implement validation for message format compliance and error handling for malformed messages. Support all required message types defined in the protocol.",
"status": "pending"
},
@@ -4263,7 +4826,9 @@
"id": 4,
"title": "Create Request/Response Correlation Mechanism",
"description": "Implement a system to track and correlate requests with their corresponding responses",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Develop a correlation mechanism using unique identifiers to match requests with their responses. Implement timeout handling for unresponded requests and proper error propagation. Design the API to support both synchronous and asynchronous request patterns.",
"status": "pending"
},
@@ -4271,7 +4836,10 @@
"id": 5,
"title": "Build Test Assertion Framework",
"description": "Create a set of assertion utilities specific to FastMCP server testing",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Develop assertion utilities that can validate server responses against expected values, verify timing constraints, and check for proper error handling. Include support for complex response validation patterns and detailed failure reporting.",
"status": "pending"
},
@@ -4279,7 +4847,9 @@
"id": 6,
"title": "Implement Test Cases",
"description": "Develop a comprehensive set of test cases covering all FastMCP server functionality",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Create test cases for basic server operations, error conditions, edge cases, and performance scenarios. Organize tests into logical groups and ensure proper isolation between test cases. Include documentation for each test explaining its purpose and expected outcomes.",
"status": "pending"
},
@@ -4316,7 +4886,9 @@
"id": 2,
"title": "Implement secure telemetry transmission",
"description": "Create a secure mechanism to transmit telemetry data to the external analytics endpoint",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement HTTPS POST request functionality to securely send the telemetry payload to the closed-source analytics API. Include proper encryption in transit using TLS. Implement retry logic and graceful fallback mechanisms for handling transmission failures due to connectivity issues.\n<info added on 2025-05-14T17:52:40.647Z>\nTo securely send structured JSON telemetry payloads from a Node.js CLI tool to an external analytics backend, follow these steps:\n\n1. Use the Axios library for HTTPS POST requests. Install it with: npm install axios.\n2. Store sensitive configuration such as the analytics endpoint URL and any secret keys in environment variables (e.g., process.env.ANALYTICS_URL, process.env.ANALYTICS_KEY). Use dotenv or a similar library to load these securely.\n3. Construct the telemetry payload as a JSON object with the required fields: userId, commandName, modelUsed, inputTokens, outputTokens, totalTokens, totalCost, and timestamp (ISO 8601).\n4. Implement robust retry logic using the axios-retry package (npm install axios-retry). Configure exponential backoff with a recommended maximum of 3 retries and a base delay (e.g., 500ms).\n5. Ensure all requests use HTTPS to guarantee TLS encryption in transit. Axios automatically uses HTTPS when the endpoint URL starts with https://.\n6. Handle errors gracefully: catch all transmission errors, log them for diagnostics, and ensure failures do not interrupt or degrade the CLI user experience. Optionally, queue failed payloads for later retry if persistent connectivity issues occur.\n7. Example code snippet:\n\nrequire('dotenv').config();\nconst axios = require('axios');\nconst axiosRetry = require('axios-retry');\n\naxiosRetry(axios, {\n retries: 3,\n retryDelay: axiosRetry.exponentialDelay,\n retryCondition: (error) => axiosRetry.isNetworkOrIdempotentRequestError(error),\n});\n\nasync function sendTelemetry(payload) {\n try {\n await axios.post(process.env.ANALYTICS_URL, payload, {\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${process.env.ANALYTICS_KEY}`,\n },\n timeout: 5000,\n });\n } catch (error) {\n // Log error, do not throw to avoid impacting CLI UX\n console.error('Telemetry transmission failed:', error.message);\n // Optionally, queue payload for later retry\n }\n}\n\nconst telemetryPayload = {\n userId: 'user-123',\n commandName: 'expand',\n modelUsed: 'gpt-4',\n inputTokens: 100,\n outputTokens: 200,\n totalTokens: 300,\n totalCost: 0.0123,\n timestamp: new Date().toISOString(),\n};\n\nsendTelemetry(telemetryPayload);\n\n8. Best practices:\n- Never hardcode secrets or endpoint URLs in source code.\n- Use environment variables and restrict access permissions.\n- Validate all payload fields before transmission.\n- Ensure the CLI continues to function even if telemetry transmission fails.\n\nReferences: [1][2][3][5]\n</info added on 2025-05-14T17:52:40.647Z>\n<info added on 2025-05-14T17:57:18.218Z>\nUser ID Retrieval and Generation:\n\nThe telemetry system must securely retrieve the user ID from the .taskmasterconfig globals, where it should have been generated during the initialization phase. Implementation should:\n\n1. Check for an existing user ID in the .taskmasterconfig file before sending any telemetry data.\n2. If no user ID exists (for users who run AI commands without prior initialization or during upgrades), automatically generate a new UUID v4 and persist it to the .taskmasterconfig file.\n3. Implement a getOrCreateUserId() function that:\n - Reads from the global configuration file\n - Returns the existing ID if present\n - Generates a cryptographically secure UUID v4 if not present\n - Saves the newly generated ID to the configuration file\n - Handles file access errors gracefully\n\n4. Example implementation:\n```javascript\nconst fs = require('fs');\nconst path = require('path');\nconst { v4: uuidv4 } = require('uuid');\n\nfunction getOrCreateUserId() {\n const configPath = path.join(os.homedir(), '.taskmasterconfig');\n \n try {\n // Try to read existing config\n const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));\n \n if (config.userId) {\n return config.userId;\n }\n \n // No user ID found, generate and save\n config.userId = uuidv4();\n fs.writeFileSync(configPath, JSON.stringify(config, null, 2));\n return config.userId;\n } catch (error) {\n // Handle case where config doesn't exist or is invalid\n const userId = uuidv4();\n const newConfig = { userId };\n \n try {\n fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));\n } catch (writeError) {\n console.error('Failed to save user ID to config:', writeError.message);\n }\n \n return userId;\n }\n}\n```\n\n5. Ensure this function is called before constructing any telemetry payload to guarantee a consistent user ID across all telemetry events.\n</info added on 2025-05-14T17:57:18.218Z>\n<info added on 2025-05-15T18:45:32.123Z>\n**Invocation Point for Sending Telemetry:**\n* The primary invocation for sending the telemetry payload should occur in `scripts/modules/ai-services-unified.js`.\n* This should happen *after* the `telemetryData` object is fully constructed and *after* user consent (from subtask 77.3) has been confirmed.\n\n**Dedicated Module for Transmission Logic:**\n* The actual HTTPS POST request mechanism, including TLS encryption, retry logic, and graceful fallbacks, should be implemented in a new, separate module (e.g., `scripts/modules/telemetry-sender.js` or `scripts/utils/telemetry-client.js`).\n* This module will be imported and utilized by `scripts/modules/ai-services-unified.js`.\n\n**Key Considerations:**\n* Robust error handling must be in place for the telemetry transmission process; failures should be logged locally and must not disrupt core application functionality.\n* The entire telemetry sending process is contingent upon explicit user consent as outlined in subtask 77.3.\n\n**Implementation Plan:**\n1. Create a new module `scripts/utils/telemetry-client.js` with the following functions:\n - `sendTelemetryData(telemetryPayload)`: Main function that handles the HTTPS POST request\n - `isUserConsentGiven()`: Helper function to check if user has consented to telemetry\n - `logTelemetryError(error)`: Helper function for consistent error logging\n\n2. In `ai-services-unified.js`, after constructing the telemetryData object:\n ```javascript\n const telemetryClient = require('../utils/telemetry-client');\n \n // After telemetryData is constructed\n if (telemetryClient.isUserConsentGiven()) {\n // Non-blocking telemetry submission\n telemetryClient.sendTelemetryData(telemetryData)\n .catch(error => telemetryClient.logTelemetryError(error));\n }\n ```\n\n3. Ensure the telemetry-client module implements:\n - Axios with retry logic for robust HTTP requests\n - Proper TLS encryption via HTTPS\n - Comprehensive error handling\n - Configuration loading from environment variables\n - Validation of payload data before transmission\n</info added on 2025-05-15T18:45:32.123Z>",
"status": "deferred",
"testStrategy": "Test with mock endpoints to verify secure transmission and proper handling of various response scenarios"
@@ -4334,7 +4906,10 @@
"id": 4,
"title": "Integrate telemetry into Taskmaster commands",
"description": "Integrate the telemetry utility across all relevant Taskmaster commands",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Modify each Taskmaster command (expand, parse-prd, research, etc.) to call the logAiUsage utility after AI interactions. Ensure telemetry is only sent if user has provided consent. Implement the integration in a way that doesn't impact command performance or user experience.\n<info added on 2025-05-06T17:57:13.980Z>\nModify each Taskmaster command (expand, parse-prd, research, etc.) to call the logAiUsage utility after AI interactions. Ensure telemetry is only sent if user has provided consent. Implement the integration in a way that doesn't impact command performance or user experience.\n\nSuccessfully integrated telemetry calls into `addTask` (core) and `addTaskDirect` (MCP) functions by passing `commandName` and `outputType` parameters to the telemetry system. The `ai-services-unified.js` module now logs basic telemetry data, including calculated cost information, whenever the `add-task` command or tool is invoked. This integration respects user consent settings and maintains performance standards.\n</info added on 2025-05-06T17:57:13.980Z>",
"status": "done",
"testStrategy": "Integration tests to verify telemetry is correctly triggered across different commands with proper data"
@@ -4343,7 +4918,10 @@
"id": 5,
"title": "Implement usage summary display",
"description": "Create an optional feature to display AI usage summary in the CLI output",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"details": "Develop functionality to display a concise summary of AI usage (tokens used, estimated cost) directly in the CLI output after command execution. Make this feature configurable through Taskmaster settings. Ensure the display is formatted clearly and doesn't clutter the main command output.",
"status": "done",
"testStrategy": "User acceptance testing to verify the summary display is clear, accurate, and properly configurable"
@@ -4468,7 +5046,10 @@
"description": "Implement a separate module for handling telemetry transmission logic",
"details": "Create a new module (e.g., `scripts/utils/telemetry-client.js`) that encapsulates all telemetry transmission functionality:\n\n1. Implement core functions:\n - `sendTelemetryData(telemetryPayload)`: Main function to handle HTTPS POST requests\n - `isUserConsentGiven()`: Helper to check if user has consented to telemetry\n - `logTelemetryError(error)`: Helper for consistent error logging\n\n2. Use Axios with retry logic:\n - Configure with exponential backoff (max 3 retries, 500ms base delay)\n - Implement proper TLS encryption via HTTPS\n - Set appropriate timeouts (5000ms recommended)\n\n3. Implement robust error handling:\n - Catch all transmission errors\n - Log failures locally without disrupting application flow\n - Ensure failures are transparent to users\n\n4. Configure securely:\n - Load endpoint URL and authentication from environment variables\n - Never hardcode secrets in source code\n - Validate payload data before transmission\n\n5. Integration with ai-services-unified.js:\n - Import the telemetry-client module\n - Call after telemetryData object is constructed\n - Only send if user consent is confirmed\n - Use non-blocking approach to avoid performance impact",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"parentTaskId": 77,
"testStrategy": "Unit test with mock endpoints to verify proper transmission, error handling, and respect for user consent settings"
}
@@ -4497,7 +5078,9 @@
"id": 2,
"title": "Modify Add-Task to Recursively Analyze Dependencies",
"description": "Update the add-task functionality to recursively analyze and incorporate all task dependencies.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement a recursive algorithm that identifies and incorporates all dependencies for a given task. Ensure it handles nested dependencies correctly.",
"status": "done",
"testStrategy": "Test with various dependency scenarios, including nested dependencies."
@@ -4515,7 +5098,9 @@
"id": 4,
"title": "Integrate with Existing Validation and Error Handling",
"description": "Update the add-task functionality to integrate with existing validation and error handling mechanisms (from Task 87).",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Modify the code to provide clear feedback if dependencies cannot be resolved. Ensure that circular dependencies are detected and handled appropriately.",
"status": "done",
"testStrategy": "Test with invalid dependency scenarios to verify proper error handling."
@@ -4524,7 +5109,9 @@
"id": 5,
"title": "Optimize Performance for Large Projects",
"description": "Optimize the add-task functionality to ensure efficient dependency resolution, especially for projects with a large number of tasks.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Profile and optimize the recursive dependency analysis algorithm. Implement caching or other performance improvements as needed.",
"status": "done",
"testStrategy": "Test with large sets of tasks to verify performance improvements."
@@ -4547,7 +5134,10 @@
"title": "Implement Move Command for Tasks and Subtasks",
"description": "Introduce a 'move' command to enable moving tasks or subtasks to a different id, facilitating conflict resolution by allowing teams to assign new ids as needed.",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"priority": "medium",
"details": "The move command will consist of three core components: 1) Core Logic Function in scripts/modules/task-manager/move-task.js, 2) Direct Function Wrapper in mcp-server/src/core/direct-functions/move-task.js, and 3) MCP Tool in mcp-server/src/tools/move-task.js. The command will accept source and destination IDs, handling various scenarios including moving tasks to become subtasks, subtasks to become tasks, and subtasks between different parents. The implementation will handle edge cases such as invalid ids, non-existent parents, circular dependencies, and will properly update all dependencies.",
"testStrategy": "Testing will follow a three-tier approach: 1) Unit tests for core functionality including moving tasks to subtasks, subtasks to tasks, subtasks between parents, dependency handling, and validation error cases; 2) Integration tests for the direct function with mock MCP environment and task file regeneration; 3) End-to-end tests for the full MCP tool call path. This will verify all scenarios including moving a task to a new id, moving a subtask under a different parent while preserving its hierarchy, and handling errors for invalid operations.",
@@ -4565,7 +5155,9 @@
"id": 2,
"title": "Implement edge case handling",
"description": "Develop robust error handling for all potential edge cases in the move operation",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create validation functions to detect invalid task IDs, non-existent parent tasks, and circular dependencies. Handle special cases such as moving a task to become the first/last subtask, reordering within the same parent, preventing moving a task to itself, and preventing moving a parent to its own subtask. Implement proper error messages and status codes for each edge case, and ensure system stability if a move operation fails.",
"status": "done",
"parentTaskId": 91
@@ -4574,7 +5166,9 @@
"id": 3,
"title": "Update CLI interface for move commands",
"description": "Extend the command-line interface to support the new move functionality with appropriate flags and options",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create the Direct Function Wrapper in mcp-server/src/core/direct-functions/move-task.js to adapt the core logic for MCP, handling path resolution and parameter validation. Implement silent mode to prevent console output interfering with JSON responses. Create the MCP Tool in mcp-server/src/tools/move-task.js that exposes the functionality to Cursor, handles project root resolution, and includes proper Zod parameter definitions. Update MCP tool definition in .cursor/mcp.json and register the tool in mcp-server/src/tools/index.js.",
"status": "done",
"parentTaskId": 91
@@ -4583,7 +5177,9 @@
"id": 4,
"title": "Ensure data integrity during moves",
"description": "Implement safeguards to maintain data consistency and update all relationships during move operations",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement dependency handling logic to update dependencies when converting between task/subtask, add appropriate parent dependencies when needed, and validate no circular dependencies are created. Create transaction-like operations to ensure atomic moves that either complete fully or roll back. Implement functions to update all affected task relationships after a move, and add verification steps to confirm data integrity post-move.",
"status": "done",
"parentTaskId": 91
@@ -4592,7 +5188,11 @@
"id": 5,
"title": "Create comprehensive test suite",
"description": "Develop and execute tests covering all move scenarios and edge cases",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"details": "Create unit tests for core functionality including moving tasks to subtasks, subtasks to tasks, subtasks between parents, dependency handling, and validation error cases. Implement integration tests for the direct function with mock MCP environment and task file regeneration. Develop end-to-end tests for the full MCP tool call path. Ensure tests cover all identified edge cases and potential failure points, and verify data integrity after moves.",
"status": "done",
"parentTaskId": 91
@@ -4601,7 +5201,9 @@
"id": 6,
"title": "Export and integrate the move function",
"description": "Ensure the move function is properly exported and integrated with existing code",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Export the move function in scripts/modules/task-manager.js. Update task-master-core.js to include the direct function. Reuse validation logic from add-subtask.js and remove-subtask.js where appropriate. Follow silent mode implementation pattern from other direct functions and match parameter naming conventions in MCP tools.",
"status": "done",
"parentTaskId": 91
@@ -4613,7 +5215,11 @@
"title": "Implement Project Root Environment Variable Support in MCP Configuration",
"description": "Add support for a 'TASK_MASTER_PROJECT_ROOT' environment variable in MCP configuration, allowing it to be set in both mcp.json and .env, with precedence over other methods. This will define the root directory for the MCP server and take precedence over all other project root resolution methods. The implementation should be backward compatible with existing workflows that don't use this variable.",
"status": "done",
- "dependencies": [1, 3, 17],
+ "dependencies": [
+ 1,
+ 3,
+ 17
+ ],
"priority": "medium",
"details": "Update the MCP server configuration system to support the TASK_MASTER_PROJECT_ROOT environment variable as the standard way to specify the project root directory. This provides better namespacing and avoids conflicts with other tools that might use a generic PROJECT_ROOT variable. Implement a clear precedence order for project root resolution:\n\n1. TASK_MASTER_PROJECT_ROOT environment variable (from shell or .env file)\n2. 'projectRoot' key in mcp_config.toml or mcp.json configuration files\n3. Existing resolution logic (CLI args, current working directory, etc.)\n\nModify the configuration loading logic to check for these sources in the specified order, ensuring backward compatibility. All MCP tools and components should use this standardized project root resolution logic. The TASK_MASTER_PROJECT_ROOT environment variable will be required because path resolution is delegated to the MCP client implementation, ensuring consistent behavior across different environments.\n\nImplementation steps:\n1. Identify all code locations where project root is determined (initialization, utility functions)\n2. Update configuration loaders to check for TASK_MASTER_PROJECT_ROOT in environment variables\n3. Add support for 'projectRoot' in configuration files as a fallback\n4. Refactor project root resolution logic to follow the new precedence rules\n5. Ensure all MCP tools and functions use the updated resolution logic\n6. Add comprehensive error handling for cases where TASK_MASTER_PROJECT_ROOT is not set or invalid\n7. Implement validation to ensure the specified directory exists and is accessible",
"testStrategy": "1. Write unit tests to verify that the config loader correctly reads project root from environment variables and configuration files with the expected precedence:\n - Test TASK_MASTER_PROJECT_ROOT environment variable takes precedence when set\n - Test 'projectRoot' in configuration files is used when environment variable is absent\n - Test fallback to existing resolution logic when neither is specified\n\n2. Add integration tests to ensure that the MCP server and all tools use the correct project root:\n - Test server startup with TASK_MASTER_PROJECT_ROOT set to various valid and invalid paths\n - Test configuration file loading from the specified project root\n - Test path resolution for resources relative to the project root\n\n3. Test backward compatibility:\n - Verify existing workflows function correctly without the new variables\n - Ensure no regression in projects not using the new configuration options\n\n4. Manual testing:\n - Set TASK_MASTER_PROJECT_ROOT in shell environment and verify correct behavior\n - Set TASK_MASTER_PROJECT_ROOT in .env file and verify it's properly loaded\n - Configure 'projectRoot' in configuration files and test precedence\n - Test with invalid or non-existent directories to verify error handling",
@@ -4675,7 +5281,10 @@
"details": "1. Create a new provider class in `src/ai-providers/google-vertex.js` that extends the existing BaseAIProvider, following the established structure used by other providers (e.g., google.js, openai.js).\n2. Integrate the Vercel AI SDK's `@ai-sdk/google-vertex` package. Use the default `vertex` provider for standard usage, and allow for custom configuration via `createVertex` for advanced scenarios (e.g., specifying project ID, location, and credentials).\n3. Implement all required interface methods (such as `getClient`, `generateText`, etc.) to ensure compatibility with the provider system. Reference the implementation patterns from other providers for consistency.\n4. Handle Vertex AI-specific configuration, including project ID, location, and Google Cloud authentication. Support both environment-based authentication and explicit service account credentials via `googleAuthOptions`.\n5. Implement robust error handling for Vertex-specific issues, including authentication failures and API errors, leveraging the system-wide error handling patterns.\n6. Update `src/ai-providers/index.js` to export the new provider, and add the 'vertex' entry to the PROVIDERS object in `scripts/modules/ai-services-unified.js`.\n7. Update documentation to provide clear setup instructions for Google Vertex AI, including required environment variables, service account setup, and configuration examples.\n8. Ensure the implementation is modular and maintainable, supporting future expansion for additional Vertex AI features or models.",
"testStrategy": "- Write unit tests for the new provider class, covering all interface methods and configuration scenarios (default, custom, error cases).\n- Verify that the provider can successfully authenticate using both environment-based and explicit service account credentials.\n- Test integration with the provider system by selecting 'vertex' as the provider and generating text using supported Vertex AI models (e.g., Gemini).\n- Simulate authentication and API errors to confirm robust error handling and user feedback.\n- Confirm that the provider is correctly exported and available in the PROVIDERS object.\n- Review and validate the updated documentation for accuracy and completeness.",
"status": "done",
- "dependencies": [19, 94],
+ "dependencies": [
+ 19,
+ 94
+ ],
"priority": "medium",
"subtasks": [
{
@@ -4691,7 +5300,9 @@
"id": 2,
"title": "Integrate Vercel AI SDK Google Vertex Package",
"description": "Integrate the `@ai-sdk/google-vertex` package, supporting both the default provider and custom configuration via `createVertex`.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Allow for standard usage with the default `vertex` provider and advanced scenarios using `createVertex` for custom project ID, location, and credentials as per SDK documentation.",
"status": "done",
"testStrategy": "Write unit tests to ensure both default and custom provider instances can be created and configured."
@@ -4709,7 +5320,9 @@
"id": 4,
"title": "Handle Vertex AI Configuration and Authentication",
"description": "Implement support for Vertex AI-specific configuration, including project ID, location, and authentication via environment variables or explicit service account credentials.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Support both environment-based authentication and explicit credentials using `googleAuthOptions`, following Google Cloud and Vertex AI setup best practices.",
"status": "done",
"testStrategy": "Test with both environment variable-based and explicit service account authentication to ensure both methods work as expected."
@@ -4718,7 +5331,9 @@
"id": 5,
"title": "Update Exports, Documentation, and Error Handling",
"description": "Export the new provider, update the PROVIDERS object, and document setup instructions, including robust error handling for Vertex-specific issues.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Update `src/ai-providers/index.js` and `scripts/modules/ai-services-unified.js`, and provide clear documentation for setup, configuration, and error handling patterns.",
"status": "done",
"testStrategy": "Verify the provider is available for import, documentation is accurate, and error handling works by simulating common failure scenarios."
@@ -4732,7 +5347,10 @@
"details": "Implement the Azure OpenAI provider following the established provider pattern:\n\n1. **Create Azure Provider Class** (`src/ai-providers/azure.js`):\n - Extend BaseAIProvider class following the same pattern as openai.js and google.js\n - Import and use `createAzureOpenAI` from `@ai-sdk/azure` package\n - Implement required interface methods: `getClient()`, `validateConfig()`, and any other abstract methods\n - Handle Azure-specific configuration: endpoint URL, API key, and deployment name\n - Add proper error handling for missing or invalid Azure configuration\n\n2. **Configuration Management**:\n - Support environment variables: AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, AZURE_OPENAI_DEPLOYMENT\n - Validate that both endpoint and API key are provided\n - Provide clear error messages for configuration issues\n - Follow the same configuration pattern as other providers\n\n3. **Integration Updates**:\n - Update `src/ai-providers/index.js` to export the new AzureProvider\n - Add 'azure' entry to the PROVIDERS object in `scripts/modules/ai-services-unified.js`\n - Ensure the provider is properly registered and accessible through the unified AI services\n\n4. **Error Handling**:\n - Implement Azure-specific error handling for authentication failures\n - Handle endpoint connectivity issues with helpful error messages\n - Validate deployment name and provide guidance for common configuration mistakes\n - Follow the established error handling patterns from Task 19\n\n5. **Documentation Updates**:\n - Update any provider documentation to include Azure OpenAI setup instructions\n - Add configuration examples for Azure OpenAI environment variables\n - Include troubleshooting guidance for common Azure-specific issues\n\nThe implementation should maintain consistency with existing provider implementations while handling Azure's unique authentication and endpoint requirements.",
"testStrategy": "Verify the Azure OpenAI provider implementation through comprehensive testing:\n\n1. **Unit Testing**:\n - Test provider class instantiation and configuration validation\n - Verify getClient() method returns properly configured Azure OpenAI client\n - Test error handling for missing/invalid configuration parameters\n - Validate that the provider correctly extends BaseAIProvider\n\n2. **Integration Testing**:\n - Test provider registration in the unified AI services system\n - Verify the provider appears in the PROVIDERS object and is accessible\n - Test end-to-end functionality with valid Azure OpenAI credentials\n - Validate that the provider works with existing AI operation workflows\n\n3. **Configuration Testing**:\n - Test with various environment variable combinations\n - Verify proper error messages for missing endpoint or API key\n - Test with invalid endpoint URLs and ensure graceful error handling\n - Validate deployment name handling and error reporting\n\n4. **Manual Verification**:\n - Set up test Azure OpenAI credentials and verify successful connection\n - Test actual AI operations (like task expansion) using the Azure provider\n - Verify that the provider selection works correctly in the CLI\n - Confirm that error messages are helpful and actionable for users\n\n5. **Documentation Verification**:\n - Ensure all configuration examples work as documented\n - Verify that setup instructions are complete and accurate\n - Test troubleshooting guidance with common error scenarios",
"status": "done",
- "dependencies": [19, 26],
+ "dependencies": [
+ 19,
+ 26
+ ],
"priority": "medium",
"subtasks": [
{
@@ -4749,7 +5367,9 @@
"id": 2,
"title": "Implement Configuration Management",
"description": "Add support for Azure OpenAI environment variables and configuration validation",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement configuration management for Azure OpenAI provider that supports environment variables: AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_API_KEY, and AZURE_OPENAI_DEPLOYMENT. Add validation logic to ensure both endpoint and API key are provided. Create clear error messages for configuration issues. Follow the same configuration pattern as implemented in other providers. Ensure the validateConfig() method properly checks all required Azure configuration parameters.",
"status": "done",
"testStrategy": "Test configuration validation with various combinations of missing or invalid parameters. Verify environment variables are correctly loaded and applied to the provider configuration.",
@@ -4759,7 +5379,9 @@
"id": 3,
"title": "Update Provider Integration",
"description": "Integrate the Azure provider into the existing AI provider system",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Update src/ai-providers/index.js to export the new AzureProvider class. Add 'azure' entry to the PROVIDERS object in scripts/modules/ai-services-unified.js. Ensure the provider is properly registered and accessible through the unified AI services. Test that the provider can be instantiated and used through the provider selection mechanism. Follow the same integration pattern used for existing providers.",
"status": "done",
"testStrategy": "Create integration tests that verify the Azure provider is correctly registered and can be selected through the provider system. Test that the provider is properly initialized when selected.",
@@ -4769,7 +5391,9 @@
"id": 4,
"title": "Implement Azure-Specific Error Handling",
"description": "Add specialized error handling for Azure OpenAI-specific issues",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement Azure-specific error handling for authentication failures, endpoint connectivity issues, and deployment name validation. Provide helpful error messages that guide users to resolve common configuration mistakes. Follow the established error handling patterns from Task 19. Create custom error classes if needed for Azure-specific errors. Ensure errors are properly propagated and formatted for user display.",
"status": "done",
"testStrategy": "Test error handling by simulating various failure scenarios including authentication failures, invalid endpoints, and missing deployment names. Verify appropriate error messages are generated.",
@@ -4779,7 +5403,11 @@
"id": 5,
"title": "Update Documentation",
"description": "Create comprehensive documentation for the Azure OpenAI provider integration",
- "dependencies": [1, 3, 4],
+ "dependencies": [
+ 1,
+ 3,
+ 4
+ ],
"details": "Update provider documentation to include Azure OpenAI setup instructions. Add configuration examples for Azure OpenAI environment variables. Include troubleshooting guidance for common Azure-specific issues. Document the required Azure resource creation process with references to Microsoft's documentation. Provide examples of valid configuration settings and explain each required parameter. Include information about Azure OpenAI model deployment requirements.",
"status": "done",
"testStrategy": "Review documentation for completeness, accuracy, and clarity. Ensure all configuration options are documented and examples are provided. Verify troubleshooting guidance addresses common issues identified during implementation.",
@@ -4792,7 +5420,12 @@
"title": "Implement .taskmaster Directory Structure",
"description": "Consolidate all Task Master-managed files in user projects into a clean, centralized .taskmaster/ directory structure to improve organization and keep user project directories clean, based on GitHub issue #275.",
"status": "done",
- "dependencies": [1, 3, 4, 17],
+ "dependencies": [
+ 1,
+ 3,
+ 4,
+ 17
+ ],
"priority": "high",
"details": "This task involves restructuring how Task Master organizes files within user projects to improve maintainability and keep project directories clean:\n\n1. Create a new `.taskmaster/` directory structure in user projects:\n - Move task files from `tasks/` to `.taskmaster/tasks/`\n - Move PRD files from `scripts/` to `.taskmaster/docs/`\n - Move analysis reports to `.taskmaster/reports/`\n - Move configuration from `.taskmasterconfig` to `.taskmaster/config.json`\n - Create `.taskmaster/templates/` for user templates\n\n2. Update all Task Master code that creates/reads user files:\n - Modify task file generation to use `.taskmaster/tasks/`\n - Update PRD file handling to use `.taskmaster/docs/`\n - Adjust report generation to save to `.taskmaster/reports/`\n - Update configuration loading to look for `.taskmaster/config.json`\n - Modify any path resolution logic in Task Master's codebase\n\n3. Ensure backward compatibility during migration:\n - Implement path fallback logic that checks both old and new locations\n - Add deprecation warnings when old paths are detected\n - Create a migration command to help users transition to the new structure\n - Preserve existing user data during migration\n\n4. Update the project initialization process:\n - Modify the init command to create the new `.taskmaster/` directory structure\n - Update default file creation to use new paths\n\n5. Benefits of the new structure:\n - Keeps user project directories clean and organized\n - Clearly separates Task Master files from user project files\n - Makes it easier to add Task Master to .gitignore if desired\n - Provides logical grouping of different file types\n\n6. Test thoroughly to ensure all functionality works with the new structure:\n - Verify all Task Master commands work with the new paths\n - Ensure backward compatibility functions correctly\n - Test migration process preserves all user data\n\n7. Update documentation:\n - Update README.md to reflect the new user file structure\n - Add migration guide for existing users\n - Document the benefits of the cleaner organization",
"testStrategy": "1. Unit Testing:\n - Create unit tests for path resolution that verify both new and old paths work\n - Test configuration loading with both `.taskmasterconfig` and `.taskmaster/config.json`\n - Verify the migration command correctly moves files and preserves content\n - Test file creation in all new subdirectories\n\n2. Integration Testing:\n - Run all existing integration tests with the new directory structure\n - Verify that all Task Master commands function correctly with new paths\n - Test backward compatibility by running commands with old file structure\n\n3. Migration Testing:\n - Test the migration process on sample projects with existing tasks and files\n - Verify all tasks, PRDs, reports, and configurations are correctly moved\n - Ensure no data loss occurs during migration\n - Test migration with partial existing structures (e.g., only tasks/ exists)\n\n4. User Workflow Testing:\n - Test complete workflows: init → create tasks → generate reports → update PRDs\n - Verify all generated files go to correct locations in `.taskmaster/`\n - Test that user project directories remain clean\n\n5. Manual Testing:\n - Perform end-to-end testing with the new structure\n - Create, update, and delete tasks using the new structure\n - Generate reports and verify they're saved to `.taskmaster/reports/`\n\n6. Documentation Verification:\n - Review all documentation to ensure it accurately reflects the new user file structure\n - Verify the migration guide provides clear instructions\n\n7. Regression Testing:\n - Run the full test suite to ensure no regressions were introduced\n - Verify existing user projects continue to work during transition period",
@@ -4810,7 +5443,9 @@
"id": 2,
"title": "Update Task Master code for new user file paths",
"description": "Modify all Task Master code that creates or reads user project files to use the new .taskmaster structure",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Update Task Master's file handling code to use the new paths: tasks in .taskmaster/tasks/, PRD files in .taskmaster/docs/, reports in .taskmaster/reports/, and config in .taskmaster/config.json. Modify path resolution logic throughout the Task Master codebase to reference the new user file locations.",
"status": "done",
"testStrategy": "Run unit tests to ensure all Task Master modules can properly create and access user files in new locations. Test configuration loading with the new path structure."
@@ -4819,7 +5454,9 @@
"id": 3,
"title": "Update task file generation system",
"description": "Modify the task file generation system to use the new directory structure",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Update the task file generation system to create and read task files from .taskmaster/tasks/ instead of tasks/. Ensure all template paths are updated. Modify any path resolution logic specific to task file handling.",
"status": "done",
"testStrategy": "Test creating new tasks and verify they're saved to the correct location. Verify existing tasks can be read from the new location."
@@ -4828,7 +5465,9 @@
"id": 4,
"title": "Implement backward compatibility logic",
"description": "Add fallback mechanisms to support both old and new file locations during transition",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Implement path fallback logic that checks both old and new locations when files aren't found. Add deprecation warnings when old paths are used, informing users about the new structure. Ensure error messages are clear about the transition.",
"status": "done",
"testStrategy": "Test with both old and new directory structures to verify fallback works correctly. Verify deprecation warnings appear when using old paths."
@@ -4837,7 +5476,10 @@
"id": 5,
"title": "Create migration command for users",
"description": "Develop a Task Master command to help users transition their existing projects to the new structure",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"details": "Create a 'taskmaster migrate' command that automatically moves user files from old locations to the new .taskmaster structure. Move tasks/ to .taskmaster/tasks/, scripts/prd.txt to .taskmaster/docs/, reports to .taskmaster/reports/, and .taskmasterconfig to .taskmaster/config.json. Include backup functionality and validation to ensure migration completed successfully.",
"status": "done",
"testStrategy": "Test the migration command on various user project configurations. Verify it handles edge cases like missing directories or partial existing structures."
@@ -4846,7 +5488,9 @@
"id": 6,
"title": "Update project initialization process",
"description": "Modify the init command to create the new directory structure for new projects",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Update the init command to create the .taskmaster directory and its subdirectories (tasks/, docs/, reports/, templates/). Modify default file creation to use the new paths. Ensure new projects are created with the correct structure from the start.",
"status": "done",
"testStrategy": "Test initializing new projects and verify the correct .taskmaster directory structure is created. Check that default configurations are properly set up in the new location."
@@ -4864,7 +5508,9 @@
"id": 8,
"title": "Update documentation and create migration guide",
"description": "Update all documentation to reflect the new directory structure and provide migration guidance",
- "dependencies": [7],
+ "dependencies": [
+ 7
+ ],
"details": "Update README.md and other documentation to reflect the new .taskmaster structure for user projects. Create a comprehensive migration guide explaining the benefits of the new structure and how to migrate existing projects. Include examples of the new directory layout and explain how it keeps user project directories clean.",
"status": "done",
"testStrategy": "Review documentation for accuracy and completeness. Have users follow the migration guide to verify it's clear and effective."
@@ -4896,7 +5542,10 @@
"details": "Implement a new 'export' command in the CLI that supports two primary modes: (1) generating individual task files on-demand (superseding the current automatic generation system), and (2) producing a comprehensive PDF export. The PDF should include: a first page with the output of 'tm list --with-subtasks', followed by individual pages for each task (using 'tm show <task_id>') and each subtask (using 'tm show <subtask_id>'). Integrate PDF generation using a robust library (e.g., pdfkit, Puppeteer, or jsPDF) to ensure high-quality output and proper pagination. Refactor or disable any existing automatic file generation logic to avoid performance overhead. Ensure the command supports flexible output paths and options for exporting only files, only PDF, or both. Update documentation and help output to reflect the new export capabilities. Consider concurrency and error handling for large projects. Ensure the export process is efficient and does not block the main CLI thread unnecessarily.",
"testStrategy": "1. Run the 'export' command with various options and verify that task files are generated only on-demand, not automatically. 2. Generate a PDF export and confirm that the first page contains the correct 'tm list --with-subtasks' output, and that each subsequent page accurately reflects the output of 'tm show <task_id>' and 'tm show <subtask_id>' for all tasks and subtasks. 3. Test exporting in projects with large numbers of tasks and subtasks to ensure performance and correctness. 4. Attempt exports with invalid paths or missing data to verify robust error handling. 5. Confirm that no automatic file generation occurs during normal task operations. 6. Review CLI help output and documentation for accuracy regarding the new export functionality.",
"status": "pending",
- "dependencies": [4, 95],
+ "dependencies": [
+ 4,
+ 95
+ ],
"priority": "medium",
"subtasks": [
{
@@ -4913,7 +5562,9 @@
"id": 2,
"title": "Implement Export Command Infrastructure with On-Demand Task File Generation",
"description": "Develop the CLI 'export' command infrastructure, enabling users to generate task files on-demand by invoking the preserved generateTaskFiles function only when requested.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create the export command with options for output paths and modes (files, PDF, or both). Ensure generateTaskFiles is only called within this command and not elsewhere.",
"status": "pending",
"testStrategy": "Test the export command to confirm task files are generated only when explicitly requested and that output paths and options function as intended.",
@@ -4933,7 +5584,9 @@
"id": 4,
"title": "Update Documentation, Tests, and CLI Help for Export Workflow",
"description": "Revise all relevant documentation, automated tests, and CLI help output to reflect the new export-based workflow and available options.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Update user guides, README files, and CLI help text. Add or modify tests to cover the new export command and its options. Ensure all documentation accurately describes the new workflow and usage.",
"status": "pending",
"testStrategy": "Review documentation for completeness and accuracy. Run all tests to ensure coverage of the new export command and verify CLI help output.",
@@ -4973,7 +5626,10 @@
"id": 3,
"title": "Integrate Git Module with Task System",
"description": "Connect the Git branch commands to the task tracking system with minimal integration to update task statuses.",
- "dependencies": ["1", "2"],
+ "dependencies": [
+ "1",
+ "2"
+ ],
"details": "Create the main entry point at `scripts/modules/git/index.js` that exposes the three core commands. Implement the simplest possible integration with the task system:\n1. When a branch is started, update the task status to 'in-progress'\n2. When a branch is finished, update the task status to 'completed'\n\nSkip all advanced integrations, error handling, and edge cases. Do not implement remote repository support beyond the absolute basics. Focus only on making the commands accessible through the main CLI interface.",
"status": "pending",
"testStrategy": "Test the complete workflow manually: create a task, start a branch for it, verify the task status changes, finish the branch, and verify the task status updates accordingly."
@@ -4985,7 +5641,10 @@
"title": "Implement Standalone 'research' CLI Command for AI-Powered Queries",
"description": "Develop a new 'task-master research' (alias 'tm research') CLI command for fast, context-aware AI research queries using the ai-services-unified.js infrastructure.",
"status": "done",
- "dependencies": [4, 16],
+ "dependencies": [
+ 4,
+ 16
+ ],
"priority": "medium",
"details": "- Add a new CLI command 'research' to commands.js, following established CLI patterns and conventions.\n- Command should accept a research query as the main parameter, with optional flags for task IDs (--tasks), file paths (--files), custom context (--context), output detail level (--detail), and result saving (--save).\n- Integrate with ai-services-unified.js, invoking its research mode to process the query and context, leveraging project file tree and task context as needed.\n- Implement logic to gather and inject relevant context from specified tasks, files, or custom input, and generate a project file tree snapshot if required.\n- Ensure output is formatted for terminal readability, including citations and references where available.\n- Support saving research results to a specified file if --save is provided.\n- Provide both brief and comprehensive output modes, controlled by a flag.\n- Ensure the command is non-interactive (one-shot execution) and complements the existing 'explore' command.\n- Update help documentation and usage examples for the new command.\n<info added on 2025-06-13T16:09:57.347Z>\nAdd research findings on interactive CLI best practices to inform implementation decisions for the research command and potential future interactive features:\n\n**Interactive CLI Best Practices Research Results:**\n\nKey findings for Node.js CLI development include empathic user-friendly design (prompting for missing arguments rather than failing), stateful context-aware interactions using XDG Base Directory Specification for config storage, and conversation threading with libraries like Inquirer.js for chaining prompts based on previous answers.\n\nImplementation recommendations: Use Inquirer.js for interactive flows, implement state management for user preferences across sessions, structure commands to support multi-step context-aware conversations, enhance output with color formatting using chalk, and design keyboard-friendly navigation without mouse requirements.\n\nSpecific patterns include branching conversations where follow-up prompts are triggered based on user selections, persistent context storage between CLI runs through file-based serialization, and rich UI elements like lists and checkboxes for improved accessibility.\n\nConsider applying these patterns to enhance the research command with optional interactive modes for query refinement and result exploration, while maintaining the primary non-interactive one-shot execution design.\n</info added on 2025-06-13T16:09:57.347Z>\n<info added on 2025-06-13T16:46:28.375Z>\nTesting append functionality: The research command implementation is progressing well. Successfully integrated enhanced follow-up functionality with conversation threading and save-to-task capabilities.\n</info added on 2025-06-13T16:46:28.375Z>\n<info added on 2025-06-14T10:15:00.000Z>\nRegular update test: Add information about the successful implementation of the append mode functionality which allows timestamped updates to tasks. This functionality enables research results to be appended to existing task details with proper timestamps, maintaining a chronological record of research activities and findings. The append mode integrates seamlessly with the existing task update mechanisms and follows the established patterns for task modification and file regeneration.\n</info added on 2025-06-14T10:15:00.000Z>",
"testStrategy": "- Write unit and integration tests to verify correct parsing of command-line arguments and flags.\n- Test that the command invokes ai-services-unified.js in research mode with the correct parameters and context.\n- Validate that context from tasks, files, and custom input is correctly gathered and passed to the research engine.\n- Confirm that output is properly formatted, includes citations, and is displayed in the terminal as expected.\n- Test saving results to files and handling of file system errors.\n- Ensure the command works in both brief and comprehensive modes.\n- Verify that the command does not enter interactive mode and exits cleanly after execution.\n- Check help output and usage documentation for accuracy and completeness.\n- Test the append mode functionality for timestamped updates to task details.\n- Validate that research-to-task linking works correctly with proper task file updates.",
@@ -5002,7 +5661,9 @@
"id": 2,
"title": "Parameter and Flag Handling",
"description": "Define and implement parsing for all arguments, flags, and options accepted by the 'research' command, including validation and default values.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Use a command-line parsing framework to handle parameters. Ensure support for optional and required arguments, order-independence, and clear error messages for invalid input.\n<info added on 2025-05-25T06:00:42.350Z>\n✅ **Parameter and Flag Handling Implementation Complete**\n\nSuccessfully implemented comprehensive parameter validation and processing for the research command:\n\n**✅ Implemented Features:**\n1. **Comprehensive Parameter Validation:**\n - Prompt validation (required, non-empty string)\n - Detail level validation (low, medium, high)\n - Task ID format validation (supports \"15\" and \"15.2\" formats)\n - File path validation (comma-separated, existence checks)\n - Save target validation (security checks for path traversal)\n\n2. **Advanced Parameter Processing:**\n - Comma-separated value parsing for task IDs and file paths\n - Whitespace trimming and normalization\n - Project root detection using `findProjectRoot()`\n - Relative/absolute path handling for files\n - Default value application\n\n3. **Informative Error Messages:**\n - Specific error messages for each validation failure\n - Clear examples of correct usage\n - Helpful suggestions for fixing errors\n - Much more informative than basic Commander.js errors\n\n4. **Structured Output:**\n - Creates validated parameters object with all processed values\n - Proper type conversion and normalization\n - Ready for consumption by core research function\n\n**✅ Validation Examples Tested:**\n- Missing prompt: Shows Commander.js error (expected behavior)\n- Invalid detail level: \"Error: Detail level must be one of: low, medium, high\"\n- Invalid task ID format: \"Error parsing task IDs: Invalid task ID format: \"invalid_format\". Expected format: \"15\" or \"15.2\"\"\n- Valid parameters: Successfully processes and creates structured parameter object\n\n**✅ Security Features:**\n- Path traversal protection for save targets\n- File existence validation\n- Input sanitization and trimming\n\nThe parameter validation is now production-ready and follows the same patterns used throughout the Task Master codebase. Ready to proceed to subtask 94.3 (Context Gathering Utility).\n</info added on 2025-05-25T06:00:42.350Z>",
"status": "done"
},
@@ -5020,7 +5681,10 @@
"description": "Implement the core research function in scripts/modules/task-manager/ following the add-task.js pattern",
"details": "Create a new core function (e.g., research.js) in scripts/modules/task-manager/ that:\n- Accepts parameters: query, context options (task IDs, file paths, custom context), project tree flag, detail level\n- Implements context gathering using the contextGatherer utility from subtask 94.3\n- Integrates with ai-services-unified.js using research role\n- Handles both CLI and MCP output formats\n- Returns structured results with telemetry data\n- Follows the same parameter validation and error handling patterns as add-task.js\n<info added on 2025-05-25T06:29:01.194Z>\n✅ COMPLETED: Added loading spinner to research command\n\n**Implementation Details:**\n- Imported `startLoadingIndicator` and `stopLoadingIndicator` from ui.js\n- Added loading indicator that shows \"Researching with AI...\" during AI service calls\n- Properly wrapped AI service call in try/catch/finally blocks to ensure spinner stops on both success and error\n- Loading indicator only shows in CLI mode (outputFormat === 'text'), not in MCP mode\n- Follows the same pattern as add-task.js for consistent user experience\n\n**Testing:**\n- Tested with `node bin/task-master.js research \"What is TypeScript?\" --detail=low`\n- Confirmed spinner appears during AI processing and disappears when complete\n- Telemetry display works correctly after spinner stops\n\nThe research command now provides the same polished user experience as other AI-powered commands in the system.\n</info added on 2025-05-25T06:29:01.194Z>",
"status": "done",
- "dependencies": ["98.2", "98.3"],
+ "dependencies": [
+ "98.2",
+ "98.3"
+ ],
"parentTaskId": 98
},
{
@@ -5029,7 +5693,9 @@
"description": "Create the MCP direct function wrapper in mcp-server/src/core/direct-functions/ following the add-task pattern",
"details": "Create a new direct function (e.g., research.js) in mcp-server/src/core/direct-functions/ that:\n- Follows the addTaskDirect pattern for parameter handling and error management\n- Uses enableSilentMode/disableSilentMode to prevent console output interference\n- Creates logger wrapper using createLogWrapper utility\n- Validates required parameters (query, projectRoot)\n- Calls the core research function with proper context (session, mcpLog, projectRoot)\n- Returns standardized result object with success/error structure\n- Handles telemetry data propagation\n- Export and register in task-master-core.js",
"status": "done",
- "dependencies": ["98.4"],
+ "dependencies": [
+ "98.4"
+ ],
"parentTaskId": 98
},
{
@@ -5038,7 +5704,9 @@
"description": "Create the MCP tool in mcp-server/src/tools/ following the add-task tool pattern",
"details": "Create a new MCP tool (e.g., research.js) in mcp-server/src/tools/ that:\n- Defines zod schema for all research command parameters (query, id, files, context, project-tree, save, detail)\n- Uses withNormalizedProjectRoot HOF to handle project path normalization\n- Calls findTasksJsonPath to locate tasks.json file\n- Invokes the direct function with proper parameter mapping\n- Uses handleApiResult for standardized response formatting\n- Registers the tool as 'research' (snake_case) in the MCP server\n- Handles errors with createErrorResponse\n- Register in mcp-server/src/tools/index.js\n- Update .cursor/mcp.json with tool definition",
"status": "done",
- "dependencies": ["98.5"],
+ "dependencies": [
+ "98.5"
+ ],
"parentTaskId": 98
},
{
@@ -5065,7 +5733,9 @@
"description": "Leverage the successfully implemented append mode functionality to enable seamless integration of research results into task details",
"details": "Build upon the existing append mode functionality to enhance research-to-task integration:\n\n- Utilize the timestamped update mechanism for appending research findings to task details\n- Ensure research results maintain chronological order when appended to tasks\n- Integrate with the existing task modification and file regeneration patterns\n- Support both direct research appending and research reference linking\n- Maintain consistency with the established append mode formatting and timestamp patterns\n- Test integration with the existing task update workflows\n\nThis subtask leverages the already-implemented append mode infrastructure to provide a robust foundation for research result integration into the task management system.",
"status": "done",
- "dependencies": ["98.8"],
+ "dependencies": [
+ "98.8"
+ ],
"parentTaskId": 98
}
]
@@ -5095,7 +5765,9 @@
"description": "Modify generateTasksFromPRD to embed PRD context and maintain source mappings",
"details": "## Implementation Requirements\n\n### Core Modifications to generateTasksFromPRD:\n1. **Add PRD Context Embedding**\n - Modify task generation prompt to include relevant PRD excerpts\n - Ensure each generated task includes source section references\n - Preserve original PRD language and specifications in task metadata\n\n2. **Implement Context Windowing**\n - For large PRDs, implement intelligent context windowing\n - Include relevant sections for each task being generated\n - Maintain context relationships between related tasks\n\n3. **Enhanced Task Structure**\n - Add prdContext field to task objects\n - Include sourceSection, originalText, and relatedSections\n - Store contextWindow for later use in expansions\n\n### Technical Implementation:\n```javascript\n// Enhanced task generation with context\nconst generateTaskWithContext = async (prdSection, relatedSections, fullPRD) => {\n const contextWindow = buildContextWindow(prdSection, relatedSections, fullPRD);\n const prompt = `\n Generate a task based on this PRD section:\n \n PRIMARY SECTION:\n ${prdSection.content}\n \n RELATED CONTEXT:\n ${contextWindow}\n \n Ensure the task preserves all specific requirements and technical details.\n `;\n \n // Generate task with embedded context\n const task = await generateTask(prompt);\n task.prdContext = {\n sourceSection: prdSection.title,\n originalText: prdSection.content,\n relatedSections: relatedSections.map(s => s.title),\n contextWindow: contextWindow\n };\n \n return task;\n};\n```\n\n### Context Preservation Strategy:\n- Map each task to its source PRD sections\n- Preserve technical specifications and requirements language\n- Maintain relationships between interdependent features\n- Store context for later use in expansion phase\n\n### Integration with Existing Flow:\n- Modify existing generateTasksFromPRD function\n- Maintain backward compatibility with simple PRDs\n- Add new metadata fields without breaking existing structure\n- Ensure context is available for subsequent operations",
"status": "pending",
- "dependencies": ["99.1"],
+ "dependencies": [
+ "99.1"
+ ],
"parentTaskId": 99
},
{
@@ -5104,7 +5776,9 @@
"description": "Add optional --expand-tasks flag and intelligent expansion using preserved PRD context",
"details": "## Implementation Requirements\n\n### Core Features:\n1. **Add --expand-tasks CLI Flag**\n - Optional flag for parse-prd command\n - Triggers automatic expansion after initial task generation\n - Configurable expansion depth and strategy\n\n2. **Two-Pass Processing System**\n - First pass: Generate tasks with PRD context preservation\n - Second pass: Expand tasks using their embedded PRD context\n - Maintain context fidelity throughout the process\n\n3. **Context-Aware Expansion Logic**\n - Use preserved PRD context for each task's expansion\n - Include relevant PRD excerpts in expansion prompts\n - Ensure subtasks maintain fidelity to original specifications\n\n### Technical Implementation:\n```javascript\n// Enhanced parse-prd with expansion pipeline\nconst parsePRDWithExpansion = async (prdContent, options) => {\n // Phase 1: Analyze and generate tasks with context\n const prdAnalysis = await analyzePRDStructure(prdContent);\n const tasksWithContext = await generateTasksWithContext(prdAnalysis);\n \n // Phase 2: Expand tasks if requested\n if (options.expandTasks) {\n for (const task of tasksWithContext) {\n if (shouldExpandTask(task, prdAnalysis)) {\n const expandedSubtasks = await expandTaskWithPRDContext(task);\n task.subtasks = expandedSubtasks;\n }\n }\n }\n \n return tasksWithContext;\n};\n\n// Context-aware task expansion\nconst expandTaskWithPRDContext = async (task) => {\n const { prdContext } = task;\n const expansionPrompt = `\n Expand this task into detailed subtasks using the original PRD context:\n \n TASK: ${task.title}\n DESCRIPTION: ${task.description}\n \n ORIGINAL PRD CONTEXT:\n ${prdContext.originalText}\n \n RELATED SECTIONS:\n ${prdContext.contextWindow}\n \n Generate subtasks that preserve all technical details and requirements from the PRD.\n `;\n \n return await generateSubtasks(expansionPrompt);\n};\n```\n\n### CLI Integration:\n- Add --expand-tasks flag to parse-prd command\n- Add --expansion-depth option for controlling subtask levels\n- Add --preserve-detail flag for maximum context preservation\n- Maintain backward compatibility with existing parse-prd usage\n\n### Expansion Strategy:\n- Determine which tasks should be expanded based on complexity\n- Use PRD context to generate accurate, detailed subtasks\n- Preserve technical specifications and implementation details\n- Validate subtask accuracy against original PRD content\n\n### Performance Considerations:\n- Implement batching for large numbers of tasks\n- Add progress indicators for long-running expansions\n- Optimize context window sizes for efficiency\n- Cache PRD analysis results for reuse",
"status": "pending",
- "dependencies": ["99.2"],
+ "dependencies": [
+ "99.2"
+ ],
"parentTaskId": 99
},
{
@@ -5113,7 +5787,9 @@
"description": "Modify existing expand-task functionality to leverage preserved PRD context for more accurate expansions",
"details": "## Implementation Requirements\n\n### Core Enhancements to expand-task.js:\n1. **PRD Context Detection**\n - Check if task has embedded prdContext metadata\n - Extract relevant PRD sections for expansion\n - Fall back to existing expansion logic if no PRD context\n\n2. **Context-Enhanced Expansion Prompts**\n - Include original PRD excerpts in expansion prompts\n - Add related section context for comprehensive understanding\n - Preserve technical specifications and requirements language\n\n3. **Validation and Quality Assurance**\n - Validate generated subtasks against original PRD content\n - Ensure technical accuracy and requirement compliance\n - Flag potential discrepancies for review\n\n### Technical Implementation:\n```javascript\n// Enhanced expand-task with PRD context\nconst expandTaskWithContext = async (taskId, options, context) => {\n const task = await getTask(taskId);\n \n // Check for PRD context\n if (task.prdContext) {\n return await expandWithPRDContext(task, options);\n } else {\n // Fall back to existing expansion logic\n return await expandTaskStandard(task, options);\n }\n};\n\nconst expandWithPRDContext = async (task, options) => {\n const { prdContext } = task;\n \n const enhancedPrompt = `\n Expand this task into detailed subtasks using the original PRD context:\n \n TASK DETAILS:\n Title: ${task.title}\n Description: ${task.description}\n Current Details: ${task.details}\n \n ORIGINAL PRD CONTEXT:\n Source Section: ${prdContext.sourceSection}\n Original Requirements:\n ${prdContext.originalText}\n \n RELATED CONTEXT:\n ${prdContext.contextWindow}\n \n EXPANSION REQUIREMENTS:\n - Preserve all technical specifications from the PRD\n - Maintain requirement accuracy and completeness\n - Generate ${options.num || 'appropriate number of'} subtasks\n - Include implementation details that reflect PRD specifics\n \n Generate subtasks that are grounded in the original PRD content.\n `;\n \n const subtasks = await generateSubtasks(enhancedPrompt, options);\n \n // Add PRD context inheritance to subtasks\n subtasks.forEach(subtask => {\n subtask.prdContext = {\n inheritedFrom: task.id,\n sourceSection: prdContext.sourceSection,\n relevantExcerpt: extractRelevantExcerpt(prdContext, subtask)\n };\n });\n \n return subtasks;\n};\n```\n\n### Integration Points:\n1. **Modify existing expand-task.js**\n - Add PRD context detection logic\n - Enhance prompt generation with context\n - Maintain backward compatibility\n\n2. **Update expansion validation**\n - Add PRD compliance checking\n - Implement quality scoring for context fidelity\n - Flag potential accuracy issues\n\n3. **CLI and MCP Integration**\n - Update expand-task command to leverage PRD context\n - Add options for context-aware expansion\n - Maintain existing command interface\n\n### Context Inheritance Strategy:\n- Pass relevant PRD context to generated subtasks\n- Create context inheritance chain for nested expansions\n- Preserve source traceability throughout expansion tree\n- Enable future re-expansion with maintained context\n\n### Quality Assurance Features:\n- Semantic similarity checking between subtasks and PRD\n- Technical requirement compliance validation\n- Automated flagging of potential context drift\n- User feedback integration for continuous improvement",
"status": "pending",
- "dependencies": ["99.2"],
+ "dependencies": [
+ "99.2"
+ ],
"parentTaskId": 99
},
{
@@ -5122,7 +5798,9 @@
"description": "Implement new command-line flags and MCP tool parameters for enhanced PRD parsing",
"details": "## Implementation Requirements\n\n### New CLI Options for parse-prd:\n1. **--expand-tasks**\n - Automatically expand generated tasks using PRD context\n - Boolean flag, default false\n - Triggers in-flight expansion pipeline\n\n2. **--preserve-detail**\n - Maximum detail preservation mode\n - Boolean flag, default false\n - Ensures highest fidelity to PRD content\n\n3. **--adaptive-count**\n - Let AI determine optimal task count based on PRD complexity\n - Boolean flag, default false\n - Overrides --num-tasks when enabled\n\n4. **--context-window-size**\n - Control how much PRD context to include in expansions\n - Integer value, default 2000 characters\n - Balances context richness with performance\n\n5. **--expansion-depth**\n - Control how many levels deep to expand tasks\n - Integer value, default 1\n - Prevents excessive nesting\n\n### MCP Tool Parameter Updates:\n```javascript\n// Enhanced parse_prd MCP tool parameters\n{\n input: \"Path to PRD file\",\n output: \"Output path for tasks.json\",\n numTasks: \"Number of top-level tasks (overridden by adaptiveCount)\",\n expandTasks: \"Boolean - automatically expand tasks with PRD context\",\n preserveDetail: \"Boolean - maximum detail preservation mode\",\n adaptiveCount: \"Boolean - AI determines optimal task count\",\n contextWindowSize: \"Integer - context size for expansions\",\n expansionDepth: \"Integer - levels of expansion to perform\",\n research: \"Boolean - use research model for enhanced analysis\",\n force: \"Boolean - overwrite existing files\"\n}\n```\n\n### CLI Command Updates:\n```bash\n# Enhanced parse-prd command examples\ntask-master parse-prd prd.txt --expand-tasks --preserve-detail\ntask-master parse-prd prd.txt --adaptive-count --expansion-depth=2\ntask-master parse-prd prd.txt --context-window-size=3000 --research\n```\n\n### Implementation Details:\n1. **Update commands.js**\n - Add new option definitions\n - Update parse-prd command handler\n - Maintain backward compatibility\n\n2. **Update MCP tool definition**\n - Add new parameter schemas\n - Update tool description and examples\n - Ensure parameter validation\n\n3. **Parameter Processing Logic**\n - Validate parameter combinations\n - Set appropriate defaults\n - Handle conflicting options gracefully\n\n### Validation Rules:\n- expansion-depth must be positive integer ≤ 3\n- context-window-size must be between 500-5000 characters\n- adaptive-count overrides num-tasks when both specified\n- expand-tasks requires either adaptive-count or num-tasks > 5\n\n### Help Documentation Updates:\n- Update command help text with new options\n- Add usage examples for different scenarios\n- Document parameter interactions and constraints\n- Include performance considerations for large PRDs",
"status": "pending",
- "dependencies": ["99.3"],
+ "dependencies": [
+ "99.3"
+ ],
"parentTaskId": 99
},
{
@@ -5131,7 +5809,10 @@
"description": "Create test suite for PRD analysis, context preservation, and expansion accuracy",
"details": "## Implementation Requirements\n\n### Test Categories:\n1. **PRD Analysis Testing**\n - Test section identification with various PRD formats\n - Validate complexity scoring accuracy\n - Test boundary detection for different document structures\n - Verify context mapping correctness\n\n2. **Context Preservation Testing**\n - Validate PRD context embedding in generated tasks\n - Test context window generation and sizing\n - Verify source section mapping accuracy\n - Test context inheritance in subtasks\n\n3. **Expansion Accuracy Testing**\n - Compare PRD-grounded vs standard expansions\n - Measure semantic similarity between PRD and subtasks\n - Test technical requirement preservation\n - Validate expansion depth and quality\n\n4. **Integration Testing**\n - Test full parse-prd pipeline with expansion\n - Validate CLI option combinations\n - Test MCP tool parameter handling\n - Verify backward compatibility\n\n### Test Data Requirements:\n```javascript\n// Test PRD samples\nconst testPRDs = {\n simple: \"Basic PRD with minimal technical details\",\n complex: \"Detailed PRD with extensive technical specifications\",\n structured: \"Well-organized PRD with clear sections\",\n unstructured: \"Free-form PRD with mixed content\",\n technical: \"Highly technical PRD with specific requirements\",\n large: \"Very large PRD testing context window limits\"\n};\n```\n\n### Validation Metrics:\n1. **Detail Preservation Score**\n - Semantic similarity between PRD and generated tasks\n - Technical requirement coverage percentage\n - Specification accuracy rating\n\n2. **Context Fidelity Score**\n - Accuracy of source section mapping\n - Relevance of included context windows\n - Quality of context inheritance\n\n3. **Expansion Quality Score**\n - Subtask relevance to parent task and PRD\n - Technical accuracy of implementation details\n - Completeness of requirement coverage\n\n### Test Implementation:\n```javascript\n// Example test structure\ndescribe('Enhanced Parse-PRD', () => {\n describe('PRD Analysis', () => {\n test('should identify sections correctly', async () => {\n const analysis = await analyzePRDStructure(testPRDs.structured);\n expect(analysis.sections).toHaveLength(expectedSectionCount);\n expect(analysis.overallComplexity).toBeGreaterThan(0);\n });\n \n test('should calculate appropriate task count', async () => {\n const analysis = await analyzePRDStructure(testPRDs.complex);\n expect(analysis.recommendedTaskCount).toBeGreaterThan(10);\n });\n });\n \n describe('Context Preservation', () => {\n test('should embed PRD context in tasks', async () => {\n const tasks = await generateTasksWithContext(testPRDs.technical);\n tasks.forEach(task => {\n expect(task.prdContext).toBeDefined();\n expect(task.prdContext.sourceSection).toBeTruthy();\n expect(task.prdContext.originalText).toBeTruthy();\n });\n });\n });\n \n describe('Expansion Accuracy', () => {\n test('should generate relevant subtasks from PRD context', async () => {\n const task = createTestTaskWithPRDContext();\n const subtasks = await expandTaskWithPRDContext(task);\n \n const relevanceScore = calculateRelevanceScore(subtasks, task.prdContext);\n expect(relevanceScore).toBeGreaterThan(0.8);\n });\n });\n});\n```\n\n### Performance Testing:\n- Test with large PRDs (>10,000 words)\n- Measure processing time for different complexity levels\n- Test memory usage with extensive context preservation\n- Validate timeout handling for long-running operations\n\n### Quality Assurance Tools:\n- Automated semantic similarity checking\n- Technical requirement compliance validation\n- Context drift detection algorithms\n- User acceptance testing framework\n\n### Continuous Integration:\n- Add tests to existing CI pipeline\n- Set up performance benchmarking\n- Implement quality gates for PRD processing\n- Create regression testing for context preservation",
"status": "pending",
- "dependencies": ["99.4", "99.5"],
+ "dependencies": [
+ "99.4",
+ "99.5"
+ ],
"parentTaskId": 99
}
]
@@ -5143,7 +5824,9 @@
"details": "## Core Problem Statement\n\nThe current help menu in `displayHelp()` function (ui.js:434-734) is hardcoded with static command information that can become outdated when:\n\n1. **Command Changes**: New options/flags are added to existing commands\n2. **New Commands**: New commands are added to commands.js but not reflected in help\n3. **Command Removal**: Commands are removed but help text remains\n4. **Inconsistent Documentation**: Help text doesn't match actual command behavior\n5. **Maintenance Burden**: Developers must remember to update help when modifying commands\n\n## Technical Implementation Requirements\n\n### 1. Command Introspection System\n- **Extract Command Metadata**: Parse Commander.js program instance to extract:\n - Command names and aliases\n - Command descriptions\n - All options/flags with their descriptions and default values\n - Required vs optional parameters\n - Argument specifications\n- **Command Categorization**: Implement intelligent categorization based on:\n - Command name patterns (e.g., 'add-*', 'remove-*', 'set-*')\n - Command descriptions containing keywords\n - Manual category overrides for edge cases\n- **Validation**: Ensure all registered commands are captured and categorized\n\n### 2. Dynamic Help Generation Engine\n- **Template System**: Create flexible templates for:\n - Category headers with consistent styling\n - Command entries with proper formatting\n - Option/flag documentation with type information\n - Example usage generation\n- **Formatting Logic**: Implement dynamic column width calculation based on:\n - Terminal width detection\n - Content length analysis\n - Responsive layout adjustments\n- **Content Optimization**: Handle text wrapping, truncation, and spacing automatically\n\n### 3. Enhanced Command Documentation\n- **Auto-Generated Examples**: Create realistic usage examples by:\n - Combining command names with common option patterns\n - Using project-specific values (task IDs, file paths)\n - Showing both simple and complex usage scenarios\n- **Option Details**: Display comprehensive option information:\n - Short and long flag variants (-f, --file)\n - Data types and format requirements\n - Default values and behavior\n - Required vs optional indicators\n- **Cross-References**: Add intelligent linking between related commands\n\n### 4. Integration Points\n- **Commands.js Integration**: \n - Access the programInstance after all commands are registered\n - Extract metadata without affecting command functionality\n - Handle edge cases like hidden commands or aliases\n- **UI.js Refactoring**:\n - Replace static commandCategories array with dynamic generation\n - Maintain existing visual styling and layout\n - Preserve terminal width responsiveness\n - Keep configuration and quick start sections\n\n### 5. Category Classification Logic\nImplement smart categorization rules:\n```javascript\nconst categoryRules = {\n 'Project Setup & Configuration': ['init', 'models'],\n 'Task Generation': ['parse-prd', 'generate'],\n 'Task Management': ['list', 'set-status', 'update', 'add-task', 'remove-task'],\n 'Subtask Management': ['add-subtask', 'remove-subtask', 'clear-subtasks'],\n 'Task Analysis & Breakdown': ['analyze-complexity', 'complexity-report', 'expand', 'research'],\n 'Task Navigation & Viewing': ['next', 'show'],\n 'Dependency Management': ['add-dependency', 'remove-dependency', 'validate-dependencies', 'fix-dependencies']\n};\n```\n\n### 6. Error Handling and Fallbacks\n- **Graceful Degradation**: Fall back to static help if introspection fails\n- **Missing Information**: Handle commands with incomplete metadata\n- **Performance Considerations**: Cache generated help content when possible\n- **Debug Mode**: Provide verbose output for troubleshooting categorization\n\n## Implementation Architecture\n\n### Core Functions to Implement:\n1. **`extractCommandMetadata(programInstance)`**\n - Parse Commander.js instance\n - Extract all command and option information\n - Return structured metadata object\n\n2. **`categorizeCommands(commandMetadata)`**\n - Apply categorization rules\n - Handle special cases and overrides\n - Return categorized command structure\n\n3. **`generateDynamicHelp(categorizedCommands)`**\n - Create formatted help content\n - Apply consistent styling\n - Handle responsive layout\n\n4. **`displayDynamicHelp(programInstance)`**\n - Replace current displayHelp() function\n - Integrate with existing banner and footer content\n - Maintain backward compatibility\n\n### File Structure Changes:\n- **ui.js**: Replace static help with dynamic generation\n- **commands.js**: Ensure all commands have proper descriptions and option documentation\n- **New utility functions**: Add command introspection helpers\n\n## Testing Requirements\n\n### Unit Tests:\n- Command metadata extraction accuracy\n- Categorization logic correctness\n- Help content generation formatting\n- Terminal width responsiveness\n\n### Integration Tests:\n- Full help menu generation from actual commands\n- Consistency between help and actual command behavior\n- Performance with large numbers of commands\n\n### Manual Testing:\n- Visual verification of help output\n- Terminal width adaptation testing\n- Comparison with current static help for completeness\n\n## Benefits\n\n1. **Automatic Synchronization**: Help always reflects actual command state\n2. **Reduced Maintenance**: No manual help updates needed for command changes\n3. **Consistency**: Guaranteed alignment between help and implementation\n4. **Extensibility**: Easy to add new categorization rules or formatting\n5. **Accuracy**: Eliminates human error in help documentation\n6. **Developer Experience**: Faster development with automatic documentation\n\n## Migration Strategy\n\n1. **Phase 1**: Implement introspection system alongside existing static help\n2. **Phase 2**: Add categorization and dynamic generation\n3. **Phase 3**: Replace static help with dynamic system\n4. **Phase 4**: Remove static command definitions and add validation tests\n\nThis implementation will create a self-documenting CLI that maintains accuracy and reduces the burden on developers to manually maintain help documentation.",
"testStrategy": "",
"status": "pending",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"priority": "medium",
"subtasks": [
{
@@ -5161,7 +5844,9 @@
"description": "Implement smart categorization logic to group commands into logical categories for the help menu",
"details": "## Implementation Requirements\n\n### Core Function: `categorizeCommands(commandMetadata)`\n\n**Location**: Add to `ui.js` or `help-utils.js` module\n\n**Functionality**:\n1. **Category Definition System**:\n - Define category rules with command name patterns\n - Support keyword-based categorization from descriptions\n - Allow manual overrides for edge cases\n - Maintain existing category structure for consistency\n\n2. **Categorization Rules**:\n```javascript\nconst categoryRules = {\n 'Project Setup & Configuration': {\n commands: ['init', 'models'],\n patterns: [/^models/, /^init/],\n keywords: ['setup', 'configure', 'initialization'],\n color: 'blue'\n },\n 'Task Generation': {\n commands: ['parse-prd', 'generate'],\n patterns: [/^parse/, /^generate/],\n keywords: ['create', 'generate', 'parse'],\n color: 'cyan'\n },\n 'Task Management': {\n commands: ['list', 'set-status', 'update', 'add-task', 'remove-task'],\n patterns: [/^(list|set-|update|add-|remove-)/, /status$/],\n keywords: ['manage', 'update', 'modify', 'status'],\n color: 'green'\n },\n 'Subtask Management': {\n commands: ['add-subtask', 'remove-subtask', 'clear-subtasks'],\n patterns: [/subtask/],\n keywords: ['subtask', 'sub-task'],\n color: 'yellow'\n },\n 'Task Analysis & Breakdown': {\n commands: ['analyze-complexity', 'complexity-report', 'expand', 'research'],\n patterns: [/^(analyze|complexity|expand|research)/],\n keywords: ['analyze', 'complexity', 'expand', 'research', 'breakdown'],\n color: 'magenta'\n },\n 'Task Navigation & Viewing': {\n commands: ['next', 'show'],\n patterns: [/^(next|show|view|display)/],\n keywords: ['view', 'show', 'display', 'navigate'],\n color: 'cyan'\n },\n 'Dependency Management': {\n commands: ['add-dependency', 'remove-dependency', 'validate-dependencies', 'fix-dependencies'],\n patterns: [/dependency|dependencies/],\n keywords: ['dependency', 'dependencies', 'depend'],\n color: 'blue'\n }\n};\n```\n\n3. **Categorization Algorithm**:\n - **Exact Match**: Check if command name is in category's command list\n - **Pattern Matching**: Test command name against regex patterns\n - **Keyword Analysis**: Search command description for category keywords\n - **Fallback Category**: Create \"Other Commands\" for uncategorized commands\n - **Priority System**: Handle commands that match multiple categories\n\n4. **Category Validation**:\n - Ensure all commands are categorized\n - Detect and warn about duplicate categorizations\n - Validate category color assignments\n - Check for empty categories\n\n### Technical Implementation:\n1. **Categorization Logic**:\n```javascript\nfunction categorizeCommands(commandMetadata) {\n const categorizedCommands = {};\n const uncategorized = [];\n \n // Initialize categories\n Object.keys(categoryRules).forEach(categoryName => {\n categorizedCommands[categoryName] = {\n ...categoryRules[categoryName],\n commands: []\n };\n });\n \n // Categorize each command\n Object.values(commandMetadata).forEach(command => {\n const category = findBestCategory(command);\n if (category) {\n categorizedCommands[category].commands.push(command);\n } else {\n uncategorized.push(command);\n }\n });\n \n // Handle uncategorized commands\n if (uncategorized.length > 0) {\n categorizedCommands['Other Commands'] = {\n color: 'gray',\n commands: uncategorized\n };\n }\n \n return categorizedCommands;\n}\n```\n\n2. **Best Category Detection**:\n - Score each category based on match strength\n - Prefer exact command name matches over patterns\n - Weight keyword matches by frequency and relevance\n - Return highest-scoring category\n\n3. **Dynamic Category Creation**:\n - Support adding new categories without code changes\n - Allow category rules to be loaded from configuration\n - Handle category inheritance and hierarchies\n\n### Testing Requirements:\n- Test categorization accuracy for all existing commands\n- Verify handling of new commands not in predefined lists\n- Test pattern matching and keyword detection\n- Validate category completeness and no duplicates",
"status": "pending",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"parentTaskId": 100
},
{
@@ -5179,7 +5864,9 @@
"description": "Replace the static help system with the new dynamic help generation and ensure seamless integration",
"details": "## Implementation Requirements\n\n### Core Integration Tasks:\n\n1. **Replace displayHelp() Function**:\n - **Location**: `ui.js` lines 434-734\n - **Action**: Replace static help content with dynamic generation\n - **Preserve**: Existing function signature and color scheme\n - **Enhance**: Add new parameters for filtering and customization\n\n2. **Update Function Signature**:\n```javascript\n// Current: displayHelp()\n// New: displayHelp(options = {})\nfunction displayHelp(options = {}) {\n const {\n category = null, // Filter by specific category\n command = null, // Show help for specific command\n search = null, // Search query for commands\n verbose = false, // Show detailed help\n noColor = false // Disable colors for accessibility\n } = options;\n \n // Dynamic help generation logic\n}\n```\n\n3. **Integration with commands.js**:\n - **Access Program Instance**: Get reference to Commander.js program\n - **Timing**: Ensure commands are fully registered before help generation\n - **Caching**: Cache command metadata to avoid repeated parsing\n\n4. **Update Help Command Registration**:\n```javascript\n// In commands.js, update help command\nprogram\n .command('help [command]')\n .description('Display help information')\n .option('-c, --category <category>', 'Show help for specific category')\n .option('-s, --search <query>', 'Search commands by keyword')\n .option('-v, --verbose', 'Show detailed help information')\n .option('--no-color', 'Disable colored output')\n .action(async (command, options) => {\n displayHelp({\n command,\n category: options.category,\n search: options.search,\n verbose: options.verbose,\n noColor: !options.color\n });\n });\n```\n\n5. **Fallback and Error Handling**:\n - **Graceful Degradation**: Fall back to static help if dynamic generation fails\n - **Error Recovery**: Handle malformed command definitions\n - **Performance**: Ensure help generation doesn't slow down CLI startup\n\n### Technical Implementation:\n\n1. **Program Instance Access**:\n```javascript\n// Method 1: Pass program instance to displayHelp\nfunction displayHelp(options = {}, programInstance = null) {\n if (!programInstance) {\n // Fallback to static help or error\n console.warn('Dynamic help unavailable, using static fallback');\n return displayStaticHelp();\n }\n \n const commandMetadata = extractCommandMetadata(programInstance);\n const categorizedCommands = categorizeCommands(commandMetadata);\n return generateHelpContent(categorizedCommands, options);\n}\n\n// Method 2: Global program reference\nlet globalProgramInstance = null;\nexport function setProgramInstance(program) {\n globalProgramInstance = program;\n}\n```\n\n2. **Initialization Sequence**:\n - Commands are registered in `commands.js`\n - Program instance is made available to help system\n - Help system caches command metadata on first use\n - Subsequent help calls use cached data\n\n3. **Backward Compatibility**:\n - Maintain existing `displayHelp()` calls without parameters\n - Preserve existing color scheme and formatting style\n - Keep same output structure for scripts that parse help output\n\n4. **Performance Optimization**:\n - Cache command metadata after first extraction\n - Lazy-load help content generation\n - Minimize impact on CLI startup time\n - Support incremental cache updates\n\n### Integration Points:\n\n1. **Update All Help Call Sites**:\n - Search codebase for `displayHelp()` calls\n - Update calls to pass program instance or use global reference\n - Test all help invocation paths\n\n2. **Enhanced Help Commands**:\n - `task-master help` - General help (existing behavior)\n - `task-master help <command>` - Command-specific help\n - `task-master help --category <cat>` - Category-specific help\n - `task-master help --search <query>` - Search-based help\n\n3. **Error Handling Integration**:\n - Update error messages to suggest relevant help commands\n - Provide contextual help suggestions based on failed commands\n - Integrate with existing error reporting system\n\n### Testing Requirements:\n\n1. **Integration Testing**:\n - Test help system with all existing commands\n - Verify backward compatibility with existing help calls\n - Test new help command options and parameters\n\n2. **Performance Testing**:\n - Measure help generation time with full command set\n - Test CLI startup time impact\n - Verify caching effectiveness\n\n3. **Compatibility Testing**:\n - Test with different terminal types and capabilities\n - Verify color output and no-color modes\n - Test with various screen sizes and widths\n\n4. **Error Scenario Testing**:\n - Test behavior with malformed command definitions\n - Verify fallback to static help when needed\n - Test graceful handling of missing metadata\n\n### Migration Strategy:\n\n1. **Phase 1**: Implement dynamic help system alongside existing static help\n2. **Phase 2**: Update help command to use dynamic system with fallback\n3. **Phase 3**: Replace all displayHelp() calls with dynamic version\n4. **Phase 4**: Remove static help content and cleanup old code\n5. **Phase 5**: Add enhanced help features (search, filtering, etc.)",
"status": "pending",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"parentTaskId": 100
},
{
@@ -5188,7 +5875,9 @@
"description": "Implement advanced help features including command search, category filtering, and contextual help suggestions",
"details": "## Implementation Requirements\n\n### Enhanced Help Features:\n\n1. **Command Search Functionality**:\n```javascript\nfunction searchCommands(query, commandMetadata) {\n const results = [];\n const searchTerms = query.toLowerCase().split(' ');\n \n Object.values(commandMetadata).forEach(command => {\n let score = 0;\n \n // Search in command name (highest weight)\n if (command.name.toLowerCase().includes(query.toLowerCase())) {\n score += 10;\n }\n \n // Search in description (medium weight)\n if (command.description && command.description.toLowerCase().includes(query.toLowerCase())) {\n score += 5;\n }\n \n // Search in option descriptions (lower weight)\n command.options?.forEach(option => {\n if (option.description.toLowerCase().includes(query.toLowerCase())) {\n score += 2;\n }\n });\n \n // Fuzzy matching for command names\n if (fuzzyMatch(command.name, query)) {\n score += 3;\n }\n \n if (score > 0) {\n results.push({ command, score });\n }\n });\n \n return results.sort((a, b) => b.score - a.score);\n}\n```\n\n2. **Category Filtering**:\n - Allow users to view help for specific categories only\n - Support partial category name matching\n - Provide category list when invalid category specified\n - Enable multiple category selection\n\n3. **Contextual Help Suggestions**:\n```javascript\nfunction suggestRelatedCommands(commandName, commandMetadata) {\n const suggestions = [];\n const command = commandMetadata[commandName];\n \n if (!command) return suggestions;\n \n // Find commands in same category\n const category = findCommandCategory(commandName);\n if (category) {\n suggestions.push(...getCategoryCommands(category));\n }\n \n // Find commands with similar names\n Object.keys(commandMetadata).forEach(name => {\n if (name !== commandName && similarity(name, commandName) > 0.6) {\n suggestions.push(commandMetadata[name]);\n }\n });\n \n // Find commands with related functionality\n const keywords = extractKeywords(command.description);\n keywords.forEach(keyword => {\n const related = findCommandsByKeyword(keyword, commandMetadata);\n suggestions.push(...related);\n });\n \n return deduplicateAndScore(suggestions);\n}\n```\n\n4. **Interactive Help Mode**:\n - Implement step-by-step help wizard\n - Guide users through command selection\n - Provide examples and use cases\n - Support help history and bookmarks\n\n### Advanced Features:\n\n1. **Help Caching and Performance**:\n```javascript\nclass HelpCache {\n constructor() {\n this.cache = new Map();\n this.lastUpdate = null;\n this.commandMetadata = null;\n }\n \n getHelp(key, generator) {\n if (this.cache.has(key) && !this.isStale()) {\n return this.cache.get(key);\n }\n \n const content = generator();\n this.cache.set(key, content);\n return content;\n }\n \n invalidate() {\n this.cache.clear();\n this.lastUpdate = Date.now();\n }\n \n isStale() {\n return Date.now() - this.lastUpdate > 300000; // 5 minutes\n }\n}\n```\n\n2. **Help Export and Documentation**:\n - Export help content to markdown format\n - Generate man pages from command metadata\n - Create HTML documentation\n - Support JSON export for API documentation\n\n3. **Accessibility Enhancements**:\n - Screen reader friendly output\n - High contrast mode support\n - Keyboard navigation for interactive help\n - Alternative text descriptions for visual elements\n\n4. **Internationalization Support**:\n - Support for multiple languages\n - Localized command descriptions\n - Cultural formatting preferences\n - RTL language support\n\n### Command-Specific Help Features:\n\n1. **Detailed Command Help**:\n```javascript\nfunction displayCommandHelp(commandName, commandMetadata) {\n const command = commandMetadata[commandName];\n if (!command) {\n console.error(`Command '${commandName}' not found.`);\n suggestSimilarCommands(commandName, commandMetadata);\n return;\n }\n \n console.log(chalk.cyan.bold(`\\\\n${command.name.toUpperCase()} COMMAND HELP\\\\n`));\n console.log(`Description: ${command.description}\\\\n`);\n \n // Usage examples\n if (command.examples) {\n console.log(chalk.yellow.bold('Examples:'));\n command.examples.forEach(example => {\n console.log(` ${chalk.green(example.command)}`);\n console.log(` ${example.description}\\\\n`);\n });\n }\n \n // Detailed options\n if (command.options && command.options.length > 0) {\n console.log(chalk.yellow.bold('Options:'));\n command.options.forEach(option => {\n console.log(` ${chalk.cyan(option.flags.padEnd(20))} ${option.description}`);\n if (option.defaultValue) {\n console.log(`${' '.repeat(22)}Default: ${option.defaultValue}`);\n }\n if (option.examples) {\n console.log(`${' '.repeat(22)}Example: ${option.examples[0]}`);\n }\n });\n }\n \n // Related commands\n const related = suggestRelatedCommands(commandName, commandMetadata);\n if (related.length > 0) {\n console.log(chalk.yellow.bold('\\\\nRelated Commands:'));\n related.slice(0, 5).forEach(cmd => {\n console.log(` ${chalk.cyan(cmd.name)} - ${cmd.description}`);\n });\n }\n}\n```\n\n2. **Usage Examples Generation**:\n - Auto-generate common usage patterns\n - Include real-world scenarios\n - Show before/after examples\n - Provide troubleshooting tips\n\n### Error Integration:\n\n1. **Smart Error Messages**:\n```javascript\nfunction enhanceErrorWithHelp(error, commandName, commandMetadata) {\n console.error(chalk.red(error.message));\n \n // Suggest correct usage\n if (commandMetadata[commandName]) {\n console.log(chalk.yellow('\\\\nCorrect usage:'));\n console.log(` ${formatCommandUsage(commandMetadata[commandName])}`);\n }\n \n // Suggest similar commands\n const suggestions = findSimilarCommands(commandName, commandMetadata);\n if (suggestions.length > 0) {\n console.log(chalk.yellow('\\\\nDid you mean:'));\n suggestions.slice(0, 3).forEach(cmd => {\n console.log(` ${chalk.cyan(cmd.name)} - ${cmd.description}`);\n });\n }\n \n // Provide help command\n console.log(chalk.gray(`\\\\nFor more help: task-master help ${commandName}`));\n}\n```\n\n### Testing Requirements:\n\n1. **Search Functionality Testing**:\n - Test search accuracy with various queries\n - Verify fuzzy matching and scoring\n - Test performance with large command sets\n - Validate search result ranking\n\n2. **Feature Integration Testing**:\n - Test all new help command options\n - Verify category filtering accuracy\n - Test contextual suggestions relevance\n - Validate caching behavior\n\n3. **Accessibility Testing**:\n - Test with screen readers\n - Verify keyboard navigation\n - Test color contrast and no-color modes\n - Validate output formatting\n\n4. **Performance Testing**:\n - Measure search response times\n - Test caching effectiveness\n - Verify memory usage with large datasets\n - Test concurrent help requests\n\n### Documentation Updates:\n\n1. **Update README**:\n - Document new help features\n - Provide usage examples\n - Update command reference\n - Add troubleshooting section\n\n2. **Create Help Documentation**:\n - Comprehensive help system guide\n - Advanced usage patterns\n - Customization options\n - Integration examples",
"status": "pending",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"parentTaskId": 100
},
{
@@ -5227,7 +5916,9 @@
"description": "Implement intelligent content formatting to convert Task Master tasks into properly formatted GitHub issues",
"details": "## Implementation Requirements\n\n### Core Formatting Service\n```javascript\n// scripts/modules/github/task-formatter.js\nclass TaskToGitHubFormatter {\n constructor(options = {}) {\n this.options = {\n includeTaskId: true,\n includeMetadata: true,\n convertSubtasksToChecklist: true,\n addTaskMasterReference: true,\n ...options\n };\n }\n \n formatTaskAsIssue(task, exportOptions = {}) {\n return {\n title: this.formatTitle(task, exportOptions),\n body: this.formatBody(task, exportOptions),\n labels: this.formatLabels(task, exportOptions),\n assignees: this.formatAssignees(task, exportOptions)\n };\n }\n}\n```\n\n### Title Formatting\n```javascript\nformatTitle(task, options) {\n let title = task.title;\n \n // Add task ID prefix if enabled\n if (this.options.includeTaskId && !options.hideTaskId) {\n title = `[Task ${task.id}] ${title}`;\n }\n \n // Add priority indicator for high priority tasks\n if (task.priority === 'high') {\n title = `🔥 ${title}`;\n }\n \n // Truncate if too long (GitHub limit is 256 characters)\n if (title.length > 250) {\n title = title.substring(0, 247) + '...';\n }\n \n return title;\n}\n```\n\n### Body Formatting\n```javascript\nformatBody(task, options) {\n let body = '';\n \n // Header with task metadata\n if (this.options.includeMetadata) {\n body += this.formatMetadataSection(task);\n }\n \n // Main description\n if (task.description) {\n body += `## Description\\n\\n${task.description}\\n\\n`;\n }\n \n // Implementation details\n if (task.details) {\n body += `## Implementation Details\\n\\n${this.formatDetails(task.details)}\\n\\n`;\n }\n \n // Test strategy\n if (task.testStrategy) {\n body += `## Test Strategy\\n\\n${task.testStrategy}\\n\\n`;\n }\n \n // Subtasks as checklist\n if (task.subtasks && task.subtasks.length > 0 && this.options.convertSubtasksToChecklist) {\n body += this.formatSubtasksSection(task.subtasks);\n }\n \n // Dependencies\n if (task.dependencies && task.dependencies.length > 0) {\n body += this.formatDependenciesSection(task.dependencies);\n }\n \n // Task Master reference\n if (this.options.addTaskMasterReference) {\n body += this.formatTaskMasterReference(task);\n }\n \n return body;\n}\n```\n\n### Metadata Section\n```javascript\nformatMetadataSection(task) {\n let metadata = '## Task Information\\n\\n';\n metadata += `| Field | Value |\\n`;\n metadata += `|-------|-------|\\n`;\n metadata += `| **Task ID** | ${task.id} |\\n`;\n metadata += `| **Priority** | ${this.formatPriority(task.priority)} |\\n`;\n metadata += `| **Status** | ${this.formatStatus(task.status)} |\\n`;\n \n if (task.dependencies && task.dependencies.length > 0) {\n metadata += `| **Dependencies** | ${task.dependencies.join(', ')} |\\n`;\n }\n \n if (task.complexityScore) {\n metadata += `| **Complexity** | ${task.complexityScore}/10 |\\n`;\n }\n \n metadata += '\\n';\n return metadata;\n}\n```\n\n### Subtasks Formatting\n```javascript\nformatSubtasksSection(subtasks) {\n let section = '## Subtasks\\n\\n';\n \n subtasks.forEach(subtask => {\n const checked = subtask.status === 'done' ? 'x' : ' ';\n section += `- [${checked}] **${subtask.title}**`;\n \n if (subtask.description) {\n section += ` - ${subtask.description}`;\n }\n \n section += '\\n';\n \n // Add subtask details as indented content\n if (subtask.details) {\n const indentedDetails = subtask.details\n .split('\\n')\n .map(line => ` ${line}`)\n .join('\\n');\n section += `${indentedDetails}\\n`;\n }\n });\n \n section += '\\n';\n return section;\n}\n```\n\n### Label Generation\n```javascript\nformatLabels(task, options) {\n const labels = [];\n \n // Always add task-master label\n labels.push('task-master');\n \n // Priority-based labels\n if (task.priority === 'high') {\n labels.push('priority:high');\n } else if (task.priority === 'low') {\n labels.push('priority:low');\n }\n \n // Status-based labels\n if (task.status === 'in-progress') {\n labels.push('in-progress');\n }\n \n // Complexity-based labels\n if (task.complexityScore >= 8) {\n labels.push('complexity:high');\n } else if (task.complexityScore <= 3) {\n labels.push('complexity:low');\n }\n \n // Custom labels from options\n if (options.labels) {\n labels.push(...options.labels);\n }\n \n return labels;\n}\n```\n\n### Markdown Conversion\n```javascript\nformatDetails(details) {\n // Convert Task Master specific formatting to GitHub markdown\n let formatted = details;\n \n // Convert code blocks\n formatted = formatted.replace(/```(\\w+)?\\n([\\s\\S]*?)```/g, (match, lang, code) => {\n return `\\`\\`\\`${lang || ''}\\n${code}\\`\\`\\``;\n });\n \n // Convert inline code\n formatted = formatted.replace(/`([^`]+)`/g, '`$1`');\n \n // Convert headers\n formatted = formatted.replace(/^(#{1,6})\\s+(.+)$/gm, '$1 $2');\n \n // Convert lists\n formatted = formatted.replace(/^\\s*[-*+]\\s+(.+)$/gm, '- $1');\n \n // Convert numbered lists\n formatted = formatted.replace(/^\\s*\\d+\\.\\s+(.+)$/gm, (match, content, offset, string) => {\n const lineNumber = string.substring(0, offset).split('\\n').length;\n return `${lineNumber}. ${content}`;\n });\n \n return formatted;\n}\n```\n\n### Task Master Reference\n```javascript\nformatTaskMasterReference(task) {\n return `\\n---\\n\\n*This issue was exported from Task Master*\\n\\n` +\n `**Original Task**: #${task.id}\\n` +\n `**Exported**: ${new Date().toISOString()}\\n` +\n `**Task Master Project**: ${this.getProjectName()}\\n`;\n}\n```\n\n### Template System\n```javascript\nclass IssueTemplateManager {\n constructor() {\n this.templates = {\n default: new DefaultTemplate(),\n bug: new BugTemplate(),\n feature: new FeatureTemplate(),\n epic: new EpicTemplate()\n };\n }\n \n applyTemplate(task, templateName, options) {\n const template = this.templates[templateName] || this.templates.default;\n return template.format(task, options);\n }\n}\n\nclass BugTemplate extends TaskToGitHubFormatter {\n formatTitle(task, options) {\n return `🐛 [BUG] ${task.title}`;\n }\n \n formatBody(task, options) {\n let body = '## Bug Report\\n\\n';\n body += `**Task ID**: ${task.id}\\n\\n`;\n \n if (task.description) {\n body += `### Description\\n${task.description}\\n\\n`;\n }\n \n if (task.details) {\n body += `### Steps to Reproduce\\n${task.details}\\n\\n`;\n }\n \n body += `### Expected Behavior\\n<!-- Describe what should happen -->\\n\\n`;\n body += `### Actual Behavior\\n<!-- Describe what actually happens -->\\n\\n`;\n \n return body + this.formatTaskMasterReference(task);\n }\n}\n```\n\n### Testing Requirements\n- Unit tests for all formatting methods\n- Test with various task structures (with/without subtasks, different priorities)\n- Markdown conversion accuracy testing\n- Template system testing\n- Character limit and truncation testing\n- Special character handling (emojis, unicode)\n- Large content handling and performance testing",
"status": "pending",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"parentTaskId": 101
},
{
@@ -5245,7 +5936,9 @@
"description": "Implement the command-line interface and MCP tools for GitHub export functionality",
"details": "## Implementation Requirements\n\n### CLI Command Implementation\n```javascript\n// In scripts/modules/commands.js\nprogram\n .command('github-export')\n .description('Export Task Master task to GitHub issue with bidirectional linking')\n .requiredOption('-i, --id <taskId>', 'Task ID to export')\n .requiredOption('-r, --repo <owner/repo>', 'Target GitHub repository (owner/repo format)')\n .option('-t, --token <token>', 'GitHub Personal Access Token (or use GITHUB_TOKEN env var)')\n .option('--title <title>', 'Override the GitHub issue title')\n .option('--labels <labels>', 'Comma-separated list of GitHub labels to add')\n .option('--assignees <assignees>', 'Comma-separated list of GitHub usernames to assign')\n .option('--milestone <milestone>', 'GitHub milestone number or title')\n .option('--template <template>', 'Issue template to use (bug, feature, epic, default)')\n .option('--include-subtasks', 'Include subtasks as checklist items in the issue')\n .option('--separate-subtasks', 'Create separate GitHub issues for each subtask')\n .option('--dry-run', 'Preview the issue content without actually creating it')\n .option('--force', 'Overwrite existing GitHub link if task is already linked')\n .option('--no-link-back', 'Do not add Task Master reference to the GitHub issue')\n .option('--sync', 'Enable automatic synchronization between task and issue')\n .action(async (options) => {\n try {\n await handleGitHubExport(options);\n } catch (error) {\n console.error(chalk.red('GitHub export failed:'), error.message);\n process.exit(1);\n }\n });\n```\n\n### Core Export Handler\n```javascript\n// scripts/modules/github/github-export-handler.js\nasync function handleGitHubExport(options) {\n const {\n id: taskId,\n repo: repository,\n token,\n title: titleOverride,\n labels,\n assignees,\n milestone,\n template = 'default',\n includeSubtasks,\n separateSubtasks,\n dryRun,\n force,\n linkBack = true,\n sync = false\n } = options;\n\n // Validate inputs\n await validateExportOptions(options);\n \n // Get task details\n const task = await getTask(taskId);\n if (!task) {\n throw new Error(`Task ${taskId} not found`);\n }\n \n // Check for existing GitHub link\n if (task.metadata?.githubIssue && !force) {\n const existingUrl = task.metadata.githubIssue.url;\n console.log(chalk.yellow(`Task ${taskId} is already linked to GitHub issue: ${existingUrl}`));\n console.log(chalk.gray('Use --force to overwrite the existing link'));\n return;\n }\n \n // Initialize GitHub service\n const githubToken = token || process.env.GITHUB_TOKEN;\n if (!githubToken) {\n throw new Error('GitHub token required. Use --token flag or set GITHUB_TOKEN environment variable');\n }\n \n const githubService = new GitHubExportService(githubToken);\n const formatter = new TaskToGitHubFormatter();\n const linkManager = new GitHubLinkManager(githubService);\n \n // Format task content\n const exportOptions = {\n titleOverride,\n labels: labels ? labels.split(',').map(l => l.trim()) : [],\n assignees: assignees ? assignees.split(',').map(a => a.trim()) : [],\n milestone,\n template,\n includeSubtasks,\n linkBack\n };\n \n const issueData = formatter.formatTaskAsIssue(task, exportOptions);\n \n // Dry run - just show what would be created\n if (dryRun) {\n console.log(chalk.cyan('\\\\n=== DRY RUN - GitHub Issue Preview ===\\\\n'));\n console.log(chalk.bold('Title:'), issueData.title);\n console.log(chalk.bold('\\\\nLabels:'), issueData.labels.join(', ') || 'None');\n console.log(chalk.bold('\\\\nAssignees:'), issueData.assignees.join(', ') || 'None');\n console.log(chalk.bold('\\\\nBody:'));\n console.log(issueData.body);\n console.log(chalk.cyan('\\\\n=== End Preview ===\\\\n'));\n return;\n }\n \n // Show progress\n console.log(chalk.blue(`Exporting task ${taskId} to GitHub repository ${repository}...`));\n \n // Export to GitHub\n const result = await githubService.exportTask(task, repository, exportOptions);\n \n if (result.success) {\n console.log(chalk.green(`✅ Successfully exported task ${taskId} to GitHub!`));\n console.log(chalk.cyan(`GitHub Issue: ${result.issueUrl}`));\n \n // Add bidirectional link\n await linkManager.addGitHubLinkToTask(taskId, result.issueUrl, result.issue.number, repository);\n \n if (linkBack) {\n await linkManager.updateGitHubIssueWithTaskReference(result.issueUrl, taskId, getProjectName());\n }\n \n if (sync) {\n await linkManager.enableSync(taskId);\n console.log(chalk.blue('🔄 Synchronization enabled for this task'));\n }\n \n // Handle subtasks if requested\n if (separateSubtasks && task.subtasks && task.subtasks.length > 0) {\n console.log(chalk.blue('\\\\nExporting subtasks as separate issues...'));\n await exportSubtasksAsSeparateIssues(task.subtasks, repository, githubService, linkManager);\n }\n \n } else {\n throw new Error(result.error || 'Export failed');\n }\n}\n```\n\n### MCP Tool Implementation\n```javascript\n// mcp-server/src/tools/github-export.js\nimport { githubExportDirect } from '../core/direct-functions/github-export-direct.js';\nimport { handleApiResult, withNormalizedProjectRoot } from './utils.js';\n\nexport function registerGitHubExportTool(server) {\n server.addTool({\n name: \"github_export_task\",\n description: \"Export a Task Master task to GitHub issue with bidirectional linking\",\n parameters: {\n type: \"object\",\n properties: {\n taskId: {\n type: \"string\",\n description: \"Task ID to export (required)\"\n },\n repository: {\n type: \"string\", \n description: \"GitHub repository in owner/repo format (required)\"\n },\n token: {\n type: \"string\",\n description: \"GitHub Personal Access Token (optional if GITHUB_TOKEN env var is set)\"\n },\n options: {\n type: \"object\",\n properties: {\n title: {\n type: \"string\",\n description: \"Override the GitHub issue title\"\n },\n labels: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"GitHub labels to add to the issue\"\n },\n assignees: {\n type: \"array\", \n items: { type: \"string\" },\n description: \"GitHub usernames to assign to the issue\"\n },\n milestone: {\n type: \"string\",\n description: \"GitHub milestone number or title\"\n },\n template: {\n type: \"string\",\n enum: [\"default\", \"bug\", \"feature\", \"epic\"],\n description: \"Issue template to use\"\n },\n includeSubtasks: {\n type: \"boolean\",\n description: \"Include subtasks as checklist items\"\n },\n separateSubtasks: {\n type: \"boolean\", \n description: \"Create separate issues for subtasks\"\n },\n dryRun: {\n type: \"boolean\",\n description: \"Preview without creating the issue\"\n },\n force: {\n type: \"boolean\",\n description: \"Overwrite existing GitHub link\"\n },\n linkBack: {\n type: \"boolean\",\n description: \"Add Task Master reference to GitHub issue\"\n },\n enableSync: {\n type: \"boolean\",\n description: \"Enable automatic synchronization\"\n }\n }\n },\n projectRoot: {\n type: \"string\",\n description: \"Project root directory path\"\n }\n },\n required: [\"taskId\", \"repository\"]\n },\n execute: withNormalizedProjectRoot(async (args, { log, session }) => {\n try {\n const result = await githubExportDirect(args, log, { session });\n return handleApiResult(result, log);\n } catch (error) {\n log(`GitHub export error: ${error.message}`);\n return {\n success: false,\n error: error.message\n };\n }\n })\n });\n}\n```\n\n### Direct Function Implementation\n```javascript\n// mcp-server/src/core/direct-functions/github-export-direct.js\nimport { handleGitHubExport } from '../../../../scripts/modules/github/github-export-handler.js';\nimport { createLogWrapper } from '../../tools/utils.js';\n\nexport async function githubExportDirect(args, log, context = {}) {\n const { session } = context;\n const mcpLog = createLogWrapper(log);\n \n try {\n // Prepare options for the core handler\n const options = {\n id: args.taskId,\n repo: args.repository,\n token: args.token,\n ...args.options,\n projectRoot: args.projectRoot\n };\n \n // Call the core export handler\n const result = await handleGitHubExport(options, {\n session,\n mcpLog,\n outputFormat: 'json' // Request JSON output for MCP\n });\n \n return {\n success: true,\n data: {\n taskId: args.taskId,\n repository: args.repository,\n issueUrl: result.issueUrl,\n issueNumber: result.issue.number,\n exportedAt: new Date().toISOString(),\n message: `Successfully exported task ${args.taskId} to GitHub issue #${result.issue.number}`\n }\n };\n \n } catch (error) {\n mcpLog(`GitHub export failed: ${error.message}`);\n return {\n success: false,\n error: error.message\n };\n }\n}\n```\n\n### Validation Functions\n```javascript\n// scripts/modules/github/validation.js\nasync function validateExportOptions(options) {\n const { id: taskId, repo: repository, token } = options;\n \n // Validate task ID\n if (!taskId || !/^\\\\d+(\\\\.\\\\d+)*$/.test(taskId)) {\n throw new Error('Invalid task ID format');\n }\n \n // Validate repository format\n if (!repository || !/^[a-zA-Z0-9._-]+\\\\/[a-zA-Z0-9._-]+$/.test(repository)) {\n throw new Error('Repository must be in owner/repo format');\n }\n \n // Validate GitHub token\n const githubToken = token || process.env.GITHUB_TOKEN;\n if (!githubToken) {\n throw new Error('GitHub token is required');\n }\n \n if (!/^gh[ps]_[a-zA-Z0-9]{36,}$/.test(githubToken)) {\n console.warn(chalk.yellow('Warning: GitHub token format appears invalid'));\n }\n \n // Validate labels format\n if (options.labels) {\n const labels = options.labels.split(',').map(l => l.trim());\n for (const label of labels) {\n if (label.length > 50) {\n throw new Error(`Label \"${label}\" is too long (max 50 characters)`);\n }\n }\n }\n \n // Validate assignees format\n if (options.assignees) {\n const assignees = options.assignees.split(',').map(a => a.trim());\n for (const assignee of assignees) {\n if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(assignee)) {\n throw new Error(`Invalid GitHub username: ${assignee}`);\n }\n }\n }\n}\n```\n\n### Help Integration\n```javascript\n// Add to help system\nconst githubExportHelp = {\n command: 'github-export',\n description: 'Export Task Master task to GitHub issue',\n usage: 'task-master github-export --id=<taskId> --repo=<owner/repo> [options]',\n examples: [\n {\n command: 'task-master github-export --id=42 --repo=myorg/myproject',\n description: 'Export task 42 to GitHub repository'\n },\n {\n command: 'task-master github-export --id=42 --repo=myorg/myproject --labels=\"bug,urgent\" --assignees=\"john,jane\"',\n description: 'Export with custom labels and assignees'\n },\n {\n command: 'task-master github-export --id=42 --repo=myorg/myproject --dry-run',\n description: 'Preview the GitHub issue without creating it'\n },\n {\n command: 'task-master github-export --id=42 --repo=myorg/myproject --template=bug --sync',\n description: 'Export using bug template with sync enabled'\n }\n ],\n options: [\n { flag: '--id <taskId>', description: 'Task ID to export (required)' },\n { flag: '--repo <owner/repo>', description: 'GitHub repository (required)' },\n { flag: '--token <token>', description: 'GitHub Personal Access Token' },\n { flag: '--title <title>', description: 'Override issue title' },\n { flag: '--labels <labels>', description: 'Comma-separated labels' },\n { flag: '--assignees <users>', description: 'Comma-separated assignees' },\n { flag: '--milestone <milestone>', description: 'GitHub milestone' },\n { flag: '--template <template>', description: 'Issue template (bug, feature, epic)' },\n { flag: '--include-subtasks', description: 'Include subtasks as checklist' },\n { flag: '--separate-subtasks', description: 'Create separate issues for subtasks' },\n { flag: '--dry-run', description: 'Preview without creating' },\n { flag: '--force', description: 'Overwrite existing GitHub link' },\n { flag: '--no-link-back', description: 'Skip Task Master reference in issue' },\n { flag: '--sync', description: 'Enable automatic synchronization' }\n ]\n};\n```\n\n### Testing Requirements\n- Unit tests for CLI option parsing and validation\n- Integration tests for MCP tool functionality\n- End-to-end tests with real GitHub repositories\n- Error handling tests for various failure scenarios\n- Dry-run functionality testing\n- Template system testing\n- Subtask export testing (both checklist and separate issues)\n- Authentication and authorization testing\n- Rate limiting and retry logic testing",
"status": "pending",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"parentTaskId": 101
},
{
@@ -5254,7 +5947,9 @@
"description": "Implement thorough testing for the GitHub export system and create comprehensive documentation",
"details": "## Implementation Requirements\n\n### Testing Strategy\n\n#### 1. Unit Tests\n```javascript\n// tests/unit/github-export.test.js\ndescribe('GitHub Export System', () => {\n describe('GitHubExportService', () => {\n test('should validate repository access', async () => {\n const service = new GitHubExportService('mock-token');\n const mockGitHub = jest.spyOn(service, 'validateRepositoryAccess');\n \n await service.exportTask(mockTask, 'owner', 'repo');\n expect(mockGitHub).toHaveBeenCalledWith('owner', 'repo');\n });\n \n test('should handle authentication errors', async () => {\n const service = new GitHubExportService('invalid-token');\n \n await expect(service.exportTask(mockTask, 'owner', 'repo'))\n .rejects.toThrow('Authentication failed');\n });\n \n test('should respect rate limits', async () => {\n const service = new GitHubExportService('valid-token');\n const rateLimiter = jest.spyOn(service.rateLimiter, 'removeTokens');\n \n await service.exportTask(mockTask, 'owner', 'repo');\n expect(rateLimiter).toHaveBeenCalled();\n });\n });\n \n describe('TaskToGitHubFormatter', () => {\n test('should format task title correctly', () => {\n const formatter = new TaskToGitHubFormatter();\n const task = { id: 42, title: 'Test Task', priority: 'high' };\n \n const result = formatter.formatTitle(task);\n expect(result).toBe('🔥 [Task 42] Test Task');\n });\n \n test('should truncate long titles', () => {\n const formatter = new TaskToGitHubFormatter();\n const longTitle = 'A'.repeat(300);\n const task = { id: 1, title: longTitle };\n \n const result = formatter.formatTitle(task);\n expect(result.length).toBeLessThanOrEqual(250);\n expect(result).toEndWith('...');\n });\n \n test('should format subtasks as checklist', () => {\n const formatter = new TaskToGitHubFormatter();\n const task = {\n id: 1,\n title: 'Parent Task',\n subtasks: [\n { title: 'Subtask 1', status: 'done' },\n { title: 'Subtask 2', status: 'pending' }\n ]\n };\n \n const result = formatter.formatBody(task);\n expect(result).toContain('- [x] **Subtask 1**');\n expect(result).toContain('- [ ] **Subtask 2**');\n });\n \n test('should generate appropriate labels', () => {\n const formatter = new TaskToGitHubFormatter();\n const task = { priority: 'high', complexityScore: 9 };\n \n const labels = formatter.formatLabels(task);\n expect(labels).toContain('task-master');\n expect(labels).toContain('priority:high');\n expect(labels).toContain('complexity:high');\n });\n });\n \n describe('GitHubLinkManager', () => {\n test('should add GitHub link to task metadata', async () => {\n const linkManager = new GitHubLinkManager(mockGitHubService);\n const taskId = '42';\n const issueUrl = 'https://github.com/owner/repo/issues/123';\n \n await linkManager.addGitHubLinkToTask(taskId, issueUrl, 123, 'owner/repo');\n \n const task = await getTask(taskId);\n expect(task.metadata.githubIssue).toBeDefined();\n expect(task.metadata.githubIssue.url).toBe(issueUrl);\n expect(task.metadata.githubIssue.number).toBe(123);\n });\n \n test('should validate GitHub links', async () => {\n const linkManager = new GitHubLinkManager(mockGitHubService);\n const linkInfo = {\n repository: 'owner/repo',\n number: 123,\n status: 'active'\n };\n \n mockGitHubService.getIssue.mockResolvedValue({ state: 'open' });\n \n const result = await linkManager.validateGitHubLink('42', linkInfo);\n expect(result.valid).toBe(true);\n expect(result.status).toBe('active');\n });\n });\n});\n```\n\n#### 2. Integration Tests\n```javascript\n// tests/integration/github-export-integration.test.js\ndescribe('GitHub Export Integration', () => {\n let testRepository;\n let githubToken;\n \n beforeAll(() => {\n githubToken = process.env.GITHUB_TEST_TOKEN;\n testRepository = process.env.GITHUB_TEST_REPO || 'taskmaster-test/test-repo';\n \n if (!githubToken) {\n throw new Error('GITHUB_TEST_TOKEN environment variable required for integration tests');\n }\n });\n \n test('should export task to real GitHub repository', async () => {\n const task = createTestTask();\n const service = new GitHubExportService(githubToken);\n \n const result = await service.exportTask(task, testRepository, {\n labels: ['test', 'automated'],\n template: 'default'\n });\n \n expect(result.success).toBe(true);\n expect(result.issueUrl).toMatch(/https:\\\\/\\\\/github\\\\.com\\\\/.+\\\\/issues\\\\/\\\\d+/);\n \n // Cleanup: Close the test issue\n await service.updateIssue(testRepository, result.issue.number, { state: 'closed' });\n });\n \n test('should handle repository permission errors', async () => {\n const task = createTestTask();\n const service = new GitHubExportService(githubToken);\n \n await expect(service.exportTask(task, 'private/inaccessible-repo'))\n .rejects.toThrow(/permission|access/i);\n });\n \n test('should respect GitHub API rate limits', async () => {\n const service = new GitHubExportService(githubToken);\n const tasks = Array.from({ length: 10 }, () => createTestTask());\n \n const startTime = Date.now();\n \n for (const task of tasks) {\n await service.exportTask(task, testRepository);\n }\n \n const endTime = Date.now();\n const duration = endTime - startTime;\n \n // Should take some time due to rate limiting\n expect(duration).toBeGreaterThan(1000);\n });\n});\n```\n\n#### 3. CLI Tests\n```javascript\n// tests/cli/github-export-cli.test.js\ndescribe('GitHub Export CLI', () => {\n test('should validate required options', async () => {\n const result = await runCLI(['github-export']);\n \n expect(result.exitCode).toBe(1);\n expect(result.stderr).toContain('required option');\n });\n \n test('should perform dry run correctly', async () => {\n const result = await runCLI([\n 'github-export',\n '--id=42',\n '--repo=owner/repo',\n '--dry-run'\n ]);\n \n expect(result.exitCode).toBe(0);\n expect(result.stdout).toContain('DRY RUN');\n expect(result.stdout).toContain('GitHub Issue Preview');\n });\n \n test('should handle invalid task ID', async () => {\n const result = await runCLI([\n 'github-export',\n '--id=invalid',\n '--repo=owner/repo'\n ]);\n \n expect(result.exitCode).toBe(1);\n expect(result.stderr).toContain('Invalid task ID');\n });\n \n test('should validate repository format', async () => {\n const result = await runCLI([\n 'github-export',\n '--id=42',\n '--repo=invalid-format'\n ]);\n \n expect(result.exitCode).toBe(1);\n expect(result.stderr).toContain('owner/repo format');\n });\n});\n```\n\n#### 4. MCP Tool Tests\n```javascript\n// tests/mcp/github-export-mcp.test.js\ndescribe('GitHub Export MCP Tool', () => {\n test('should export task via MCP', async () => {\n const args = {\n taskId: '42',\n repository: 'owner/repo',\n token: 'test-token',\n options: {\n labels: ['test'],\n dryRun: true\n }\n };\n \n const result = await githubExportDirect(args, mockLog, { session: mockSession });\n \n expect(result.success).toBe(true);\n expect(result.data.taskId).toBe('42');\n });\n \n test('should handle MCP tool errors', async () => {\n const args = {\n taskId: 'invalid',\n repository: 'owner/repo'\n };\n \n const result = await githubExportDirect(args, mockLog, { session: mockSession });\n \n expect(result.success).toBe(false);\n expect(result.error).toBeDefined();\n });\n});\n```\n\n### Mock Data and Utilities\n```javascript\n// tests/utils/github-mocks.js\nexport function createTestTask() {\n return {\n id: Math.floor(Math.random() * 1000),\n title: 'Test Task',\n description: 'This is a test task for GitHub export',\n details: 'Implementation details for the test task',\n priority: 'medium',\n status: 'pending',\n subtasks: [\n { title: 'Test Subtask 1', status: 'done' },\n { title: 'Test Subtask 2', status: 'pending' }\n ]\n };\n}\n\nexport function mockGitHubAPI() {\n return {\n getIssue: jest.fn(),\n createIssue: jest.fn(),\n updateIssue: jest.fn(),\n getRepository: jest.fn()\n };\n}\n\nexport function createMockGitHubResponse(issueNumber = 123) {\n return {\n id: issueNumber,\n number: issueNumber,\n title: 'Test Issue',\n body: 'Test issue body',\n state: 'open',\n html_url: `https://github.com/owner/repo/issues/${issueNumber}`,\n created_at: new Date().toISOString(),\n updated_at: new Date().toISOString()\n };\n}\n```\n\n### Documentation\n\n#### 1. User Guide\n```markdown\n# GitHub Export Feature\n\n## Overview\nThe GitHub Export feature allows you to create GitHub issues directly from your Task Master tasks, maintaining bidirectional links between tasks and issues.\n\n## Setup\n\n### 1. GitHub Token\nCreate a GitHub Personal Access Token with the following permissions:\n- `repo` (for private repositories)\n- `public_repo` (for public repositories)\n\nSet the token as an environment variable:\n```bash\nexport GITHUB_TOKEN=your_token_here\n```\n\n### 2. Basic Usage\n```bash\n# Export a task to GitHub\ntask-master github-export --id=42 --repo=myorg/myproject\n\n# Export with custom labels and assignees\ntask-master github-export --id=42 --repo=myorg/myproject \\\\\n --labels=\"bug,urgent\" --assignees=\"john,jane\"\n\n# Preview before creating\ntask-master github-export --id=42 --repo=myorg/myproject --dry-run\n```\n\n## Advanced Features\n\n### Templates\nUse predefined templates for different issue types:\n```bash\n# Bug report template\ntask-master github-export --id=42 --repo=myorg/myproject --template=bug\n\n# Feature request template\ntask-master github-export --id=42 --repo=myorg/myproject --template=feature\n```\n\n### Subtask Handling\n```bash\n# Include subtasks as checklist items\ntask-master github-export --id=42 --repo=myorg/myproject --include-subtasks\n\n# Create separate issues for each subtask\ntask-master github-export --id=42 --repo=myorg/myproject --separate-subtasks\n```\n\n### Synchronization\n```bash\n# Enable automatic synchronization\ntask-master github-export --id=42 --repo=myorg/myproject --sync\n```\n\n## Troubleshooting\n\n### Common Issues\n1. **Authentication Error**: Verify your GitHub token has the correct permissions\n2. **Repository Not Found**: Ensure the repository exists and you have access\n3. **Rate Limit Exceeded**: Wait for the rate limit to reset or use a different token\n\n### Link Management\n```bash\n# Validate all GitHub links\ntask-master github-link --validate\n\n# Sync specific task with GitHub\ntask-master github-link --sync 42\n\n# Remove GitHub link from task\ntask-master github-link --remove 42\n```\n```\n\n#### 2. API Documentation\n```markdown\n# GitHub Export API Reference\n\n## MCP Tool: github_export_task\n\n### Parameters\n- `taskId` (string, required): Task ID to export\n- `repository` (string, required): GitHub repository in owner/repo format\n- `token` (string, optional): GitHub Personal Access Token\n- `options` (object, optional): Export configuration\n\n### Options Object\n- `title` (string): Override issue title\n- `labels` (array): GitHub labels to add\n- `assignees` (array): GitHub usernames to assign\n- `milestone` (string): GitHub milestone\n- `template` (string): Issue template (bug, feature, epic, default)\n- `includeSubtasks` (boolean): Include subtasks as checklist\n- `separateSubtasks` (boolean): Create separate issues for subtasks\n- `dryRun` (boolean): Preview without creating\n- `force` (boolean): Overwrite existing GitHub link\n- `linkBack` (boolean): Add Task Master reference to issue\n- `enableSync` (boolean): Enable automatic synchronization\n\n### Response\n```json\n{\n \"success\": true,\n \"data\": {\n \"taskId\": \"42\",\n \"repository\": \"owner/repo\",\n \"issueUrl\": \"https://github.com/owner/repo/issues/123\",\n \"issueNumber\": 123,\n \"exportedAt\": \"2024-01-15T10:30:00.000Z\",\n \"message\": \"Successfully exported task 42 to GitHub issue #123\"\n }\n}\n```\n```\n\n### Performance Testing\n```javascript\n// tests/performance/github-export-performance.test.js\ndescribe('GitHub Export Performance', () => {\n test('should export large task within time limit', async () => {\n const largeTask = createLargeTask(); // Task with many subtasks and long content\n const service = new GitHubExportService('test-token');\n \n const startTime = performance.now();\n await service.exportTask(largeTask, 'owner/repo');\n const endTime = performance.now();\n \n expect(endTime - startTime).toBeLessThan(5000); // Should complete in under 5 seconds\n });\n \n test('should handle concurrent exports', async () => {\n const service = new GitHubExportService('test-token');\n const tasks = Array.from({ length: 5 }, () => createTestTask());\n \n const promises = tasks.map(task => service.exportTask(task, 'owner/repo'));\n const results = await Promise.all(promises);\n \n results.forEach(result => {\n expect(result.success).toBe(true);\n });\n });\n});\n```\n\n### Test Configuration\n```javascript\n// jest.config.js additions\nmodule.exports = {\n // ... existing config\n testEnvironment: 'node',\n setupFilesAfterEnv: ['<rootDir>/tests/setup/github-setup.js'],\n testMatch: [\n '**/tests/**/*.test.js',\n '**/tests/**/*.spec.js'\n ],\n collectCoverageFrom: [\n 'scripts/modules/github/**/*.js',\n 'mcp-server/src/tools/github-*.js',\n 'mcp-server/src/core/direct-functions/github-*.js'\n ],\n coverageThreshold: {\n global: {\n branches: 80,\n functions: 80,\n lines: 80,\n statements: 80\n }\n }\n};\n```\n\n### Continuous Integration\n```yaml\n# .github/workflows/github-export-tests.yml\nname: GitHub Export Tests\n\non: [push, pull_request]\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v3\n - uses: actions/setup-node@v3\n with:\n node-version: '18'\n - run: npm ci\n - run: npm run test:github-export\n env:\n GITHUB_TEST_TOKEN: ${{ secrets.GITHUB_TEST_TOKEN }}\n GITHUB_TEST_REPO: ${{ secrets.GITHUB_TEST_REPO }}\n```",
"status": "pending",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"parentTaskId": 101
}
]
@@ -5366,7 +6061,11 @@
"title": "Implement Tagged Task Lists System for Multi-Context Task Management",
"description": "Develop a comprehensive tagged task lists system enabling users to organize, filter, and manage tasks across multiple contexts (e.g., personal, branch, version) with full backward compatibility.",
"status": "done",
- "dependencies": [3, 11, 19],
+ "dependencies": [
+ 3,
+ 11,
+ 19
+ ],
"priority": "medium",
"details": "1. Extend the tasks.json schema to support a 'tags' structure, with 'master' as the default tag containing all existing tasks. Ensure seamless migration for users without tags.\n2. Add a 'defaultTag' configuration option to config.json in the global section, defaulting to 'master'.\n3. Implement tag management CLI commands: add-tag, delete, list, use (switch), rename, and copy. Each command should update the relevant data structures and persist changes.\n4. Update all existing task commands (list, add-task, set-status, etc.) to accept a --tag flag, filtering or applying actions within the specified tag context.\n5. Implement automatic tag creation from git branch names using a --from-branch flag, integrating with git APIs to detect current branch.\n6. Maintain the current tag state in .taskmaster/state.json with currentTag set to 'master' by default, ensuring session persistence and correct context switching.\n7. Guarantee backward compatibility: users without tags continue to operate in the 'master' context transparently.\n8. Provide comprehensive documentation and migration notes for users, and update help menus to reflect new tag-related features.",
"testStrategy": "- Migrate an existing tasks.json and verify all tasks appear under the 'master' tag.\n- Create, delete, rename, and copy tags using add-tag and other commands; confirm correct data structure updates and persistence.\n- Switch between tags and verify task isolation and context switching.\n- Use --tag flag with all supported commands and confirm correct filtering and operation.\n- Test --from-branch flag by switching git branches and verifying tag creation and selection.\n- Simulate usage without tags to ensure backward compatibility.\n- Review documentation and help menus for accuracy and completeness.\n- Run automated and manual tests for all new and modified commands, including edge cases (e.g., duplicate tag names, tag deletion with tasks).",
@@ -5384,7 +6083,9 @@
"id": 2,
"title": "Implement Seamless Migration for Existing Users",
"description": "Develop a migration script or logic to move existing tasks into the 'master' tag for users upgrading from previous versions.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Ensure no data loss and that users without tags continue to operate transparently.",
"status": "done",
"testStrategy": "Test migration on various legacy datasets and verify task integrity post-migration."
@@ -5393,7 +6094,9 @@
"id": 3,
"title": "Add 'defaultTag' Configuration Option to config.json Global Section",
"description": "Introduce a 'defaultTag' field in the global section of config.json, defaulting to 'master', and update configuration handling logic.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Allow users to set and persist their preferred default tag in the global configuration section.\n<info added on 2025-06-11T20:46:57.669Z>\nAdded global.defaultTag configuration option to .taskmaster/config.json structure in assets/config.json. Implemented complete tags section including autoSwitchOnBranch and gitIntegration options. Created migrateConfigJson() function in utils.js to handle updating existing configuration files during the migration process. Configuration is automatically created and updated during the silent migration process to ensure seamless transition for existing users.\n</info added on 2025-06-11T20:46:57.669Z>",
"status": "done",
"testStrategy": "Check that the default tag is respected on startup and when creating new tasks."
@@ -5402,7 +6105,10 @@
"id": 4,
"title": "Develop Tag Management CLI Commands",
"description": "Implement CLI commands for tag management: add-tag, delete, list, use (switch), rename, and copy, ensuring all changes are persisted.",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Each command should update the tasks.json and config files as needed. The primary command for creating tags should be 'add-tag' to maintain consistency with other task-master commands.\n<info added on 2025-06-12T07:14:51.761Z>\n✅ **COMPLETED: CLI Command Integration for Tag Management**\n\nSuccessfully implemented complete CLI command integration for all tag management functions with enhanced UX features:\n\n**Commands Implemented:**\n\n1. **`task-master tags [--show-metadata]`** - List all available tags\n - Shows tag names, task counts, completion status\n - Optional metadata display (creation date, description)\n - Dynamic table width that adapts to terminal size\n - Current tag indicator with visual highlighting\n\n2. **`task-master add-tag <name> [options]`** - Create new tags\n - `--copy-from-current` - Copy tasks from current tag\n - `--copy-from=<tag>` - Copy tasks from specified tag\n - `-d, --description <text>` - Set tag description\n - **Default behavior: Creates empty tags** (fixed from previous copying behavior)\n\n3. **`task-master delete-tag <name> [--yes]`** - Delete tags with enhanced safety\n - **Changed from `--force` to `--yes`** for consistency\n - **Double confirmation system** using inquirer:\n - First: Yes/No confirmation prompt\n - Second: Type tag name to confirm deletion\n - Visual warning box showing impact\n - Automatic current tag switching if deleting active tag\n\n4. **`task-master use-tag <name>`** - Switch tag contexts\n - Updates current tag in state.json\n - Validates tag existence before switching\n - Clear success messaging\n\n5. **`task-master rename-tag <old> <new>`** - Rename existing tags\n - Validates both source and target names\n - Updates current tag reference if renaming active tag\n\n6. **`task-master copy-tag <source> <target> [options]`** - Copy tags\n - `-d, --description <text>` - Set description for new tag\n - Deep copy of all tasks and metadata\n\n**Key Improvements Made:**\n\nEnhanced User Experience:\n- **Double confirmation for destructive operations** using inquirer prompts\n- **Consistent option naming** (`--yes` instead of `--force`)\n- **Dynamic table layouts** that use full terminal width\n- **Visual warning boxes** for dangerous operations\n- **Contextual help displays** on command errors\n\nTechnical Fixes:\n- **Fixed critical `_rawTaggedData` corruption bug** in readJSON/writeJSON cycle\n- **Dynamic task counting** instead of stored counters (eliminates sync issues)\n- **Master tag metadata enhancement** with creation dates and descriptions\n- **Proper error handling** with command-specific help displays\n\nCLI Integration:\n- **Added all commands to help menu** in ui.js under \"Tag Management\" section\n- **Comprehensive help functions** for each command with examples\n- **Error handlers with contextual help** for better user guidance\n- **Consistent command patterns** following established CLI conventions\n\n**Testing Completed:**\n- ✅ Created empty tags (default behavior)\n- ✅ Created tags with task copying (explicit flags)\n- ✅ Listed tags with and without metadata\n- ✅ Double confirmation for tag deletion\n- ✅ Tag switching and current tag persistence\n- ✅ Table width responsiveness\n- ✅ Master tag metadata enhancement\n- ✅ Error handling and help displays\n\n**Files Modified:**\n- `scripts/modules/commands.js` - Added all tag management commands\n- `scripts/modules/task-manager/tag-management.js` - Enhanced functions with inquirer\n- `scripts/modules/ui.js` - Added tag commands to help menu\n- Fixed critical data corruption bug in utils.js\n\nThe CLI integration is now complete and production-ready with enhanced safety features and improved user experience!\n</info added on 2025-06-12T07:14:51.761Z>",
"status": "done",
"testStrategy": "Unit test each CLI command for correct behavior and data persistence, specifically testing add-tag command."
@@ -5411,7 +6117,9 @@
"id": 5,
"title": "Update Task Commands to Support --tag Flag",
"description": "Modify all existing task-related CLI commands (list, add-task, set-status, etc.) to accept a --tag flag, applying actions within the specified tag context.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Ensure commands filter or apply actions only to tasks within the selected tag.\n<info added on 2025-06-11T18:23:45.185Z>\nDependencies: [4, 13, 14] - Requires CLI commands foundation, MCP tools integration, and state management utilities to properly implement --tag flag support across both CLI and MCP interfaces.\n</info added on 2025-06-11T18:23:45.185Z>\n<info added on 2025-06-12T22:44:17.705Z>\n**CURRENT STATUS ANALYSIS - Commands Needing --tag Flag + projectRoot Fix**\n\nAfter fixing the migration bug in readJSON and updating `list` and `move` commands, here's the current status:\n\n**✅ COMPLETED:**\n- `list` command - Has projectRoot fix + tag support working\n- `move` command - Has projectRoot fix + tag support working \n\n**❌ STILL NEED BOTH --tag FLAG + projectRoot FIX:**\n\n**High Priority (Core Task Operations):**\n1. `show` - View specific tasks (needs tag context)\n2. `add-task` - Create tasks (needs tag context) \n3. `set-status` - Update task status (needs tag context)\n4. `next` - Find next task (needs tag context)\n\n**Medium Priority (Task Modification):**\n5. `update-task` - Update specific task (needs tag context)\n6. `update-subtask` - Update subtask (needs tag context)\n7. `add-subtask` - Add subtasks (needs tag context)\n8. `remove-task` - Remove tasks (needs tag context)\n9. `remove-subtask` - Remove subtasks (needs tag context)\n10. `clear-subtasks` - Clear subtasks (needs tag context)\n11. `expand` - Expand tasks (needs tag context)\n\n**Lower Priority (Dependencies & Analysis):**\n12. `add-dependency` - Add dependencies (needs tag context)\n13. `remove-dependency` - Remove dependencies (needs tag context)\n14. `validate-dependencies` - Validate deps (needs tag context)\n15. `fix-dependencies` - Fix deps (needs tag context)\n16. `generate` - Generate task files (needs tag context)\n17. `analyze-complexity` - Analyze complexity (needs tag context)\n18. `complexity-report` - View complexity report (needs tag context)\n\n**✅ DON'T NEED TAG SUPPORT:**\n- `init`, `models`, `parse-prd`, `research`, `migrate`, `sync-readme`\n- Tag management commands (they manage tags themselves)\n\n**NEXT STEPS:**\n1. Start with high-priority commands (`show`, `add-task`, `set-status`, `next`)\n2. Add `--tag` flag to each command\n3. Ensure `findProjectRoot()` is called and passed to underlying functions\n4. Update underlying functions to accept and use projectRoot parameter\n5. Test migration and tag resolution for each command\n\n**PATTERN TO FOLLOW:**\nSame pattern as `list` and `move` commands:\n- Add `--tag` option to CLI command\n- Call `findProjectRoot()` in action function\n- Pass `{ projectRoot }` context to underlying function\n- Update underlying function signature to accept context parameter\n- Pass projectRoot to readJSON/writeJSON calls\n</info added on 2025-06-12T22:44:17.705Z>\n<info added on 2025-06-12T22:47:22.415Z>\n**PROGRESS UPDATE - show Command Completed Successfully**\n\n✅ **COMPLETED: `show` command**\n- Added `--tag` flag support to CLI command\n- Fixed `findProjectRoot()` call and projectRoot passing\n- Updated `displayTaskById` function to accept context parameter with projectRoot\n- Updated `displayMultipleTasksSummary` function to accept context parameter\n- Fixed readJSON calls to include projectRoot for proper tag resolution and migration\n- **TESTED SUCCESSFULLY**: `task-master show 103` works perfectly with no errors\n\n**TECHNICAL DETAILS:**\n- CLI command now calls `findProjectRoot()` and passes `{ projectRoot, tag }` context\n- UI functions extract projectRoot from context and pass to `readJSON(tasksPath, projectRoot, tag)`\n- Migration logic now works correctly when viewing tasks\n- Both single task and multiple task views work properly\n\n**UPDATED STATUS - 1 of 4 High-Priority Commands Complete:**\n1. ✅ `show` - **COMPLETED** \n2. ❌ `add-task` - Create tasks (needs tag context)\n3. ❌ `set-status` - Update task status (needs tag context) \n4. ❌ `next` - Find next task (needs tag context)\n\n**NEXT ACTION:** Continue with `add-task` command following the same proven pattern:\n- Add `--tag` flag to CLI command\n- Call `findProjectRoot()` in action function \n- Pass `{ projectRoot, tag }` context to underlying function\n- Update underlying function to accept context and pass projectRoot to readJSON/writeJSON\n</info added on 2025-06-12T22:47:22.415Z>\n<info added on 2025-06-12T22:49:16.724Z>\n**PROGRESS UPDATE - add-task Command Completed Successfully**\n\n✅ **COMPLETED: `add-task` command**\n- Already had `--tag` flag support in CLI command\n- Already had `findProjectRoot()` call and projectRoot passing\n- Already had proper context object with `{ projectRoot, tag }`\n- Underlying `addTask` function already properly handles tag parameter and projectRoot\n- **TESTED SUCCESSFULLY**: `task-master add-task --prompt=\"Test task for tag support\" --priority=low` works perfectly with no errors\n\n**TECHNICAL DETAILS:**\n- CLI command already calls `findProjectRoot()` and passes `{ projectRoot, tag }` context\n- `addTask` function extracts projectRoot from context and passes to `readJSON(tasksPath, projectRoot)`\n- Migration logic works correctly when adding tasks\n- Tag resolution and context handling work properly\n\n**COMPLETED HIGH-PRIORITY COMMANDS:**\n1. ✅ `show` - **COMPLETED** \n2. ✅ `add-task` - **COMPLETED**\n3. ❌ `set-status` - Update task status (needs tag context)\n4. ❌ `next` - Find next task (needs tag context)\n\n**REMAINING WORK:**\nNext commands to fix: `set-status` and `next` commands following the same pattern.\n</info added on 2025-06-12T22:49:16.724Z>\n<info added on 2025-06-13T02:48:17.985Z>\n**FINAL PROGRESS UPDATE - Tag Management Issues Resolved**\n\n✅ **COMPLETED: All Tag Management Issues Fixed**\n\n**Major Issues Resolved:**\n1. **Rogue `\"created\"` property cleanup** - Fixed root-level `\"created\"` property in master tag that was outside metadata\n2. **Tags command error fixed** - Resolved undefined `taskCount` error by making calculation dynamic\n3. **Data corruption prevention** - Enhanced `writeJSON` to automatically filter rogue properties during write operations\n\n**Technical Fixes Applied:**\n- **Enhanced `writeJSON` function** to automatically clean up rogue `created` and `description` properties from tag objects\n- **Fixed `taskCount` calculation** to be dynamic (`tasks.length`) instead of hardcoded field\n- **Cleaned up existing corruption** in master tag through forced write operation\n- **All `created` properties** now properly located in `metadata` objects only\n\n**Commands Status Update:**\n✅ **COMPLETED HIGH-PRIORITY COMMANDS:**\n1. ✅ `show` - Added --tag flag + fixed projectRoot passing\n2. ✅ `add-task` - Already had proper tag support \n3. ✅ `list` - Already had proper tag support\n4. ✅ `move` - Already had proper tag support\n5. ✅ `tags` - Fixed errors and working perfectly\n\n**REMAINING COMMANDS TO FIX:**\n❌ `set-status` - Update task status (needs tag context)\n❌ `next` - Find next task (needs tag context)\n❌ `update-task` - Update specific task (needs tag context)\n❌ `update-subtask` - Update subtask (needs tag context)\n❌ `add-subtask` - Add subtasks (needs tag context)\n❌ `remove-task` - Remove tasks (needs tag context)\n❌ `remove-subtask` - Remove subtasks (needs tag context)\n\n**Data Integrity Status:**\n- ✅ Migration logic working correctly\n- ✅ Tag creation/deletion working with proper metadata\n- ✅ File corruption prevention active\n- ✅ Automatic cleanup during write operations\n- ✅ Tagged task lists system fully functional\n\n**Next Steps:** Continue with remaining commands (set-status, next, etc.) to complete task 103.5\n</info added on 2025-06-13T02:48:17.985Z>\n<info added on 2025-06-13T03:57:35.440Z>\n**CRITICAL BUG FIX & PROGRESS UPDATE**\n\n✅ **COMPLETED: Fixed critical tag-deletion bug** affecting `add-subtask` and likely other commands.\n- **Root Cause:** The core `writeJSON` function was not accepting `projectRoot` and `tag` parameters, causing it to overwrite the entire `tasks.json` file with only the data for the current tag, deleting all other tags.\n- **The Fix:** The `writeJSON` signature and logic have been corrected to properly accept `projectRoot` and `tag` context. It now correctly merges resolved tag data back into the full tagged data structure before writing, preserving data integrity.\n- **Impact:** This single, critical fix likely resolves the tag-deletion bug for all commands that modify the tasks file.\n\n**UPDATED COMMAND STATUS:**\nMany commands previously listed as \"remaining\" are now likely fixed due to the `writeJSON` correction.\n\n- ✅ `list`, `show`, `add-task`, `move`\n- ✅ `add-subtask` (tested and confirmed fixed)\n- ❓ **Likely Fixed (Pending Confirmation):** `set-status`, `remove-task`, `remove-subtask`, `clear-subtasks`, `update-task`, `update-subtask`, `expand`, `generate`, and all dependency commands.\n\n**NEXT STEPS:**\nSystematically test the \"Likely Fixed\" commands to confirm they no longer corrupt the `tasks.json` file. Then, implement the `--tag` flag for those that still need it.\n</info added on 2025-06-13T03:57:35.440Z>\n<info added on 2025-06-13T03:58:43.036Z>\n**PROGRESS UPDATE - `set-status` command verified**\n\n✅ **COMPLETED: `set-status` command is confirmed fixed.**\n- **Test:** Created a new tag, ran `set-status` on an existing task, and verified that the new tag was NOT deleted.\n- **Confirmation:** The underlying fix to the `writeJSON` function correctly preserves the full tagged data structure.\n\n**UPDATED COMMAND STATUS:**\n- ✅ `list`, `show`, `add-task`, `move`, `add-subtask`\n- ✅ `set-status` **(Newly Verified)**\n- ❓ **Likely Fixed (Pending Confirmation):** `remove-task`, `remove-subtask`, `clear-subtasks`, `update-task`, `update-subtask`, `expand`, `generate`, and all dependency commands.\n\n**NEXT STEPS:**\nContinue systematically testing the remaining commands. Next up is `remove-task`.\n</info added on 2025-06-13T03:58:43.036Z>\n<info added on 2025-06-13T04:01:04.367Z>\n**PROGRESS UPDATE - `remove-task` command fixed**\n\n✅ **COMPLETED: `remove-task` command has been fixed and is now fully tag-aware.**\n- **CLI Command:** Updated `remove-task` in `commands.js` to include the `--tag` option and pass `projectRoot` and `tag` context to the core function.\n- **Core Function:** Refactored the `removeTask` function in `scripts/modules/task-manager/remove-task.js`.\n - It now accepts a `context` object.\n - It reads the raw tagged data structure using `readJSON` with the correct context.\n - It operates only on the tasks within the specified (or current) tag.\n - It correctly updates the full `rawData` object before writing.\n - It calls `writeJSON` and `generateTaskFiles` with the correct context to prevent data corruption.\n- **Impact:** The `remove-task` command should no longer cause tag deletion or data corruption.\n\n**UPDATED COMMAND STATUS:**\n- ✅ `list`, `show`, `add-task`, `move`, `add-subtask`, `set-status`\n- ✅ `remove-task` **(Newly Fixed)**\n- ❓ **Likely Fixed (Pending Confirmation):** `remove-subtask`, `clear-subtasks`, `update-task`, `update-subtask`, `expand`, `generate`, and all dependency commands.\n\n**NEXT STEPS:**\nTest the `remove-task` command to verify the fix. Then continue with the remaining commands.\n</info added on 2025-06-13T04:01:04.367Z>\n<info added on 2025-06-13T04:13:22.909Z>\n**FINAL COMPLETION STATUS - All Critical Data Corruption Bugs Resolved**\n\nThe root cause of the tag deletion bug has been identified and fixed in the `generateTaskFiles` function. This function was incorrectly reading a single tag's data and then causing `validateAndFixDependencies` to overwrite the entire `tasks.json` file.\n\n**The Core Fix:**\n- `generateTaskFiles` has been refactored to be fully tag-aware\n- It now reads the complete raw data structure, preserving all tags\n- It performs its operations (validation, file generation) only on the tasks of the specified tag, without affecting other tags\n- This prevents the data corruption that was affecting `add-task`, `add-subtask`, and likely other commands\n\n**System Stability Achieved:**\nThe critical `writeJSON` and `generateTaskFiles` fixes have stabilized the entire system. All commands that modify `tasks.json` are now safe from data corruption.\n\n**Final Command Status - All Core Commands Working:**\n✅ `list`, `show`, `add-task`, `move`, `add-subtask`, `set-status`, `remove-task` - All confirmed working correctly without causing data loss\n✅ All other commands are presumed stable due to the core infrastructure fixes\n\n**Tagged Task List System Status: STABLE**\nThe tagged task list system is now considered stable and production-ready for all primary task modification commands. The --tag flag implementation is complete and functional across the command suite.\n</info added on 2025-06-13T04:13:22.909Z>\n<info added on 2025-06-13T07:01:11.925Z>\n**MAJOR MILESTONE ACHIEVED - Tagged Command Implementation Complete!**\n\n✅ **CRITICAL BUG FIXES COMPLETED:**\n- Fixed parse-prd data corruption bug that was deleting other tags\n- Enhanced tag preservation logic in both parse-prd.js and commands.js\n- Fixed confirmation logic to check tag-specific task existence (not just file existence)\n\n✅ **PARSE-PRD TAG SUPPORT - FULLY WORKING:**\n- parse-prd --tag=feature-name: Creates tasks in specific tag contexts\n- Non-existent tags are created automatically and silently\n- Existing tags are preserved during new tag creation\n- Append mode works correctly within tag contexts\n- Smart confirmation only prompts when target tag has existing tasks\n\n✅ **ANALYZE-COMPLEXITY TAG SUPPORT - FULLY WORKING:**\n- analyze-complexity --tag=branch: Generates tag-specific reports\n- File naming: master → task-complexity-report.json, others → task-complexity-report_tagname.json\n- complexity-report --tag=branch: Reads from correct tag-specific report file\n- Complete isolation between different tag contexts\n\n✅ **COMPREHENSIVE TESTING COMPLETED:**\n- Tested parse-prd with new tag creation (test-prd-tag)\n- Tested parse-prd with append mode (added 2 more tasks to existing 3)\n- Tested analyze-complexity with tag-specific report generation\n- Tested complexity-report with tag-specific report reading\n- Verified tag preservation and no data corruption across all operations\n\n✅ **CHANGESET & COMMIT COMPLETED:**\n- Updated changeset to describe new tag features (minor version bump)\n- Committed comprehensive changes with detailed commit message\n- All changes properly documented and versioned\n\n🚀 **SYSTEM IMPACT:**\nThe core tagged task lists system is now complete and production-ready! Users can:\n- Parse PRDs into separate contexts on the fly: parse-prd --tag=feature-branch\n- Generate isolated complexity reports: analyze-complexity --tag=experiment\n- Work across multiple project contexts without conflicts\n- Enable rapid prototyping and parallel development workflows\n\n**TAGGED COMMAND SUITE STATUS: COMPLETE**\nAll critical commands now support --tag flag with full data integrity preservation. The tagged task management system is stable and ready for advanced workflow integration.\n</info added on 2025-06-13T07:01:11.925Z>",
"status": "done",
"testStrategy": "Test each command with and without the --tag flag for correct scoping."
@@ -5420,7 +6128,9 @@
"id": 6,
"title": "Integrate Automatic Tag Creation from Git Branches",
"description": "Implement logic to create tags based on git branch names using a --from-branch flag, integrating with git APIs to detect the current branch.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Enable seamless context switching between code branches and task tags. Use add-tag internally when creating tags from branch names.\n<info added on 2025-06-13T17:27:34.449Z>\n**Code Context Analysis Complete**\n\n**Current State:**\n- `state.json` has `branchTagMapping: {}` ready for storing git branch to tag mappings\n- `config.json` has `tags.enabledGitworkflow: false` and `tags.autoSwitchTagWithBranch: false` controls\n- Existing tag management functions in `scripts/modules/task-manager/tag-management.js` provide `createTag`, `useTag`, `switchCurrentTag` utilities\n- No existing git integration - need to add git CLI dependencies\n\n**Implementation Plan:**\n\n1. **Add Git Dependencies**: Add `simple-git` package for git operations (better than calling CLI directly)\n2. **Create Git Utilities Module**: `scripts/modules/utils/git-utils.js` with functions:\n - `getCurrentBranch()` - Get current git branch name\n - `isGitRepository()` - Check if we're in a git repo\n - `getBranchList()` - Get list of all branches\n - `onBranchChange()` - Hook for branch change detection\n\n3. **Enhance Tag Management**: Add git integration functions:\n - `createTagFromBranch(branchName)` - Create tag from git branch name\n - `autoSwitchTagForBranch()` - Auto-switch tag when branch changes\n - `updateBranchTagMapping()` - Update state.json mapping\n\n4. **Add CLI Commands**:\n - `--from-branch` flag for `add-tag` command\n - `task-master sync-git` command for manual git-tag synchronization\n\n5. **Configuration Integration**: \n - Check `config.tags.enabledGitworkflow` before git operations\n - Use `config.tags.autoSwitchTagWithBranch` for automatic switching\n\n**Next Steps**: Start with adding simple-git dependency and creating git utilities module.\n</info added on 2025-06-13T17:27:34.449Z>\n<info added on 2025-06-13T17:45:03.727Z>\n**Updated Implementation Strategy - Automatic Git Integration**\n\n**Revised Approach:**\n- Eliminate manual `sync-git` command for seamless user experience\n- Implement automatic git-tag synchronization following the established migration pattern\n- Integration occurs transparently during normal task operations without user intervention\n- Behavior controlled entirely through existing configuration flags\n\n**Updated Implementation Plan:**\n\n1. **Simplified Git Dependencies**: Keep `simple-git` package for git operations\n\n2. **Enhanced Git Utilities Module**: `scripts/modules/utils/git-utils.js` with streamlined functions:\n - `getCurrentBranch()` - Get current git branch name\n - `isGitRepository()` - Check if we're in a git repo\n - `shouldAutoSync()` - Check if git workflow is enabled and conditions are met\n\n3. **Automatic Integration Hook**: \n - Add `checkAndSyncGitTags()` function to utils.js\n - Integrate into `readJSON()` similar to migration system\n - Automatically create tags from branch names when conditions are met\n - Update branch-tag mappings in state.json transparently\n\n4. **Streamlined Tag Management**: Remove complex CLI additions:\n - No `--from-branch` flag needed for `add-tag`\n - No manual `sync-git` command\n - Automatic tag creation and switching based on git context\n\n5. **Configuration-Driven Behavior**:\n - `config.tags.enabledGitworkflow` enables/disables entire system\n - `config.tags.autoSwitchTagWithBranch` controls automatic tag switching\n - Silent operation when disabled, seamless when enabled\n\n**Benefits**: Zero-friction git integration that \"just works\" when enabled, following established project patterns for automatic system enhancements.\n</info added on 2025-06-13T17:45:03.727Z>\n<info added on 2025-06-13T17:50:24.997Z>\n**✅ IMPLEMENTATION COMPLETED**\n\n**Final Implementation Summary:**\n\n1. **Proper Module Organization**: \n - Moved `checkAndAutoSwitchGitTag` function to correct location in `scripts/modules/utils/git-utils.js`\n - Updated imports in `utils.js` to use the git-utils version\n - Maintains clean separation of concerns with git operations in dedicated module\n\n2. **Seamless Integration Architecture**:\n - Function automatically executes during `readJSON()` operations\n - Integrates with both migration system and normal tagged format processing\n - Zero user intervention required - works transparently in background\n\n3. **Smart Git-Tag Synchronization**:\n - Automatically switches to existing tags matching current branch names\n - Creates new tags for branches without corresponding tags\n - Updates `state.json` branch-tag mappings for persistent tracking\n - Validates branch names (excludes main/master/develop/dev/HEAD)\n\n4. **Configuration-Driven Operation**:\n - Controlled by `config.tags.enabledGitworkflow` and `config.tags.autoSwitchTagWithBranch` flags\n - Silent operation when disabled, seamless when enabled\n - Uses `console.debug` for error handling to avoid disrupting normal operations\n\n5. **MCP-Compatible Design**:\n - All functions require `projectRoot` parameter for MCP compatibility\n - Leverages existing git utility functions (`isGitRepository`, `getCurrentBranch`, `isValidBranchForTag`, `sanitizeBranchNameForTag`)\n - Follows established project patterns for automatic system enhancements\n\n**Status**: Implementation complete and ready for production use. Users can enable automatic git integration by configuring the appropriate flags in `.taskmaster/config.json`.\n</info added on 2025-06-13T17:50:24.997Z>\n<info added on 2025-06-14T01:01:52.559Z>\n**SCOPE SIMPLIFIED: Basic CLI Git Integration Only**\n\n**Implementation Status Changed:**\n- **CANCELLED**: All automatic git-tag synchronization features\n- **CANCELLED**: Configuration-driven git workflow automation \n- **CANCELLED**: Silent background git integration\n- **CANCELLED**: Branch-tag mapping persistence and auto-switching\n\n**COMPLETED: Core Git Utilities**\n- Git utilities module with MCP-compatible functions ready\n- Branch name sanitization and validation implemented\n- Git repository detection working\n\n**REMAINING WORK: CLI Integration**\n- Add `--from-branch` flag to `add-tag` command in `scripts/modules/commands.js`\n- Integrate existing git utilities with tag creation workflow\n- Enable `task-master add-tag --from-branch` command functionality\n\n**Final Simplified Scope:**\nSingle explicit command: `task-master add-tag --from-branch`\n- Detects current git branch name\n- Sanitizes branch name to valid tag format\n- Creates new tag with sanitized name\n- No automation, no background processes, no persistent mappings\n\n**Benefits**: Explicit user control, predictable behavior, simple implementation, easy debugging, clear separation of concerns between git and task management.\n\n**Next Step**: Implement CLI flag integration to complete the simplified git integration feature.\n</info added on 2025-06-14T01:01:52.559Z>",
"status": "done",
"testStrategy": "Test tag creation and switching in repositories with multiple branches."
@@ -5429,7 +6139,9 @@
"id": 7,
"title": "Update State Management for Current Tag Tracking",
"description": "Ensure .taskmaster/state.json properly tracks the current tag with currentTag field set to 'master' by default during initialization.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Update initialization logic to create state.json with currentTag set to 'master', ensuring the state file accurately reflects the active tag across sessions.\n<info added on 2025-06-11T20:49:28.104Z>\nSTATE MANAGEMENT: Updated scripts/init.js to create state.json during initialization with proper initial state: currentTag: 'master', lastSwitched timestamp, branchTagMapping, migrationNoticeShown flag. createStateJson() function in utils.js handles state file creation during migration. State management integrated into complete migration system.\n</info added on 2025-06-11T20:49:28.104Z>",
"status": "done",
"testStrategy": "Verify state persistence after restarts and tag switches, confirm initialization creates proper currentTag field."
@@ -5438,7 +6150,9 @@
"id": 8,
"title": "Ensure Full Backward Compatibility",
"description": "Guarantee that users without tags continue to operate in the 'master' context without disruption or required changes.",
- "dependencies": [7],
+ "dependencies": [
+ 7
+ ],
"details": "Test all workflows for legacy users and ensure no regressions.",
"status": "done",
"testStrategy": "Regression test with legacy data and workflows."
@@ -5447,7 +6161,9 @@
"id": 9,
"title": "Update Documentation and Help Menus",
"description": "Revise user documentation, migration notes, and CLI help menus to reflect new tag-related features and usage patterns, specifically documenting the add-tag command.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Provide clear instructions and examples for all tag management features, ensuring add-tag command is properly documented with consistent naming.",
"status": "done",
"testStrategy": "Review documentation for completeness and clarity; user acceptance testing."
@@ -5467,7 +6183,10 @@
"description": "Implement core tag management functions in scripts/modules/task-manager/ following the established pattern. Include functions for createTag, deleteTag, listTags, useTag, renameTag, copyTag, and tag resolution logic.",
"details": "",
"status": "done",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"parentTaskId": 103
},
{
@@ -5476,7 +6195,9 @@
"description": "Create MCP direct function wrappers in mcp-server/src/core/direct-functions/ for all tag management operations, following the established pattern like add-task.js",
"details": "<info added on 2025-06-13T14:32:43.186Z>\nSuccessfully implemented all 6 MCP direct function wrappers in `mcp-server/src/core/direct-functions/`:\n\n**Created Files:**\n1. **`add-tag.js`** - Direct function for creating new tags with options for copying tasks and descriptions\n2. **`delete-tag.js`** - Direct function for deleting tags with automatic confirmation bypass for MCP\n3. **`list-tags.js`** - Direct function for listing all tags with optional metadata display\n4. **`use-tag.js`** - Direct function for switching current tag context\n5. **`rename-tag.js`** - Direct function for renaming existing tags\n6. **`copy-tag.js`** - Direct function for copying tags with all tasks and metadata\n\n**Integration Completed:**\n- Updated `mcp-server/src/core/task-master-core.js` to import and export all new direct functions\n- Added all functions to the directFunctions Map for dynamic dispatch\n- Followed established patterns from existing direct functions (add-task.js, etc.)\n\n**Key Features Implemented:**\n- **Silent Mode Management**: All functions properly enable/disable silent mode for MCP responses\n- **Error Handling**: Comprehensive error handling with structured error codes and messages\n- **Parameter Validation**: Full validation of required parameters with helpful error messages\n- **Logger Integration**: Proper MCP logger wrapper integration using createLogWrapper utility\n- **JSON Output**: All functions return structured JSON responses suitable for MCP clients\n- **Context Support**: Full session and projectRoot context support for all operations\n\n**Technical Details:**\n- All functions accept `tasksJsonPath`, `projectRoot`, and operation-specific parameters\n- Proper async/await error handling with silent mode restoration in finally blocks\n- Consistent return format: `{ success: boolean, data?: any, error?: { code: string, message: string } }`\n- Integration with existing tag management functions from `scripts/modules/task-manager/tag-management.js`\n\nThe MCP direct function layer is now complete and ready for MCP tool integration in the next phase.\n</info added on 2025-06-13T14:32:43.186Z>",
"status": "done",
- "dependencies": [11],
+ "dependencies": [
+ 11
+ ],
"parentTaskId": 103
},
{
@@ -5485,7 +6206,9 @@
"description": "Implement MCP tools in mcp-server/src/tools/ for all tag management operations (add-tag, delete-tag, list-tags, use-tag, rename-tag, copy-tag), following the established pattern like add-task.js",
"details": "",
"status": "done",
- "dependencies": [12],
+ "dependencies": [
+ 12
+ ],
"parentTaskId": 103
},
{
@@ -5494,7 +6217,10 @@
"description": "Implement utilities for reading/writing current tag state, tag resolution logic (currentTag from state -> --tag flag -> defaultTag fallback), and state file validation",
"details": "",
"status": "done",
- "dependencies": [3, 7],
+ "dependencies": [
+ 3,
+ 7
+ ],
"parentTaskId": 103
},
{
@@ -5503,7 +6229,9 @@
"description": "Create specific migration logic to transform existing tasks.json format (array of tasks) to the new tagged format ({tags: {master: {tasks: [...]}}}). Include validation and rollback capabilities.",
"details": "<info added on 2025-06-11T20:50:25.721Z>\nMIGRATION LOGIC: Implemented in scripts/modules/utils.js with performCompleteTagMigration(), migrateConfigJson(), createStateJson(), and markMigrationForNotice() functions. Silent migration triggers on readJSON() for tasks.json files. Migration notice system implemented in commands.js with displayTaggedTasksFYI() from ui.js. Complete 3-part migration: tasks.json + config.json + state.json all handled automatically.\n</info added on 2025-06-11T20:50:25.721Z>",
"status": "done",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"parentTaskId": 103
},
{
@@ -5512,7 +6240,10 @@
"description": "Update all documentation in /docs to reflect the new tagged task lists architecture and migration system",
"details": "Update docs to be aware of the new tagged structure: - Update command-reference.md with new tag-related commands - Update task-structure.md to explain tagged format - Update configuration.md with tagged system config - Update tutorial.md with tagged workflow - Update migration-guide.md for tagged migration - Ensure all examples reflect new structure\n<info added on 2025-06-11T21:12:52.662Z>\nCOMPLETED: All documentation files have been successfully updated to reflect the tagged task lists system. Key updates include:\n\n- docs/task-structure.md: Added complete tagged format explanation, data structure overview, migration details, and best practices\n- docs/configuration.md: Updated with tagged system configuration, state management, and new settings\n- docs/migration-guide.md: Added comprehensive tagged system migration process, verification steps, and team coordination guidelines\n- .cursor/rules/*.mdc files: Updated architecture.mdc, dev_workflow.mdc, taskmaster.mdc, tasks.mdc, utilities.mdc, new_features.mdc, git_workflow.mdc, and glossary.mdc to be aware of tagged system\n\nAll documentation now properly reflects Part 1 implementation and prepares for Part 2 features. Documentation is fully aligned with the new tagged task structure.\n</info added on 2025-06-11T21:12:52.662Z>",
"status": "done",
- "dependencies": ["103.8", "103.9"],
+ "dependencies": [
+ "103.8",
+ "103.9"
+ ],
"parentTaskId": 103
},
{
@@ -5549,7 +6280,12 @@
"title": "Implement 'scope-up' and 'scope-down' CLI Commands for Dynamic Task Complexity Adjustment",
"description": "Add new CLI commands 'scope-up' and 'scope-down' to enable users to dynamically increase or decrease the complexity of tasks or subtasks, with support for multiple IDs, strength levels, milestone-aware adjustments, and custom prompts for targeted modifications.",
"status": "done",
- "dependencies": [3, 11, 19, 94],
+ "dependencies": [
+ 3,
+ 11,
+ 19,
+ 94
+ ],
"priority": "high",
"details": "1. Extend the CLI (commands.js) to introduce 'scope-up' and 'scope-down' commands, following established subcommand patterns for consistency and discoverability. \n2. Accept comma-separated task/subtask IDs and an optional '--strength' flag (light|regular|heavy, defaulting to regular). Validate all inputs, ensuring referenced tasks/subtasks exist and strength is valid.\n3. Implement a '--prompt' flag that allows users to specify custom instructions for how to scope up/down tasks, including targeting specific parts of tasks/subtasks (e.g., removing unnecessary test sections, focusing on particular implementation aspects).\n4. Fetch current task details and associated milestone context to inform the adjustment logic.\n5. Implement core logic functions that:\n - Construct context-aware AI prompts for scaling complexity up or down, leveraging the current state, project phase, strength parameter, and any user-provided custom prompt.\n - Call the unified AI service (ai-services-unified.js) to generate new task/subtask content at the desired complexity level.\n - Replace existing task details and subtasks with the AI-generated output, preserving historical versions for rollback/comparison.\n - Ensure task dependency integrity and update tasks.json and related files accordingly.\n6. Integrate robust error handling for invalid IDs, parameters, or AI failures, and provide clear CLI output showing before/after differences.\n7. Add corresponding MCP tool equivalents for integrated environments and update documentation/help text to reflect new commands and usage patterns.\n8. Ensure compatibility with batch operations, milestone-based guidelines, and existing task management workflows.",
"testStrategy": "- Write unit and integration tests for both 'scope-up' and 'scope-down' commands, covering single and multiple ID scenarios, all strength levels, custom prompts, and edge cases (e.g., non-existent IDs, invalid strength values).\n- Test various custom prompt scenarios, including prompts that target specific sections of tasks/subtasks for modification.\n- Simulate CLI usage to verify correct parsing, validation, and error handling.\n- Test AI prompt construction and output integration, ensuring that task complexity is adjusted as expected for each strength level, milestone context, and custom prompt.\n- Verify that historical data is preserved and that before/after summaries are accurate and clear.\n- Confirm that task dependencies remain intact and that batch operations work as intended.\n- Validate MCP tool integration and documentation updates.",
@@ -5567,7 +6303,9 @@
"id": 2,
"title": "Implement task/subtask retrieval and context gathering",
"description": "Create functions to retrieve task/subtask details and gather relevant context information needed for complexity adjustment.",
- "dependencies": ["104.1"],
+ "dependencies": [
+ "104.1"
+ ],
"details": "1. Implement a function to fetch task and subtask details by ID from tasks.json\n2. Create a function to gather milestone context for the specified tasks\n3. Implement validation to ensure all specified IDs exist and are valid\n4. Add error handling for missing or invalid tasks/subtasks\n5. Create a data structure to hold the original task state for later comparison\n6. Implement functions to determine if an ID refers to a task or subtask\n7. Add support for handling multiple IDs in a single command execution",
"status": "done",
"testStrategy": "Test task and subtask retrieval with various ID formats. Verify correct handling of both task and subtask IDs. Test error cases like non-existent IDs and malformed ID strings."
@@ -5576,7 +6314,9 @@
"id": 3,
"title": "Develop core complexity adjustment logic",
"description": "Implement the core functions that construct AI prompts and process responses to adjust task complexity up or down.",
- "dependencies": ["104.2"],
+ "dependencies": [
+ "104.2"
+ ],
"details": "1. Create separate handler functions for scope-up and scope-down operations\n2. Implement prompt construction logic that incorporates:\n - Current task/subtask details\n - Milestone context\n - Strength parameter (light/regular/heavy)\n - User-provided custom prompt\n3. Add integration with ai-services-unified.js to generate new content\n4. Implement response parsing to extract updated task details\n5. Create utility functions to determine how much to increase/decrease complexity based on strength\n6. Add special handling for different task components (description, implementation details, test strategy)",
"status": "done",
"testStrategy": "Test prompt construction with various inputs and strength levels. Mock AI service responses to test parsing logic. Verify that different strength levels produce appropriately scaled adjustments."
@@ -5585,7 +6325,9 @@
"id": 4,
"title": "Implement task update and persistence logic",
"description": "Create functions to update tasks/subtasks with new content while preserving integrity and handling dependencies.",
- "dependencies": ["104.3"],
+ "dependencies": [
+ "104.3"
+ ],
"details": "1. Implement functions to update task and subtask objects with new content\n2. Create logic to preserve task dependency integrity during updates\n3. Add version history tracking to store previous versions of tasks\n4. Implement file writing functions to persist changes to tasks.json\n5. Add validation to ensure updated tasks maintain required fields and format\n6. Implement rollback capability in case of errors\n7. Create utility functions to display before/after differences in the CLI\n8. Add support for batch updates when multiple IDs are provided",
"status": "done",
"testStrategy": "Test task updates with various scenarios including single tasks, subtasks, and multiple items. Verify that dependencies remain intact after updates. Test rollback functionality by simulating errors during the update process."
@@ -5594,7 +6336,9 @@
"id": 5,
"title": "Integrate with MCP tool and add comprehensive error handling",
"description": "Add MCP tool equivalents for the new commands and implement robust error handling throughout the implementation.",
- "dependencies": ["104.4"],
+ "dependencies": [
+ "104.4"
+ ],
"details": "1. Create MCP tool equivalents for scope-up and scope-down commands\n2. Implement comprehensive error handling for all potential failure points:\n - Network errors during AI service calls\n - Invalid task/subtask IDs\n - Malformed AI responses\n - File system errors\n3. Add clear user feedback with colorized output showing differences\n4. Implement progress indicators for longer operations\n5. Update documentation to include the new commands\n6. Add examples of common usage patterns to help text\n7. Ensure compatibility with existing task management workflows\n8. Add logging integration using the existing logging system\n<info added on 2025-08-02T14:00:38.363Z>\nMCP Integration Complete:\n\n✅ **Direct Functions Created:**\n- Created `mcp-server/src/core/direct-functions/scope-up.js` - Direct function wrapper for scope-up functionality\n- Created `mcp-server/src/core/direct-functions/scope-down.js` - Direct function wrapper for scope-down functionality\n- Both follow the exact same pattern as add-task direct function with proper error handling and silent mode\n\n✅ **MCP Tools Created:**\n- Created `mcp-server/src/tools/scope-up.js` - MCP tool for scope_up_task \n- Created `mcp-server/src/tools/scope-down.js` - MCP tool for scope_down_task\n- Both follow the exact same pattern as add-task tool with proper Zod schema validation\n\n✅ **Integration Updates:**\n- Added imports and exports to `mcp-server/src/core/task-master-core.js` for both direct functions\n- Added imports and registrations to `mcp-server/src/tools/index.js` in Group 5: Task Creation & Modification\n- Tools will be available as `mcp_task-master-ai_scope_up_task` and `mcp_task-master-ai_scope_down_task` after MCP server restart\n\n✅ **Tool Parameters:**\n- `id`: Comma-separated list of task IDs (required)\n- `strength`: light/regular/heavy (optional, defaults to regular) \n- `prompt`: Custom scoping instructions (optional)\n- `file`: Path to tasks.json (optional, auto-detected)\n- `projectRoot`: Absolute project path (required)\n- `tag`: Tag context (optional, uses current tag)\n- `research`: Enable research mode (optional, defaults to false)\n\n✅ **Error Handling:**\n- Comprehensive error handling for missing parameters, invalid task IDs, AI failures\n- Structured error responses with appropriate error codes\n- Silent mode handling to prevent CLI output interference\n\n**Status**: MCP integration complete. Requires MCP server restart for new tools to become available.\n</info added on 2025-08-02T14:00:38.363Z>",
"status": "done",
"testStrategy": "Test error handling by simulating various failure conditions. Verify that appropriate error messages are displayed. Test MCP tool integration and ensure consistent behavior between CLI and MCP interfaces. Perform end-to-end testing with real tasks to verify the complete workflow."
@@ -5617,7 +6361,9 @@
"details": "Implement TTS functionality including:\n- Add --tts flag to all relevant taskmaster commands (list, show, generate, etc.)\n- Integrate with system TTS engines (Windows SAPI, macOS say command, Linux espeak/festival)\n- Create TTS configuration options in the configuration management system\n- Add voice selection options (male/female, different languages if available)\n- Implement audio output settings (volume, speed, pitch)\n- Add TTS-specific error handling for cases where TTS is unavailable\n- Create fallback behavior when TTS fails (silent failure or text output)\n- Support for reading task titles, descriptions, and status updates aloud\n- Add option to read entire task lists or individual task details\n- Implement TTS for command confirmations and error messages\n- Create TTS output formatting to make spoken text more natural (removing markdown, formatting numbers/dates appropriately)\n- Add configuration option to enable/disable TTS globally\n<info added on 2025-06-14T21:55:53.499Z>\nAdd comprehensive testing strategy for TTS functionality:\n\n**TTS Testing Requirements:**\n- Test TTS flag functionality across all commands (list, show, generate) with various voice configurations\n- Validate TTS engine integration on different platforms (Windows SAPI, macOS say, Linux espeak/festival)\n- Test voice selection options and audio output settings (volume, speed, pitch) with edge cases\n- Verify TTS error handling when engines are unavailable or fail\n- Test fallback behavior scenarios (silent failure vs text output)\n- Validate TTS output formatting for natural speech (markdown removal, number/date pronunciation)\n- Test global TTS enable/disable configuration settings\n- Verify TTS works correctly with task titles, descriptions, and status updates of varying lengths and complexity\n- Test TTS performance with large task lists and individual task details\n- Validate TTS for command confirmations and error messages across different error scenarios\n\n**Automated TTS Test Cases:**\n- Enable TTS flag and verify audio output generation without errors\n- Test each supported TTS engine with fallback when primary engine fails\n- Validate configuration persistence for TTS settings across application restarts\n- Test TTS with special characters, long text, and multilingual content\n- Verify TTS integration doesn't interfere with normal command execution or file operations\n- Test concurrent TTS operations and resource management\n- Validate TTS accessibility compliance and user experience consistency\n</info added on 2025-06-14T21:55:53.499Z>\n<info added on 2025-06-14T22:07:04.840Z>\n**Duplicate Save Prevention Testing for TTS Implementation:**\n\nSince TTS functionality involves configuration persistence and potential concurrent operations, implement specific tests to prevent duplicate saves in the TTS context:\n\n- Test TTS configuration saves to prevent duplicate entries in configuration files when users rapidly change voice settings, volume, or other audio parameters\n- Validate that TTS engine initialization doesn't create duplicate configuration entries when switching between different TTS engines (Windows SAPI, macOS say, Linux espeak)\n- Test concurrent TTS operations to ensure audio output settings aren't duplicated when multiple commands with --tts flag run simultaneously\n- Verify that TTS preference saves are atomic and don't result in corrupted or duplicate configuration data during rapid user interactions\n- Implement unique constraint checks for TTS configuration entries to prevent duplicate voice profiles or audio settings\n- Test TTS configuration persistence across application restarts to ensure settings aren't duplicated on reload\n- Validate that TTS error logging doesn't create duplicate log entries when TTS engines fail or fallback mechanisms activate\n- Test edge cases where users rapidly toggle global TTS enable/disable settings to prevent duplicate configuration states\n- Ensure TTS-related task metadata (like audio output preferences per task) doesn't create duplicate entries in tasks.json\n- Implement locking mechanisms for TTS configuration file operations to prevent race conditions during concurrent access\n\nThis testing should be integrated with the existing TTS test strategy to ensure robust duplicate prevention across all TTS-related save operations.\n</info added on 2025-06-14T22:07:04.840Z>\n<info added on 2025-06-14T22:08:10.995Z>\n**Claude API Integration Testing for TTS Commands:**\n\nAdd specific testing requirements for Claude API integration within the TTS implementation context:\n\n- Test Claude API connectivity when generating TTS-enabled task content to ensure API calls don't interfere with audio output generation\n- Validate Claude API authentication and error handling when TTS commands request AI-generated content with --tts flag enabled\n- Test Claude API response parsing and integration with TTS output formatting to ensure AI-generated text is properly converted for speech synthesis\n- Verify Claude API token usage tracking doesn't conflict with TTS configuration persistence mechanisms\n- Test concurrent operations where Claude API calls and TTS audio generation occur simultaneously\n- Validate Claude API retry and backoff logic works correctly when TTS commands fail and need to regenerate content\n- Test Claude API integration with task generation workflows that include TTS output requirements\n- Ensure Claude API error messages are properly formatted for TTS output when --tts flag is enabled\n- Test Claude API model parameter configuration persistence alongside TTS configuration settings\n- Validate that Claude API failures gracefully fallback without breaking TTS functionality for existing task content\n- Test environment variable handling for ANTHROPIC_API_KEY in conjunction with TTS engine configuration\n- Verify Claude API integration logging doesn't create conflicts with TTS error logging mechanisms\n\nThis testing should ensure seamless integration between Claude API functionality and TTS features without interference or duplicate save issues.\n</info added on 2025-06-14T22:08:10.995Z>\n<info added on 2025-06-14T22:10:22.106Z>\n**Final Duplicate Save Testing Protocol - Research Session 6/14/2025:**\n\n**Comprehensive Test Environment Setup:**\n- Create clean test environment with known state of tasks.json and TTS configuration files\n- Back up current tasks.json, TTS settings, and Claude API configuration before testing\n- Ensure all TTS engines and Claude API connectivity are functional for comprehensive testing\n\n**Duplicate Save Test Scenarios for TTS Implementation:**\n- Test saving TTS configuration with identical voice settings to verify no duplicate entries\n- Attempt simultaneous TTS configuration saves while audio output is active\n- Test Claude API task generation with --tts flag to ensure no duplicate task entries in tasks.json\n- Validate TTS preference persistence doesn't create duplicate configuration entries during rapid setting changes\n- Test concurrent TTS operations with multiple commands to verify no duplicate audio output settings\n- Simulate race conditions between TTS configuration saves and Claude API calls\n\n**Manual and Automated Test Execution:**\n- Execute TTS commands with --tts flag while monitoring tasks.json for duplicate entries\n- Test Claude API integration with TTS-enabled commands to verify single task creation\n- Validate TTS configuration file integrity after multiple rapid setting changes\n- Test TTS error logging to ensure no duplicate log entries during engine failures\n- Verify TTS-related task metadata saves don't create duplicate entries\n\n**Edge Case Testing for TTS Context:**\n- Test TTS configuration saves with minor variations (case sensitivity, whitespace) in voice names\n- Validate duplicate detection with similar TTS settings across different engines\n- Test large-scale TTS operations to ensure performance and correctness\n- Verify TTS global enable/disable toggle doesn't create duplicate configuration states\n\n**Validation and Documentation:**\n- Monitor TTS configuration files, tasks.json, and logs for any duplicate entries\n- Document test results in provided table format with TTS-specific scenarios\n- Verify error handling provides clear feedback for TTS-related duplicate save attempts\n- Confirm regression testing covers all TTS functionality without introducing new duplicate save issues\n- Complete stakeholder confirmation before closing duplicate save testing for TTS implementation\n</info added on 2025-06-14T22:10:22.106Z>",
"testStrategy": "Test TTS functionality across different operating systems (Windows, macOS, Linux). Verify that the --tts flag works with all major commands. Test voice configuration options and ensure audio output settings are properly applied. Test error handling when TTS services are unavailable. Verify that text formatting for speech is natural and understandable. Test with various task content types including special characters, code snippets, and long descriptions. Ensure TTS can be disabled and enabled through configuration.",
"status": "pending",
- "dependencies": [16],
+ "dependencies": [
+ 16
+ ],
"priority": "medium",
"subtasks": []
}
@@ -5694,7 +6440,9 @@
"details": "Implement dependency graph management using efficient data structures to support large graphs (500+ tasks). Integrate with Taskmaster MCP commands to fetch and monitor task dependencies and tags. Implement circular dependency detection algorithms. Use event-driven notifications for dependency status changes. Optimize for sub-second response times. Cache dependency data for performance.",
"testStrategy": "Unit test dependency graph operations and circular dependency detection. Integration test with Taskmaster MCP mock server. Performance test with large dependency graphs. Validate event notifications on dependency changes.",
"priority": "high",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"status": "pending",
"subtasks": [
{
@@ -5710,7 +6458,9 @@
"id": 2,
"title": "Integrate Taskmaster MCP Commands for Dependency Fetching and Monitoring",
"description": "Connect the dependency monitor to Taskmaster MCP to fetch task dependencies and tags, and monitor their status in real-time.",
- "dependencies": ["2.1"],
+ "dependencies": [
+ "2.1"
+ ],
"details": "Implement API integration with Taskmaster MCP commands to retrieve task dependency data and tags. Set up listeners or polling mechanisms to detect changes in dependencies and update the graph accordingly.",
"status": "pending",
"testStrategy": "Integration test with Taskmaster MCP mock server to validate data fetching and real-time monitoring."
@@ -5719,7 +6469,9 @@
"id": 3,
"title": "Implement Circular Dependency Detection Algorithms",
"description": "Develop algorithms to detect circular dependencies within the task dependency graph to prevent execution deadlocks.",
- "dependencies": ["2.1"],
+ "dependencies": [
+ "2.1"
+ ],
"details": "Use graph traversal techniques such as depth-first search (DFS) or Tarjan's algorithm to identify cycles in the dependency graph. Ensure detection is efficient to maintain sub-second response times.",
"status": "pending",
"testStrategy": "Unit test with various graph scenarios including cyclic and acyclic graphs to verify detection accuracy."
@@ -5728,7 +6480,10 @@
"id": 4,
"title": "Develop Event-Driven Notification System for Dependency Status Changes",
"description": "Create an event-driven mechanism to notify relevant components or users when dependency statuses change.",
- "dependencies": ["2.2", "2.3"],
+ "dependencies": [
+ "2.2",
+ "2.3"
+ ],
"details": "Implement event listeners that trigger notifications on dependency status updates, such as completion, failure, or changes in dependency relationships. Ensure notifications are timely and scalable.",
"status": "pending",
"testStrategy": "Integration test event notifications with simulated dependency status changes to verify correct triggering and delivery."
@@ -5737,7 +6492,12 @@
"id": 5,
"title": "Optimize Performance and Cache Dependency Data",
"description": "Enhance the system to achieve sub-second response times by optimizing algorithms and caching dependency data effectively.",
- "dependencies": ["2.1", "2.2", "2.3", "2.4"],
+ "dependencies": [
+ "2.1",
+ "2.2",
+ "2.3",
+ "2.4"
+ ],
"details": "Profile and optimize graph operations and data fetching. Implement caching strategies to reduce redundant computations and network calls. Validate that the system maintains performance under load with large dependency graphs.",
"status": "pending",
"testStrategy": "Performance test with large-scale graphs and high-frequency updates to ensure response time targets are met."
@@ -5751,7 +6511,9 @@
"details": "Use a priority queue data structure to manage task execution order. Support up to 10 concurrent tasks with resource reservation and conflict detection. Integrate with Taskmaster MCP commands for task execution, cancellation, and status updates. Implement timeout and cancellation logic. Persist execution history in SQLite for analytics. Provide APIs for querying execution status and history.",
"testStrategy": "Unit test queue management, priority scheduling, and concurrency control. Integration test with Taskmaster MCP commands. Simulate resource conflicts and timeouts. Verify execution history persistence and retrieval.",
"priority": "high",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"status": "pending",
"subtasks": [
{
@@ -5767,7 +6529,9 @@
"id": 2,
"title": "Implement Parallel Task Execution with Resource Conflict Detection",
"description": "Enable concurrent execution of up to 10 tasks while managing resource reservations and detecting conflicts to prevent resource contention.",
- "dependencies": ["3.1"],
+ "dependencies": [
+ "3.1"
+ ],
"details": "Develop concurrency control to allow up to 10 parallel tasks. Implement resource reservation mechanisms and conflict detection algorithms to avoid simultaneous access to conflicting resources. Integrate with the priority queue to select tasks eligible for execution.",
"status": "pending",
"testStrategy": "Unit test concurrency limits and resource conflict detection logic. Simulate resource conflicts and verify that conflicting tasks are not executed concurrently."
@@ -5776,7 +6540,9 @@
"id": 3,
"title": "Integrate Taskmaster MCP Commands for Task Lifecycle Management",
"description": "Integrate the execution manager with Taskmaster MCP commands to support task execution, cancellation, and status updates.",
- "dependencies": ["3.1"],
+ "dependencies": [
+ "3.1"
+ ],
"details": "Implement interfaces to send commands to Taskmaster MCP for starting, cancelling, and querying task statuses. Ensure synchronization between the execution manager state and Taskmaster MCP responses.",
"status": "pending",
"testStrategy": "Integration test with Taskmaster MCP mock or real API. Verify correct command dispatch, response handling, and state synchronization."
@@ -5785,7 +6551,10 @@
"id": 4,
"title": "Implement Timeout and Cancellation Logic for Task Execution",
"description": "Add timeout handling and cancellation support to manage long-running or stalled tasks effectively.",
- "dependencies": ["3.2", "3.3"],
+ "dependencies": [
+ "3.2",
+ "3.3"
+ ],
"details": "Implement mechanisms to track task execution time and cancel tasks exceeding their timeout thresholds. Support manual cancellation requests and ensure proper cleanup and state updates upon cancellation.",
"status": "pending",
"testStrategy": "Unit test timeout triggers and cancellation flows. Simulate long-running tasks and verify timely cancellation and resource release."
@@ -5794,7 +6563,9 @@
"id": 5,
"title": "Persist Execution History and Provide Query APIs",
"description": "Store task execution history in SQLite for analytics and provide APIs to query execution status and history.",
- "dependencies": ["3.4"],
+ "dependencies": [
+ "3.4"
+ ],
"details": "Design a schema in SQLite to record task execution details including start time, end time, status, priority, and resource usage. Implement APIs to query current execution status and historical data for analytics and reporting.",
"status": "pending",
"testStrategy": "Unit test database persistence and retrieval operations. Integration test API endpoints for querying execution status and history."
@@ -5808,7 +6579,10 @@
"details": "Design safety constraint schemas and validation logic using JSON Schema. Implement emergency stop and pause functionality with immediate effect. Integrate user approval workflows for critical tasks. Monitor resource usage and detect runaway automation. Implement file permission validation and backup mechanisms. Log all safety-related events for audit purposes.",
"testStrategy": "Unit test safety constraint validation and emergency controls. Simulate safety violations and verify automatic responses. Test user approval workflows. Perform security testing for file protection and access control.",
"priority": "high",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"status": "pending",
"subtasks": [
{
@@ -5824,7 +6598,9 @@
"id": 2,
"title": "Implement Emergency Stop and Pause Functionality",
"description": "Develop mechanisms to immediately halt or pause ongoing automation tasks upon emergency triggers.",
- "dependencies": ["4.1"],
+ "dependencies": [
+ "4.1"
+ ],
"details": "Build emergency stop and pause controls that can be triggered manually or automatically. Ensure these controls take immediate effect to prevent unsafe operations and allow safe recovery or intervention.",
"status": "pending",
"testStrategy": "Simulate emergency conditions and verify that tasks stop or pause instantly and safely."
@@ -5833,7 +6609,9 @@
"id": 3,
"title": "Integrate User Approval Workflows for Critical Tasks",
"description": "Create workflows requiring explicit user approval before executing high-risk or critical automation tasks.",
- "dependencies": ["4.1"],
+ "dependencies": [
+ "4.1"
+ ],
"details": "Design and implement user interaction flows that prompt for approval on critical operations. Ensure integration with task execution logic to block unauthorized or unapproved actions.",
"status": "pending",
"testStrategy": "Test approval prompts, user responses, and enforcement of approval requirements before task execution."
@@ -5842,7 +6620,9 @@
"id": 4,
"title": "Implement File Protection and Backup Mechanisms",
"description": "Develop validation for file permissions and automatic backup processes to protect critical files from unauthorized changes or loss.",
- "dependencies": ["4.1"],
+ "dependencies": [
+ "4.1"
+ ],
"details": "Validate file access permissions before operations to prevent unauthorized modifications. Implement backup routines to save file states prior to changes, enabling recovery in case of violations or failures.",
"status": "pending",
"testStrategy": "Perform security testing on file access controls and verify backup creation and restoration processes."
@@ -5851,7 +6631,10 @@
"id": 5,
"title": "Monitor Resource Usage and Log Safety Events",
"description": "Continuously monitor resource consumption to detect runaway automation and log all safety-related events for auditing.",
- "dependencies": ["4.1", "4.2"],
+ "dependencies": [
+ "4.1",
+ "4.2"
+ ],
"details": "Implement monitoring tools to track CPU, memory, and other resource usage in real-time. Detect violations such as runaway tasks and trigger safety responses. Log all safety events including constraint violations, emergency stops, approvals, and file protections for audit trails.",
"status": "pending",
"testStrategy": "Simulate resource overuse and safety violations to verify detection and logging accuracy."
@@ -5865,7 +6648,9 @@
"details": "Integrate with Kiro's file watcher for file system monitoring. Use Taskmaster MCP API to detect task status changes. Integrate Git event listeners for commits, branch changes, and merges. Connect to build system events for test and compilation results. Implement configurable event filters and pattern matching. Use debouncing and batching to optimize performance under high-frequency events.",
"testStrategy": "Unit test event filtering, debouncing, and batching logic. Integration test with simulated file system, Git, and build events. Verify correct triggering of hooks and task execution.",
"priority": "medium",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"status": "pending",
"subtasks": [
{
@@ -5908,7 +6693,12 @@
"id": 5,
"title": "Implement Configurable Event Filtering, Pattern Matching, Debouncing, and Batching",
"description": "Develop filtering mechanisms and pattern matching for events, and implement debouncing and batching to optimize performance under high-frequency event loads.",
- "dependencies": ["5.1", "5.2", "5.3", "5.4"],
+ "dependencies": [
+ "5.1",
+ "5.2",
+ "5.3",
+ "5.4"
+ ],
"details": "Create configurable filters to selectively process events based on criteria. Implement pattern matching for event attributes. Use debouncing to delay processing of rapid event bursts and batching to group events for efficient handling.",
"status": "pending",
"testStrategy": "Unit test filtering, pattern matching, debouncing, and batching logic. Integration test with high-frequency simulated events to validate performance optimization and correct hook triggering."
@@ -5922,7 +6712,9 @@
"details": "Integrate with Kiro's agent communication system to intercept prompts. Analyze conversation content using natural language processing to suggest relevant tasks. Inject task context dynamically into AI conversations. Update task statuses based on agent responses. Implement relevance scoring and context-aware filtering for task suggestions.",
"testStrategy": "Unit test prompt interception and context injection. Use mock AI conversations to validate task suggestion accuracy. Integration test with Kiro agent communication system. Verify task status updates triggered by prompts.",
"priority": "medium",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"status": "pending",
"subtasks": [
{
@@ -5938,7 +6730,9 @@
"id": 2,
"title": "Implement Natural Language Processing for Task Suggestion",
"description": "Analyze intercepted conversation content using NLP techniques to automatically suggest relevant tasks based on the context.",
- "dependencies": ["6.1"],
+ "dependencies": [
+ "6.1"
+ ],
"details": "Use NLP models to parse and understand agent prompts and conversation transcripts. Extract intent and key entities to match against existing tasks. Implement relevance scoring and context-aware filtering to prioritize task suggestions.",
"status": "pending",
"testStrategy": "Unit test NLP parsing and intent extraction with diverse conversation samples. Validate task suggestion accuracy using mock AI conversations."
@@ -5947,7 +6741,9 @@
"id": 3,
"title": "Develop Dynamic Task Context Injection into AI Conversations",
"description": "Create functionality to inject relevant task context dynamically into AI conversations to enhance agent understanding and response quality.",
- "dependencies": ["6.1"],
+ "dependencies": [
+ "6.1"
+ ],
"details": "Design the context injection mechanism to append or embed task-related information into AI prompts or responses. Ensure context is relevant, concise, and updated in real-time based on conversation flow.",
"status": "pending",
"testStrategy": "Unit test context injection with simulated AI conversations. Verify that injected context improves task relevance without causing prompt overload."
@@ -5956,7 +6752,10 @@
"id": 4,
"title": "Implement Task Status Update Mechanism Based on Agent Responses",
"description": "Build the logic to update task statuses automatically by interpreting agent responses and AI conversation outcomes.",
- "dependencies": ["6.2", "6.3"],
+ "dependencies": [
+ "6.2",
+ "6.3"
+ ],
"details": "Monitor agent replies and AI outputs to detect task progress or completion signals. Map conversation cues to task status changes such as 'in progress', 'completed', or 'needs review'. Ensure updates are synchronized with the task management system.",
"status": "pending",
"testStrategy": "Unit test status update triggers with varied agent response scenarios. Integration test with task management API to confirm status synchronization."
@@ -5965,7 +6764,9 @@
"id": 5,
"title": "Implement Relevance Scoring and Context-Aware Filtering for Task Suggestions",
"description": "Enhance task suggestion accuracy by applying relevance scoring algorithms and context-aware filters to prioritize and refine suggested tasks.",
- "dependencies": ["6.2"],
+ "dependencies": [
+ "6.2"
+ ],
"details": "Develop scoring models that evaluate task relevance based on conversation context, task metadata, and historical data. Apply filters to exclude irrelevant or low-priority tasks. Continuously refine scoring criteria based on feedback and usage patterns.",
"status": "pending",
"testStrategy": "Unit test scoring and filtering logic with controlled datasets. Perform A/B testing to measure improvement in suggestion relevance."
@@ -5979,7 +6780,9 @@
"details": "Monitor code changes via file system and version control integration. Track implementation progress and milestones automatically. Validate task acceptance criteria and mark completion. Propagate status updates through dependency chains. Detect and resolve conflicts in task updates. Integrate with version control systems for change tracking.",
"testStrategy": "Unit test progress tracking and acceptance validation logic. Integration test with version control events and Taskmaster MCP updates. Simulate conflict scenarios and verify resolution mechanisms.",
"priority": "medium",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"status": "pending",
"subtasks": [
{
@@ -5995,7 +6798,9 @@
"id": 2,
"title": "Develop Acceptance Criteria Validation and Task Completion Marking",
"description": "Create logic to validate task acceptance criteria automatically upon code updates and mark tasks as completed when criteria are met.",
- "dependencies": ["7.1"],
+ "dependencies": [
+ "7.1"
+ ],
"details": "Implement validation rules to check if code changes satisfy predefined acceptance criteria. Automate task status updates to 'completed' when criteria validation passes.",
"status": "pending",
"testStrategy": "Unit test acceptance criteria validation logic with various scenarios. Integration test with task status updates triggered by code changes."
@@ -6004,7 +6809,9 @@
"id": 3,
"title": "Implement Dependency Update Propagation Through Task Chains",
"description": "Design and implement propagation of status updates through dependent tasks to maintain consistency across the dependency graph.",
- "dependencies": ["7.2"],
+ "dependencies": [
+ "7.2"
+ ],
"details": "Use efficient data structures to manage dependency chains and propagate status changes downstream. Integrate with Taskmaster MCP to fetch and update dependency statuses.",
"status": "pending",
"testStrategy": "Unit test dependency propagation logic. Integration test with Taskmaster MCP mock server to verify correct update flows."
@@ -6013,7 +6820,9 @@
"id": 4,
"title": "Detect and Resolve Conflicts in Task Updates",
"description": "Develop mechanisms to detect conflicts arising from concurrent or incompatible task updates and implement resolution strategies.",
- "dependencies": ["7.1"],
+ "dependencies": [
+ "7.1"
+ ],
"details": "Implement conflict detection algorithms triggered by update hooks. Provide automated or manual conflict resolution workflows to maintain task integrity.",
"status": "pending",
"testStrategy": "Simulate conflict scenarios and verify detection accuracy. Test resolution mechanisms for correctness and robustness."
@@ -6022,7 +6831,10 @@
"id": 5,
"title": "Integrate Update-Based Hook Processor with Version Control Systems",
"description": "Ensure seamless integration of the update-based hook processor with version control systems for effective change tracking and hook execution.",
- "dependencies": ["7.1", "7.4"],
+ "dependencies": [
+ "7.1",
+ "7.4"
+ ],
"details": "Implement Git update hook scripts that invoke the processor before ref updates. Ensure hooks are executable and handle parameters such as refname and old/new commit hashes.",
"status": "pending",
"testStrategy": "Integration test with Git repositories to verify hook triggering on push events. Validate correct parameter handling and processor invocation."
@@ -6036,7 +6848,10 @@
"details": "Use React with TypeScript for UI components. Implement WebSocket client for real-time updates. Use D3.js for interactive dependency chain visualization and Chart.js for analytics. Provide controls for pause/resume/stop automation, hook toggles, manual task triggers, safety configuration, and tag management. Style with CSS Modules. Ensure responsive and performant UI.",
"testStrategy": "Unit test UI components with Jest and React Testing Library. Perform integration tests with backend WebSocket server. Conduct usability testing with sample users. Validate real-time updates and control responsiveness.",
"priority": "medium",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"status": "pending",
"subtasks": [
{
@@ -6061,7 +6876,9 @@
"id": 3,
"title": "Build Interactive Visualization Components",
"description": "Develop interactive visualizations for dependency graphs (D3.js) and analytics charts (Chart.js) to display task dependencies, execution trends, and system health.",
- "dependencies": ["8.2"],
+ "dependencies": [
+ "8.2"
+ ],
"details": "Implement a dependency graph visualization using D3.js for interactive exploration of task dependencies and status. Use Chart.js for rendering analytics (e.g., execution history, queue lengths, health metrics). Ensure visualizations are performant with large datasets and support user interactions like zoom, filter, and tooltips.",
"status": "pending",
"testStrategy": "Unit test visualization components for rendering accuracy and interaction handling. Integration test with live and simulated data streams. Validate performance with large datasets."
@@ -6079,7 +6896,12 @@
"id": 5,
"title": "Ensure Dashboard Performance, Responsiveness, and Maintainability",
"description": "Optimize the dashboard for fast rendering, smooth interactions, and maintainable code structure.",
- "dependencies": ["8.1", "8.2", "8.3", "8.4"],
+ "dependencies": [
+ "8.1",
+ "8.2",
+ "8.3",
+ "8.4"
+ ],
"details": "Profile and optimize dashboard performance, focusing on rendering speed, memory usage, and real-time update handling. Enforce TypeScript best practices: strict typing, consistent naming, and avoidance of 'any' type[1]. Use React hooks and functional components for state management. Apply CSS Modules for scoped, maintainable styles. Implement code splitting and lazy loading where beneficial.",
"status": "pending",
"testStrategy": "Performance test dashboard under heavy data load and frequent updates. Audit code for TypeScript and React best practices[1]. Conduct cross-browser and cross-device responsiveness testing."
@@ -6093,7 +6915,11 @@
"details": "Implement KiroHookAdapter for hook registration, lifecycle, and event handling within Kiro IDE plugin architecture. Implement TaskmasterMCPAdapter for full MCP command support including task operations, tags, complexity analysis, and research features. Integrate file system monitoring and agent communication. Ensure error handling and retry logic for MCP communication. Integrate UI components into Kiro IDE interface.",
"testStrategy": "Perform end-to-end integration testing with Kiro IDE and Taskmaster MCP servers. Validate all hook types and task operations. Test error handling and recovery. Conduct performance and compatibility testing within Kiro IDE.",
"priority": "high",
- "dependencies": [1, 3, 7],
+ "dependencies": [
+ 1,
+ 3,
+ 7
+ ],
"status": "pending",
"subtasks": [
{
@@ -6109,7 +6935,9 @@
"id": 2,
"title": "Implement TaskmasterMCPAdapter for MCP Command Support",
"description": "Create the TaskmasterMCPAdapter to provide full support for MCP commands including task operations, tags, complexity analysis, and research features.",
- "dependencies": ["9.1"],
+ "dependencies": [
+ "9.1"
+ ],
"details": "Develop the adapter to interface with Taskmaster MCP servers, supporting commands for task creation, updates, tagging, complexity metrics, and research functionalities. Ensure robust communication and command execution.",
"status": "pending",
"testStrategy": "Unit test MCP command implementations and command parsing. Integration test with Taskmaster MCP servers to validate command execution and response handling."
@@ -6118,7 +6946,10 @@
"id": 3,
"title": "Integrate File System Monitoring and Agent Communication",
"description": "Integrate file system event monitoring and agent communication mechanisms to support real-time updates and interactions within Kiro IDE.",
- "dependencies": ["9.1", "9.2"],
+ "dependencies": [
+ "9.1",
+ "9.2"
+ ],
"details": "Implement file watcher integration to detect file changes and trigger appropriate hooks or MCP commands. Establish reliable communication channels between Kiro IDE agents and backend services.",
"status": "pending",
"testStrategy": "Test file system event detection and propagation. Validate agent communication reliability and message handling under various scenarios."
@@ -6127,7 +6958,10 @@
"id": 4,
"title": "Implement Error Handling and Retry Logic for MCP Communication",
"description": "Develop comprehensive error handling and retry mechanisms for all MCP communication to ensure robustness and fault tolerance.",
- "dependencies": ["9.2", "9.3"],
+ "dependencies": [
+ "9.2",
+ "9.3"
+ ],
"details": "Design error detection, logging, and recovery strategies for MCP command failures. Implement retry policies with backoff and failure escalation to maintain stable integration.",
"status": "pending",
"testStrategy": "Simulate MCP communication failures and verify error handling paths. Test retry logic effectiveness and system recovery under intermittent failures."
@@ -6136,7 +6970,12 @@
"id": 5,
"title": "Integrate UI Components into Kiro IDE Interface",
"description": "Integrate and embed UI components related to Kiro hooks and Taskmaster MCP commands into the Kiro IDE interface for user interaction.",
- "dependencies": ["9.1", "9.2", "9.3", "9.4"],
+ "dependencies": [
+ "9.1",
+ "9.2",
+ "9.3",
+ "9.4"
+ ],
"details": "Develop UI elements to display hook statuses, task operations, tags, and complexity analysis results. Ensure seamless user experience and interaction within the Kiro IDE environment.",
"status": "pending",
"testStrategy": "Perform UI integration testing to validate component rendering and interaction. Conduct end-to-end tests to verify UI updates reflect backend state changes accurately."
@@ -6150,7 +6989,10 @@
"details": "Build a React-based configuration editor UI with templates and validation using JSON Schema. Support editing of automation rules, safety profiles, resource limits, and tag inheritance. Implement import/export functionality for configuration sharing. Integrate version control for configuration history and rollback. Provide real-time validation feedback and error highlighting.",
"testStrategy": "Unit test configuration editor components and validation logic. Integration test import/export and version control features. Perform user acceptance testing for usability and correctness.",
"priority": "medium",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"status": "pending",
"subtasks": [
{
@@ -6166,7 +7008,9 @@
"id": 2,
"title": "Implement JSON Schema-Based Validation and Real-Time Feedback",
"description": "Integrate JSON Schema validation into the editor to validate configuration inputs dynamically and provide immediate error highlighting and feedback to users.",
- "dependencies": ["10.1"],
+ "dependencies": [
+ "10.1"
+ ],
"details": "Use JSON Schema to define validation rules for automation rules, safety profiles, resource limits, and tag inheritance. Implement real-time validation that triggers on user input and displays errors inline within the editor UI.",
"status": "pending",
"testStrategy": "Unit test validation logic with various valid and invalid configuration samples. Verify error messages and UI error highlighting."
@@ -6175,7 +7019,10 @@
"id": 3,
"title": "Develop Import and Export Functionality for Configuration Sharing",
"description": "Enable users to import existing configuration files and export current configurations for sharing and backup purposes.",
- "dependencies": ["10.1", "10.2"],
+ "dependencies": [
+ "10.1",
+ "10.2"
+ ],
"details": "Implement file handling features to load configuration JSON files into the editor and export the current configuration state to JSON files. Ensure validation is performed on import and errors are reported to users.",
"status": "pending",
"testStrategy": "Integration test import/export workflows with valid and invalid files. Verify that imported configurations populate the editor correctly and exported files match the current state."
@@ -6184,7 +7031,10 @@
"id": 4,
"title": "Integrate Version Control for Configuration History and Rollback",
"description": "Add version control capabilities to track configuration changes, view history, and rollback to previous versions within the editor.",
- "dependencies": ["10.1", "10.3"],
+ "dependencies": [
+ "10.1",
+ "10.3"
+ ],
"details": "Implement integration with a version control system (e.g., Git or a custom solution) to save configuration snapshots. Provide UI components to browse history, compare versions, and revert changes. Ensure seamless user experience within the React editor.",
"status": "pending",
"testStrategy": "Integration test version control operations including commit, history browsing, diff viewing, and rollback. Verify data integrity and UI responsiveness."
@@ -6193,7 +7043,10 @@
"id": 5,
"title": "Support Editing of Automation Rules, Safety Profiles, Resource Limits, and Tag Inheritance",
"description": "Extend the editor to support detailed editing capabilities for all configuration aspects including automation rules, safety constraints, resource limits, and tag contexts with inheritance.",
- "dependencies": ["10.1", "10.2"],
+ "dependencies": [
+ "10.1",
+ "10.2"
+ ],
"details": "Design and implement UI forms and editors for each configuration domain. Ensure that editing respects validation rules and supports inheritance logic for tags. Provide user-friendly interfaces for complex configuration structures.",
"status": "pending",
"testStrategy": "Unit and integration test editing workflows for each configuration type. Validate inheritance behavior and constraint enforcement."
@@ -6232,7 +7085,9 @@
"id": 2,
"title": "Configure build and test infrastructure",
"description": "Set up tsup build configuration for dual format support and Jest testing configuration",
- "dependencies": ["115.1"],
+ "dependencies": [
+ "115.1"
+ ],
"details": "Create tsup.config.js with dual format configuration (ESM and CJS), entry points from src/index.ts, declaration files generation, and sourcemaps. Configure jest.config.js with TypeScript preset, ESM support, proper module name mapping, coverage thresholds (80%), and test environment setup. Create .gitignore for node_modules, dist, and coverage directories. Add npm scripts in package.json for build, test, test:watch, and test:coverage commands.\n<info added on 2025-08-06T10:50:49.396Z>\nBuild process successfully configured with tsup.config.ts (TypeScript configuration file instead of JavaScript) supporting dual format output and multiple entry points including submodules. Jest configuration established with comprehensive ESM support and path alias mapping. Created tests/setup.ts for centralized test environment configuration. Added ES2022 compilation target for modern JavaScript features. Enhanced .gitignore to exclude additional development-specific files beyond the basic directories.\n</info added on 2025-08-06T10:50:49.396Z>",
"status": "done",
"testStrategy": "Run 'npm run build' to verify tsup configuration works, execute 'npm test' with a simple test file to confirm Jest setup, check that both .mjs and .cjs files are generated in dist/"
@@ -6241,7 +7096,9 @@
"id": 3,
"title": "Create barrel export files for all directories",
"description": "Implement index.ts files in each directory to enable clean imports throughout the package",
- "dependencies": ["115.1"],
+ "dependencies": [
+ "115.1"
+ ],
"details": "Create index.ts in src/ that exports from all subdirectories. Create index.ts in each subdirectory (types/, interfaces/, providers/, parsers/, builders/, utils/, errors/) with appropriate exports. For now, add placeholder comments indicating what will be exported from each module. Ensure proper export syntax for TypeScript types and interfaces using 'export type' where appropriate. Structure exports to allow consumers to import like '@task-master/tm-core/types' or from the main entry point.\n<info added on 2025-08-06T10:51:56.837Z>\nImplementation complete. All barrel export files have been created successfully with:\n\n- Main src/index.ts exporting from all subdirectories with proper TypeScript syntax\n- Individual index.ts files in types/, providers/, storage/, parser/, utils/, and errors/ directories\n- Proper ES module syntax with .js extensions for TypeScript compatibility\n- Placeholder exports with @deprecated JSDoc tags to indicate future implementation\n- Clean module structure supporting both root imports and submodule imports like '@task-master/tm-core/types'\n- All files include appropriate documentation comments explaining their purpose\n</info added on 2025-08-06T10:51:56.837Z>",
"status": "done",
"testStrategy": "Compile with TypeScript to ensure all index.ts files are valid, verify no circular dependencies exist, check that imports from package root work correctly"
@@ -6250,7 +7107,10 @@
"id": 4,
"title": "Add development tooling and documentation",
"description": "Set up development tools, linting, and initial documentation structure",
- "dependencies": ["115.1", "115.2"],
+ "dependencies": [
+ "115.1",
+ "115.2"
+ ],
"details": "Create .eslintrc.js with TypeScript plugin and recommended rules for consistent code style. Add prettier configuration for code formatting. Create README.md with package overview, installation instructions, and usage examples (marked as 'coming soon'). Add CHANGELOG.md to track version changes. Create npm scripts for linting and formatting. Add pre-commit hooks configuration if needed. Document the dual ESM/CJS support in README.\n<info added on 2025-08-06T10:53:45.056Z>\nI'll analyze the user's request and the context to determine what new information should be added to the subtask's details.Successfully completed development tooling and documentation setup. Created .eslintrc.js with TypeScript plugin and comprehensive rules including no-explicit-any, consistent-type-imports, and proper TypeScript checks. Added .prettierrc.json with sensible defaults for consistent code formatting. Created comprehensive README.md with package overview, installation instructions, usage examples for both ESM and CommonJS, modular imports, architecture description, development setup, and detailed roadmap for tasks 116-125. Added CHANGELOG.md following Keep a Changelog format with current package status and planned features. All development tooling is configured and ready for use.\n</info added on 2025-08-06T10:53:45.056Z>",
"status": "done",
"testStrategy": "Run eslint on sample TypeScript files, verify prettier formats code consistently, ensure all npm scripts execute without errors"
@@ -6259,7 +7119,12 @@
"id": 5,
"title": "Validate package structure and prepare for development",
"description": "Perform final validation of the package structure and ensure it's ready for implementation",
- "dependencies": ["115.1", "115.2", "115.3", "115.4"],
+ "dependencies": [
+ "115.1",
+ "115.2",
+ "115.3",
+ "115.4"
+ ],
"details": "Run 'npm install' to ensure all dependencies are properly resolved. Execute 'tsc --noEmit' to verify TypeScript configuration is correct. Create a simple smoke test in tests/ that imports from the package to verify module resolution works. Ensure the package can be linked locally for testing in other projects. Verify that both CommonJS and ESM imports work correctly. Create a checklist in README for remaining implementation tasks based on tasks 116-125.\n<info added on 2025-08-06T11:02:21.457Z>\nSuccessfully validated package structure with comprehensive testing. All validations passed: npm install resolved dependencies without issues, TypeScript compilation (tsc --noEmit) showed no errors, and dual-format build (npm run build) successfully generated both ESM and CJS outputs with proper TypeScript declarations. Created and executed comprehensive smoke test suite covering all module imports, placeholder functionality, and type definitions - all 8 tests passing. Code quality tools (ESLint, Prettier) are properly configured and show no issues. Package is confirmed ready for local linking and supports both CommonJS and ESM import patterns. README updated with implementation checklist marking Task 115 as complete and clearly outlining remaining implementation tasks 116-125. Package structure validation is complete and development environment is fully prepared for core implementation phase.\n</info added on 2025-08-06T11:02:21.457Z>",
"status": "done",
"testStrategy": "Successfully run all build and test commands, verify package can be imported in both ESM and CJS test files, ensure TypeScript compilation produces no errors, confirm all directories contain appropriate index.ts files"
@@ -6273,7 +7138,9 @@
"details": "Create types/index.ts with Task, Subtask, TaskMetadata interfaces and type literals (TaskStatus, TaskPriority, TaskComplexity). Create all interface files: storage.interface.ts with IStorage methods, ai-provider.interface.ts with IAIProvider and AIOptions, configuration.interface.ts with IConfiguration. Use strict typing throughout, no 'any' types allowed. Follow naming conventions: interfaces prefixed with 'I', type literals in PascalCase.",
"testStrategy": "Compile with TypeScript to ensure no type errors, create mock implementations to verify interfaces are complete, use type checking in IDE to confirm all required properties are defined",
"priority": "high",
- "dependencies": [115],
+ "dependencies": [
+ 115
+ ],
"status": "done",
"subtasks": [
{
@@ -6289,7 +7156,9 @@
"id": 2,
"title": "Define Type Literals and Enums",
"description": "Create all type literal definitions for TaskStatus, TaskPriority, and TaskComplexity in the types file",
- "dependencies": ["116.1"],
+ "dependencies": [
+ "116.1"
+ ],
"details": "In types/index.ts, define type literals: TaskStatus = 'pending' | 'in-progress' | 'done' | 'deferred' | 'cancelled' | 'blocked'; TaskPriority = 'low' | 'medium' | 'high' | 'critical'; TaskComplexity = 'simple' | 'moderate' | 'complex' | 'very-complex'. Consider using const assertions for better type inference. Export all type literals.\n<info added on 2025-08-06T11:04:04.675Z>\nType literals were already implemented in subtask 116.1 as part of the comprehensive type system. The types/index.ts file includes all required type literals: TaskStatus with values 'pending' | 'in-progress' | 'done' | 'deferred' | 'cancelled' | 'blocked' | 'review', TaskPriority with values 'low' | 'medium' | 'high' | 'critical', and TaskComplexity with values 'simple' | 'moderate' | 'complex' | 'very-complex'. All type literals are properly exported and include comprehensive JSDoc documentation. TypeScript compilation verified the types work correctly.\n</info added on 2025-08-06T11:04:04.675Z>",
"status": "done",
"testStrategy": "Use TypeScript compiler to verify type literals work correctly, test with invalid values to ensure type checking catches errors"
@@ -6298,7 +7167,9 @@
"id": 3,
"title": "Create Storage Interface Definition",
"description": "Create storage.interface.ts with IStorage interface defining all storage operation methods",
- "dependencies": ["116.1"],
+ "dependencies": [
+ "116.1"
+ ],
"details": "Create interfaces/storage.interface.ts file. Define IStorage interface with methods: loadTasks(tag?: string): Promise<Task[]>; saveTasks(tasks: Task[], tag?: string): Promise<void>; appendTasks(tasks: Task[], tag?: string): Promise<void>; updateTask(taskId: string, updates: Partial<Task>, tag?: string): Promise<void>; deleteTask(taskId: string, tag?: string): Promise<void>; exists(tag?: string): Promise<boolean>. Import Task type from types/index.ts.\n<info added on 2025-08-06T11:05:00.573Z>\nImplementation completed successfully. Extended IStorage interface beyond original specification to include metadata operations (loadMetadata, saveMetadata), tag management (getAllTags, deleteTag, renameTag, copyTag), and lifecycle methods (initialize, close, getStats). Added StorageStats interface for monitoring storage metrics and StorageConfig interface for configuration options. Implemented BaseStorage abstract class that provides common functionality including task validation using validateTask method, tag sanitization with sanitizeTag to ensure valid filenames, and backup path generation through getBackupPath for data safety. The abstract class serves as a foundation for concrete storage implementations, reducing code duplication and ensuring consistent behavior across different storage backends. All methods properly typed with async/await patterns and comprehensive error handling considerations.\n</info added on 2025-08-06T11:05:00.573Z>",
"status": "done",
"testStrategy": "Create mock implementation of IStorage to verify all methods are properly typed, ensure Promise return types are correct"
@@ -6307,7 +7178,9 @@
"id": 4,
"title": "Create AI Provider Interface Definition",
"description": "Create ai-provider.interface.ts with IAIProvider interface and AIOptions type",
- "dependencies": ["116.1"],
+ "dependencies": [
+ "116.1"
+ ],
"details": "Create interfaces/ai-provider.interface.ts file. Define AIOptions interface with properties: temperature (number), maxTokens (number), stream (boolean), topP (number), frequencyPenalty (number). Define IAIProvider interface with methods: generateCompletion(prompt: string, options?: AIOptions): Promise<string>; calculateTokens(text: string): number; getName(): string; getModel(): string; getDefaultModel(): string; isAvailable(): Promise<boolean>.\n<info added on 2025-08-06T11:06:15.795Z>\nFile successfully updated with expanded interface implementation details including comprehensive method signatures and supporting interfaces: AIOptions with full parameter set (temperature, maxTokens, stream, model, topP, topK, frequencyPenalty, presencePenalty, stopSequences, systemPrompt), AIResponse structure with content and usage metadata, AIModel interface for model information, ProviderInfo for capability tracking, ProviderUsageStats for usage monitoring, AIProviderConfig for initialization, and additional interfaces for streaming support. Documented BaseAIProvider abstract class implementation with validation, usage tracking, and common utility methods. All interfaces properly typed with strict TypeScript patterns and async/await support. No compilation errors.\n</info added on 2025-08-06T11:06:15.795Z>",
"status": "done",
"testStrategy": "Create stub implementation to verify interface completeness, test optional parameters work correctly"
@@ -6316,7 +7189,10 @@
"id": 5,
"title": "Create Configuration Interface Definition",
"description": "Create configuration.interface.ts with IConfiguration interface for all config options",
- "dependencies": ["116.1", "116.2"],
+ "dependencies": [
+ "116.1",
+ "116.2"
+ ],
"details": "Create interfaces/configuration.interface.ts file. Define IConfiguration interface with properties: projectPath (string), aiProvider (string), apiKeys (Record<string, string>), models (object with main, research, fallback as strings), enableTags (boolean), defaultTag (string), maxConcurrentTasks (number), retryAttempts (number), retryDelay (number). Import necessary types from types/index.ts. Ensure all properties have appropriate types with no 'any' usage.\n<info added on 2025-08-06T11:07:43.367Z>\nImplementation completed successfully. Created comprehensive configuration system with:\n\n- Core IConfiguration interface with all required properties: projectPath, aiProvider, apiKeys, models configuration, providers settings, tasks management, tags configuration, storage options, retry behavior, logging preferences, and security settings\n- Supporting interfaces for each configuration section: ModelConfig for AI model selection, ProviderConfig for API provider settings, TaskSettings for task management options, TagSettings for tag-based organization, StorageSettings for persistence configuration, RetrySettings for error handling, LoggingSettings for debugging options, SecuritySettings for API key management\n- Configuration management system with IConfigurationFactory for creating configs from various sources (file, environment, defaults) and IConfigurationManager for runtime config operations including loading, saving, validation, watching for changes, and merging configurations\n- Validation system with ConfigValidationResult interface for detailed error reporting, ConfigSchema for JSON schema validation, and EnvironmentConfig for environment variable mapping\n- DEFAULT_CONFIG_VALUES constant providing sensible defaults for all configuration options\n- All interfaces properly typed with strict TypeScript typing, no 'any' usage, proper imports from types/index\n- Successfully exported all interfaces through main index.ts for package consumers\n- TypeScript compilation confirmed passing without any type errors\n</info added on 2025-08-06T11:07:43.367Z>",
"status": "done",
"testStrategy": "Create sample configuration objects to verify interface covers all needed options, test with partial configs to ensure optional properties work"
@@ -6330,7 +7206,9 @@
"details": "Implement FileStorage class in storage/file-storage.ts following Repository pattern. Constructor accepts projectPath, private basePath property set to {projectPath}/.taskmaster. Implement all IStorage methods: loadTasks, saveTasks, appendTasks, updateTask, deleteTask, exists. Handle file operations with proper error handling (ENOENT returns empty arrays). Use JSON format with tasks array and metadata object containing version and lastModified. Create getTasksPath method to handle tag-based file paths.",
"testStrategy": "Unit test all FileStorage methods with mock file system, test error scenarios (missing files, invalid JSON), verify tag-based path generation, test concurrent operations, ensure proper directory creation",
"priority": "high",
- "dependencies": [116],
+ "dependencies": [
+ 116
+ ],
"status": "done",
"subtasks": [
{
@@ -6346,7 +7224,9 @@
"id": 2,
"title": "Implement file path management and helper methods",
"description": "Create internal helper methods for managing file paths and ensuring directory structure exists",
- "dependencies": ["117.1"],
+ "dependencies": [
+ "117.1"
+ ],
"details": "Implement private getTasksPath(tag?: string) method that returns path to tasks file based on optional tag parameter. If tag provided, return `${basePath}/tasks/${tag}.json`, otherwise `${basePath}/tasks/tasks.json`. Create private ensureDirectoryExists() method that creates .taskmaster and tasks directories if they don't exist using fs.mkdir with recursive option. Add private method for safe JSON parsing with error handling.",
"status": "done",
"testStrategy": "Test getTasksPath with and without tags, verify directory creation works recursively, test JSON parsing with valid and invalid data"
@@ -6355,7 +7235,9 @@
"id": 3,
"title": "Implement read operations: loadTasks and exists",
"description": "Implement methods for reading tasks from the file system with proper error handling",
- "dependencies": ["117.2"],
+ "dependencies": [
+ "117.2"
+ ],
"details": "Implement loadTasks(tag?: string) method: use getTasksPath to get file path, read file using fs.readFile, parse JSON content, return tasks array from parsed data. Handle ENOENT error by returning empty array. Handle JSON parse errors appropriately. Implement exists(tag?: string) method: use fs.access to check if file exists at getTasksPath location, return boolean result.",
"status": "done",
"testStrategy": "Test loadTasks with existing files, missing files (ENOENT), corrupted JSON files. Test exists method with present and absent files"
@@ -6364,7 +7246,9 @@
"id": 4,
"title": "Implement write operations: saveTasks and appendTasks",
"description": "Implement methods for persisting tasks to the file system with metadata",
- "dependencies": ["117.3"],
+ "dependencies": [
+ "117.3"
+ ],
"details": "Implement saveTasks(tasks: Task[], tag?: string) method: ensure directory exists, create data object with tasks array and metadata object containing version (e.g., '1.0.0') and lastModified (ISO timestamp). Write to file using fs.writeFile with JSON.stringify and proper formatting. Implement appendTasks(tasks: Task[], tag?: string) method: load existing tasks, merge with new tasks (avoiding duplicates by ID), call saveTasks with merged array.",
"status": "done",
"testStrategy": "Test saveTasks creates files with correct structure, verify metadata is included, test appendTasks merges correctly without duplicates"
@@ -6373,7 +7257,9 @@
"id": 5,
"title": "Implement update and delete operations",
"description": "Implement methods for modifying and removing individual tasks with atomic operations",
- "dependencies": ["117.4"],
+ "dependencies": [
+ "117.4"
+ ],
"details": "Implement updateTask(taskId: string, updates: Partial<Task>, tag?: string) method: load tasks, find task by ID, merge updates using object spread, save updated tasks array. Return boolean indicating success. Implement deleteTask(taskId: string, tag?: string) method: load tasks, filter out task with matching ID, save filtered array. Return boolean indicating if task was found and deleted. Ensure both operations are atomic using temporary files if needed.",
"status": "done",
"testStrategy": "Test updateTask with existing and non-existing tasks, verify partial updates work correctly. Test deleteTask removes correct task, handles missing tasks gracefully"
@@ -6387,7 +7273,9 @@
"details": "Convert existing base-provider.js to TypeScript abstract class BaseProvider implementing IAIProvider. Add protected properties for apiKey and model. Create abstract methods: generateCompletion, calculateTokens, getName, getModel, getDefaultModel. Apply Template Method pattern for common provider logic like error handling and retry logic. Ensure proper type safety throughout.",
"testStrategy": "Create MockProvider extending BaseProvider to test abstract class functionality, verify all abstract methods are properly defined, test error handling and common logic",
"priority": "high",
- "dependencies": [116],
+ "dependencies": [
+ 116
+ ],
"status": "done",
"subtasks": [
{
@@ -6403,7 +7291,9 @@
"id": 2,
"title": "Implement BaseProvider abstract class with core properties",
"description": "Create the abstract BaseProvider class implementing IAIProvider with protected properties for apiKey and model configuration",
- "dependencies": ["118.1"],
+ "dependencies": [
+ "118.1"
+ ],
"details": "In base-provider.ts, define abstract class BaseProvider implements IAIProvider with protected properties: apiKey: string, model: string, maxRetries: number = 3, retryDelay: number = 1000. Add constructor that accepts BaseProviderConfig interface with apiKey and optional model. Implement getModel() method to return current model.\n<info added on 2025-08-06T12:28:45.485Z>\nI've reviewed the existing BaseAIProvider interface in the interfaces file. The task requires creating a separate BaseProvider abstract class in base-provider.ts that implements the IAIProvider interface, with specific protected properties and configuration. This appears to be a deliberate architectural decision to have a more concrete base class with built-in retry logic and configuration management that all provider implementations will extend.\n</info added on 2025-08-06T12:28:45.485Z>\n<info added on 2025-08-06T13:14:24.539Z>\nSuccessfully implemented BaseProvider abstract class:\n\nIMPLEMENTED FILES:\n✅ packages/tm-core/src/providers/base-provider.ts - Created new BaseProvider abstract class\n✅ packages/tm-core/src/providers/index.ts - Updated to export BaseProvider\n\nIMPLEMENTATION DETAILS:\n- Created BaseProviderConfig interface with required apiKey and optional model\n- BaseProvider abstract class implements IAIProvider interface\n- Protected properties implemented as specified:\n - apiKey: string \n - model: string\n - maxRetries: number = 3\n - retryDelay: number = 1000\n- Constructor accepts BaseProviderConfig and sets apiKey and model (using getDefaultModel() if not provided)\n- Implemented getModel() method that returns current model\n- All IAIProvider methods declared as abstract (to be implemented by concrete providers)\n- Uses .js extension for ESM import compatibility\n- TypeScript compilation verified successful\n\nThe BaseProvider provides the foundation for concrete provider implementations with shared retry logic properties and standardized configuration.\n</info added on 2025-08-06T13:14:24.539Z>\n<info added on 2025-08-20T17:16:14.037Z>\nREFACTORING REQUIRED: The BaseProvider implementation needs to be relocated from packages/tm-core/src/providers/base-provider.ts to packages/tm-core/src/providers/ai/base-provider.ts following the new directory structure. The class must implement the Template Method pattern with the following structure:\n\n1. Keep constructor concise (under 10 lines) - only initialize apiKey and model properties\n2. Remove maxRetries and retryDelay from constructor - these should be class-level constants or configurable separately\n3. Implement all abstract methods from IAIProvider: generateCompletion, calculateTokens, getName, getModel, getDefaultModel\n4. Add protected template methods for extensibility:\n - validateInput(input: string): void - for input validation with early returns\n - prepareRequest(input: string, options?: any): any - for request preparation\n - handleResponse(response: any): string - for response processing\n - handleError(error: any): never - for consistent error handling\n5. Apply clean code principles: extract complex logic into small focused methods, use early returns to reduce nesting, ensure each method has single responsibility\n\nThe refactored BaseProvider will serve as a robust foundation using Template Method pattern, allowing concrete providers to override specific behaviors while maintaining consistent structure and error handling across all AI provider implementations.\n</info added on 2025-08-20T17:16:14.037Z>\n<info added on 2025-08-21T15:57:30.467Z>\nREFACTORING UPDATE: The BaseProvider implementation in packages/tm-core/src/providers/base-provider.ts is now affected by the core/ folder removal and needs its import paths updated. Since base-provider.ts imports from '../interfaces/provider.interface.js', this import remains valid as both providers/ and interfaces/ are at the same level. No changes needed to BaseProvider imports due to the flattening. The file structure reorganization maintains the relative path relationship between providers/ and interfaces/ directories.\n</info added on 2025-08-21T15:57:30.467Z>",
"status": "done",
"testStrategy": "Create a test file that attempts to instantiate BaseProvider directly (should fail) and verify that protected properties are accessible in child classes"
@@ -6412,7 +7302,9 @@
"id": 3,
"title": "Define abstract methods and implement Template Method pattern",
"description": "Add all abstract methods to BaseProvider and implement the Template Method pattern for common provider operations",
- "dependencies": ["118.2"],
+ "dependencies": [
+ "118.2"
+ ],
"details": "Add abstract methods: protected abstract generateCompletionInternal(prompt: string, options?: CompletionOptions): Promise<CompletionResult>, abstract calculateTokens(text: string): number, abstract getName(): string, abstract getDefaultModel(): string. Implement public generateCompletion() as template method that calls generateCompletionInternal() with error handling and retry logic.\n<info added on 2025-08-20T17:16:38.315Z>\nApply Template Method pattern following clean code principles:\n\nDefine abstract methods:\n- protected abstract generateCompletionInternal(prompt: string, options?: CompletionOptions): Promise<CompletionResult>\n- protected abstract calculateTokens(text: string): number\n- protected abstract getName(): string\n- protected abstract getDefaultModel(): string\n- protected abstract getMaxRetries(): number\n- protected abstract getRetryDelay(): number\n\nImplement template method generateCompletion():\n- Call validateInput() with early returns for invalid prompt/options\n- Call prepareRequest() to format the request\n- Execute generateCompletionInternal() with retry logic\n- Call handleResponse() to process the result\n- Call handleError() in catch blocks\n\nAdd protected helper methods:\n- validateInput(prompt: string, options?: CompletionOptions): ValidationResult - Check prompt length, validate options, return early on errors\n- prepareRequest(prompt: string, options?: CompletionOptions): PreparedRequest - Format prompt, merge with defaults, add metadata\n- handleResponse(result: CompletionResult): ProcessedResult - Validate response format, extract completion text, add usage metrics\n- handleError(error: unknown, attempt: number): void - Log error details, determine if retryable, throw TaskMasterError\n\nExtract retry logic helpers:\n- shouldRetry(error: unknown, attempt: number): boolean - Check error type and attempt count\n- calculateBackoffDelay(attempt: number): number - Use exponential backoff with jitter\n- isRateLimitError(error: unknown): boolean - Detect rate limit responses\n- isTimeoutError(error: unknown): boolean - Detect timeout errors\n\nUse named constants:\n- DEFAULT_MAX_RETRIES = 3\n- BASE_RETRY_DELAY_MS = 1000\n- MAX_RETRY_DELAY_MS = 32000\n- BACKOFF_MULTIPLIER = 2\n- JITTER_FACTOR = 0.1\n\nEnsure each method stays under 30 lines by extracting complex logic into focused helper methods.\n</info added on 2025-08-20T17:16:38.315Z>",
"status": "done",
"testStrategy": "Create MockProvider extending BaseProvider to verify all abstract methods must be implemented and template method properly delegates to internal methods"
@@ -6421,7 +7313,9 @@
"id": 4,
"title": "Implement error handling and retry logic with exponential backoff",
"description": "Add comprehensive error handling and retry mechanism with exponential backoff for API calls in the template method",
- "dependencies": ["118.3"],
+ "dependencies": [
+ "118.3"
+ ],
"details": "In generateCompletion() template method, wrap generateCompletionInternal() in try-catch with retry logic. Implement exponential backoff: delay * Math.pow(2, attempt). Add error types: ProviderError, RateLimitError, AuthenticationError extending Error. Log errors in development mode only. Handle specific error cases like rate limits (429), authentication errors (401), and network timeouts.",
"status": "done",
"testStrategy": "Test retry logic with MockProvider that fails N times then succeeds, verify exponential backoff timing, test different error scenarios and their handling"
@@ -6430,7 +7324,9 @@
"id": 5,
"title": "Add validation, logging, and completion options handling",
"description": "Implement input validation, debug logging for development, and proper handling of completion options like temperature and max tokens",
- "dependencies": ["118.4"],
+ "dependencies": [
+ "118.4"
+ ],
"details": "Add validatePrompt() method to check for empty/invalid prompts. Add validateOptions() to ensure temperature is between 0-2, maxTokens is positive. Implement debug logging using console.log only when NODE_ENV !== 'production'. Create CompletionOptions interface with optional temperature, maxTokens, topP, frequencyPenalty, presencePenalty. Ensure all validation errors throw descriptive ProviderError instances.",
"status": "done",
"testStrategy": "Test validation with invalid inputs (empty prompts, negative maxTokens, temperature > 2), verify logging only occurs in development, test option merging with defaults"
@@ -6444,7 +7340,9 @@
"details": "Implement ProviderFactory class in ai/provider-factory.ts with static create method. Use switch statement for provider selection ('anthropic', 'openai', 'google'). Implement dynamic imports for each provider to enable tree-shaking. Return Promise<IAIProvider> from create method. Handle unknown providers with meaningful error messages. Ensure proper typing for configuration object.",
"testStrategy": "Test factory with each provider type, verify dynamic imports work correctly, test error handling for unknown providers, mock dynamic imports for unit testing",
"priority": "medium",
- "dependencies": [118],
+ "dependencies": [
+ 118
+ ],
"status": "pending",
"subtasks": [
{
@@ -6460,7 +7358,9 @@
"id": 2,
"title": "Implement provider selection logic with switch statement",
"description": "Add the core switch statement logic to handle different provider types",
- "dependencies": ["119.1"],
+ "dependencies": [
+ "119.1"
+ ],
"details": "Inside the static create method, implement switch statement on provider type parameter. Add cases for 'anthropic', 'openai', and 'google'. Add default case that throws a descriptive error for unknown providers (e.g., throw new Error(`Unknown provider: ${providerType}`)). Structure each case to prepare for dynamic imports.",
"status": "pending",
"testStrategy": "Test switch statement with valid and invalid provider types, verify error messages"
@@ -6469,7 +7369,9 @@
"id": 3,
"title": "Add dynamic imports for each provider",
"description": "Implement dynamic import() statements for lazy loading provider modules",
- "dependencies": ["119.2"],
+ "dependencies": [
+ "119.2"
+ ],
"details": "In each switch case, use dynamic import() to load the provider module: for 'anthropic' case use await import('./providers/anthropic-provider'), similar for OpenAI and Google providers. Extract the default export or specific class from each dynamic import. This enables tree-shaking by only loading the selected provider.",
"status": "pending",
"testStrategy": "Mock dynamic imports in tests, verify only requested provider is loaded"
@@ -6478,7 +7380,9 @@
"id": 4,
"title": "Instantiate providers with configuration",
"description": "Create provider instances with proper configuration passing",
- "dependencies": ["119.3"],
+ "dependencies": [
+ "119.3"
+ ],
"details": "After each dynamic import, instantiate the provider class with the configuration object passed to create method. Ensure configuration object is properly typed (use IConfiguration or relevant subset). Return the instantiated provider instance. Handle any instantiation errors and wrap them with context about which provider failed.",
"status": "pending",
"testStrategy": "Test provider instantiation with various configuration objects, verify configuration is passed correctly"
@@ -6487,7 +7391,9 @@
"id": 5,
"title": "Add error handling and validation",
"description": "Implement comprehensive error handling for all failure scenarios",
- "dependencies": ["119.4"],
+ "dependencies": [
+ "119.4"
+ ],
"details": "Wrap dynamic imports in try-catch blocks to handle module loading failures. Add validation for configuration object before passing to providers. Create custom error messages that include the provider type and specific failure reason. Consider adding a ProviderFactoryError custom error class. Ensure all errors bubble up properly while maintaining async/await chain.",
"status": "pending",
"testStrategy": "Test various error scenarios: missing provider modules, invalid configurations, network failures during dynamic import"
@@ -6501,7 +7407,9 @@
"details": "Create AnthropicProvider class in ai/providers/anthropic-provider.ts extending BaseProvider. Import and use @anthropic-ai/sdk. Initialize private client property in constructor. Implement all abstract methods: generateCompletion using Claude API, calculateTokens using appropriate tokenizer, getName returning 'anthropic', getModel returning current model, getDefaultModel returning 'claude-3-sonnet-20240229'. Wrap API errors with context.",
"testStrategy": "Mock Anthropic SDK for unit tests, test API error handling, verify token calculation accuracy, test with different model configurations",
"priority": "high",
- "dependencies": [118],
+ "dependencies": [
+ 118
+ ],
"status": "pending",
"subtasks": [
{
@@ -6517,7 +7425,9 @@
"id": 2,
"title": "Implement constructor and client initialization",
"description": "Create the constructor that accepts configuration and initializes the Anthropic SDK client",
- "dependencies": ["120.1"],
+ "dependencies": [
+ "120.1"
+ ],
"details": "Implement constructor accepting IConfiguration parameter. Call super(config) to initialize BaseProvider. Initialize the private client property by creating new Anthropic instance with apiKey from config.apiKeys.anthropic. Add validation to ensure API key exists, throwing meaningful error if missing. Store the model configuration from config.model or use default.",
"status": "pending",
"testStrategy": "Test constructor with valid and invalid configurations, verify client initialization, test API key validation"
@@ -6526,7 +7436,9 @@
"id": 3,
"title": "Implement generateCompletion method with Claude API",
"description": "Implement the main generateCompletion method that calls Anthropic's Claude API and handles responses",
- "dependencies": ["120.2"],
+ "dependencies": [
+ "120.2"
+ ],
"details": "Implement async generateCompletion method accepting ChatMessage array. Map ChatMessage format to Anthropic's expected format (role and content). Use client.messages.create() with appropriate parameters including model, max_tokens, and messages. Transform Anthropic response format to ChatCompletion interface. Handle streaming vs non-streaming responses. Implement proper error handling wrapping API errors with context.",
"status": "pending",
"testStrategy": "Mock Anthropic SDK client.messages.create, test with various message formats, verify response transformation, test error scenarios"
@@ -6535,7 +7447,9 @@
"id": 4,
"title": "Implement token calculation and utility methods",
"description": "Implement calculateTokens method and other required abstract methods from BaseProvider",
- "dependencies": ["120.3"],
+ "dependencies": [
+ "120.3"
+ ],
"details": "Implement calculateTokens method using appropriate tokenizer (tiktoken or claude-tokenizer if available). Implement getName method returning 'anthropic' string constant. Implement getModel method returning current model from configuration. Implement getDefaultModel method returning 'claude-3-sonnet-20240229'. Add any additional helper methods for token counting or message formatting.",
"status": "pending",
"testStrategy": "Test token calculation accuracy with various input strings, verify utility methods return correct values"
@@ -6544,7 +7458,9 @@
"id": 5,
"title": "Add comprehensive error handling and type exports",
"description": "Implement robust error handling throughout the class and ensure proper TypeScript exports",
- "dependencies": ["120.4"],
+ "dependencies": [
+ "120.4"
+ ],
"details": "Wrap all Anthropic API calls in try-catch blocks. Create custom error messages that include context about the operation being performed. Handle rate limiting errors specifically. Ensure all methods have proper TypeScript return types. Export the AnthropicProvider class as default export. Add JSDoc comments for all public methods. Ensure proper error propagation maintaining stack traces.",
"status": "pending",
"testStrategy": "Test various API error scenarios, verify error messages include context, test rate limit handling, ensure TypeScript types are correctly exported"
@@ -6558,7 +7474,10 @@
"details": "Create PromptBuilder class with buildParsePrompt and buildExpandPrompt methods using template literals. Include specific JSON format instructions. Create TaskParser class accepting IAIProvider and IConfiguration via constructor (Dependency Injection). Implement parsePRD method to read PRD file, use PromptBuilder to create prompt, call AI provider, extract tasks from response, and enrich with metadata. Handle parsing errors gracefully.",
"testStrategy": "Unit test prompt building with various inputs, mock AI provider responses, test JSON extraction logic, verify error handling for malformed responses, integration test with real PRD files",
"priority": "high",
- "dependencies": [119, 120],
+ "dependencies": [
+ 119,
+ 120
+ ],
"status": "pending",
"subtasks": [
{
@@ -6574,7 +7493,9 @@
"id": 2,
"title": "Implement TaskParser Class with DI",
"description": "Create TaskParser class accepting IAIProvider and IConfiguration through constructor injection",
- "dependencies": ["121.1"],
+ "dependencies": [
+ "121.1"
+ ],
"details": "Create src/services/task-parser.ts. Define TaskParser class with constructor(private aiProvider: IAIProvider, private config: IConfiguration). Add private promptBuilder property initialized in constructor. Implement basic class structure with placeholder methods. Ensure proper TypeScript typing for all parameters and properties. Follow dependency injection pattern for testability.\n<info added on 2025-08-20T17:17:49.624Z>\nUpdate file location to src/services/tasks/task-parser.ts instead of src/services/task-parser.ts. Refactor parsePRD() method to stay under 40 lines by extracting logic into helper methods: readPRD(), validatePRD(), extractTasksFromResponse(), and enrichTasksWithMetadata(). Each helper method should be under 20 lines. Implement early returns in validation methods for cleaner code flow. Remove any file I/O operations from the parser class - delegate all storage operations to injected dependencies. Ensure clean separation of concerns with parser focused only on task parsing logic.\n</info added on 2025-08-20T17:17:49.624Z>",
"status": "pending",
"testStrategy": "Test constructor properly stores injected dependencies. Verify class instantiation with mock providers. Test TypeScript compilation with proper interface implementations."
@@ -6583,7 +7504,9 @@
"id": 3,
"title": "Implement parsePRD Method Core Logic",
"description": "Create the main parsePRD method that orchestrates the PRD parsing workflow",
- "dependencies": ["121.2"],
+ "dependencies": [
+ "121.2"
+ ],
"details": "Implement parsePRD(filePath: string): Promise<ParsedTask[]> method in TaskParser. Read PRD file using fs.promises.readFile. Use promptBuilder.buildParsePrompt() to create AI prompt. Call aiProvider.generateResponse() with constructed prompt. Extract JSON array from AI response using regex or JSON.parse. Handle potential parsing errors with try-catch blocks. Return empty array on errors after logging.",
"status": "pending",
"testStrategy": "Test with mock AI provider returning valid JSON. Test file reading with various file paths. Mock file system for controlled testing. Verify proper error logging without throwing."
@@ -6592,7 +7515,9 @@
"id": 4,
"title": "Add Task Enrichment and Metadata",
"description": "Enhance parsed tasks with additional metadata and validation",
- "dependencies": ["121.3"],
+ "dependencies": [
+ "121.3"
+ ],
"details": "After extracting tasks from AI response, enrich each task with metadata: add createdAt timestamp, set initial status to 'pending', validate required fields (id, title, description). Add priority field with default 'medium' if not provided. Ensure all tasks have valid structure before returning. Create private enrichTask(task: any): ParsedTask method for this logic. Handle missing or malformed task data gracefully.",
"status": "pending",
"testStrategy": "Test enrichment adds all required metadata. Verify validation catches malformed tasks. Test default values are applied correctly. Ensure timestamps are properly formatted."
@@ -6601,7 +7526,9 @@
"id": 5,
"title": "Implement Comprehensive Error Handling",
"description": "Add robust error handling throughout the TaskParser implementation",
- "dependencies": ["121.4"],
+ "dependencies": [
+ "121.4"
+ ],
"details": "Wrap file reading in try-catch to handle FILE_NOT_FOUND errors. Catch AI provider errors and wrap in appropriate TaskMasterError. Handle JSON parsing errors when extracting from AI response. Add specific error handling for network timeouts, rate limits, and malformed responses. Log errors with context in development mode only. Return meaningful error messages without exposing internals. Ensure all errors are properly typed as TaskMasterError instances.",
"status": "pending",
"testStrategy": "Test each error scenario separately: missing files, AI provider failures, malformed JSON, network errors. Verify proper error codes are used. Test that errors don't expose sensitive information."
@@ -6615,7 +7542,9 @@
"details": "Implement ConfigManager in config/config-manager.ts accepting Partial<IConfiguration> in constructor. Use Zod to create validation schema matching IConfiguration interface. Implement get method with TypeScript generics for type-safe access, getAll returning full config, validate method for validation. Set defaults: projectPath = process.cwd(), aiProvider = 'anthropic', enableTags = true. Handle validation errors with clear messages.",
"testStrategy": "Test with various configuration combinations, verify Zod validation catches invalid configs, test default values, ensure type safety of get method",
"priority": "medium",
- "dependencies": [116],
+ "dependencies": [
+ 116
+ ],
"status": "in-progress",
"subtasks": [
{
@@ -6631,7 +7560,9 @@
"id": 2,
"title": "Implement ConfigManager class constructor and storage",
"description": "Create ConfigManager class with constructor that accepts Partial<IConfiguration> and initializes configuration with defaults",
- "dependencies": ["122.1"],
+ "dependencies": [
+ "122.1"
+ ],
"details": "Define ConfigManager class with private config property. In constructor, merge provided partial config with defaults (projectPath = process.cwd(), aiProvider = 'anthropic', enableTags = true). Store the merged configuration internally. Ensure the class is properly typed with IConfiguration interface.",
"status": "pending",
"testStrategy": "Test constructor with various partial configs, verify defaults are applied correctly, test with empty config"
@@ -6640,7 +7571,10 @@
"id": 3,
"title": "Implement validate method with error handling",
"description": "Create validate method that uses Zod schema to validate configuration and provides clear error messages",
- "dependencies": ["122.1", "122.2"],
+ "dependencies": [
+ "122.1",
+ "122.2"
+ ],
"details": "Implement validate(): void method that runs configSchema.parse(this.config) within try-catch block. On ZodError, transform the error into user-friendly messages that clearly indicate which fields are invalid and why. Consider creating a custom error class for configuration validation errors. The method should throw if validation fails.",
"status": "pending",
"testStrategy": "Test with invalid configs to ensure proper error messages, verify all validation rules work correctly"
@@ -6649,7 +7583,9 @@
"id": 4,
"title": "Implement type-safe get method with generics",
"description": "Create generic get method for retrieving individual configuration values with TypeScript type inference",
- "dependencies": ["122.2"],
+ "dependencies": [
+ "122.2"
+ ],
"details": "Implement get<K extends keyof IConfiguration>(key: K): IConfiguration[K] method that returns the value for a specific configuration key. Use TypeScript generics and keyof operator to ensure type safety. The method should provide proper type inference so consumers get the correct type based on the key they request.",
"status": "pending",
"testStrategy": "Test type inference with different keys, verify TypeScript catches invalid keys at compile time"
@@ -6658,7 +7594,11 @@
"id": 5,
"title": "Implement getAll method and finalize class",
"description": "Create getAll method to return full configuration and ensure proper exports",
- "dependencies": ["122.2", "122.3", "122.4"],
+ "dependencies": [
+ "122.2",
+ "122.3",
+ "122.4"
+ ],
"details": "Implement getAll(): IConfiguration method that returns a deep copy of the entire configuration object to prevent external mutations. Add JSDoc comments to all public methods. Export the ConfigManager class and ensure it's properly integrated with the module structure. Consider adding a static factory method if needed.",
"status": "pending",
"testStrategy": "Test getAll returns complete config, verify returned object is immutable, test integration with other modules"
@@ -6672,7 +7612,9 @@
"details": "Create id-generator.ts with generateTaskId and generateSubtaskId functions using specified formats with timestamp and random components. Create TaskMasterError class extending Error in errors/task-master-error.ts with error codes (FILE_NOT_FOUND, PARSE_ERROR, etc.). Ensure errors don't expose internal details. Add development-only logging.",
"testStrategy": "Test ID generation for uniqueness and format compliance, verify error classes properly extend Error, test error message formatting, ensure no sensitive data in errors",
"priority": "low",
- "dependencies": [116],
+ "dependencies": [
+ 116
+ ],
"status": "in-progress",
"subtasks": [
{
@@ -6697,7 +7639,9 @@
"id": 3,
"title": "Implement error sanitization and security features",
"description": "Add security features to prevent exposure of sensitive internal details in error messages",
- "dependencies": ["123.2"],
+ "dependencies": [
+ "123.2"
+ ],
"details": "In TaskMasterError class, add private sanitizeDetails() method that removes sensitive data like API keys, file paths beyond project root, and internal state. Implement toJSON() method that returns sanitized error object for external consumption. Add static isSafeForProduction() method to validate error messages don't contain patterns like absolute paths, environment variables, or API credentials. Store original details in private property for debugging.",
"status": "pending",
"testStrategy": "Test sanitization removes absolute paths, API keys, and sensitive patterns, verify toJSON returns safe object, test original details are preserved internally"
@@ -6706,7 +7650,10 @@
"id": 4,
"title": "Add development-only logging functionality",
"description": "Implement conditional logging that only operates in development environment",
- "dependencies": ["123.2", "123.3"],
+ "dependencies": [
+ "123.2",
+ "123.3"
+ ],
"details": "In task-master-error.ts, add static enableDevLogging property defaulting to process.env.NODE_ENV !== 'production'. Add logError() method that console.error's full error details only when enableDevLogging is true. Include timestamp, error code, sanitized message, and full stack trace in dev logs. In production, log only error code and safe message. Create static setDevLogging(enabled: boolean) to control logging.",
"status": "pending",
"testStrategy": "Test logging output in dev vs production modes, verify sensitive data isn't logged in production, test log format includes all required fields"
@@ -6715,7 +7662,11 @@
"id": 5,
"title": "Create specialized error subclasses",
"description": "Implement specific error classes for different error scenarios inheriting from TaskMasterError",
- "dependencies": ["123.2", "123.3", "123.4"],
+ "dependencies": [
+ "123.2",
+ "123.3",
+ "123.4"
+ ],
"details": "Create FileNotFoundError extending TaskMasterError with code FILE_NOT_FOUND, accepting filePath parameter. Create ParseError with code PARSE_ERROR for parsing failures, accepting source and line number. Create ValidationError with code VALIDATION_ERROR for data validation, accepting field and value. Create APIError with code API_ERROR for external API failures, accepting statusCode and provider. Each should format appropriate user-friendly messages while storing technical details internally.",
"status": "pending",
"testStrategy": "Test each error class constructor and message formatting, verify inheritance chain, test that each error type has correct code, ensure specialized errors work with logging system"
@@ -6729,7 +7680,11 @@
"details": "Create TaskMasterCore class in index.ts with private properties for config, storage, aiProvider, and parser. Implement initialize method for lazy loading of AI provider. Implement parsePRD method that coordinates parser, storage, and configuration. Implement getTasks for retrieving stored tasks. Apply Facade pattern to hide complexity. Export createTaskMaster factory function, all types and interfaces. Use proper import paths with .js extensions for ESM.",
"testStrategy": "Integration test full parse flow, test lazy initialization, verify facade properly delegates to subsystems, test with different configurations, ensure exports are correct",
"priority": "high",
- "dependencies": [117, 121, 122],
+ "dependencies": [
+ 117,
+ 121,
+ 122
+ ],
"status": "pending",
"subtasks": [
{
@@ -6745,7 +7700,9 @@
"id": 2,
"title": "Implement initialize method for lazy loading",
"description": "Create the initialize method that handles lazy loading of AI provider and parser instances based on configuration",
- "dependencies": ["124.1"],
+ "dependencies": [
+ "124.1"
+ ],
"details": "Implement async initialize() method in TaskMasterCore. Check if _aiProvider is null, if so create appropriate provider based on config.aiProvider value using a factory pattern or switch statement. Similarly initialize _parser if null. Store instances in private properties for reuse. Handle provider initialization errors gracefully. Ensure method is idempotent - calling multiple times should not recreate instances. Use dynamic imports if needed for code splitting.",
"status": "pending",
"testStrategy": "Test lazy initialization occurs only once, verify correct provider is instantiated based on config, test error handling for invalid providers, ensure idempotency"
@@ -6754,7 +7711,10 @@
"id": 3,
"title": "Implement parsePRD method with coordination logic",
"description": "Create parsePRD method that coordinates the parser, AI provider, and storage to parse PRD content and store results",
- "dependencies": ["124.1", "124.2"],
+ "dependencies": [
+ "124.1",
+ "124.2"
+ ],
"details": "Implement async parsePRD(content: string) method. First call initialize() to ensure components are loaded. Use _parser.parse() to parse the PRD content, passing the AI provider for task generation. Take the parsed tasks and use _storage.saveTasks() to persist them. Handle errors from parser or storage operations. Return the parsed tasks array. Implement proper error context and logging for debugging.",
"status": "pending",
"testStrategy": "Integration test with mock parser and storage, verify coordination between components, test error propagation from subsystems, ensure tasks are properly stored"
@@ -6763,7 +7723,9 @@
"id": 4,
"title": "Implement getTasks method and other facade methods",
"description": "Create getTasks method and any other necessary facade methods to retrieve and manage tasks",
- "dependencies": ["124.1"],
+ "dependencies": [
+ "124.1"
+ ],
"details": "Implement async getTasks() method that calls _storage.loadTasks() and returns the tasks array. Add getTask(id: string) for retrieving single task. Consider adding updateTask, deleteTask methods if needed. All methods should follow facade pattern - simple interface hiding complex operations. Add proper TypeScript return types for all methods. Handle storage not initialized scenarios.",
"status": "pending",
"testStrategy": "Test task retrieval with various scenarios, verify proper delegation to storage, test edge cases like empty task lists or invalid IDs"
@@ -6772,7 +7734,12 @@
"id": 5,
"title": "Create factory function and module exports",
"description": "Implement createTaskMaster factory function and set up all module exports including types and interfaces",
- "dependencies": ["124.1", "124.2", "124.3", "124.4"],
+ "dependencies": [
+ "124.1",
+ "124.2",
+ "124.3",
+ "124.4"
+ ],
"details": "Create createTaskMaster(options?: Partial<IConfiguration>) factory function that returns a new TaskMasterCore instance. Export this as the primary entry point. Re-export all types and interfaces from submodules: ITask, IConfiguration, IAIProvider, ITaskStorage, IPRDParser, etc. Use 'export type' for type-only exports. Ensure all imports use .js extensions for ESM. Create index.d.ts if needed for better TypeScript support. Add JSDoc comments for public API.",
"status": "pending",
"testStrategy": "Test factory function creates proper instances, verify all exports are accessible, test TypeScript type inference works correctly, ensure ESM imports resolve properly"
@@ -6786,7 +7753,10 @@
"details": "Create OpenAIProvider and GoogleProvider classes extending BaseProvider, throwing 'not yet implemented' errors. Create MockProvider in tests/mocks for testing without API calls. Write unit tests for TaskParser, integration tests for parse-prd flow, ensure 80% code coverage. Follow kebab-case naming for test files. Test error scenarios comprehensively.",
"testStrategy": "Run full test suite with coverage report, verify all edge cases are tested, ensure mock provider behaves like real providers, test both success and failure paths",
"priority": "medium",
- "dependencies": [120, 124],
+ "dependencies": [
+ 120,
+ 124
+ ],
"status": "pending",
"subtasks": [
{
@@ -6820,7 +7790,9 @@
"id": 4,
"title": "Write unit tests for TaskParser",
"description": "Create comprehensive unit tests for TaskParser class covering all methods and edge cases",
- "dependencies": ["125.3"],
+ "dependencies": [
+ "125.3"
+ ],
"details": "Create tests/unit/task-parser.test.ts file. Test TaskParser constructor with different providers. Test parseFromText method with valid/invalid inputs. Test error handling for malformed responses. Use MockProvider to simulate API responses. Test task ID generation and structure validation. Ensure all public methods are covered.",
"status": "pending",
"testStrategy": "Achieve 100% code coverage for TaskParser class, test both success and failure paths, verify error messages are appropriate"
@@ -6829,7 +7801,10 @@
"id": 5,
"title": "Write integration tests for parse-prd flow",
"description": "Create end-to-end integration tests for the complete PRD parsing workflow",
- "dependencies": ["125.3", "125.4"],
+ "dependencies": [
+ "125.3",
+ "125.4"
+ ],
"details": "Create tests/integration/parse-prd-flow.test.ts file. Test full flow from PRD input to task output. Test with MockProvider simulating successful parsing. Test error scenarios (file not found, parse errors, network failures). Test task dependency resolution. Verify output format matches expected structure. Test with different PRD formats and sizes.",
"status": "pending",
"testStrategy": "Run coverage report to ensure 80% overall coverage, verify all critical paths are tested, ensure tests are deterministic and don't depend on external services"
@@ -6863,7 +7838,9 @@
"details": "Create a function in the StartCommand class that builds the standardized prompt with the actual task data (title, description, details) instead of instructing Claude to run 'tm show'.\n\n```typescript\nprivate buildPrompt(task: Task): string {\n return `You are an AI coding assistant with access to this repository's codebase.\n\nHere are the task details to implement:\n\nTask ID: ${task.id}\nTitle: ${task.title}\nDescription: ${task.description}\nDetails: ${task.details}\n\nImplement the task with these requirements:\n- Make the SMALLEST number of code changes possible\n- Follow ALL existing patterns in the codebase (you have access to analyze the code)\n- Do NOT over-engineer the solution\n- Use existing files/functions/patterns wherever possible\n- When complete, print: COMPLETED: <brief summary of changes>\n\nPlease implement this task now.`;\n}\n```\n<info added on 2025-09-12T02:40:01.812Z>\nThe prompt builder function will handle task context retrieval by instructing Claude to use the task-master show command. This approach ensures Claude has access to all necessary task details before implementation begins. The command syntax \"tm show ${taskId}\" embedded in the prompt will direct Claude to first gather the complete task context, including description, requirements, and any existing implementation details, before proceeding with code changes.\n</info added on 2025-09-12T02:40:01.812Z>\n\n<info added>\nThe updated approach eliminates the need for Claude to run 'tm show' by directly providing the task details in the prompt. The function now takes a Task object instead of just the task ID, allowing it to include the complete task information directly in the prompt.\n</info added>",
"testStrategy": "Verify the prompt is correctly formatted by calling the function with a sample task object and checking that the output includes all the task details (ID, title, description, details) properly inserted into the template.",
"priority": "medium",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"status": "done",
"subtasks": []
},
@@ -6874,7 +7851,9 @@
"details": "Implement the functionality to execute the claude command with the built prompt. This should use Node.js child_process.exec() to run the command directly in the terminal.\n\n```typescript\nimport { exec } from 'child_process';\n\n// Inside execute method, after task validation\nprivate async executeClaude(prompt: string): Promise<void> {\n console.log('Starting claude-code to implement the task...');\n \n try {\n // Execute claude with the prompt\n const claudeCommand = `claude \"${prompt.replace(/\"/g, '\\\\\"')}\"`;\n \n // Use execSync to wait for the command to complete\n const { execSync } = require('child_process');\n execSync(claudeCommand, { stdio: 'inherit' });\n \n console.log('Claude session completed.');\n } catch (error) {\n console.error('Error executing claude-code:', error.message);\n process.exit(1);\n }\n}\n```\n\nThen call this method from the execute method after building the prompt.",
"testStrategy": "Test by running the command with a valid task ID and verifying that the claude command is executed with the correct prompt. Check that the command handles errors appropriately if claude-code is not available.",
"priority": "high",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"status": "done",
"subtasks": []
},
@@ -6885,7 +7864,10 @@
"details": "Update the execute method in the StartCommand class to integrate all the components and implement the complete execution flow with the updated approach:\n1. Get task details directly using TaskMasterCore\n2. Build standardized prompt with actual task data\n3. Execute claude-code\n4. Check git status for changes\n5. Auto-mark task as done if changes detected\n\n```typescript\npublic async execute(taskId: string): Promise<void> {\n // Get task details directly\n const core = await createTaskMasterCore();\n const task = await core.tasks.getById(parseInt(taskId, 10));\n \n if (!task) {\n console.error(`Task with ID ${taskId} not found`);\n process.exit(1);\n }\n \n // Build prompt with actual task data\n const prompt = this.buildPrompt(task);\n \n // Execute claude-code\n await this.executeClaude(prompt);\n \n // Check git status\n const changedFiles = await this.checkGitChanges();\n \n if (changedFiles.length > 0) {\n console.log('\\nChanges detected in the following files:');\n changedFiles.forEach(file => console.log(`- ${file}`));\n \n // Auto-mark task as done\n await this.markTaskAsDone(taskId);\n console.log(`\\nTask ${taskId} completed successfully and marked as done.`);\n } else {\n console.warn('\\nNo changes detected after claude-code execution. Task not marked as done.');\n }\n}\n```",
"testStrategy": "Test the complete execution flow by running the start command with a valid task ID and verifying that all steps are executed correctly. Verify that the task details are correctly retrieved from TaskMasterCore and included in the prompt. Test with both scenarios: when changes are detected and when no changes are detected.",
"priority": "high",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"status": "done",
"subtasks": []
},
@@ -6896,7 +7878,9 @@
"details": "Update the CLI application to register the new start command. This involves importing the StartCommand class and adding it to the commands array in the CLI initialization.\n\nIn `apps/cli/src/index.ts` or the appropriate file where commands are registered:\n\n```typescript\nimport { StartCommand } from './commands/start.command';\n\n// Add StartCommand to the commands array\nconst commands = [\n // ... existing commands\n new StartCommand(),\n];\n\n// Register all commands\ncommands.forEach(command => command.register(program));\n```",
"testStrategy": "Verify the command is correctly registered by running the CLI with --help and checking that the start command appears in the list of available commands.",
"priority": "high",
- "dependencies": [7],
+ "dependencies": [
+ 7
+ ],
"status": "done",
"subtasks": []
},
@@ -6943,7 +7927,9 @@
"id": 2,
"title": "Implement event emitter system for workflow progress tracking",
"description": "Create the event emitter infrastructure to broadcast workflow state changes and progress updates",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement EventEmitter-based system for WorkflowOrchestrator with typed event interfaces (WorkflowEvent). Define event types for phase changes, progress updates, errors, and completion. Include emit(), on(), off(), and once() methods with proper type safety. Support event filtering and listener management.",
"status": "pending",
"testStrategy": "Unit tests for event emission, listener registration/removal, and event type validation"
@@ -6961,7 +7947,9 @@
"id": 4,
"title": "Integrate TaskService and ConfigManager dependencies",
"description": "Implement dependency injection and integration with existing TaskService and ConfigManager services",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Create constructor that accepts TaskService and ConfigManager dependencies. Implement methods to retrieve workflow configuration from ConfigManager and interact with TaskService for task operations. Include dependency validation and error handling for missing or invalid services. Add configuration loading and validation logic.",
"status": "pending",
"testStrategy": "Unit tests with mocked dependencies, integration tests verifying service interactions and configuration loading"
@@ -6970,7 +7958,11 @@
"id": 5,
"title": "Implement workflow lifecycle methods and state machine",
"description": "Create the core workflow control methods including start, pause, resume, and stop functionality",
- "dependencies": [1, 2, 4],
+ "dependencies": [
+ 1,
+ 2,
+ 4
+ ],
"details": "Implement start() method to initialize workflow and begin Preflight phase. Create pause()/resume() methods for workflow interruption handling. Add stop() method for graceful workflow termination. Include state machine logic to manage workflow progression, error recovery, and cleanup operations. Support workflow validation before start.",
"status": "pending",
"testStrategy": "Unit tests for lifecycle methods, state machine transitions, error handling, and workflow validation logic"
@@ -6984,7 +7976,9 @@
"details": "Create packages/tm-core/src/services/git-adapter.ts that provides TypeScript interface over scripts/modules/utils/git-utils.js. Include methods: isGitRepository, getCurrentBranch, createBranch, checkoutBranch, isWorkingTreeClean, commitChanges, pushBranch, getDefaultBranch. Implement branch naming pattern support using config.git.branchPattern with {tag}, {id}, {slug} tokens. Add confirmation gates for destructive operations.",
"testStrategy": "Unit tests with mocked git commands, integration tests with temporary git repositories. Test branch naming patterns, confirmation flows, and error handling for git failures.",
"priority": "high",
- "dependencies": [31],
+ "dependencies": [
+ 31
+ ],
"status": "pending",
"subtasks": [
{
@@ -7000,7 +7994,9 @@
"id": 2,
"title": "Implement core git operations with error handling",
"description": "Implement the main git operation methods with proper error handling and validation",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement createBranch, checkoutBranch, isWorkingTreeClean, commitChanges, pushBranch methods in GitAdapter. Add comprehensive error handling for git command failures, invalid repository states, and network issues. Include proper validation for branch names, commit messages, and repository state before operations.",
"status": "pending",
"testStrategy": "Unit tests with mocked git commands for success and failure scenarios. Integration tests with temporary git repositories testing actual git operations"
@@ -7009,7 +8005,9 @@
"id": 3,
"title": "Add branch naming pattern support with token replacement",
"description": "Implement configurable branch naming patterns using template tokens for automated branch creation",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement branch naming pattern support using config.git.branchPattern. Create token replacement system for {tag}, {id}, {slug} tokens. Add pattern validation and sanitization for git-safe branch names. Support multiple pattern templates and fallback naming strategies for edge cases.",
"status": "pending",
"testStrategy": "Unit tests for token replacement logic, pattern validation, and branch name sanitization. Test various pattern configurations and edge cases"
@@ -7018,7 +8016,9 @@
"id": 4,
"title": "Integrate confirmation gates for destructive operations",
"description": "Add user confirmation prompts and safety checks for potentially destructive git operations",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Implement confirmation gates for destructive operations like branch deletion, force push, and uncommitted changes overwrite. Add configurable confirmation levels (always, auto, never) and interactive prompts. Include safety checks for working tree state, unpushed commits, and branch protection rules.",
"status": "pending",
"testStrategy": "Unit tests for confirmation flow logic and safety checks. Integration tests simulating user interactions and validating destructive operation prevention"
@@ -7032,7 +8032,9 @@
"details": "Create packages/tm-core/src/services/test-runner-adapter.ts that detects test commands from package.json scripts (npm test, pnpm test, etc.), executes targeted and full test runs, parses test results and coverage reports. Support Jest, Vitest, and generic npm scripts. Implement TestResult interface with pass/fail counts, coverage percentages, and detailed failure information. Include timeout handling and retry logic.",
"testStrategy": "Unit tests for framework detection logic, test execution with mocked child_process, coverage parsing. Integration tests with actual test frameworks in fixture projects.",
"priority": "high",
- "dependencies": [31],
+ "dependencies": [
+ 31
+ ],
"status": "pending",
"subtasks": [
{
@@ -7048,7 +8050,9 @@
"id": 2,
"title": "Create test execution engine with process management",
"description": "Implement the core test execution system that spawns child processes and manages test command execution with proper timeout and error handling",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create TestExecutor class that uses child_process.spawn to run test commands, implements configurable timeouts, handles process termination, captures stdout/stderr streams, and provides retry logic for failed executions. Support both targeted test runs (specific files) and full test suite execution.",
"status": "pending",
"testStrategy": "Unit tests with mocked child_process, integration tests with actual test commands, timeout and retry scenario testing"
@@ -7057,7 +8061,9 @@
"id": 3,
"title": "Implement Jest-specific result parsing",
"description": "Create Jest result parser that extracts test outcomes, failure details, and coverage information from Jest's output formats",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Parse Jest JSON reporter output to extract pass/fail counts, test file results, error messages, stack traces, and execution times. Handle both verbose and summary output modes. Extract coverage data from Jest coverage reports including line, branch, function, and statement coverage percentages.",
"status": "pending",
"testStrategy": "Unit tests with sample Jest output JSON files, edge cases for malformed output, coverage parsing validation"
@@ -7066,7 +8072,9 @@
"id": 4,
"title": "Implement Vitest-specific result parsing",
"description": "Create Vitest result parser that handles Vitest's unique output format and coverage reporting structure",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Parse Vitest reporter output to extract test results, support both default and JSON reporters, handle Vitest's specific error formatting and stack traces. Extract coverage information from Vitest's coverage providers (c8, istanbul) with proper percentage calculations and file-level coverage details.",
"status": "pending",
"testStrategy": "Unit tests with Vitest output samples, comparison with Jest parser for consistency, coverage provider compatibility testing"
@@ -7075,7 +8083,10 @@
"id": 5,
"title": "Create unified TestResult interface and data structures",
"description": "Design and implement comprehensive TypeScript interfaces for test results, coverage data, and failure information that works across all supported frameworks",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Define TestResult interface with pass/fail counts, execution time, coverage percentages (line, branch, function, statement), detailed failure information with file paths and line numbers. Create CoverageReport interface with file-level and overall coverage data. Implement result aggregation and normalization logic.",
"status": "pending",
"testStrategy": "Unit tests for interface compliance across frameworks, data transformation accuracy, edge cases for missing coverage data"
@@ -7084,7 +8095,11 @@
"id": 6,
"title": "Integrate components into TestRunnerAdapter service",
"description": "Assemble all components into the main TestRunnerAdapter class with public API methods for framework detection, test execution, and result retrieval",
- "dependencies": [1, 2, 5],
+ "dependencies": [
+ 1,
+ 2,
+ 5
+ ],
"details": "Create main TestRunnerAdapter class that orchestrates framework detection, test execution, and result parsing. Implement public methods: detectFramework(), runTests(), runTargetedTests(), and getLastResults(). Add configuration options for timeout, retry count, and coverage options. Include comprehensive error handling and logging.",
"status": "pending",
"testStrategy": "Integration tests with real test projects, end-to-end workflow testing, error handling validation, performance testing with large test suites"
@@ -7098,7 +8113,11 @@
"details": "Create apps/cli/src/commands/autopilot.command.ts using Commander.js. Implement flags: --dry-run, --no-push, --no-pr, --no-confirm, --force, --max-attempts, --resume. Add preflight checks (clean working tree, test command detection, tool availability). Integrate with WorkflowOrchestrator and existing UI components from apps/cli/src/ui/components/. Show detailed execution plan in dry-run mode.",
"testStrategy": "Unit tests for command parsing, flag handling, dry-run output formatting. Integration tests with mock WorkflowOrchestrator to verify command flow without actual git operations.",
"priority": "medium",
- "dependencies": [31, 32, 33],
+ "dependencies": [
+ 31,
+ 32,
+ 33
+ ],
"status": "pending",
"subtasks": [
{
@@ -7114,7 +8133,9 @@
"id": 2,
"title": "Implement comprehensive flag handling system",
"description": "Add all required command-line flags with proper parsing, validation, and default values",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement flags: --dry-run, --no-push, --no-pr, --no-confirm, --force, --max-attempts, --resume. Add proper flag parsing with Commander.js, validation logic, type definitions, and default value handling. Ensure flags are properly documented and follow CLI conventions.",
"status": "pending",
"testStrategy": "Unit tests for flag parsing, validation logic, default values, and error handling for invalid flag combinations"
@@ -7123,7 +8144,9 @@
"id": 3,
"title": "Build preflight check validation system",
"description": "Create comprehensive preflight checks for git status, tool availability, and environment validation",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement preflight checks including: clean working tree validation, test command detection, required tool availability (git, gh), project structure validation. Create modular check system with clear error reporting and suggestions for resolution. Integrate with existing UI components for user feedback.",
"status": "pending",
"testStrategy": "Unit tests for individual preflight checks, error reporting, and validation logic. Integration tests with mock git states and tool availability scenarios"
@@ -7132,7 +8155,9 @@
"id": 4,
"title": "Integrate WorkflowOrchestrator and execution planning",
"description": "Connect the command to WorkflowOrchestrator and implement detailed dry-run execution plan display",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Integrate with WorkflowOrchestrator for actual workflow execution. Implement dry-run mode showing detailed execution plan with task breakdown, estimated timeline, and resource requirements. Use existing UI components from apps/cli/src/ui/components/ for formatted output and user interaction.",
"status": "pending",
"testStrategy": "Integration tests with mock WorkflowOrchestrator to verify command flow, dry-run output formatting, and execution plan accuracy without actual git operations"
@@ -7146,7 +8171,10 @@
"details": "Enhance packages/tm-core/src/services/task-execution-service.ts to support test generation mode. Create TestGenerationService that uses existing executor framework with surgical-test-generator prompts. Implement prompt composition system that loads rules from .cursor/rules/ and .claude/agents/, combines with task context, and generates focused failing tests. Support framework-specific test patterns (Jest, Vitest).",
"testStrategy": "Unit tests for prompt composition, test generation calls with mocked executors. Integration tests generating actual test files and verifying they fail appropriately.",
"priority": "medium",
- "dependencies": [31, 33],
+ "dependencies": [
+ 31,
+ 33
+ ],
"status": "pending",
"subtasks": [
{
@@ -7162,7 +8190,9 @@
"id": 2,
"title": "Create TestGenerationService with executor framework integration",
"description": "Implement a new TestGenerationService that leverages the existing executor framework to generate surgical tests using specialized prompts.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create packages/tm-core/src/services/test-generation-service.ts that extends or uses the executor framework. Implement methods for generating failing tests based on task context. Add support for surgical-test-generator specific prompts and parameters. Include error handling, logging, and result validation. Integrate with TaskExecutionService's new test generation mode.",
"status": "pending",
"testStrategy": "Unit tests for test generation methods with mocked surgical-test-generator calls. Integration tests generating actual test files and verifying they compile but fail appropriately."
@@ -7171,7 +8201,9 @@
"id": 3,
"title": "Implement prompt composition system for rule and context integration",
"description": "Build a sophisticated prompt composition system that loads rules from .cursor/rules/ and .claude/agents/, combines them with task context, and generates focused test generation prompts.",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Create prompt composition logic within TestGenerationService or as a separate utility. Implement file system scanning for rule files in .cursor/rules/ and .claude/agents/ directories. Add template system for combining rules with task context, subtask details, and framework-specific requirements. Include validation for prompt completeness and token replacement functionality.",
"status": "pending",
"testStrategy": "Unit tests for rule loading, template processing, and context injection. Integration tests verifying complete prompt generation with various rule combinations and task contexts."
@@ -7180,7 +8212,9 @@
"id": 4,
"title": "Add framework-specific test pattern support",
"description": "Implement support for generating tests in different testing frameworks (Jest, Vitest) with appropriate patterns and conventions.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Extend TestGenerationService to detect project testing framework through package.json analysis or configuration. Create framework-specific templates and patterns for Jest and Vitest. Implement test file naming conventions, import statements, and assertion patterns specific to each framework. Add configuration options to override framework detection and customize test generation patterns.",
"status": "pending",
"testStrategy": "Unit tests for framework detection logic and template generation. Integration tests generating tests for both Jest and Vitest projects, verifying correct syntax and runnable test files."
@@ -7194,7 +8228,12 @@
"details": "Extend WorkflowOrchestrator with SubtaskExecutor class that implements the TDD loop: RED phase (generate failing tests), GREEN phase (implement code to pass tests), COMMIT phase (git add, commit with conventional commit message). Include retry logic for GREEN phase with configurable max attempts. Integrate with existing TaskService for subtask status updates. Support timeout and backoff policies.",
"testStrategy": "Unit tests for each phase execution, retry logic, timeout handling. Integration tests with actual test files and git operations in isolated test repositories.",
"priority": "high",
- "dependencies": [31, 32, 33, 35],
+ "dependencies": [
+ 31,
+ 32,
+ 33,
+ 35
+ ],
"status": "pending",
"subtasks": [
{
@@ -7210,7 +8249,9 @@
"id": 2,
"title": "Implement RED phase test generation",
"description": "Create the RED phase logic that generates failing tests based on subtask requirements and existing codebase context",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement RED phase in SubtaskExecutor that analyzes subtask details, generates appropriate test files using AI models, and validates tests fail as expected. Include test file placement logic, import resolution, and test framework integration. Support multiple test frameworks and file naming conventions.",
"status": "pending",
"testStrategy": "Unit tests for test generation logic, file placement, and validation. Integration tests with actual test frameworks"
@@ -7219,7 +8260,10 @@
"id": 3,
"title": "Implement GREEN phase code generation",
"description": "Create the GREEN phase logic that generates implementation code to make the failing tests pass",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Implement GREEN phase that analyzes failing tests, generates implementation code using AI models, and validates tests pass. Include code placement logic, import management, and incremental implementation approach. Support multiple programming languages and frameworks with proper error handling and validation.",
"status": "pending",
"testStrategy": "Unit tests for code generation, test execution validation, and error handling. Integration tests with various test scenarios"
@@ -7228,7 +8272,10 @@
"id": 4,
"title": "Implement COMMIT phase with conventional commits",
"description": "Create the COMMIT phase that handles git operations with properly formatted conventional commit messages",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Implement COMMIT phase that stages changes, generates conventional commit messages based on task context, and commits with proper formatting. Include git status validation, conflict detection, and commit message templates. Support task ID embedding and automatic scope detection from file changes.",
"status": "pending",
"testStrategy": "Unit tests for git operations, commit message generation, and validation. Integration tests with actual git repositories"
@@ -7237,7 +8284,9 @@
"id": 5,
"title": "Implement retry mechanism for GREEN phase",
"description": "Add configurable retry logic for GREEN phase when initial implementation attempts fail",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Enhance GREEN phase with retry mechanism including configurable max attempts, exponential backoff, and failure analysis. Include retry context preservation, progressive refinement of implementation, and detailed error logging. Support different retry strategies based on failure types and provide clear feedback on retry attempts.",
"status": "pending",
"testStrategy": "Unit tests for retry logic, backoff calculations, and failure handling. Integration tests with simulated failures and recovery scenarios"
@@ -7246,7 +8295,10 @@
"id": 6,
"title": "Implement timeout and backoff policies",
"description": "Add comprehensive timeout handling and backoff policies for all TDD phases to prevent infinite execution",
- "dependencies": [1, 5],
+ "dependencies": [
+ 1,
+ 5
+ ],
"details": "Implement timeout management for each TDD phase with configurable limits, graceful degradation, and resource cleanup. Include exponential backoff for AI API calls, circuit breaker patterns for external services, and proper cancellation handling. Support per-phase timeout configuration and global execution limits.",
"status": "pending",
"testStrategy": "Unit tests for timeout handling, backoff algorithms, and cancellation logic. Integration tests with long-running operations and resource constraints"
@@ -7255,7 +8307,10 @@
"id": 7,
"title": "Integrate with TaskService for status updates",
"description": "Connect SubtaskExecutor with existing TaskService to provide real-time status updates and workflow coordination",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"details": "Integrate SubtaskExecutor with TaskService for subtask status updates, progress reporting, and workflow coordination. Include status change notifications, progress tracking, error reporting, and completion handling. Support batch updates and real-time synchronization with task management system.",
"status": "pending",
"testStrategy": "Unit tests for TaskService integration, status update logic, and event handling. Integration tests with complete workflow execution and status tracking"
@@ -7269,7 +8324,9 @@
"details": "Update packages/tm-core/src/interfaces/configuration.interface.ts to include autopilot section with: enabled, requireCleanWorkingTree, commitTemplate, defaultCommitType, maxGreenAttempts, testTimeout. Add test section with runner, coverageThresholds, targetedRunPattern. Include git section with branchPattern, pr settings. Update ConfigManager to validate and provide defaults for new settings.",
"testStrategy": "Unit tests for config validation, default value application, schema validation. Integration tests loading config from actual .taskmaster/config.json files.",
"priority": "medium",
- "dependencies": [31],
+ "dependencies": [
+ 31
+ ],
"status": "pending",
"subtasks": [
{
@@ -7285,7 +8342,9 @@
"id": 2,
"title": "Update ConfigManager validation logic",
"description": "Enhance ConfigManager to validate new autopilot configuration sections and handle schema validation",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Update ConfigManager class to include validation rules for autopilot, test, and git configuration sections. Implement schema validation using existing validation patterns, add error handling for invalid configurations, and ensure proper error messages for configuration issues. Maintain backward compatibility with existing configuration files.",
"status": "pending",
"testStrategy": "Unit tests for validation logic with valid/invalid config scenarios, error message verification"
@@ -7294,7 +8353,9 @@
"id": 3,
"title": "Implement default configuration values",
"description": "Add default value implementation for all new autopilot configuration options in ConfigManager",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement default value provider in ConfigManager for autopilot settings (enabled: false, requireCleanWorkingTree: true, maxGreenAttempts: 3, etc.), test settings (runner: 'npm test', coverageThresholds: null), and git settings (branchPattern: 'feature/*', pr settings). Ensure defaults are applied when configuration sections are missing or incomplete while preserving existing user settings.",
"status": "pending",
"testStrategy": "Integration tests loading config from actual .taskmaster/config.json files, default value application verification"
@@ -7308,7 +8369,11 @@
"details": "Create packages/tm-core/src/services/run-state-manager.ts that persists run state to .taskmaster/reports/runs/<timestamp>/. Include manifest.json (run metadata), log.jsonl (event stream), test-results/ (per-phase test outputs), commits.txt (commit SHAs). Implement JSONL event logging format and structured test result storage. Support state checkpointing for resume functionality.",
"testStrategy": "Unit tests for file operations, JSON serialization, log formatting. Integration tests creating actual run directories and verifying persistence across WorkflowOrchestrator restarts.",
"priority": "medium",
- "dependencies": [31, 33, 36],
+ "dependencies": [
+ 31,
+ 33,
+ 36
+ ],
"status": "pending",
"subtasks": [
{
@@ -7324,7 +8389,9 @@
"id": 2,
"title": "Implement run directory structure and manifest creation",
"description": "Create the standardized directory structure and manifest.json generation for run artifacts",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement createRunDirectory() method that creates .taskmaster/reports/runs/<timestamp>/ structure. Generate manifest.json with run metadata including start time, task context, git state, and configuration. Create subdirectories for test-results/ and ensure proper file permissions and error handling.",
"status": "pending",
"testStrategy": "Unit tests for directory creation, manifest JSON structure validation, and file system error handling"
@@ -7333,7 +8400,9 @@
"id": 3,
"title": "Implement JSONL event logging system",
"description": "Create structured event logging using JSONL format for run event streams",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement logEvent() method that appends structured events to log.jsonl file. Define event schema with timestamp, level, type, message, and context data. Support buffering and batch writes for performance. Include event types for task start/complete, errors, state changes, and system events.",
"status": "pending",
"testStrategy": "Unit tests for JSONL formatting, event schema validation, and log file writing with concurrent access scenarios"
@@ -7342,7 +8411,9 @@
"id": 4,
"title": "Implement test result storage and commits tracking",
"description": "Create structured storage for test outputs and commit SHA tracking",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement storeTestResults() method that saves test outputs to test-results/<phase>/ directories with proper JSON formatting. Create updateCommitLog() method that appends commit SHAs to commits.txt with timestamps and context. Support different test result formats and ensure atomic file operations.",
"status": "pending",
"testStrategy": "Unit tests for test result serialization, commit tracking, and file integrity validation"
@@ -7351,7 +8422,10 @@
"id": 5,
"title": "Implement state checkpointing and resume functionality",
"description": "Add state checkpointing capabilities and resume logic for interrupted runs",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Implement saveCheckpoint() and loadCheckpoint() methods for persisting current run state. Create resume detection logic that identifies incomplete runs and restores state. Support partial completion tracking and validate state consistency on resume. Include cleanup of corrupted or incomplete run directories.",
"status": "pending",
"testStrategy": "Integration tests for state persistence across service restarts, resume functionality validation, and corruption recovery scenarios"
@@ -7365,7 +8439,11 @@
"details": "Create packages/tm-core/src/services/pr-adapter.ts that uses gh CLI to create pull requests. Generate PR body from run manifest and test results, include task/subtask completion summary, coverage metrics, commit links. Implement PR title format: 'Task #{id} [{tag}]: {title}'. Add fallback instructions when gh CLI unavailable. Support custom PR body templates.",
"testStrategy": "Unit tests for PR body generation, gh CLI command construction, error handling. Integration tests with mocked gh CLI to verify PR creation flow and body formatting.",
"priority": "medium",
- "dependencies": [31, 32, 38],
+ "dependencies": [
+ 31,
+ 32,
+ 38
+ ],
"status": "pending",
"subtasks": [
{
@@ -7381,7 +8459,9 @@
"id": 2,
"title": "Implement gh CLI integration and command execution",
"description": "Add GitHub CLI detection, validation, and PR creation command execution functionality",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement gh CLI availability check, version validation, and authentication status verification. Add createPR method that constructs gh pr create commands with title, body, and branch parameters. Include error handling for gh CLI failures, network issues, and authentication problems. Add fallback messaging when gh CLI is unavailable.",
"status": "pending",
"testStrategy": "Unit tests with mocked child_process for gh CLI commands, error scenarios, and fallback behavior"
@@ -7390,7 +8470,9 @@
"id": 3,
"title": "Build PR body generation from run manifests and test results",
"description": "Implement comprehensive PR body generation using run data, task completion, and test metrics",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create generatePRBody method that processes run manifest data, task/subtask completion summaries, test results, coverage metrics, and commit information. Implement PR title formatting as 'Task #{id} [{tag}]: {title}'. Include sections for completed tasks, test results, coverage changes, and commit links. Add markdown formatting for readability.",
"status": "pending",
"testStrategy": "Unit tests for body generation with various run manifest scenarios, test result formatting, and markdown output validation"
@@ -7399,7 +8481,10 @@
"id": 4,
"title": "Add custom PR template system and configuration support",
"description": "Implement customizable PR body templates with variable substitution and configuration integration",
- "dependencies": [2, 3],
+ "dependencies": [
+ 2,
+ 3
+ ],
"details": "Create template system supporting custom PR body templates from .taskmaster/templates/pr-template.md. Implement variable substitution for {{taskId}}, {{taskTitle}}, {{testResults}}, {{coverage}}, {{commits}}. Add template validation, fallback to default template, and integration with ConfigManager for template paths and PR settings.",
"status": "pending",
"testStrategy": "Unit tests for template loading, variable substitution, validation, and integration with configuration system"
@@ -7413,7 +8498,10 @@
"details": "Extend packages/tm-core/src/services/task-service.ts with getNextEligibleSubtask method that considers subtask dependencies, status, and priority. Implement topological sorting for subtask execution order. Handle blocked subtasks and dependency validation. Integration with existing dependency management and task status systems.",
"testStrategy": "Unit tests for dependency resolution algorithms, edge cases with circular dependencies, priority handling. Integration tests with complex task hierarchies and dependency chains.",
"priority": "medium",
- "dependencies": [31, 36],
+ "dependencies": [
+ 31,
+ 36
+ ],
"status": "pending",
"subtasks": [
{
@@ -7429,7 +8517,9 @@
"id": 2,
"title": "Implement topological sorting for subtask ordering",
"description": "Add topological sorting algorithm to determine optimal subtask execution order",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement Kahn's algorithm or DFS-based topological sorting to order subtasks based on their dependencies. Handle priority weighting within dependency constraints. Create sorting functions that respect both dependencies and priority levels for optimal execution order.",
"status": "pending",
"testStrategy": "Unit tests for topological sort correctness, priority handling, and various dependency graph structures"
@@ -7438,7 +8528,10 @@
"id": 3,
"title": "Create task eligibility checking system",
"description": "Implement logic to determine which subtasks are eligible for execution based on status and dependencies",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Create getNextEligibleSubtask method that checks subtask status, dependency completion, and availability. Implement filtering logic for blocked, pending, and ready-to-execute subtasks. Add priority-based selection when multiple subtasks are eligible.",
"status": "pending",
"testStrategy": "Unit tests for eligibility logic with various status combinations and dependency states"
@@ -7447,7 +8540,11 @@
"id": 4,
"title": "Integrate dependency resolution with TaskService",
"description": "Integrate the dependency resolution system into the existing TaskService architecture",
- "dependencies": [1, 2, 3],
+ "dependencies": [
+ 1,
+ 2,
+ 3
+ ],
"details": "Extend packages/tm-core/src/services/task-service.ts with new dependency resolution methods. Integrate with existing task status management and dependency validation systems. Ensure backward compatibility and proper error handling for the new functionality.",
"status": "pending",
"testStrategy": "Integration tests with existing TaskService methods, complex task hierarchies, and dependency chain validation"
@@ -7461,7 +8558,11 @@
"details": "Enhance RunStateManager with checkpoint creation and restoration. Add --resume flag to autopilot command that reconstructs WorkflowOrchestrator state from persisted run data. Implement state validation to ensure safe resume (git state, file changes, test status). Support partial phase resume (e.g., retry GREEN phase after manual fixes).",
"testStrategy": "Unit tests for state serialization/deserialization, validation logic. Integration tests interrupting and resuming workflows at different phases, verifying state consistency.",
"priority": "medium",
- "dependencies": [34, 36, 38],
+ "dependencies": [
+ 34,
+ 36,
+ 38
+ ],
"status": "pending",
"subtasks": [
{
@@ -7477,7 +8578,9 @@
"id": 2,
"title": "Implement state restoration logic",
"description": "Create state restoration functionality to reconstruct WorkflowOrchestrator from persisted checkpoint data",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add methods to RunStateManager for loading checkpoint files, deserializing workflow state, and reconstructing WorkflowOrchestrator instance. Implement state reconstruction including phase restoration, task progress, git branch context, and test results. Handle checkpoint file validation and corruption detection with appropriate error messaging.",
"status": "pending",
"testStrategy": "Unit tests for checkpoint loading, state deserialization, WorkflowOrchestrator reconstruction. Test error handling for corrupted or invalid checkpoint files."
@@ -7486,7 +8589,9 @@
"id": 3,
"title": "Add state validation for safe resume",
"description": "Implement validation logic to ensure safe workflow resumption by checking git state, file changes, and test status",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Create validation methods to verify git working tree is clean, current branch matches checkpoint, no unexpected file changes occurred, and test environment is consistent. Implement safety checks for package.json changes, dependency updates, and configuration modifications. Provide detailed validation failure messages and recovery suggestions.",
"status": "pending",
"testStrategy": "Unit tests for validation logic, git state checking, file change detection. Integration tests with scenarios like dirty working tree, branch changes, and dependency modifications."
@@ -7495,7 +8600,9 @@
"id": 4,
"title": "Add --resume flag to autopilot command",
"description": "Implement CLI flag for resuming interrupted autopilot workflows from checkpoints",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Add --resume flag to autopilot command that lists available checkpoints, allows selection of specific checkpoint, and initiates workflow restoration. Implement checkpoint discovery from .taskmaster/checkpoints/ directory, display checkpoint metadata (timestamp, phase, progress), and handle user selection. Include --resume-latest option for automatic latest checkpoint selection.",
"status": "pending",
"testStrategy": "Integration tests for CLI flag functionality, checkpoint listing, user selection handling, and automatic latest checkpoint selection. Test error scenarios like no checkpoints found."
@@ -7504,7 +8611,9 @@
"id": 5,
"title": "Support partial phase resume functionality",
"description": "Implement ability to resume workflow from specific phases like retrying GREEN phase after manual fixes",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Add phase-specific resume options allowing users to restart from particular workflow phases (Preflight, Branch, SubtaskLoop, Finalization). Implement phase validation to ensure prerequisites are met, state consistency checks for partial resume, and option to skip completed phases. Support retry scenarios like re-running tests after manual bug fixes or resuming after dependency updates.",
"status": "pending",
"testStrategy": "Integration tests for partial phase resume scenarios, phase validation logic, and state consistency checks. Test retry workflows after manual interventions and dependency changes."
@@ -7518,7 +8627,10 @@
"details": "Enhance TestRunnerAdapter to parse coverage reports from Jest/Vitest and enforce configurable thresholds (lines, branches, functions, statements). Default to 80% across all metrics. Add coverage gates in GREEN phase before commit and final test suite before PR creation. Provide detailed coverage failure reporting with suggestions for improvement.",
"testStrategy": "Unit tests for coverage report parsing from different formats (lcov, json), threshold validation logic. Integration tests with actual test runs generating coverage data.",
"priority": "medium",
- "dependencies": [33, 36],
+ "dependencies": [
+ 33,
+ 36
+ ],
"status": "pending",
"subtasks": [
{
@@ -7534,7 +8646,9 @@
"id": 2,
"title": "Implement configurable threshold validation logic",
"description": "Create threshold validation system with configurable coverage requirements",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Build threshold validation engine that accepts configurable thresholds for lines, branches, functions, and statements (default 80%). Compare parsed coverage metrics against thresholds and generate detailed validation results. Support per-metric configuration and overall coverage requirements.",
"status": "pending",
"testStrategy": "Unit tests for threshold validation with various coverage scenarios. Test edge cases like missing metrics and invalid threshold configurations."
@@ -7543,7 +8657,9 @@
"id": 3,
"title": "Add coverage gates in workflow phases",
"description": "Integrate coverage validation as gates in GREEN phase and pre-finalization",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Add coverage validation gates in the GREEN phase before allowing commits and in the final test suite before PR creation. Integrate with existing workflow phases to halt execution when coverage thresholds are not met. Provide clear gate failure messaging and next steps.",
"status": "pending",
"testStrategy": "Integration tests with actual test runs generating coverage data. Verify gates properly block workflow progression when thresholds fail."
@@ -7552,7 +8668,9 @@
"id": 4,
"title": "Create detailed coverage failure reporting system",
"description": "Implement comprehensive coverage reporting with improvement suggestions",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Build detailed coverage failure reporting that shows which metrics failed thresholds, specific uncovered lines/branches, and actionable suggestions for improvement. Include file-level coverage breakdown, highlight critical uncovered areas, and provide guidance on writing additional tests.",
"status": "pending",
"testStrategy": "Unit tests for report generation with various failure scenarios. Verify report formatting and suggestion quality with mock coverage data."
@@ -7566,7 +8684,10 @@
"details": "Create apps/cli/src/ui/tui/navigator.ts using blessed or ink for terminal UI. Left pane shows project info, active tag, task list with status indicators. Right pane coordinates with tmux to spawn executor terminal. Implement keybindings for navigation (↑/↓), task selection (Enter), workflow control (s/p/q). Real-time status updates via file watching or event streams.",
"testStrategy": "Unit tests for UI component rendering, key handling, state updates. Integration tests with tmux session management and terminal interaction simulation.",
"priority": "low",
- "dependencies": [31, 34],
+ "dependencies": [
+ 31,
+ 34
+ ],
"status": "pending",
"subtasks": [
{
@@ -7582,7 +8703,9 @@
"id": 2,
"title": "Design and implement left pane interface layout",
"description": "Create the left pane UI components showing project information, active tag, and task list with status indicators",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement left pane layout with three sections: project info header, active tag display, and scrollable task list. Add status indicators using colors/symbols (✓ done, ⏳ in-progress, ○ pending). Implement proper text wrapping, overflow handling, and responsive layout for different terminal sizes.",
"status": "pending",
"testStrategy": "Unit tests for layout rendering, status indicator display, and text formatting"
@@ -7591,7 +8714,9 @@
"id": 3,
"title": "Implement tmux integration and right pane coordination",
"description": "Create tmux session management and coordinate right pane terminal spawning for task execution",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement tmux session creation, window management, and pane coordination. Create TmuxAdapter class to handle session lifecycle, window/pane creation for executor terminals. Ensure proper cleanup of tmux sessions and handle edge cases like existing sessions or tmux not available.",
"status": "pending",
"testStrategy": "Integration tests for tmux session management, pane creation, and cleanup procedures"
@@ -7600,7 +8725,9 @@
"id": 4,
"title": "Build navigation system with keybindings",
"description": "Implement keyboard navigation system with arrow keys, Enter for selection, and workflow control keys",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement keyboard event handling for navigation (↑/↓ arrow keys), task selection (Enter), and workflow control (s for start, p for pause, q for quit). Add visual feedback for selected items, proper focus management, and keyboard shortcut help display. Handle edge cases like empty task lists.",
"status": "pending",
"testStrategy": "Unit tests for key handling logic, navigation state management, and selection behavior"
@@ -7609,7 +8736,10 @@
"id": 5,
"title": "Implement real-time status updates system",
"description": "Create real-time monitoring system for task status changes using file watching or event streams",
- "dependencies": [2, 3],
+ "dependencies": [
+ 2,
+ 3
+ ],
"details": "Implement file system watching for tasks.json changes or event-based updates for real-time status synchronization. Update UI components when task status changes, add smooth transitions, and handle concurrent updates. Consider using chokidar for file watching or implement event emitter pattern for status changes.",
"status": "pending",
"testStrategy": "Integration tests for file watching, event handling, and UI update responsiveness"
@@ -7618,7 +8748,10 @@
"id": 6,
"title": "Implement event handling and user experience polish",
"description": "Add comprehensive event handling, error management, and user experience improvements for the TUI navigator",
- "dependencies": [4, 5],
+ "dependencies": [
+ 4,
+ 5
+ ],
"details": "Implement comprehensive error handling for tmux failures, terminal resize events, and graceful degradation. Add loading states, confirmation dialogs for destructive actions, and help screens. Implement proper cleanup on exit, signal handling (SIGINT, SIGTERM), and recovery from unexpected states.",
"status": "pending",
"testStrategy": "Integration tests for error scenarios, terminal interaction simulation, and edge case handling"
@@ -7632,7 +8765,9 @@
"details": "Create packages/tm-core/src/services/prompt-composer.ts that loads and combines prompt fragments from .cursor/rules/, task context, and phase-specific instructions. Implement template system with token replacement ({task}, {subtask}, {framework}). Support rule precedence and conditional inclusion based on project type. Generate targeted prompts for RED (test generation) and GREEN (implementation) phases.",
"testStrategy": "Unit tests for template processing, rule loading, context injection. Integration tests generating complete prompts and validating content relevance and accuracy.",
"priority": "medium",
- "dependencies": [35],
+ "dependencies": [
+ 35
+ ],
"status": "pending",
"subtasks": [
{
@@ -7648,7 +8783,9 @@
"id": 2,
"title": "Implement template system with token replacement",
"description": "Build template processing engine that supports dynamic token replacement and conditional logic",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement processTemplate() method supporting token replacement for {task}, {subtask}, {framework}, {phase} placeholders. Add conditional template sections with {{#if condition}} syntax. Support nested replacements and escape sequences. Include template validation and syntax error reporting with helpful error messages.",
"status": "pending",
"testStrategy": "Unit tests for token replacement accuracy, conditional logic evaluation, nested template processing, and error handling for malformed templates"
@@ -7657,7 +8794,9 @@
"id": 3,
"title": "Implement rule loading and precedence system",
"description": "Create rule fragment loading system from .cursor/rules/ with proper precedence and conditional inclusion",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement loadRules() method that scans .cursor/rules/ directory for rule files, parses rule metadata including precedence levels and project type conditions. Support rule inheritance and override patterns. Implement conditional inclusion based on project framework detection (React, Vue, Node.js, etc.). Cache loaded rules for performance.",
"status": "pending",
"testStrategy": "Unit tests for file system scanning, rule parsing, precedence resolution, and conditional filtering. Integration tests with various project structures and rule configurations"
@@ -7666,7 +8805,10 @@
"id": 4,
"title": "Implement context injection and phase-specific prompt generation",
"description": "Build context assembly system that combines task data, rules, and phase instructions into complete prompts",
- "dependencies": [2, 3],
+ "dependencies": [
+ 2,
+ 3
+ ],
"details": "Implement compose() method that combines task context, loaded rules, and phase-specific instructions into targeted prompts for RED (test generation) and GREEN (implementation) phases. Support framework-specific adaptations and context prioritization. Include prompt validation and length optimization to ensure effective AI consumption.",
"status": "pending",
"testStrategy": "Unit tests for context injection accuracy, phase-specific prompt generation, and framework adaptation. Integration tests generating complete prompts and validating content relevance for different TDD phases"
@@ -7680,7 +8822,10 @@
"details": "Enhance GitAdapter to automatically set active tag based on branch name using existing tag-management.js functionality. Extract tag from branch name using configured pattern, validate tag exists, and switch to tag context before workflow execution. Implement branch-to-tag mapping persistence and validation. Support tag creation if branch tag doesn't exist.",
"testStrategy": "Unit tests for tag extraction from branch names, tag switching logic, mapping persistence. Integration tests with actual git branches and tag management operations.",
"priority": "medium",
- "dependencies": [32, 40],
+ "dependencies": [
+ 32,
+ 40
+ ],
"status": "pending",
"subtasks": [
{
@@ -7696,7 +8841,9 @@
"id": 2,
"title": "Implement automatic tag switching workflow",
"description": "Create workflow logic that automatically switches to the appropriate tag context before executing any operations based on current branch",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement pre-workflow hook in GitAdapter that detects current branch, extracts tag using patterns from subtask 1, validates tag exists, and switches active tag context. Handle cases where extracted tag doesn't exist by optionally creating new tag or falling back to default. Ensure tag switching occurs before any workflow execution begins.",
"status": "pending",
"testStrategy": "Integration tests with actual git branches and tag switching operations. Test tag creation workflows and fallback scenarios. Verify workflow execution uses correct tag context."
@@ -7705,7 +8852,9 @@
"id": 3,
"title": "Implement branch-to-tag mapping persistence and validation",
"description": "Create persistent storage for branch-tag mappings with validation and management capabilities",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement mapping persistence using configuration files or database to store branch-to-tag relationships. Add validation logic to ensure mappings are consistent and up-to-date. Include management commands to view, update, and clean up mappings. Support mapping inheritance for branch hierarchies and pattern-based rules.",
"status": "pending",
"testStrategy": "Unit tests for mapping storage, retrieval, and validation logic. Integration tests for mapping consistency across git operations and tag management scenarios."
@@ -7719,7 +8868,12 @@
"details": "Add comprehensive error handling throughout WorkflowOrchestrator with specific error types: GitError, TestError, ConfigError, DependencyError. Implement recovery suggestions for common failures (merge conflicts, test timeouts, missing dependencies). Add --force flag to bypass certain validations. Include error context in run reports and logs.",
"testStrategy": "Unit tests for error classification, recovery suggestion generation, force flag behavior. Integration tests simulating various failure scenarios and verifying appropriate error handling.",
"priority": "medium",
- "dependencies": [31, 32, 33, 38],
+ "dependencies": [
+ 31,
+ 32,
+ 33,
+ 38
+ ],
"status": "pending",
"subtasks": [
{
@@ -7735,7 +8889,9 @@
"id": 2,
"title": "Build recovery suggestion engine with actionable recommendations",
"description": "Develop intelligent system that provides specific recovery steps based on error type and context, with automated resolution where possible",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create RecoverySuggestionEngine that maps error types to actionable recovery steps. For GitError: suggest merge conflict resolution, branch switching. For TestError: recommend timeout adjustments, dependency installation. For ConfigError: provide configuration fixes. Include automated recovery options where safe and manual step-by-step instructions.",
"status": "pending",
"testStrategy": "Unit tests for suggestion generation logic, recovery step validation. Integration tests simulating error scenarios and verifying suggested recovery actions are accurate and actionable."
@@ -7744,7 +8900,9 @@
"id": 3,
"title": "Implement error context management and preservation",
"description": "Create system to capture, store, and propagate error context throughout the workflow execution chain for detailed debugging",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Build ErrorContext class to capture execution state, command history, environment details, and task information when errors occur. Implement context serialization for persistence and context propagation through async operations. Include stack trace enhancement and correlation IDs for tracking errors across workflow phases.",
"status": "pending",
"testStrategy": "Unit tests for context capture, serialization, and propagation. Integration tests verifying context preservation across workflow phases and accurate debugging information availability."
@@ -7753,7 +8911,10 @@
"id": 4,
"title": "Add --force flag implementation with selective validation bypass",
"description": "Implement force flag mechanism that allows bypassing specific validations while maintaining critical safety checks",
- "dependencies": [2, 3],
+ "dependencies": [
+ 2,
+ 3
+ ],
"details": "Add --force flag support to WorkflowOrchestrator commands with granular control over which validations to bypass. Implement ForceContext to track bypassed checks and maintain audit trail. Define which validations are force-bypassable (dependency checks, test requirements) vs critical safety checks (git repo integrity, file permissions).",
"status": "pending",
"testStrategy": "Unit tests for force flag parsing, validation bypass logic, safety check preservation. Integration tests with various force scenarios ensuring critical protections remain active."
@@ -7762,7 +8923,11 @@
"id": 5,
"title": "Integrate error handling with logging and reporting systems",
"description": "Connect error handling system with existing logging infrastructure and enhance run reports with error context and recovery information",
- "dependencies": [2, 3, 4],
+ "dependencies": [
+ 2,
+ 3,
+ 4
+ ],
"details": "Integrate ErrorHandler with existing logging system to provide structured error logs with context. Enhance run reports to include error summaries, recovery actions taken, and performance impact. Implement error metrics collection and add error information to workflow execution summaries with actionable next steps.",
"status": "pending",
"testStrategy": "Unit tests for logging integration, report enhancement, metrics collection. Integration tests verifying complete error flow from detection through logging to reporting with proper context preservation."
@@ -7776,7 +8941,10 @@
"details": "Enhance GitAdapter with commit message generation using configurable templates. Support conventional commit format with task context: '{type}({scope}): {message} (task {id}.{subtask})'. Auto-detect commit type (feat, fix, chore) based on task content and file changes. Include commit message templates and validation against conventional commit standards.",
"testStrategy": "Unit tests for message template processing, type detection, validation logic. Integration tests generating commit messages for various task types and validating format compliance.",
"priority": "low",
- "dependencies": [32, 36],
+ "dependencies": [
+ 32,
+ 36
+ ],
"status": "pending",
"subtasks": [
{
@@ -7792,7 +8960,9 @@
"id": 2,
"title": "Implement commit type auto-detection logic",
"description": "Create intelligent detection of conventional commit types based on task content and file changes",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Analyze task descriptions, titles, and file changes to automatically determine commit type (feat, fix, chore, docs, style, refactor, test). Use pattern matching on task content and file extension analysis. Include fallback logic and confidence scoring for type suggestions.",
"status": "pending",
"testStrategy": "Unit tests for type detection algorithms with various task scenarios. Test file change analysis and pattern matching accuracy."
@@ -7801,7 +8971,10 @@
"id": 3,
"title": "Add commit message validation and GitAdapter integration",
"description": "Implement validation against conventional commit standards and integrate with GitAdapter",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Validate generated commit messages against conventional commit specification including format, length limits, and required components. Integrate template system and type detection into GitAdapter class. Add configuration options for strict vs lenient validation modes.",
"status": "pending",
"testStrategy": "Unit tests for validation rules and GitAdapter integration. Integration tests generating complete commit messages and verifying conventional commit compliance."
@@ -7815,7 +8988,9 @@
"details": "Enhance TestRunnerAdapter with framework-specific adapters for pytest (Python), go test (Go), cargo test (Rust). Implement common interface for test execution, result parsing, and coverage reporting across frameworks. Add framework detection based on project files (requirements.txt, go.mod, Cargo.toml). Maintain backward compatibility with existing JavaScript/TypeScript support.",
"testStrategy": "Unit tests for framework detection, adapter interface implementation. Integration tests with fixture projects for each supported framework, verifying test execution and result parsing.",
"priority": "low",
- "dependencies": [33],
+ "dependencies": [
+ 33
+ ],
"status": "pending",
"subtasks": [
{
@@ -7831,7 +9006,9 @@
"id": 2,
"title": "Design common adapter interface",
"description": "Create a unified interface for test execution adapters across all supported frameworks",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Define TestFrameworkAdapter interface with methods: execute(), parseResults(), getCoverage(), getTestFiles(). Create base adapter class with common functionality like result normalization, error handling, and timeout management. Define standardized result format for test outcomes, coverage data, and execution metadata.",
"status": "pending",
"testStrategy": "Unit tests for interface implementation, base adapter functionality. Mock adapter tests for interface compliance verification."
@@ -7840,7 +9017,9 @@
"id": 3,
"title": "Implement Python pytest adapter",
"description": "Create adapter for Python pytest framework with result parsing and coverage support",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement PytestAdapter extending TestFrameworkAdapter. Handle pytest command execution with proper arguments for JSON output and coverage reporting. Parse pytest JSON results into standardized format. Support pytest-cov for coverage data extraction. Handle Python virtual environment detection and activation.",
"status": "pending",
"testStrategy": "Unit tests for pytest command construction, result parsing. Integration tests with real Python projects using pytest and pytest-cov."
@@ -7849,7 +9028,9 @@
"id": 4,
"title": "Implement Go and Rust adapters",
"description": "Create adapters for Go test and Rust cargo test frameworks with result parsing",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement GoTestAdapter for 'go test' command with JSON output parsing and coverage support via go tool cover. Implement CargoTestAdapter for 'cargo test' with JSON message parsing and coverage via cargo-tarpaulin. Both adapters should handle framework-specific output formats and convert to standardized result structure.",
"status": "pending",
"testStrategy": "Unit tests for command execution and result parsing for both Go and Rust. Integration tests with sample Go modules and Rust crates."
@@ -7858,7 +9039,10 @@
"id": 5,
"title": "Integrate adapters with TestRunnerAdapter and ensure backward compatibility",
"description": "Extend existing TestRunnerAdapter to use new framework adapters while maintaining JavaScript/TypeScript support",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Modify TestRunnerAdapter to use FrameworkDetector and route to appropriate adapter. Maintain existing Jest/Vitest functionality as default for JavaScript/TypeScript projects. Add adapter factory pattern for framework selection. Ensure all existing TestRunnerAdapter methods work unchanged for backward compatibility.",
"status": "pending",
"testStrategy": "Unit tests for adapter routing and factory pattern. Integration tests verifying existing Jest/Vitest functionality remains unchanged. Cross-framework integration tests."
@@ -7872,7 +9056,10 @@
"details": "Enhance WorkflowOrchestrator with EventEmitter-based streaming of workflow events (phase changes, test results, commit creation). Implement structured event format with timestamps, phase info, and progress data. Support event persistence to run logs and optional WebSocket streaming for external monitoring. Include progress percentage calculation and time estimates.",
"testStrategy": "Unit tests for event emission, formatting, persistence. Integration tests monitoring complete workflow execution with event verification and progress tracking accuracy.",
"priority": "low",
- "dependencies": [31, 38],
+ "dependencies": [
+ 31,
+ 38
+ ],
"status": "pending",
"subtasks": [
{
@@ -7888,7 +9075,9 @@
"id": 2,
"title": "Implement structured event format with timestamps and metadata",
"description": "Create standardized event format including timestamps, phase information, progress data, and metadata",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Define TypeScript interfaces for workflow events with required fields: eventType, timestamp, phaseInfo, progressPercentage, timeEstimates, metadata. Implement event formatting utilities and validation. Include progress calculation logic based on workflow phases and subtask completion.",
"status": "pending",
"testStrategy": "Unit tests for event format validation, timestamp accuracy, progress percentage calculations. Test event serialization and deserialization."
@@ -7897,7 +9086,9 @@
"id": 3,
"title": "Add event persistence to run logs",
"description": "Implement event logging system to persist workflow events to run logs for historical tracking",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Create event persistence layer that writes structured events to run log files. Implement log rotation and retention policies. Add event querying capabilities for retrieving historical workflow data. Ensure thread-safe writing and proper error handling for file operations.",
"status": "pending",
"testStrategy": "Unit tests for event persistence, log file management, and querying. Integration tests verifying complete workflow event logging and retrieval accuracy."
@@ -7906,7 +9097,9 @@
"id": 4,
"title": "Implement optional WebSocket streaming for external monitoring",
"description": "Create WebSocket server for real-time event streaming to external monitoring clients",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement optional WebSocket server using ws library for streaming events to external clients. Add connection management, authentication, and rate limiting. Support multiple client connections with event filtering. Include graceful connection handling and error recovery mechanisms.",
"status": "pending",
"testStrategy": "Unit tests for WebSocket server setup, client connection handling, event broadcasting. Integration tests with multiple clients receiving real-time workflow events."
@@ -7920,7 +9113,10 @@
"details": "Enhance TestRunnerAdapter with test targeting based on file changes and test dependencies. Implement test impact analysis to identify which tests are affected by implementation changes. Support framework-specific targeting (Jest --findRelatedTests, Vitest changed files). Fall back to full test suite if targeting fails or for final validation.",
"testStrategy": "Unit tests for change detection, test dependency analysis, targeting logic. Integration tests with various project structures verifying targeted test selection accuracy and performance improvements.",
"priority": "low",
- "dependencies": [33, 36],
+ "dependencies": [
+ 33,
+ 36
+ ],
"status": "pending",
"subtasks": [
{
@@ -7936,7 +9132,9 @@
"id": 2,
"title": "Build test dependency analysis engine",
"description": "Create dependency mapping system to understand which tests are affected by specific file changes",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement TestDependencyAnalyzer that maps source files to test files through import analysis, test file naming conventions, and explicit dependency declarations. Parse import statements, require calls, and dynamic imports. Build dependency graph with file-to-test relationships. Support both direct and transitive dependencies.",
"status": "pending",
"testStrategy": "Unit tests for import parsing, dependency graph construction, transitive dependency resolution. Integration tests with real project structures."
@@ -7945,7 +9143,9 @@
"id": 3,
"title": "Create framework-specific targeting adapters",
"description": "Implement framework-specific test targeting using native tools like Jest --findRelatedTests and Vitest changed files",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Create FrameworkTargetingAdapter with implementations for Jest (--findRelatedTests), Vitest (--changed), and generic fallback. Abstract framework detection and command generation. Handle framework-specific configuration and edge cases. Provide unified interface for all test runners.",
"status": "pending",
"testStrategy": "Unit tests for each framework adapter, command generation, framework detection. Integration tests with actual Jest and Vitest projects."
@@ -7954,7 +9154,10 @@
"id": 4,
"title": "Implement test impact calculation algorithm",
"description": "Create intelligent algorithm to calculate which tests should run based on change analysis and dependency mapping",
- "dependencies": [2, 3],
+ "dependencies": [
+ 2,
+ 3
+ ],
"details": "Implement TestImpactCalculator that combines file changes with dependency analysis to determine minimal test set. Use scoring algorithm considering change severity, dependency depth, and historical test failures. Optimize for both coverage and performance. Include confidence metrics for targeting decisions.",
"status": "pending",
"testStrategy": "Unit tests for impact calculation logic, scoring algorithms, confidence metrics. Performance tests with large codebases and dependency graphs."
@@ -7963,7 +9166,10 @@
"id": 5,
"title": "Add fallback logic and integration with TestRunnerAdapter",
"description": "Integrate targeting system with existing TestRunnerAdapter and implement robust fallback mechanisms",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Enhance TestRunnerAdapter with intelligent targeting methods. Implement fallback to full test suite when targeting fails, confidence is low, or for final validation. Add configuration options for targeting aggressiveness and fallback thresholds. Include performance monitoring and targeting effectiveness metrics.",
"status": "pending",
"testStrategy": "Integration tests with TestRunnerAdapter, fallback scenario testing, performance benchmarks. End-to-end tests verifying targeting accuracy and fallback reliability."
@@ -7977,7 +9183,10 @@
"details": "Enhance autopilot command dry-run mode with detailed execution timeline showing all phases, subtasks, estimated durations, and dependencies. Include preflight check results, branch operations, test generation/execution plans, and finalization steps. Add ASCII art progress visualization and resource requirements (git, gh, test tools).",
"testStrategy": "Unit tests for timeline calculation, duration estimation, visualization formatting. Integration tests generating dry-run output for various task complexities and verifying accuracy of plans.",
"priority": "low",
- "dependencies": [34, 40],
+ "dependencies": [
+ 34,
+ 40
+ ],
"status": "pending",
"subtasks": [
{
@@ -7993,7 +9202,9 @@
"id": 2,
"title": "Implement duration estimation algorithms",
"description": "Create intelligent duration estimation based on task complexity and historical data",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Develop estimation algorithms in apps/cli/src/commands/autopilot/estimator.ts. Analyze task complexity factors (subtask count, file changes, test requirements). Use historical execution data or baseline estimates. Account for tool dependencies (git, gh, test runners) and system resources. Include confidence intervals and estimation accuracy tracking.",
"status": "pending",
"testStrategy": "Unit tests for estimation algorithms with various complexity scenarios. Integration tests comparing estimates against actual execution times for accuracy validation."
@@ -8002,7 +9213,10 @@
"id": 3,
"title": "Create ASCII art progress visualization",
"description": "Build comprehensive visualization formatter for execution timeline display",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Create visualization formatter in apps/cli/src/commands/autopilot/visualizer.ts. Generate ASCII art timeline with phase bars, dependency arrows, and progress indicators. Include execution tree view showing task hierarchy and parallel operations. Add resource requirement badges (git, gh, npm) and time estimates. Support colored output with status indicators.",
"status": "pending",
"testStrategy": "Unit tests for ASCII art generation, timeline formatting, and colored output. Visual regression tests comparing output layouts for different terminal widths and task complexities."
@@ -8025,7 +9239,11 @@
"details": "Create tests/integration/autopilot/ with full workflow tests using temporary git repositories, mock task data, and isolated test environments. Test complete red-green-commit cycles, error recovery, resume functionality, and PR creation. Include performance benchmarks and resource usage validation. Support both Jest and Vitest test execution.",
"testStrategy": "Integration tests with isolated environments, git repository fixtures, mock GitHub API responses. Performance tests measuring workflow execution times and resource consumption across different project sizes.",
"priority": "medium",
- "dependencies": [36, 39, 41],
+ "dependencies": [
+ 36,
+ 39,
+ 41
+ ],
"status": "pending",
"subtasks": [
{
@@ -8041,7 +9259,9 @@
"id": 2,
"title": "Implement mock integrations and external service stubs",
"description": "Create comprehensive mocks for GitHub API, git operations, and external dependencies to enable controlled testing of autopilot workflows",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Develop mock implementations for GitHub API responses (PR creation, status checks), git command execution, and external tool integrations. Create MockGitHubService and MockGitService classes that can simulate various scenarios including API failures, network timeouts, and authentication errors. Include configurable response patterns for different test scenarios.",
"status": "pending",
"testStrategy": "Test mock accuracy against real API responses, verify error scenario simulation, and ensure mocks can be configured for different test cases without conflicts."
@@ -8050,7 +9270,10 @@
"id": 3,
"title": "Create end-to-end workflow test scenarios",
"description": "Implement comprehensive test cases covering complete autopilot workflows including success paths, error scenarios, and edge cases",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Develop test suites for complete red-green-commit cycles, error recovery scenarios, resume functionality after interruption, and PR creation workflows. Include tests for various project types, different task complexities, and failure modes (test failures, build errors, git conflicts). Create scenario-based test data with realistic task structures and dependencies.",
"status": "pending",
"testStrategy": "Integration tests that verify complete workflow execution, error handling paths, and state persistence across resume operations. Performance validation for different project sizes and task counts."
@@ -8059,7 +9282,9 @@
"id": 4,
"title": "Implement performance benchmarking and resource monitoring",
"description": "Create performance testing infrastructure to measure autopilot workflow execution times, memory usage, and resource consumption",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Develop performance testing harness that measures workflow execution times, memory consumption, CPU usage, and git repository size impacts. Create benchmarking utilities that can test across different project sizes (small, medium, large codebases) and task counts. Include regression testing to detect performance degradation and resource leak detection.",
"status": "pending",
"testStrategy": "Performance tests with baseline measurements, resource usage monitoring, and regression detection. Validate that workflows complete within acceptable time limits for different project scales."
@@ -8068,7 +9293,10 @@
"id": 5,
"title": "Develop test isolation and parallelization strategies",
"description": "Implement robust test isolation mechanisms to ensure autopilot integration tests can run safely in parallel without interference",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Create test isolation strategies using unique temporary directories, port management for local services, and process isolation for concurrent test execution. Implement test cleanup mechanisms that prevent state leakage between tests. Include parallel execution support for both Jest and Vitest with proper resource management and conflict prevention.",
"status": "pending",
"testStrategy": "Concurrency tests to verify isolation effectiveness, cleanup verification, and resource contention prevention. Test that parallel execution produces consistent results without race conditions."
@@ -8077,7 +9305,11 @@
"id": 6,
"title": "Create comprehensive result validation and reporting",
"description": "Implement validation mechanisms to verify autopilot workflow results and create detailed test reporting for integration test outcomes",
- "dependencies": [3, 4, 5],
+ "dependencies": [
+ 3,
+ 4,
+ 5
+ ],
"details": "Develop result validation utilities that verify git history correctness, PR content accuracy, task completion status, and workflow state consistency. Create comprehensive test reporting that includes performance metrics, resource usage statistics, and detailed failure analysis. Include visual diff tools for comparing expected vs actual workflow outcomes.",
"status": "pending",
"testStrategy": "Validation tests for result verification accuracy, reporting completeness, and failure diagnosis capabilities. Test that validation can detect subtle workflow inconsistencies and state corruption."
@@ -8091,7 +9323,9 @@
"details": "Create detailed documentation covering autopilot setup, configuration options, workflow phases, error handling, and best practices. Include example PRD files that demonstrate autopilot-compatible task structure. Add troubleshooting guide for common issues (git conflicts, test failures, dependency problems). Create demo video or GIF showing complete workflow execution.",
"testStrategy": "Documentation validation through user testing, example verification by running actual autopilot workflows, link checking and format validation. Accessibility and clarity review for technical documentation.",
"priority": "low",
- "dependencies": [52],
+ "dependencies": [
+ 52
+ ],
"status": "pending",
"subtasks": [
{
@@ -8107,7 +9341,9 @@
"id": 2,
"title": "Create example PRD files and templates",
"description": "Develop example PRD files that demonstrate autopilot-compatible task structure and workflow patterns",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create example PRD files in .taskmaster/docs/examples/ showing different project types (web app, API, CLI tool) with autopilot-compatible task structures. Include templates for common scenarios and best practices for task decomposition that works well with autonomous workflows.",
"status": "pending",
"testStrategy": "Example verification by running actual autopilot workflows against the example PRDs to ensure they execute successfully and produce expected results"
@@ -8116,7 +9352,9 @@
"id": 3,
"title": "Write troubleshooting guide",
"description": "Create comprehensive troubleshooting guide for common autopilot workflow issues and their solutions",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Document common issues like git conflicts during autonomous commits, test failures in red-green-refactor cycles, dependency resolution problems, workflow resume failures, and GitHub API rate limiting. Include step-by-step resolution guides, preventive measures, and debugging techniques.",
"status": "pending",
"testStrategy": "Troubleshooting guide validation by testing resolution steps against actual error scenarios and user feedback collection"
@@ -8125,7 +9363,10 @@
"id": 4,
"title": "Create demo materials and workflow visualization",
"description": "Produce demo video or GIF showing complete autopilot workflow execution from start to finish",
- "dependencies": [2, 3],
+ "dependencies": [
+ 2,
+ 3
+ ],
"details": "Create visual demo materials showing complete autopilot workflow: PRD parsing, task expansion, autonomous TDD cycles, git operations, test execution, and PR creation. Include screen recordings or animated GIFs demonstrating successful workflow execution and key decision points.",
"status": "pending",
"testStrategy": "Demo material validation through user testing sessions, accessibility review for visual content, and verification that examples accurately represent actual workflow behavior"
@@ -8164,7 +9405,9 @@
"id": 2,
"title": "Implement argument parsing and validation",
"description": "Add task ID argument parsing and --dry-run flag support with validation",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add task ID as required positional argument with validation to ensure it exists in tasks.json. Implement --dry-run boolean flag with proper Commander.js syntax. Add argument validation logic to check task ID format and existence. Include error handling for invalid inputs.",
"status": "done",
"testStrategy": "Unit tests for argument parsing with valid/invalid task IDs and flag combinations"
@@ -8173,7 +9416,9 @@
"id": 3,
"title": "Add help text and command documentation",
"description": "Implement comprehensive help text, usage examples, and command documentation",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Add detailed command description, usage examples showing 'tm autopilot <taskId>' and 'tm autopilot <taskId> --dry-run'. Include examples with real task IDs, explain dry-run mode behavior, and provide troubleshooting tips. Follow help text patterns from existing commands.",
"status": "done",
"testStrategy": "Unit tests for help text display and content validation"
@@ -8182,7 +9427,9 @@
"id": 4,
"title": "Implement command registration system",
"description": "Register the autopilot command with the CLI application and ensure proper integration",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Add autopilot command registration to the main CLI application in apps/cli/src/index.ts or appropriate registration file. Ensure command is properly exported and available when running 'tm autopilot'. Follow existing command registration patterns used by other commands.",
"status": "done",
"testStrategy": "Integration tests for command registration and CLI availability"
@@ -8191,7 +9438,9 @@
"id": 5,
"title": "Create basic execute method with dry-run logic",
"description": "Implement the main execute method with basic dry-run mode and task loading logic",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Implement the execute method that loads the specified task from tasks.json, validates task existence, and handles dry-run mode by displaying what would be executed without performing actions. Add basic task loading using existing task utilities and prepare structure for future autopilot logic.",
"status": "done",
"testStrategy": "Unit tests for execute method with valid tasks and dry-run mode behavior"
@@ -8205,7 +9454,9 @@
"details": "Create a PreflightChecker class that: 1) Detects test command from package.json scripts.test field, 2) Checks git working tree status using existing git-utils.js, 3) Validates availability of git, gh, node/npm tools, 4) Detects default branch. Return structured status for each check with success/failure indicators.",
"testStrategy": "Unit tests for each detection method. Integration tests with different package.json configurations and git states.",
"priority": "high",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"status": "done",
"subtasks": [
{
@@ -8221,7 +9472,9 @@
"id": 2,
"title": "Implement git state validation using existing git-utils",
"description": "Add git working tree status checks using the existing git-utils.js module functions",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add checkGitWorkingTree() method to PreflightChecker that uses existing functions from scripts/modules/utils/git-utils.js. Use isGitRepository() to verify git repo, then check for uncommitted changes using git status. Return structured status indicating if working tree is clean, has staged changes, or has unstaged changes. Include helpful messages about what needs to be committed.",
"status": "done",
"testStrategy": "Unit tests with mocked git-utils functions for different git states: clean working tree, staged changes, unstaged changes, not a git repository. Integration tests with actual git repository setup."
@@ -8230,7 +9483,9 @@
"id": 3,
"title": "Add tool availability validation for required commands",
"description": "Implement validation for git, gh, node/npm tool availability on the system",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Add validateRequiredTools() method that checks availability of git, gh CLI, node, and npm commands using execSync with 'which' or 'where' depending on platform. Handle platform differences (Unix vs Windows). Return structured results for each tool with version information where available. Use existing isGhCliAvailable() function from git-utils for gh CLI checking.",
"status": "done",
"testStrategy": "Unit tests mocking execSync for different scenarios: all tools available, missing tools, platform differences. Test version detection and error handling for command execution failures."
@@ -8239,7 +9494,9 @@
"id": 4,
"title": "Implement default branch detection",
"description": "Add default branch detection using existing git-utils functions",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Add detectDefaultBranch() method that uses getDefaultBranch() function from existing git-utils.js. Handle cases where default branch cannot be determined and provide fallback logic. Return structured result with detected branch name and confidence level. Include handling for repositories without remote tracking.",
"status": "done",
"testStrategy": "Unit tests mocking git-utils getDefaultBranch() for various scenarios: GitHub repo with default branch, local repo without remote, repositories with different default branches (main vs master)."
@@ -8248,7 +9505,9 @@
"id": 5,
"title": "Create comprehensive preflight check orchestration and result formatting",
"description": "Implement main runAllChecks() method that orchestrates all preflight checks and formats results",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Add runAllChecks() method that executes all preflight checks in sequence: detectTestCommand(), checkGitWorkingTree(), validateRequiredTools(), detectDefaultBranch(). Collect all results into structured PreflightResult object with overall success status, individual check results, and actionable error messages. Include summary of what passed/failed and next steps for resolving issues.",
"status": "done",
"testStrategy": "Integration tests running full preflight checks in different project configurations. Test error aggregation and result formatting. Verify that partial failures are handled gracefully with appropriate user guidance."
@@ -8262,7 +9521,9 @@
"details": "Use existing TaskService from @tm/core to load task by ID. Validate task exists, has subtasks, and subtasks have proper dependency order. If no subtasks exist, provide helpful message about needing to expand first. Reuse existing task loading patterns from other commands.",
"testStrategy": "Unit tests for task loading with various scenarios: valid task with subtasks, task without subtasks, non-existent task, tasks with dependencies.",
"priority": "medium",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"status": "done",
"subtasks": [
{
@@ -8278,7 +9539,9 @@
"id": 2,
"title": "Implement task existence validation logic",
"description": "Build validation to check if a task exists and has the proper structure for autopilot execution",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create validation functions that check: 1) Task exists in TaskMaster state, 2) Task has valid structure according to Task interface from @tm/core types, 3) Task is not in 'done' or 'cancelled' status. Return structured validation results with specific error messages for each validation failure.",
"status": "done",
"testStrategy": "Unit tests with various task scenarios: valid tasks, non-existent tasks, malformed tasks, completed tasks"
@@ -8287,7 +9550,9 @@
"id": 3,
"title": "Create subtask validation and dependency analysis",
"description": "Implement validation for subtask structure and dependency ordering for autopilot execution readiness",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Build validation logic that: 1) Checks if task has subtasks defined, 2) Validates subtask structure matches Subtask interface, 3) Analyzes dependency order to ensure subtasks can be executed sequentially, 4) Identifies any circular dependencies or missing dependencies. Provide detailed feedback on dependency issues.",
"status": "done",
"testStrategy": "Unit tests for tasks with valid subtasks, tasks without subtasks, tasks with circular dependencies, and tasks with missing dependencies"
@@ -8296,7 +9561,9 @@
"id": 4,
"title": "Implement helpful expansion messaging system",
"description": "Create user-friendly messages when tasks lack subtasks and guide users toward expansion commands",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "When validation detects tasks without subtasks, provide helpful messages explaining: 1) Why subtasks are needed for autopilot, 2) How to use 'task-master expand' to create subtasks, 3) Link to existing task expansion patterns from other commands. Include suggestions for complexity analysis if the task appears complex.",
"status": "done",
"testStrategy": "Unit tests for message generation with different task scenarios and integration tests to verify messaging appears correctly"
@@ -8305,7 +9572,9 @@
"id": 5,
"title": "Create comprehensive validation result interface and error handling",
"description": "Design and implement structured validation results with detailed error reporting for all validation scenarios",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Create ValidationResult interface that includes: 1) Success/failure status, 2) Specific error types (task not found, no subtasks, dependency issues), 3) Detailed error messages with actionable guidance, 4) Task data when validation succeeds. Implement error handling that provides clear feedback for each validation failure scenario.",
"status": "done",
"testStrategy": "Unit tests for all validation result scenarios and integration tests to verify error handling provides helpful user feedback"
@@ -8319,7 +9588,10 @@
"details": "Create ExecutionPlanDisplay class that formats and displays: preflight check results, branch/tag information, subtask execution order with RED/GREEN/COMMIT phases, estimated duration, and finalization steps. Use boxen and chalk for consistent CLI styling matching existing command patterns.",
"testStrategy": "Unit tests for display formatting with different task configurations. Visual regression tests for output formatting.",
"priority": "medium",
- "dependencies": [2, 3],
+ "dependencies": [
+ 2,
+ 3
+ ],
"status": "done",
"subtasks": [
{
@@ -8335,7 +9607,9 @@
"id": 2,
"title": "Implement preflight check results display",
"description": "Add method to format and display preflight check results with appropriate styling and status indicators",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement displayPreflightChecks() method that formats check results using chalk for colored status indicators (green checkmarks, red X's). Use boxen for section containers. Display task validation, dependency checks, and branch status results.",
"status": "done",
"testStrategy": "Unit tests for preflight display formatting with passing and failing checks"
@@ -8344,7 +9618,9 @@
"id": 3,
"title": "Implement branch and tag information display",
"description": "Add method to display planned branch creation and tag information in a formatted section",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement displayBranchInfo() method that shows planned branch name, current tag, and branch creation strategy. Use consistent styling with other sections. Display branch existence warnings if applicable.",
"status": "done",
"testStrategy": "Unit tests for branch info display with different tag configurations"
@@ -8353,7 +9629,9 @@
"id": 4,
"title": "Implement subtask execution order display with phases",
"description": "Create comprehensive display for subtask execution order showing RED/GREEN/COMMIT phases for each subtask",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement displayExecutionOrder() method that shows ordered subtasks with phase indicators (RED: tests fail, GREEN: tests pass, COMMIT: changes committed). Use color coding and clear phase separation. Include dependency information and estimated duration per subtask.",
"status": "done",
"testStrategy": "Unit tests for execution order display with various dependency patterns and phase transitions"
@@ -8362,7 +9640,11 @@
"id": 5,
"title": "Implement main display method and finalization steps",
"description": "Create the main display() method that orchestrates all sections and shows finalization steps",
- "dependencies": [2, 3, 4],
+ "dependencies": [
+ 2,
+ 3,
+ 4
+ ],
"details": "Implement main display() method that calls all section display methods in proper order. Add displayFinalizationSteps() for PR creation and cleanup steps. Include estimated total duration and final summary. Ensure consistent spacing and styling throughout.",
"status": "done",
"testStrategy": "Integration tests for complete display output and visual regression tests for CLI formatting"
@@ -8376,7 +9658,9 @@
"details": "Create BranchPlanner class that generates branch names following pattern: <tag>/task-<id>-<slug> where slug is kebab-case task title. Determine active tag from TaskMaster config. Show which tag would be set during execution. Handle edge cases like existing branches.",
"testStrategy": "Unit tests for branch name generation with various task titles and tags. Test edge cases like special characters and long titles.",
"priority": "low",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"status": "done",
"subtasks": [
{
@@ -8392,7 +9676,9 @@
"id": 2,
"title": "Implement task title to kebab-case slug conversion",
"description": "Create utility function to convert task titles into kebab-case slugs suitable for branch names",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement convertToKebabCase() method that handles special characters, spaces, and length limits. Remove non-alphanumeric characters except hyphens, convert to lowercase, and truncate to reasonable length (e.g., 50 chars). Handle edge cases like empty titles or titles with only special characters.",
"status": "done",
"testStrategy": "Unit tests with various task title formats including special characters, long titles, and edge cases"
@@ -8401,7 +9687,9 @@
"id": 3,
"title": "Implement branch name generation logic",
"description": "Create the core logic to generate branch names following the pattern <tag>/task-<id>-<slug>",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Implement generateBranchName() method that combines active tag from TaskMaster config, task ID, and kebab-case slug. Format as 'tag/task-id-slug'. Handle cases where tag is undefined or empty by using 'feature' as default. Validate generated names against git branch naming rules.",
"status": "done",
"testStrategy": "Unit tests for branch name generation with different tags, task IDs, and slugs"
@@ -8410,7 +9698,9 @@
"id": 4,
"title": "Add active tag detection from TaskMaster config",
"description": "Implement logic to determine the active tag from TaskMaster configuration state",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create getActiveTag() method that reads from TaskMaster state.json to determine current active tag. Use existing TaskService patterns to access configuration. Handle cases where no tag is set or config is missing. Return default tag 'feature' when no active tag is configured.",
"status": "done",
"testStrategy": "Unit tests for tag detection with various config states including missing config and undefined tags"
@@ -8419,7 +9709,10 @@
"id": 5,
"title": "Implement existing branch conflict detection",
"description": "Add logic to detect and handle cases where generated branch names already exist",
- "dependencies": [3, 4],
+ "dependencies": [
+ 3,
+ 4
+ ],
"details": "Create checkBranchExists() method using git-utils.js to check if generated branch name already exists locally or remotely. Implement conflict resolution by appending incremental numbers (e.g., -2, -3) to branch name. Provide warnings about existing branches in planning output.",
"status": "done",
"testStrategy": "Unit tests for branch conflict detection and resolution with mocked git commands"
@@ -8433,7 +9726,9 @@
"details": "Implement dependency resolution algorithm that: 1) Reads subtask dependencies from task data, 2) Creates execution order respecting dependencies, 3) Detects circular dependencies, 4) Groups independent subtasks. Return ordered list with dependency information for display.",
"testStrategy": "Unit tests for dependency resolution with linear dependencies, parallel subtasks, and circular dependency detection.",
"priority": "medium",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"status": "done",
"subtasks": [
{
@@ -8449,7 +9744,9 @@
"id": 2,
"title": "Implement circular dependency detection",
"description": "Add circular dependency detection to prevent infinite loops in dependency resolution",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Extend DependencyResolver to detect circular dependencies using depth-first search with visit tracking. Throw descriptive error when circular dependencies are found, including the cycle path. Add validation before attempting topological sort to fail fast on invalid dependency graphs.",
"status": "done",
"testStrategy": "Unit tests for various circular dependency scenarios: direct cycles (A→B→A), indirect cycles (A→B→C→A), and self-dependencies (A→A)"
@@ -8458,7 +9755,9 @@
"id": 3,
"title": "Add parallel subtask grouping functionality",
"description": "Group independent subtasks that can be executed in parallel phases",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement parallelization logic that groups subtasks into execution phases. Subtasks with no dependencies or whose dependencies are satisfied in previous phases can execute in parallel. Return execution plan with phase information showing which subtasks can run simultaneously.",
"status": "done",
"testStrategy": "Unit tests for parallel grouping with mixed dependency patterns, ensuring correct phase separation and parallel group identification"
@@ -8467,7 +9766,9 @@
"id": 4,
"title": "Create execution order display interfaces",
"description": "Define TypeScript interfaces for execution order results and dependency information",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create interfaces in types/ directory for ExecutionPlan, ExecutionPhase, and SubtaskDependencyInfo. Include fields for subtask ID, dependencies status, execution phase, and parallel group information. Ensure interfaces support both display formatting and autopilot execution needs.",
"status": "done",
"testStrategy": "Type checking tests and interface validation with sample data structures matching real subtask scenarios"
@@ -8476,7 +9777,12 @@
"id": 5,
"title": "Integrate with TaskService and add CLI utilities",
"description": "Integrate DependencyResolver with existing TaskService and create utility functions for CLI display",
- "dependencies": [1, 2, 3, 4],
+ "dependencies": [
+ 1,
+ 2,
+ 3,
+ 4
+ ],
"details": "Add calculateSubtaskExecutionOrder method to TaskService that uses DependencyResolver. Create UI utilities in apps/cli/src/utils/ui.ts for formatting execution order display with chalk colors and dependency status indicators. Follow existing patterns for task loading and error handling.",
"status": "done",
"testStrategy": "Integration tests with TaskService loading real task data, and visual tests for CLI display formatting with various dependency scenarios"
@@ -8490,7 +9796,9 @@
"details": "Create TDDPhasePlanner that for each subtask: 1) Determines test file paths based on project structure, 2) Identifies implementation files from subtask details, 3) Generates commit messages following conventional commits format, 4) Estimates implementation complexity. Support common project structures (src/, tests/, __tests__).",
"testStrategy": "Unit tests for file path generation with different project structures. Test commit message generation following conventional commits.",
"priority": "medium",
- "dependencies": [6],
+ "dependencies": [
+ 6
+ ],
"status": "done",
"subtasks": [
{
@@ -8506,7 +9814,9 @@
"id": 2,
"title": "Implement test file path detection logic",
"description": "Build logic to detect and generate appropriate test file paths based on common project structures",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement method to analyze project structure and determine test file paths for implementation files. Support common patterns: src/ with tests/, src/ with __tests__/, src/ with .test.js files alongside source, and packages/*/src with packages/*/tests. Use filesystem operations to check existing patterns and generate consistent test file paths.",
"status": "done",
"testStrategy": "Unit tests with mock filesystem structures testing various project layouts (Jest, Vitest, Node.js patterns). Verify correct test file paths are generated for different source file locations."
@@ -8515,7 +9825,9 @@
"id": 3,
"title": "Implement implementation file extraction from subtask details",
"description": "Parse subtask details and descriptions to identify implementation files that will be created or modified",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create method to analyze subtask details text and extract file paths mentioned or implied. Use regex patterns and natural language processing to identify: file names mentioned directly, directory structures implied by descriptions, and component/class names that translate to file paths. Handle various file extensions (.js, .ts, .tsx, .vue, .py, etc.).",
"status": "done",
"testStrategy": "Unit tests with various subtask detail examples. Test extraction accuracy with different description formats and file types. Verify edge cases like missing file paths or ambiguous descriptions."
@@ -8524,7 +9836,9 @@
"id": 4,
"title": "Implement conventional commit message generation",
"description": "Generate properly formatted conventional commit messages for each TDD phase (RED/GREEN/COMMIT)",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement method to generate conventional commit messages following the format: type(scope): description. Support commit types: test (for RED phase), feat/fix (for GREEN phase), and refactor (for COMMIT phase). Extract scope from subtask context and generate descriptive messages. Follow the pattern seen in existing hooks: feat(task-<id>): <description>.",
"status": "done",
"testStrategy": "Unit tests for commit message generation with various subtask types and scopes. Verify conventional commit format compliance and message clarity."
@@ -8533,7 +9847,11 @@
"id": 5,
"title": "Implement complexity estimation and phase organization",
"description": "Estimate implementation complexity and organize the three TDD phases (RED/GREEN/COMMIT) with appropriate metadata",
- "dependencies": [2, 3, 4],
+ "dependencies": [
+ 2,
+ 3,
+ 4
+ ],
"details": "Create method to estimate implementation complexity based on: number of files involved, description length and complexity keywords, dependencies between subtasks. Organize the output into three distinct phases: RED (test creation), GREEN (implementation), COMMIT (cleanup/refactor). Include estimated time, file lists, and commit messages for each phase.",
"status": "done",
"testStrategy": "Unit tests for complexity calculation with various subtask scenarios. Integration tests verifying complete phase planning output includes all required metadata and follows TDD workflow structure."
@@ -8547,7 +9865,10 @@
"details": "Create FinalizationPlanner that shows: 1) Full test suite execution with coverage threshold detection, 2) Branch push confirmation, 3) PR creation targeting detected default branch, 4) Duration estimation based on subtask count and complexity. Use existing git-utils.js for git operations planning.",
"testStrategy": "Unit tests for finalization step generation. Test coverage threshold detection from package.json or config files.",
"priority": "low",
- "dependencies": [2, 6],
+ "dependencies": [
+ 2,
+ 6
+ ],
"status": "done",
"subtasks": [
{
@@ -8563,7 +9884,9 @@
"id": 2,
"title": "Implement test suite execution planning with coverage detection",
"description": "Add functionality to detect test commands and coverage thresholds from package.json and project configuration",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement test command detection by reading package.json scripts for 'test', 'test:coverage', 'test:ci' commands. Parse coverage configuration from package.json, jest.config.js, vitest.config.js, or other config files to detect coverage thresholds. Generate execution plan showing which test command would be run and expected coverage requirements. Handle projects without test commands gracefully.",
"status": "done",
"testStrategy": "Unit tests for package.json parsing, config file detection, and coverage threshold extraction. Test with various project structures (Jest, Vitest, no tests)."
@@ -8572,7 +9895,9 @@
"id": 3,
"title": "Add git operations planning using existing git-utils",
"description": "Integrate with git-utils.js to plan branch push confirmation and default branch detection for PR targeting",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Use existing git-utils.js functions like getDefaultBranch(), getCurrentBranch(), and isGhCliAvailable() to plan git operations. Generate branch push confirmation plan showing current branch and target remote. Detect default branch for PR creation planning. Check if gh CLI is available for PR operations. Plan git status checks and dirty working tree warnings.",
"status": "done",
"testStrategy": "Unit tests for git-utils integration, branch detection, and gh CLI availability checking. Mock git-utils functions to test various git states."
@@ -8581,7 +9906,9 @@
"id": 4,
"title": "Implement PR creation planning",
"description": "Plan PR creation steps including title generation, body template, and target branch detection",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Generate PR creation plan that includes conventional commit-style title generation based on subtask changes, PR body template with task/subtask references, target branch detection using git-utils, and gh CLI command planning. Include checks for existing PR detection and conflict resolution. Plan PR description formatting with task context and implementation notes.",
"status": "done",
"testStrategy": "Unit tests for PR title generation, body template creation, and gh CLI command planning. Test with various task types and subtask combinations."
@@ -8590,7 +9917,11 @@
"id": 5,
"title": "Add duration estimation based on subtask complexity",
"description": "Implement duration estimation algorithm that calculates expected completion time based on subtask count and complexity",
- "dependencies": [2, 3, 4],
+ "dependencies": [
+ 2,
+ 3,
+ 4
+ ],
"details": "Create duration estimation algorithm that factors in number of subtasks, complexity indicators (file count, test coverage requirements, git operations), and historical patterns. Provide time estimates for each finalization step (testing, git operations, PR creation) and total completion time. Include confidence intervals and factors that might affect duration. Format estimates in human-readable time units.",
"status": "done",
"testStrategy": "Unit tests for duration calculation algorithms, complexity analysis, and time formatting. Test with various subtask configurations and complexity scenarios."
@@ -8604,7 +9935,10 @@
"details": "Update apps/cli/src/command-registry.ts to include AutopilotCommand. Follow existing patterns for command registration. Ensure proper cleanup and error handling. Update CLI help system to include autopilot command documentation.",
"testStrategy": "Integration tests for command registration. Test CLI help includes autopilot command. Test error handling and cleanup.",
"priority": "medium",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"status": "done",
"subtasks": [
{
@@ -8620,7 +9954,9 @@
"id": 2,
"title": "Add AutopilotCommand import to command-registry.ts",
"description": "Import the AutopilotCommand class in the command registry imports section",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add import statement for AutopilotCommand in apps/cli/src/command-registry.ts following the existing import pattern. Place it in the appropriate position with other command imports maintaining alphabetical order.",
"status": "done",
"testStrategy": "Verify import resolves correctly and doesn't break existing imports"
@@ -8629,7 +9965,9 @@
"id": 3,
"title": "Register autopilot command in CommandRegistry",
"description": "Add autopilot command metadata to the CommandRegistry.commands array",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Add autopilot command entry to the commands array in CommandRegistry class. Use 'development' category, provide appropriate description, and reference AutopilotCommand class. Follow the existing pattern with name, description, commandClass, and category fields.",
"status": "done",
"testStrategy": "Unit tests to verify command is registered and appears in registry listing"
@@ -8638,7 +9976,9 @@
"id": 4,
"title": "Export AutopilotCommand from index.ts",
"description": "Add AutopilotCommand export to the main CLI package index file",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add AutopilotCommand export to apps/cli/src/index.ts in the Commands section following the existing export pattern. Ensure it's properly exported for external usage and testing.",
"status": "done",
"testStrategy": "Verify export is available and can be imported from @tm/cli package"
@@ -8647,7 +9987,9 @@
"id": 5,
"title": "Update CLI help system for autopilot command",
"description": "Ensure autopilot command appears in help output and command listing",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Verify that the autopilot command appears in the CLI help system through the CommandRegistry.getFormattedCommandList() method. The 'development' category should be included in help output with autopilot command listed. Test help display functionality.",
"status": "done",
"testStrategy": "Integration tests for help system displaying autopilot command. Test CLI help output includes autopilot in development category."
@@ -8661,7 +10003,11 @@
"details": "Handle scenarios: missing task, task without subtasks, dirty git working tree, missing tools (git, gh, node), invalid dependencies, circular dependencies, no test command detected. Provide helpful error messages and suggestions for resolution. Use existing error patterns from other commands.",
"testStrategy": "Unit tests for each error scenario. Integration tests with various invalid configurations. Test error message clarity and helpfulness.",
"priority": "high",
- "dependencies": [1, 2, 3],
+ "dependencies": [
+ 1,
+ 2,
+ 3
+ ],
"status": "done",
"subtasks": [
{
@@ -8677,7 +10023,9 @@
"id": 2,
"title": "Add task and dependency validation error handling",
"description": "Implement error detection for missing tasks, tasks without subtasks, invalid dependencies, and circular dependency cycles",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create TaskValidator class that checks task existence in tasks.json, validates task has subtasks for autopilot execution, detects invalid dependency references, and identifies circular dependency chains. Use existing dependency validation patterns from other commands.",
"status": "done",
"testStrategy": "Unit tests for each validation scenario with mock task data. Test circular dependency detection with various dependency graphs."
@@ -8686,7 +10034,9 @@
"id": 3,
"title": "Implement tool availability validation",
"description": "Add error handling for missing required tools like gh CLI, node, and npm with helpful installation guidance",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create ToolValidator that checks availability of gh CLI, node, npm, and other required tools using spawn or which-like detection. Provide specific error messages with installation instructions for each missing tool based on the user's platform.",
"status": "done",
"testStrategy": "Unit tests for tool detection with mocked command availability. Test error messages for different missing tool combinations."
@@ -8695,7 +10045,9 @@
"id": 4,
"title": "Add test command detection error handling",
"description": "Implement error handling when no test command is detected in package.json with suggestions for configuration",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Extend PreflightChecker to handle cases where package.json is missing, has no scripts section, or no test script defined. Provide helpful error messages suggesting common test script configurations and link to documentation for test setup.",
"status": "done",
"testStrategy": "Unit tests for various package.json configurations. Test error messages for missing test scripts and invalid package.json files."
@@ -8704,7 +10056,12 @@
"id": 5,
"title": "Create comprehensive error reporting system",
"description": "Build unified error reporting that aggregates all validation failures and provides actionable resolution steps",
- "dependencies": [1, 2, 3, 4],
+ "dependencies": [
+ 1,
+ 2,
+ 3,
+ 4
+ ],
"details": "Create ErrorReporter class that collects all validation errors, formats them with clear descriptions and resolution steps, and provides a summary of required actions before autopilot can run. Follow existing error formatting patterns from other TaskMaster commands.",
"status": "done",
"testStrategy": "Integration tests combining multiple error scenarios. Test error message clarity and formatting. Verify all error types are properly handled and reported."
@@ -8744,7 +10101,9 @@
"id": 2,
"title": "Build Run ID Generation and Validation System",
"description": "Implement unique run ID generation using ISO timestamps with validation and collision detection mechanisms.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create a module that generates unique run IDs using ISO 8601 timestamps with millisecond precision. Add validation functions to ensure run ID format correctness and uniqueness within project storage. Implement collision detection and resolution strategies. Include helper functions to parse run IDs back to timestamps and compare run chronology.",
"status": "done",
"testStrategy": "Unit tests for ID generation uniqueness, format validation, and collision detection. Performance tests for rapid ID generation. Test timestamp parsing and chronological ordering.",
@@ -8754,7 +10113,9 @@
"id": 3,
"title": "Design Manifest.json Structure and Management",
"description": "Create manifest.json schema and management functions to track run metadata, configuration, and workflow state for each execution run.",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Define JSON schema for manifest.json containing run metadata (start time, end time, task ID, tag, branch), configuration snapshot, and workflow phase tracking. Implement functions to create, update, and validate manifest files. Use atomic write operations to prevent corruption. Include version field for future schema evolution and migration support.",
"status": "done",
"testStrategy": "Unit tests for schema validation, manifest creation and updates. Test atomic write operations and corruption recovery. Verify metadata accuracy and schema evolution compatibility.",
@@ -8764,7 +10125,9 @@
"id": 4,
"title": "Implement Activity.jsonl Append-Only Logging",
"description": "Build append-only logging system using JSONL format to track all workflow activities with timestamps and structured event data.",
- "dependencies": [3],
+ "dependencies": [
+ 3
+ ],
"details": "Create logging functions that append structured events to activity.jsonl file using newline-delimited JSON format. Implement event types for workflow phases, git operations, test executions, and error conditions. Ensure atomic append operations with proper file locking. Add functions to read and filter activity logs by event type, timestamp, or other criteria.",
"status": "in-progress",
"testStrategy": "Unit tests for event logging, file append operations, and log reading/filtering. Concurrency tests for simultaneous writes. Test log file integrity and recovery from interrupted operations.",
@@ -8774,7 +10137,9 @@
"id": 5,
"title": "Create State.json Mutable Checkpoint Handling",
"description": "Implement mutable state management system for workflow checkpoints, current phase tracking, and resumable execution state.",
- "dependencies": [4],
+ "dependencies": [
+ 4
+ ],
"details": "Build state management functions for mutable state.json file containing current workflow phase, progress indicators, and resumable execution context. Implement atomic read-modify-write operations with proper locking. Add checkpoint creation, state restoration, and validation functions. Support state migration between schema versions and cleanup of stale state.",
"status": "pending",
"testStrategy": "Unit tests for state read/write operations, atomic updates, and checkpoint restoration. Test state validation and migration. Verify proper cleanup of stale state and error recovery scenarios.",
@@ -8784,7 +10149,9 @@
"id": 6,
"title": "Build Directory Structure Creation and Cleanup",
"description": "Implement directory structure management with robust error handling, atomic operations, and isolation between different workflow runs.",
- "dependencies": [5],
+ "dependencies": [
+ 5
+ ],
"details": "Create functions to establish the complete directory hierarchy (~/.taskmaster/projects/<project-path>/runs/<run-id>/). Implement atomic directory creation with proper permissions and cleanup of failed operations. Add isolation mechanisms to prevent cross-run interference. Include functions to archive completed runs and clean up old data based on retention policies. Ensure no runtime artifacts remain in project directory.",
"status": "pending",
"testStrategy": "Integration tests for complete directory structure creation. Test cleanup operations and isolation between runs. Verify proper permissions and cross-platform compatibility. Test retention policies and archive functionality.",
@@ -8803,7 +10170,9 @@
"details": "Implement in TypeScript using `simple-git` (v3+) for git operations. Add methods for branch creation, checkout, commit, push, and status checks. Enforce safety: never commit on default branch, always check working tree cleanliness, confirm destructive operations unless `--no-confirm`. Generate branch names from configurable patterns. Include methods to get current/default branch. Use `chalk` for colored CLI output. Expose a clean, promise-based API. Store branch↔tag mapping in run state.",
"testStrategy": "Unit tests with mocked git commands. Integration tests with a temporary git repo to verify branch creation, commit gating, and safety checks. Negative tests: attempt commits on default branch, dirty working tree. Verify branch name generation and mapping.",
"priority": "high",
- "dependencies": ["1"],
+ "dependencies": [
+ "1"
+ ],
"status": "done",
"subtasks": [
{
@@ -8820,7 +10189,9 @@
"id": 2,
"title": "Build Working Tree Status Checker with Detailed Reporting",
"description": "Develop comprehensive working tree status checking functionality that provides detailed information about repository state and cleanliness.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create methods to check working tree cleanliness, staged changes, untracked files, and merge conflicts. Use simple-git status methods to gather detailed repository state. Implement colored output using chalk for status visualization. Add methods to categorize changes (modified, added, deleted, untracked) and provide human-readable summaries.",
"status": "pending",
"testStrategy": "Unit tests with mocked git status responses. Integration tests with temporary repos in various states (clean, dirty, staged changes, conflicts). Verify colored output and detailed reporting accuracy.",
@@ -8830,7 +10201,10 @@
"id": 3,
"title": "Implement Branch Operations with Safety Guards",
"description": "Create secure branch management functionality including creation, checkout, and listing with built-in safety mechanisms.",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Implement branch creation with validation checks, safe checkout operations that verify clean working tree, and branch listing with current branch detection. Add safety guards to prevent operations on dirty repositories. Include branch existence validation and conflict detection. Support force operations with explicit confirmation gates.",
"status": "pending",
"testStrategy": "Unit tests for branch operations with mocked git responses. Integration tests with temporary repos to verify branch creation, checkout safety, and validation logic. Test edge cases like existing branches and dirty working trees.",
@@ -8840,7 +10214,11 @@
"id": 4,
"title": "Develop Commit Operations with Metadata Embedding",
"description": "Build commit functionality that embeds workflow metadata and enforces safety rules around committing.",
- "dependencies": [1, 2, 3],
+ "dependencies": [
+ 1,
+ 2,
+ 3
+ ],
"details": "Implement commit creation with metadata embedding (task ID, workflow phase, timestamp). Add strict safety checks to prevent commits on default branch. Include staged file validation and commit message generation. Support metadata embedding in commit messages and branch-tag mapping storage in run state.",
"status": "pending",
"testStrategy": "Unit tests for commit logic with mocked git operations. Integration tests to verify metadata embedding, default branch protection, and commit creation. Test safety violations and error handling.",
@@ -8850,7 +10228,10 @@
"id": 5,
"title": "Create Default Branch Detection and Protection Logic",
"description": "Implement robust default branch detection and protection mechanisms to prevent accidental commits to main branches.",
- "dependencies": [1, 3],
+ "dependencies": [
+ 1,
+ 3
+ ],
"details": "Add methods to detect default branch (main, master, develop) from remote origin and local configuration. Implement protection logic that blocks commits and destructive operations on default branches. Support configurable branch protection patterns and override mechanisms with confirmation gates.",
"status": "pending",
"testStrategy": "Unit tests for default branch detection with various git configurations. Integration tests with repos using different default branch names. Verify protection logic and confirmation gate behavior.",
@@ -8860,7 +10241,12 @@
"id": 6,
"title": "Build Push Operations with Conflict Handling",
"description": "Develop secure push functionality that handles conflicts, validates remote state, and provides clear error reporting.",
- "dependencies": [1, 2, 3, 5],
+ "dependencies": [
+ 1,
+ 2,
+ 3,
+ 5
+ ],
"details": "Implement push operations with pre-push validation, conflict detection, and resolution guidance. Add upstream tracking setup and force-push protection. Include detailed error reporting with suggestions for conflict resolution. Support dry-run mode and confirmation gates for destructive operations.",
"status": "pending",
"testStrategy": "Unit tests for push logic with mocked remote scenarios. Integration tests with temporary repos and simulated remotes. Test conflict detection, error handling, and safety mechanisms.",
@@ -8870,7 +10256,9 @@
"id": 7,
"title": "Implement Branch Name Generation from Patterns",
"description": "Create configurable branch name generation system that follows consistent patterns and integrates with workflow state.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement branch name generation using configurable patterns (task ID, description, timestamp). Support template variables and sanitization rules for valid git branch names. Include branch-tag mapping storage and retrieval from run state. Add validation for generated names and conflict resolution.",
"status": "pending",
"testStrategy": "Unit tests for pattern parsing and name generation with various templates. Integration tests to verify generated names are valid git branch names. Test mapping storage and conflict resolution logic.",
@@ -8889,7 +10277,9 @@
"details": "Build a `TestResultValidator` class in TypeScript. Validate that RED phase results include at least one failure, GREEN phase results have zero failures. Optionally validate coverage thresholds if provided. Return structured validation results with messages and suggestions. Use `joi` (v17+) for input validation. Keep validation logic framework-agnostic—TaskMaster does not parse test output, only checks reported numbers.",
"testStrategy": "Unit tests for validation logic: RED with no failures fails validation, GREEN with failures fails validation. Test coverage threshold enforcement. Verify error messages and suggestions. Mock invalid inputs.",
"priority": "high",
- "dependencies": ["1"],
+ "dependencies": [
+ "1"
+ ],
"status": "done",
"subtasks": [
{
@@ -8906,7 +10296,9 @@
"id": 2,
"title": "Implement RED Phase Validation Logic",
"description": "Create validation logic to ensure RED phase test results contain at least one failing test, enforcing TDD semantics that require initial test failures.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement validation method that checks if failed test count is greater than zero for RED phase. Provide specific error messages when RED phase has zero failures, suggesting the developer write failing tests first. Include validation that total test count is greater than zero to prevent empty test suites. Return structured validation results with phase-specific suggestions.\n<info added on 2025-10-10T13:41:04.020Z>\nBased on my analysis of the codebase and the completed RED phase validation implementation in `packages/tm-core/src/services/test-result-validator.ts:74-100`, the subtask has been successfully completed. The implementation includes:\n\n- Proper validation that RED phase must have at least one failing test (line 84-87)\n- Empty test suite prevention with appropriate error message (line 90-93)\n- Actionable TDD workflow suggestions (lines 86, 92)\n- Integration with the base validation system for structured error handling\n\nThe test suite in `packages/tm-core/src/services/test-result-validator.test.ts:118-178` comprehensively covers all RED phase validation scenarios including success cases, zero failures, empty test suites, and error propagation. Implementation follows TypeScript best practices with proper type safety and Zod schema validation for robust input handling.\n</info added on 2025-10-10T13:41:04.020Z>",
"status": "done",
"testStrategy": "Unit tests covering RED phase with zero failures (should fail validation), RED phase with failures (should pass), empty test suite scenarios. Verify error messages provide actionable feedback for TDD workflow.",
@@ -8916,7 +10308,9 @@
"id": 3,
"title": "Implement GREEN Phase Validation Logic",
"description": "Create validation logic to ensure GREEN phase test results have zero failures, confirming that all tests pass after implementation.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement validation method that verifies failed test count equals zero for GREEN phase. Ensure at least one test exists and passed to prevent false positives from empty test suites. Provide clear error messages when GREEN phase has failures, suggesting code fixes or test adjustments. Include validation that passed test count matches or exceeds the previous RED phase test count.\n<info added on 2025-10-10T13:42:16.926Z>\nBased on my analysis of the TestResultValidator implementation in `packages/tm-core/src/services/test-result-validator.ts` and test file, I can see that the GREEN phase validation logic has been successfully implemented. The `validateGreenPhase` method at lines 106-145 contains the complete implementation with:\n\n1. Zero failures validation (lines 120-123)\n2. At least one passing test validation (lines 125-129) \n3. Test count regression tracking with warnings (lines 132-137)\n4. Comprehensive error messages and actionable suggestions\n\nThe test file shows comprehensive test coverage for all GREEN phase scenarios including edge cases. The implementation follows the project's TypeScript patterns and uses the established validation result structure.\n\nIMPLEMENTATION COMPLETE. TestResultValidator.validateGreenPhase method fully implemented with zero failures validation, minimum passing test requirement, test count regression warnings, and comprehensive error messaging. Follows existing codebase patterns using zod validation, structured error/warning/suggestion results, and maintains backward compatibility. All test scenarios covered including edge cases for empty test suites and count decreases.\n</info added on 2025-10-10T13:42:16.926Z>",
"status": "done",
"testStrategy": "Unit tests for GREEN phase with failures (should fail validation), GREEN phase with all passing tests (should pass), regression scenarios where test count decreases. Test error messages guide developers toward fixing implementation.",
@@ -8926,7 +10320,9 @@
"id": 4,
"title": "Implement Coverage Threshold Validation",
"description": "Create configurable coverage validation that enforces minimum coverage thresholds when coverage data is provided with test results.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement optional coverage validation that accepts configurable thresholds for line, branch, function, and statement coverage. Validate coverage percentages against thresholds only when coverage data is present. Provide detailed messages indicating which coverage types failed to meet thresholds and by how much. Support different threshold configurations per project and phase. Return structured results with coverage gaps and improvement suggestions.\n<info added on 2025-10-10T13:44:18.503Z>\nI'll analyze the codebase to understand the current implementation before updating the subtask details.Based on my analysis of the codebase, I can see the TestResultValidator implementation in `packages/tm-core/src/services/test-result-validator.ts` and its comprehensive test suite in `test-result-validator.test.ts`. The implementation includes:\n\n1. **Complete coverage threshold validation logic** (lines 147-197)\n2. **Configurable thresholds** for line, branch, function, and statement coverage\n3. **Skips validation when coverage data is absent** (line 162-165)\n4. **Detailed error messages** showing specific coverage gaps (lines 171-185)\n5. **Structured results** with gaps and improvement suggestions (lines 188-190)\n\nThe test file shows comprehensive test coverage including coverage threshold validation tests (lines 270-423) with various scenarios for meeting/failing thresholds and handling missing coverage data.\n\nImplementation complete. The validateCoverage method correctly handles configurable thresholds for all four coverage types (line, branch, function, statement), gracefully skips validation when coverage data is undefined, and provides specific error messages detailing which coverage types failed and by how much. The implementation supports different threshold configurations through the CoverageThresholds interface and returns structured ValidationResult objects with detailed feedback. Test suite includes 23 comprehensive test cases covering input validation, RED/GREEN phase validation, and coverage threshold scenarios.\n</info added on 2025-10-10T13:44:18.503Z>",
"status": "done",
"testStrategy": "Unit tests for coverage validation with various threshold configurations, missing coverage data (should skip validation), coverage below/above thresholds. Test different coverage types independently and in combination.",
@@ -8944,7 +10340,11 @@
"details": "Use `xstate` (v5+) or a custom lightweight state machine. Emit events for phase/subtask transitions, test runs, commits, and errors. Coordinate GitAdapter, TestResultValidator, and (future) Executor adapters. Persist state to `state.json` after each transition. Support resumption from checkpoint. Implement phase hooks for extensibility. Follow the event API specified in the PRD.",
"testStrategy": "Unit tests for state transitions and event emission. Integration tests with mocked adapters to verify full workflow lifecycle. Test resume from interrupted state. Verify event stream in `activity.jsonl`.",
"priority": "high",
- "dependencies": ["1", "2", "3"],
+ "dependencies": [
+ "1",
+ "2",
+ "3"
+ ],
"status": "done",
"subtasks": [
{
@@ -8961,7 +10361,9 @@
"id": 2,
"title": "Implement Event Emission System with Comprehensive Event Types",
"description": "Develop an event system that emits events for phase transitions, subtask transitions, test runs, commits, and errors.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create a robust event emitter integrated with the state machine that dispatches detailed events on every significant action or state change. Define a comprehensive event schema matching the PRD specifications for extensibility and observability.\n<info added on 2025-10-10T13:52:07.951Z>\nI'll analyze the codebase to understand the current implementation and then provide the update based on your completion report.Now let me look for the workflow orchestrator to understand the event emission system:Let me also check the types file to understand the event system better:Now let me check the test file to see what tests were created:Let me check how many tests are currently passing by running the test suite:Let me check the package.json to understand the test script:Based on my analysis of the codebase, I can see that the WorkflowOrchestrator has been successfully implemented with a comprehensive event emission system. The implementation includes:\n\n1. **Event system infrastructure**: `on()` and `off()` methods for listener management\n2. **Comprehensive event types**: 23 different event types defined in `types.ts`\n3. **Event emission throughout the state machine**: Events are emitted for phase transitions, TDD cycle progression, subtask lifecycle, git operations, and errors\n4. **Complete test coverage**: 23 tests covering all aspects including 8 specific event emission tests\n\nThe event system is fully integrated with the state machine and emits events for all significant workflow actions as specified in the PRD.\n\nIMPLEMENTATION COMPLETED: Event emission system fully implemented with comprehensive event types covering workflow phases, TDD cycles, subtask lifecycle, git operations, and error handling. System includes on/off listener management methods and emits detailed events with timestamps, phase context, and additional data. Full test coverage achieved with 23 passing tests including 8 dedicated event emission tests validating listener registration/removal, event data integrity, and proper emission during state transitions.\n</info added on 2025-10-10T13:52:07.951Z>",
"status": "done",
"testStrategy": "Unit tests to verify event emission on all relevant state transitions and actions.",
@@ -8971,7 +10373,9 @@
"id": 3,
"title": "Develop State Persistence and Recovery Mechanisms",
"description": "Implement saving the state machine's current state to `state.json` after each transition and support resuming from this checkpoint.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "After every state transition, serialize and persist the current state and context to `state.json`. On startup, load this file to restore the state machine to the last checkpoint, enabling workflow resumption.\n<info added on 2025-10-10T13:57:11.049Z>\nImplementation successfully completed. Added auto-persist mode functionality with enableAutoPersist() and disableAutoPersist() methods, allowing external state management integration. Implemented manual persistState() method for on-demand state persistence. Added 'state:persisted' event emission to workflow events system as defined in types.ts:85. Successfully integrated with existing state-manager module in packages/tm-core/src/storage/state-manager.ts for atomic state file operations. Comprehensive test coverage achieved with 28 passing tests covering state transitions, event emission, persistence callbacks, auto-persist enable/disable functionality, and integration scenarios.\n</info added on 2025-10-10T13:57:11.049Z>",
"status": "done",
"testStrategy": "Integration tests simulating interruptions and verifying correct state restoration from persisted data.",
@@ -8981,7 +10385,9 @@
"id": 4,
"title": "Coordinate Phases and Validate Transitions",
"description": "Implement coordination logic to validate phase transitions and ensure correct sequencing and conditions are met.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Add guards and validation logic within the state machine to enforce correct phase progression. Integrate with TestResultValidator and GitAdapter to confirm readiness before moving to next phases.",
"status": "done",
"testStrategy": "Unit and integration tests verifying that invalid transitions are blocked and validations are enforced.",
@@ -8991,7 +10397,10 @@
"id": 5,
"title": "Implement Subtask Iteration and Progress Tracking",
"description": "Manage the SubtaskLoop phase by iterating through subtasks and tracking progress through RED, GREEN, and COMMIT steps.",
- "dependencies": [1, 4],
+ "dependencies": [
+ 1,
+ 4
+ ],
"details": "Within the SubtaskLoop state, implement logic to iterate subtasks, handle RED→GREEN→COMMIT cycles, update subtask statuses, and emit progress events. Support max attempt limits and pause/resume functionality.",
"status": "done",
"testStrategy": "Integration tests with mocked subtasks verifying correct iteration, status updates, and event emission.",
@@ -9001,7 +10410,11 @@
"id": 6,
"title": "Develop Error Handling and Recovery Strategies",
"description": "Implement robust error detection, event emission, and recovery mechanisms throughout the workflow.",
- "dependencies": [1, 2, 3],
+ "dependencies": [
+ 1,
+ 2,
+ 3
+ ],
"details": "Detect errors during phases and subtasks, emit error events, and define recovery strategies such as retries, fallback states, or aborting the workflow gracefully. Ensure errors are logged and persisted.",
"status": "done",
"testStrategy": "Tests simulating errors in various phases to verify error event emission and recovery behavior.",
@@ -9011,7 +10424,10 @@
"id": 7,
"title": "Implement Resume Functionality from Checkpoints",
"description": "Enable the orchestrator to resume workflow execution seamlessly from persisted checkpoints after interruptions.",
- "dependencies": [3, 5],
+ "dependencies": [
+ 3,
+ 5
+ ],
"details": "On startup, detect existing `state.json` checkpoint, restore state machine context and state, and continue execution from the last known point, including subtask progress and phase.",
"status": "done",
"testStrategy": "Integration tests simulating process restarts and verifying correct resumption of workflow state and progress.",
@@ -9021,7 +10437,11 @@
"id": 8,
"title": "Integrate GitAdapter, TestResultValidator, and Executor Adapters",
"description": "Coordinate with GitAdapter, TestResultValidator, and future Executor adapters to perform git operations, validate test results, and execute tasks.",
- "dependencies": [1, 4, 5],
+ "dependencies": [
+ 1,
+ 4,
+ 5
+ ],
"details": "Implement adapter interfaces and invoke them at appropriate phases: GitAdapter for branch and commit operations, TestResultValidator for test result validation in RED/GREEN phases, and prepare hooks for Executor adapter integration. Ensure adapters are coordinated via events and state transitions.",
"status": "done",
"testStrategy": "Integration tests with mocked adapters verifying correct calls, coordination, and error handling.",
@@ -9039,7 +10459,9 @@
"details": "Implement a function that takes changed files, task context, and test results, then generates a commit message per the template. Determine scope from changed files (e.g., 'cli', 'core'). Use `conventional-commits` parser (v2+) for validation. Include all required metadata in the commit body. Support configurable templates via `config.json`. Optionally allow message override.",
"testStrategy": "Unit tests for message generation, scope detection, and template rendering. Verify all metadata is included. Test with various file change patterns. Validate against `conventional-commits` spec.",
"priority": "medium",
- "dependencies": ["1"],
+ "dependencies": [
+ "1"
+ ],
"status": "done",
"subtasks": [
{
@@ -9056,7 +10478,9 @@
"id": 2,
"title": "Implement intelligent scope detection from changed files",
"description": "Create a system that analyzes changed files to automatically determine the appropriate commit scope",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Build a ScopeDetector class that analyzes file paths and determines conventional commit scopes (e.g., 'cli', 'core', 'test', 'docs'). Create configurable mapping rules in config.json. Handle multiple scopes by choosing the most relevant or using a priority system. Support custom scope detection rules and fallback to generic scopes when unclear.",
"status": "done",
"testStrategy": "Unit tests for scope detection with various file path patterns. Test priority resolution for multiple scopes. Verify fallback behavior.",
@@ -9066,7 +10490,10 @@
"id": 3,
"title": "Implement metadata embedding and conventional commits compliance",
"description": "Create the core commit message generator that embeds task metadata and ensures conventional commits format compliance",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Build a CommitMessageGenerator class that combines template engine and scope detector to generate complete commit messages. Embed task metadata (ID, phase, tag, test counts, coverage) in the commit body. Use conventional-commits parser v2+ for validation. Support message override option. Format metadata as structured text or YAML in commit body for easy parsing.",
"status": "done",
"testStrategy": "Unit tests for message generation with various metadata combinations. Integration tests with conventional-commits parser validation. Test message override functionality.",
@@ -9084,7 +10511,11 @@
"details": "For each subtask, orchestrate: (1) RED: AI generates and runs tests, reports results; TaskMaster validates failures. (2) GREEN: AI implements code, runs tests, reports results; TaskMaster validates all pass. (3) COMMIT: TaskMaster stages files, generates commit message, creates commit. Update subtask status. Handle max attempts for GREEN phase. Log all phase transitions and results to `activity.jsonl`. Support pause/resume.",
"testStrategy": "Integration tests with mocked AI agent calls. Verify RED requires failures, GREEN requires passes. Test commit creation with metadata. Test max attempt logic. Verify activity log entries.",
"priority": "high",
- "dependencies": ["3", "4", "5"],
+ "dependencies": [
+ "3",
+ "4",
+ "5"
+ ],
"status": "done",
"subtasks": [
{
@@ -9101,7 +10532,9 @@
"id": 2,
"title": "Implement GREEN Phase Orchestrator",
"description": "Build the GREEN phase controller that guides AI implementation and validates all tests pass.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create GreenPhaseOrchestrator class that: (1) Calls AI agent to implement code for current subtask, (2) Runs all tests using TestResultValidator, (3) Validates that zero tests fail (GREEN requirement), (4) Tracks attempt count for max retry logic, (5) Returns structured results with implementation status. Support iterative implementation with feedback from failed test runs. Coordinate with attempt tracking system.",
"status": "done",
"testStrategy": "Unit tests with mocked AI agent and retry scenarios. Integration tests verifying GREEN phase passes only when all tests succeed. Test max attempt handling and failure modes.",
@@ -9111,7 +10544,9 @@
"id": 3,
"title": "Implement COMMIT Phase Orchestrator",
"description": "Build the COMMIT phase controller that handles file staging, commit message generation, and git operations.",
- "dependencies": [2],
+ "dependencies": [
+ 2
+ ],
"details": "Create CommitPhaseOrchestrator class that: (1) Uses GitAdapter to stage modified files, (2) Generates descriptive commit messages with subtask metadata and test results, (3) Creates git commit with structured metadata, (4) Updates subtask status to completed, (5) Handles git operation failures and rollback scenarios. Include commit message templates and ensure atomic operations.",
"status": "done",
"testStrategy": "Unit tests with mocked GitAdapter. Integration tests verifying commit creation with proper metadata. Test rollback scenarios and file staging edge cases.",
@@ -9131,7 +10566,12 @@
"id": 5,
"title": "Implement Phase Transition Validator and State Manager",
"description": "Build the state transition validator that ensures proper TDD phase sequencing and state updates.",
- "dependencies": [1, 2, 3, 4],
+ "dependencies": [
+ 1,
+ 2,
+ 3,
+ 4
+ ],
"details": "Create PhaseTransitionValidator class that: (1) Validates legal phase transitions (RED→GREEN→COMMIT), (2) Enforces phase prerequisites and exit conditions, (3) Updates workflow state with phase results, (4) Handles pause/resume functionality with state checkpoints, (5) Provides rollback capabilities for failed transitions. Integrate with WorkflowOrchestrator for state machine coordination.",
"status": "done",
"testStrategy": "Unit tests for transition validation logic and state persistence. Integration tests verifying full TDD cycle transitions. Test pause/resume scenarios and rollback handling.",
@@ -9141,7 +10581,9 @@
"id": 6,
"title": "Implement Activity Logger for Phase Tracking",
"description": "Build the comprehensive logging system that records all phase transitions and results to activity.jsonl.",
- "dependencies": [5],
+ "dependencies": [
+ 5
+ ],
"details": "Create ActivityLogger class that: (1) Logs structured entries for all phase transitions with timestamps, (2) Records test results, attempt counts, and error details, (3) Writes to activity.jsonl in append-only JSONL format, (4) Provides log querying and filtering capabilities, (5) Ensures log integrity and handles write failures gracefully. Include log rotation and cleanup policies.",
"status": "done",
"testStrategy": "Unit tests for log entry formatting and file operations. Integration tests verifying complete workflow logging. Test log rotation and error recovery scenarios.",
@@ -9159,7 +10601,10 @@
"details": "Use `commander` (v11+) for CLI construction. Commands: `start`, `next`, `complete`, `commit`, `status`, `resume`, `abort`. `next` returns JSON with action details. `complete` accepts `--results` and `--coverage`. `commit` uses enhanced message generator. `status` shows current run progress. Support `--json` flag for machine-readable output. Integrate with WorkflowOrchestrator and GitAdapter.",
"testStrategy": "Unit tests for command parsing and output formatting. Integration tests for full workflow via CLI. Test JSON output for machine consumption. Verify error handling and help text.",
"priority": "medium",
- "dependencies": ["4", "6"],
+ "dependencies": [
+ "4",
+ "6"
+ ],
"status": "done",
"subtasks": [
{
@@ -9176,7 +10621,9 @@
"id": 2,
"title": "Implement start and resume commands with workflow initialization",
"description": "Build the `start` and `resume` commands that initialize or restore the TDD workflow state, integrating with WorkflowOrchestrator.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement `tm autopilot start` command that validates project setup, initializes WorkflowOrchestrator, and begins the TDD workflow. Implement `tm autopilot resume` that restores workflow state from `state.json`. Both commands should validate dependencies (tasks 4,6) are available, handle project root detection, and provide clear feedback on initialization status.",
"status": "done",
"testStrategy": "Integration tests for workflow initialization. Test state restoration from various state.json configurations. Verify dependency checking and error messages.",
@@ -9186,7 +10633,9 @@
"id": 3,
"title": "Build next and status commands with JSON output formatting",
"description": "Create the `next` and `status` commands that provide workflow progression information with structured JSON output for machine parsing.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement `tm autopilot next` that returns JSON with the next action details (test generation, implementation, or commit). Implement `tm autopilot status` showing current run progress, active subtask, and phase. Both commands must support `--json` flag for machine-readable output and human-readable default format. Ensure consistent JSON schema across all output.",
"status": "done",
"testStrategy": "Unit tests for JSON output formatting and schema validation. Integration tests with various workflow states. Test both human and machine-readable output modes.",
@@ -9196,7 +10645,9 @@
"id": 4,
"title": "Implement complete command with result validation integration",
"description": "Build the `complete` command that accepts phase completion results and validates them against TDD requirements.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement `tm autopilot complete` command accepting `--results` (test output/implementation details) and `--coverage` (coverage metrics) flags. Integrate with result validation logic to ensure RED phase has failures and GREEN phase has all tests passing. Update workflow state and advance to next phase. Provide clear feedback on validation success/failure.",
"status": "done",
"testStrategy": "Unit tests for result parsing and validation logic. Integration tests with mocked test results and coverage data. Test error cases for invalid phase transitions.",
@@ -9206,7 +10657,9 @@
"id": 5,
"title": "Create commit and abort commands with git operation coordination",
"description": "Implement the `commit` and `abort` commands that coordinate git operations and workflow state management.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement `tm autopilot commit` that uses the enhanced commit message generator (task 5), stages appropriate files via GitAdapter, and creates commits with embedded metadata. Implement `tm autopilot abort` that safely terminates the workflow, cleaning up temporary state. Both commands should handle git operation errors gracefully and maintain workflow state consistency.",
"status": "done",
"testStrategy": "Integration tests with real git operations. Test commit message generation and metadata embedding. Verify abort command cleanup and state management. Test error handling for git failures.",
@@ -9224,7 +10677,10 @@
"details": "Implement tools: `autopilot_start`, `autopilot_next`, `autopilot_complete_phase`, `autopilot_commit`, `autopilot_status`, `autopilot_resume`. Each tool takes parameters and returns structured results. Use the same core logic as the CLI, exposed via MCP's tool interface. Document expected inputs/outputs. Ensure tools are framework-agnostic and stateless (rely on `state.json`).",
"testStrategy": "Unit tests for each tool's input/output. Integration tests with mocked MCP environment. Verify parity with CLI behavior. Test error cases and edge conditions.",
"priority": "medium",
- "dependencies": ["4", "6"],
+ "dependencies": [
+ "4",
+ "6"
+ ],
"status": "done",
"subtasks": [
{
@@ -9241,7 +10697,9 @@
"id": 2,
"title": "Implement autopilot_start and autopilot_resume tools",
"description": "Build MCP tools for workflow initialization and resumption, enabling AI agents to start new TDD workflows or resume interrupted ones.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Implement autopilot_start tool accepting tag, target directory, and configuration parameters. Create autopilot_resume tool for continuing interrupted workflows from state.json. Both tools should initialize WorkflowOrchestrator, validate preconditions, and return workflow status. Use the same core logic as CLI commands but expose via MCP interface. Handle error cases like existing workflows, missing dependencies, or invalid configurations.",
"status": "done",
"testStrategy": "Integration tests with mocked workflow state. Test start with various configurations. Test resume from different workflow states. Verify error handling for invalid scenarios.",
@@ -9251,7 +10709,9 @@
"id": 3,
"title": "Implement autopilot_next and autopilot_status tools",
"description": "Create MCP tools that provide workflow state information and determine next required actions for AI agents.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Build autopilot_next tool returning the current phase, required action, subtask context, and any parameters needed for the next step. Implement autopilot_status tool providing comprehensive workflow state including current phase, completed subtasks, test results, and progress metrics. Both tools should read from state.json and return structured data matching the event API specification. Include error handling for missing or corrupted state.",
"status": "done",
"testStrategy": "Unit tests with various workflow states. Test next action determination across all phases. Verify status reporting accuracy. Test error handling for corrupted state files.",
@@ -9261,7 +10721,9 @@
"id": 4,
"title": "Implement autopilot_complete_phase tool with validation",
"description": "Build MCP tool for phase completion that validates test results and transitions workflow state according to TDD semantics.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create autopilot_complete_phase tool accepting phase type, test results, and file changes. Integrate with TestResultValidator to enforce RED phase failures and GREEN phase passes. Update workflow state and trigger state machine transitions. Handle validation failures with clear error messages and suggested actions. Support coverage threshold validation when provided. Log phase completion to activity.jsonl.",
"status": "done",
"testStrategy": "Integration tests with TestResultValidator. Test RED phase with passing/failing tests. Test GREEN phase with various result combinations. Verify state transitions and activity logging.",
@@ -9271,7 +10733,9 @@
"id": 5,
"title": "Implement autopilot_commit tool with git operations",
"description": "Create MCP tool for automated commit creation with git staging, message generation, and metadata embedding.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Build autopilot_commit tool that stages specified files, generates appropriate commit messages based on subtask context and phase, and creates commits with embedded metadata. Integrate with GitAdapter for safety checks and branch validation. Include options for commit message templates and metadata formats. Handle git errors gracefully and provide clear feedback. Support dry-run mode for validation without committing.",
"status": "done",
"testStrategy": "Integration tests with GitAdapter and temporary git repositories. Test commit creation with various file sets. Verify metadata embedding and message generation. Test error handling for git failures.",
@@ -9289,7 +10753,11 @@
"details": "Create `CLAUDE.md` (or equivalent) with step-by-step instructions, example CLI/MCP usage, and responsibility matrix (AI vs TaskMaster). Include template prompts for test generation. Document how to parse test output, report results, and handle errors. Provide example JSON inputs/outputs for MCP tools. Keep documentation in the project's docs directory, versioned alongside code.",
"testStrategy": "Manual review of documentation for clarity and completeness. Verify example commands work against a test project. Test AI agent onboarding with the provided instructions.",
"priority": "low",
- "dependencies": ["6", "7", "8"],
+ "dependencies": [
+ "6",
+ "7",
+ "8"
+ ],
"status": "done",
"subtasks": [
{
@@ -9306,7 +10774,9 @@
"id": 2,
"title": "Create CLAUDE.md template and example prompts for AI integration",
"description": "Develop template files and example prompts that enable seamless AI agent onboarding and integration with the TaskMaster workflow system.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create CLAUDE.md template with integration instructions, develop example prompts for test generation and workflow automation, create template JSON structures for MCP tool interactions, document test output parsing patterns, and provide example error handling scenarios. Include practical integration guidance and ready-to-use prompt templates that AI agents can adapt for their specific use cases.",
"status": "done",
"testStrategy": "Test AI agent onboarding using the provided templates and instructions. Verify example prompts produce expected results.",
@@ -9324,7 +10794,9 @@
"details": "Define schema for `config.json`: autopilot settings, commit templates, test thresholds, branch patterns, etc. Use `ajv` (v8+) for schema validation. Update `.gitignore` to exclude `state/` and `reports/` directories, but keep `tasks/`, `config.json`, and `docs/` versioned. Provide default configs. Validate config on workflow start.",
"testStrategy": "Unit tests for config schema and validation. Integration tests to verify ignored directories are not committed. Test config overrides and defaults.",
"priority": "medium",
- "dependencies": ["1"],
+ "dependencies": [
+ "1"
+ ],
"status": "done",
"subtasks": [
{
@@ -9341,7 +10813,9 @@
"id": 2,
"title": "Implement Default Configuration Loading System",
"description": "Build configuration loading mechanism with defaults, environment overrides, and user customization support.",
- "dependencies": [1],
+ "dependencies": [
+ 1
+ ],
"details": "Create ConfigManager class to load default configuration, merge with user-provided config.json, and handle environment variable overrides. Implement configuration hierarchy: defaults < config.json < environment variables. Provide methods to get, set, and validate configuration values at runtime. Include configuration file creation for new projects.",
"status": "done",
"testStrategy": "Unit tests for configuration loading order, merging logic, and environment variable handling. Integration tests with sample config files.",
@@ -9361,7 +10835,10 @@
"id": 4,
"title": "Build Configuration Validation and Error Reporting",
"description": "Implement startup configuration validation with comprehensive error reporting and user-friendly error messages.",
- "dependencies": [1, 2],
+ "dependencies": [
+ 1,
+ 2
+ ],
"details": "Create validation pipeline that runs on workflow startup to verify configuration integrity. Implement detailed error reporting with specific field validation failures, suggested fixes, and examples of valid configurations. Add configuration health check command and validation summary reporting. Ensure graceful handling of missing or corrupted config files.",
"status": "done",
"testStrategy": "Unit tests for validation error messages and suggested fixes. Integration tests for startup validation flow and error handling scenarios.",
@@ -9378,10 +10855,1218 @@
"lastModified": "2025-10-10T13:16:43.150Z",
"taskCount": 10,
"completedCount": 2,
- "tags": ["tdd-phase-1-core-rails"],
+ "tags": [
+ "tdd-phase-1-core-rails"
+ ],
"created": "2025-10-10T13:35:33.065Z",
"description": "Tasks for tdd-phase-1-core-rails context",
"updated": "2025-10-10T16:07:52.412Z"
}
+ },
+ "loop": {
+ "tasks": [
+ {
+ "id": "1",
+ "title": "Define Loop Module Types and Interfaces",
+ "description": "Create TypeScript types and interfaces for the loop module in tm-core, including LoopConfig, LoopIteration, LoopResult, and LoopPreset types.",
+ "details": "Create `packages/tm-core/src/modules/loop/types.ts` with:\n\n```typescript\nexport type LoopPreset = 'default' | 'test-coverage' | 'linting' | 'duplication' | 'entropy';\n\nexport interface LoopConfig {\n iterations: number;\n prompt: LoopPreset | string; // Preset name or file path\n progressFile: string;\n sleepSeconds: number;\n onComplete?: string;\n tag?: string;\n status?: string;\n}\n\nexport interface LoopIteration {\n iteration: number;\n taskId?: string;\n status: 'success' | 'blocked' | 'error' | 'complete';\n message?: string;\n duration?: number;\n}\n\nexport interface LoopResult {\n iterations: LoopIteration[];\n totalIterations: number;\n tasksCompleted: number;\n finalStatus: 'all_complete' | 'max_iterations' | 'blocked' | 'error';\n}\n\nexport interface LoopCompletionMarker {\n type: 'complete' | 'blocked';\n reason: string;\n}\n```\n\nFollow existing patterns from `packages/tm-core/src/modules/workflow/types.ts` and `packages/tm-core/src/modules/execution/types.ts`.",
+ "testStrategy": "Unit tests verifying type exports compile correctly. Create `packages/tm-core/src/modules/loop/types.spec.ts` with tests that import all types and verify they can be instantiated with valid data and reject invalid data using TypeScript compile-time checks.",
+ "priority": "high",
+ "dependencies": [],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Create loop module directory and types.ts file",
+ "description": "Create the loop module directory structure at packages/tm-core/src/modules/loop/ and the initial types.ts file with proper file header and imports.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/types.ts` with file header comment following the pattern from workflow/types.ts and execution/types.ts. The file should be created with proper TypeScript module structure ready for type definitions.",
+ "status": "done",
+ "testStrategy": "Verify file exists at correct path and has proper TypeScript syntax.",
+ "updatedAt": "2026-01-08T21:17:16.264Z",
+ "parentId": "undefined"
+ },
+ {
+ "id": 2,
+ "title": "Define LoopPreset type and LoopConfig interface",
+ "description": "Add the LoopPreset type union and LoopConfig interface with all required properties for loop configuration.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Define `LoopPreset = 'default' | 'test-coverage' | 'linting' | 'duplication' | 'entropy'` and `LoopConfig` interface with: iterations (number), prompt (LoopPreset | string), progressFile (string), sleepSeconds (number), onComplete (optional string), tag (optional string), status (optional string).",
+ "status": "done",
+ "testStrategy": "TypeScript compile-time check - verify types can be imported and used with valid/invalid data.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T21:23:55.708Z"
+ },
+ {
+ "id": 3,
+ "title": "Define LoopIteration and LoopResult interfaces",
+ "description": "Add the LoopIteration interface for tracking individual loop iterations and LoopResult interface for overall loop execution results.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Define `LoopIteration` with: iteration (number), taskId (optional string), status ('success' | 'blocked' | 'error' | 'complete'), message (optional string), duration (optional number). Define `LoopResult` with: iterations (LoopIteration[]), totalIterations (number), tasksCompleted (number), finalStatus ('all_complete' | 'max_iterations' | 'blocked' | 'error').",
+ "status": "done",
+ "testStrategy": "TypeScript compile-time check - verify interfaces accept valid data structures and reject invalid ones.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T21:34:16.931Z"
+ },
+ {
+ "id": 4,
+ "title": "Define LoopCompletionMarker interface",
+ "description": "Add the LoopCompletionMarker interface for representing completion detection results from Claude output parsing.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Define `LoopCompletionMarker` interface with: type ('complete' | 'blocked'), reason (string). This interface will be used by the LoopCompletionService (Task 5) to return parsed marker data from Claude output.",
+ "status": "done",
+ "testStrategy": "TypeScript compile-time check - verify interface can represent both complete and blocked marker types.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T21:35:38.439Z"
+ },
+ {
+ "id": 5,
+ "title": "Export all types and create index.ts barrel export",
+ "description": "Ensure all types are properly exported from types.ts and create an index.ts barrel file for the loop module.",
+ "dependencies": [
+ 2,
+ 3,
+ 4
+ ],
+ "details": "Add export statements for all types (LoopPreset, LoopConfig, LoopIteration, LoopResult, LoopCompletionMarker) in types.ts. Create `packages/tm-core/src/modules/loop/index.ts` that re-exports from types.ts, following the pattern used in other modules like workflow and execution.",
+ "status": "done",
+ "testStrategy": "Import all types from the loop module index and verify they are accessible. Run TypeScript compiler to ensure no export errors.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T21:49:59.115Z"
+ }
+ ],
+ "complexity": 2,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a straightforward type definition task.",
+ "updatedAt": "2026-01-08T21:49:59.115Z"
+ },
+ {
+ "id": "2",
+ "title": "Create Preset Markdown Files",
+ "description": "Create bundled markdown preset files for default, test-coverage, linting, duplication, and entropy workflows in tm-core assets.",
+ "details": "Create directory `packages/tm-core/src/modules/loop/presets/` with markdown files:\n\n1. `default.md` - Standard task completion workflow (as specified in PRD)\n2. `test-coverage.md` - Test coverage workflow\n3. `linting.md` - Lint/type error fixing workflow\n4. `duplication.md` - Code duplication refactoring workflow\n5. `entropy.md` - Code smell cleanup workflow\n\nEach preset should contain:\n- Clear instructions for the agent\n- File references using `@` syntax for progress file\n- Process steps numbered 1-7\n- Completion criteria with `<loop-complete>` and `<loop-blocked>` markers\n- Important notes about single-task-per-iteration constraint\n\nAdd `packages/tm-core/src/modules/loop/presets/index.ts` exporting preset names and file paths for bundling.",
+ "testStrategy": "Snapshot tests to verify preset content structure. Integration test loading each preset and verifying it contains required markers (`<loop-complete>`, `<loop-blocked>`) and @ file references.",
+ "priority": "high",
+ "dependencies": [],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Create preset directory structure and index.ts export file",
+ "description": "Create the `packages/tm-core/src/modules/loop/presets/` directory structure with an `index.ts` file that exports preset names and provides utilities for loading bundled preset files.",
+ "dependencies": [],
+ "details": "1. Create directory `packages/tm-core/src/modules/loop/presets/`\n2. Create `index.ts` with:\n - `PRESET_NAMES` constant array: `['default', 'test-coverage', 'linting', 'duplication', 'entropy']`\n - `isValidPreset(name: string): name is LoopPreset` type guard function\n - `getPresetPath(preset: LoopPreset): string` function returning relative path to preset markdown file\n - `loadPreset(preset: LoopPreset): Promise<string>` async function that reads and returns preset content using `fs/promises`\n - Re-export preset type from loop types if needed\n3. Use `import.meta.url` and `fileURLToPath` for ESM-compatible path resolution to locate bundled markdown files relative to the compiled module",
+ "status": "done",
+ "testStrategy": "Unit test `isValidPreset()` with valid preset names (returns true), invalid names (returns false), and file paths (returns false). Test `getPresetPath()` returns correct relative paths. Test `loadPreset()` successfully loads each preset file and returns non-empty string content.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T21:53:23.312Z"
+ },
+ {
+ "id": 2,
+ "title": "Write the 5 markdown preset files with completion markers and @ syntax",
+ "description": "Create the 5 markdown preset files (default.md, test-coverage.md, linting.md, duplication.md, entropy.md) following the PRD specifications with proper completion markers and file references.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Create markdown files in `packages/tm-core/src/modules/loop/presets/`:\n\n1. **default.md** - Standard task completion workflow:\n - @ file references: `@.taskmaster/tasks/tasks.json`, `@.taskmaster/loop-progress.txt`\n - 7-step process: next task → show → implement → quality checks → set-status → commit → append progress\n - Completion markers: `<loop-complete>ALL_TASKS_DONE</loop-complete>`, `<loop-blocked>REASON</loop-blocked>`\n - Important notes: ONE task per session, keep changes small\n\n2. **test-coverage.md** - Test coverage workflow per PRD spec\n3. **linting.md** - Lint/type error fixing per PRD spec\n4. **duplication.md** - Code duplication refactoring per PRD spec\n5. **entropy.md** - Code smell cleanup per PRD spec\n\nEach preset must include:\n- Clear header with workflow name\n- Files Available section with @ syntax references\n- Numbered process steps (5-7 steps)\n- Completion criteria with `<loop-complete>` marker\n- Important notes about single-task-per-iteration constraint",
+ "status": "done",
+ "testStrategy": "Snapshot tests comparing each preset file content against expected structure. Test that each preset contains required elements: @ file reference pattern, <loop-complete> marker, <loop-blocked> marker (where applicable), numbered process steps, and single-task-per-iteration constraint note.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T21:56:55.796Z"
+ },
+ {
+ "id": 3,
+ "title": "Write snapshot tests for preset structure and required markers",
+ "description": "Create a comprehensive test suite in `packages/tm-core/src/modules/loop/presets/presets.spec.ts` to verify preset file structure, required markers, and content integrity.",
+ "dependencies": [
+ 1,
+ 2
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/presets/presets.spec.ts` with:\n\n1. **Snapshot tests** for each preset:\n - Load each preset using `loadPreset()` function\n - Use `toMatchSnapshot()` to verify content stability\n\n2. **Structure validation tests** for each preset:\n - Contains `<loop-complete>` marker with valid completion reason\n - Contains @ file reference pattern (`@.taskmaster/` or `@./`)\n - Contains numbered process steps (regex: `/^\\d+\\./m`)\n - Contains 'Important' or 'Completion Criteria' section\n - For default preset: contains `<loop-blocked>` marker\n\n3. **Index.ts function tests**:\n - `isValidPreset()` returns true for all 5 preset names\n - `isValidPreset()` returns false for invalid names and file paths\n - `loadPreset()` returns non-empty string for each preset\n - `getPresetPath()` returns paths ending in `.md`\n\n4. **Content consistency tests**:\n - All presets mention single-task-per-iteration constraint\n - All presets have progress file reference",
+ "status": "done",
+ "testStrategy": "Run tests with `npm test -w @tm/core -- --testPathPattern=presets.spec.ts`. Verify snapshot files are created in `__snapshots__/` directory. Tests should achieve 100% coverage of the preset index.ts exports.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:06:11.126Z"
+ }
+ ],
+ "complexity": 4,
+ "recommendedSubtasks": 3,
+ "expansionPrompt": "Break down into: 1) Create preset directory structure and index.ts export file, 2) Write the 5 markdown preset files (default, test-coverage, linting, duplication, entropy) with proper completion markers and @ syntax, 3) Write snapshot tests to verify preset structure and required markers",
+ "updatedAt": "2026-01-08T22:06:11.126Z"
+ },
+ {
+ "id": "3",
+ "title": "Implement Preset Resolution Service",
+ "description": "Create LoopPresetService in tm-core to resolve preset names to prompt content and detect whether a string is a preset name or file path.",
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-preset.service.ts`:\n\n```typescript\nimport { readFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport type { LoopPreset } from '../types.js';\n\nexport class LoopPresetService {\n private readonly presetsDir: string;\n private readonly validPresets: Set<LoopPreset> = new Set([\n 'default', 'test-coverage', 'linting', 'duplication', 'entropy'\n ]);\n\n constructor() {\n // Get presets directory relative to this file (bundled)\n this.presetsDir = path.join(__dirname, '../presets');\n }\n\n isPreset(prompt: string): prompt is LoopPreset {\n return this.validPresets.has(prompt as LoopPreset);\n }\n\n isFilePath(prompt: string): boolean {\n // File path if contains / or \\ or has common file extension\n return prompt.includes('/') || \n prompt.includes('\\\\') || \n /\\.(md|txt|markdown)$/i.test(prompt);\n }\n\n async resolvePrompt(prompt: LoopPreset | string): Promise<string> {\n if (this.isPreset(prompt)) {\n return this.loadPreset(prompt);\n }\n return this.loadCustomPrompt(prompt);\n }\n\n private async loadPreset(preset: LoopPreset): Promise<string> {\n const presetPath = path.join(this.presetsDir, `${preset}.md`);\n return readFile(presetPath, 'utf-8');\n }\n\n private async loadCustomPrompt(filePath: string): Promise<string> {\n return readFile(filePath, 'utf-8');\n }\n}\n```\n\nHandle error cases: file not found, invalid preset name, empty content.",
+ "testStrategy": "Unit tests for `isPreset()` and `isFilePath()` with edge cases (paths with spaces, various extensions). Integration test loading each built-in preset. Error handling tests for missing files and invalid presets.",
+ "priority": "high",
+ "dependencies": [
+ "1",
+ "2"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Implement LoopPresetService with detection and resolution methods",
+ "description": "Create the LoopPresetService class in tm-core that provides isPreset(), isFilePath(), and resolvePrompt() methods with comprehensive error handling for file operations.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-preset.service.ts` following existing service patterns. Implement:\n\n1. **Constructor**: Initialize presetsDir path relative to bundled location and validPresets Set\n2. **isPreset(prompt: string)**: Type guard that checks if prompt is a valid preset name from the validPresets Set\n3. **isFilePath(prompt: string)**: Detect file paths by checking for path separators (/, \\) or common extensions (.md, .txt, .markdown)\n4. **resolvePrompt(prompt: LoopPreset | string)**: Main method that delegates to loadPreset() or loadCustomPrompt() based on isPreset() check\n5. **loadPreset(preset: LoopPreset)**: Read preset file from presetsDir, throw descriptive error if not found\n6. **loadCustomPrompt(filePath: string)**: Read custom file, throw descriptive error if not found\n\nError handling requirements:\n- File not found: Throw TaskMasterError with code 'PRESET_NOT_FOUND' or 'CUSTOM_PROMPT_NOT_FOUND'\n- Invalid preset name: Throw TaskMasterError with code 'INVALID_PRESET' listing valid presets\n- Empty content: Throw TaskMasterError with code 'EMPTY_PROMPT_CONTENT'\n\nExport service from module index file and add appropriate JSDoc comments.",
+ "status": "done",
+ "testStrategy": null,
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:35:33.799Z"
+ },
+ {
+ "id": 2,
+ "title": "Write comprehensive unit tests for LoopPresetService",
+ "description": "Create thorough test coverage for all LoopPresetService methods including edge cases for path detection, preset validation, and error scenarios.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-preset.service.spec.ts` following existing test patterns (vi.mock for fs, describe/it structure).\n\n**Test isPreset()**:\n- Valid preset names return true: 'default', 'test-coverage', 'linting', 'duplication', 'entropy'\n- Invalid names return false: 'invalid', 'DEFAULT' (case sensitive), 'default.md', ''\n- Non-string inputs handled gracefully\n\n**Test isFilePath()**:\n- Unix paths: '/path/to/file.md', './relative/path.txt', '../parent/file.md'\n- Windows paths: 'C:\\\\path\\\\file.md', '.\\\\relative\\\\path.txt'\n- Extension detection: 'prompt.md', 'prompt.txt', 'prompt.markdown'\n- Paths with spaces: '/path/with spaces/file.md'\n- Edge cases: 'simple-name' (no path/extension) returns false\n- Mixed: 'folder/prompt' (path but no extension) returns true\n\n**Test resolvePrompt()**:\n- Mock fs.readFile for successful preset loading\n- Mock fs.readFile for successful custom file loading\n- Error: preset file not found → specific error message\n- Error: custom file not found → specific error message with provided path\n- Error: file exists but is empty → empty content error\n- Error: invalid preset name passed directly\n\n**Integration-style tests**:\n- Verify correct file path construction for presets\n- Verify custom paths are passed through unchanged",
+ "status": "done",
+ "testStrategy": "Unit tests with mocked fs module following config-loader.service.spec.ts pattern. Test each public method independently with AAA structure. Cover boundary conditions, error paths, and typical usage scenarios. Use vi.mock for node:fs/promises to isolate from filesystem.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:39:21.258Z"
+ }
+ ],
+ "complexity": 4,
+ "recommendedSubtasks": 2,
+ "expansionPrompt": "Break down into: 1) Implement LoopPresetService with isPreset(), isFilePath(), and resolvePrompt() methods including error handling, 2) Write comprehensive unit tests for all methods including edge cases (paths with spaces, various extensions, missing files)",
+ "updatedAt": "2026-01-08T22:39:21.258Z"
+ },
+ {
+ "id": "4",
+ "title": "Implement Progress File Service",
+ "description": "Create LoopProgressService in tm-core to manage the progress.txt file - appending notes, reading history, and initializing new progress files.",
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-progress.service.ts`:\n\n```typescript\nimport { appendFile, readFile, writeFile, access } from 'node:fs/promises';\nimport path from 'node:path';\n\nexport interface ProgressEntry {\n timestamp: string;\n iteration: number;\n taskId?: string;\n note: string;\n}\n\nexport class LoopProgressService {\n private readonly projectRoot: string;\n \n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n getDefaultProgressPath(): string {\n return path.join(this.projectRoot, '.taskmaster', 'loop-progress.txt');\n }\n\n async initializeProgressFile(progressFile: string, config: { preset: string; iterations: number; tag?: string }): Promise<void> {\n const header = `# Task Master Loop Progress\\n# Started: ${new Date().toISOString()}\\n# Preset: ${config.preset}\\n# Max Iterations: ${config.iterations}\\n${config.tag ? `# Tag: ${config.tag}\\n` : ''}\\n---\\n\\n`;\n await writeFile(progressFile, header, 'utf-8');\n }\n\n async appendProgress(progressFile: string, entry: ProgressEntry): Promise<void> {\n const line = `[${entry.timestamp}] Iteration ${entry.iteration}${entry.taskId ? ` (Task ${entry.taskId})` : ''}: ${entry.note}\\n`;\n await appendFile(progressFile, line, 'utf-8');\n }\n\n async readProgress(progressFile: string): Promise<string> {\n try {\n return await readFile(progressFile, 'utf-8');\n } catch {\n return '';\n }\n }\n\n async exists(progressFile: string): Promise<boolean> {\n try {\n await access(progressFile);\n return true;\n } catch {\n return false;\n }\n }\n}\n```",
+ "testStrategy": "Unit tests with mock filesystem for: initializing new file with header, appending multiple entries, reading existing progress, handling missing files gracefully. Test file format matches expected structure for agent parsing.",
+ "priority": "high",
+ "dependencies": [
+ "1"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Create LoopProgressService class with constructor and path helper",
+ "description": "Create the base service file with constructor accepting projectRoot and implement getDefaultProgressPath() method.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-progress.service.ts`. Import `node:fs/promises` and `node:path`. Define the `ProgressEntry` interface with fields: timestamp (string), iteration (number), taskId (optional string), note (string). Create the class with private `projectRoot` field, constructor, and `getDefaultProgressPath()` that returns `path.join(this.projectRoot, '.taskmaster', 'loop-progress.txt')`.",
+ "status": "done",
+ "testStrategy": "Unit test that verifies getDefaultProgressPath() returns correct path for various projectRoot values (absolute paths, relative paths, paths with spaces).",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:17:59.845Z"
+ },
+ {
+ "id": 2,
+ "title": "Implement initializeProgressFile method",
+ "description": "Add method to create a new progress file with header containing timestamp, preset, iterations, and optional tag.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Implement `async initializeProgressFile(progressFile: string, config: { preset: string; iterations: number; tag?: string }): Promise<void>`. Build header string with markdown comments showing start time (ISO format), preset name, max iterations, and optional tag line. Use `writeFile` from node:fs/promises. Ensure parent directory exists before writing using `mkdir` with recursive option.",
+ "status": "done",
+ "testStrategy": "Unit tests: verify header format contains all config values, verify tag line only appears when tag is provided, verify timestamp is valid ISO format, test with mock filesystem using vi.mock('node:fs/promises').",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:20:41.879Z"
+ },
+ {
+ "id": 3,
+ "title": "Implement appendProgress method",
+ "description": "Add method to append a formatted progress entry line to the progress file.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Implement `async appendProgress(progressFile: string, entry: ProgressEntry): Promise<void>`. Format each entry as `[{timestamp}] Iteration {iteration}{ (Task {taskId})}: {note}\\n`. The taskId portion is optional - only include if entry.taskId is defined. Use `appendFile` from node:fs/promises.",
+ "status": "done",
+ "testStrategy": "Unit tests: verify line format with taskId, verify line format without taskId, verify multiple appends accumulate correctly, verify newline is included at end of each entry.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:23:06.841Z"
+ },
+ {
+ "id": 4,
+ "title": "Implement readProgress and exists methods",
+ "description": "Add methods to read existing progress file contents and check if a progress file exists.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Implement `async readProgress(progressFile: string): Promise<string>` - returns file content or empty string if file doesn't exist (catch any error and return ''). Implement `async exists(progressFile: string): Promise<boolean>` - uses `access` from node:fs/promises, returns true if accessible, false on any error. Both methods should handle missing files gracefully without throwing.",
+ "status": "done",
+ "testStrategy": "Unit tests: readProgress returns content for existing file, readProgress returns empty string for missing file, exists returns true for existing file, exists returns false for missing file, handle permission errors gracefully.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:25:03.756Z"
+ },
+ {
+ "id": 5,
+ "title": "Export service from loop module index and write integration tests",
+ "description": "Export the new service from the loop module's index.ts and write comprehensive integration tests using real filesystem.",
+ "dependencies": [
+ 1,
+ 2,
+ 3,
+ 4
+ ],
+ "details": "Create or update `packages/tm-core/src/modules/loop/index.ts` to export `LoopProgressService` and `ProgressEntry`. Create `packages/tm-core/src/modules/loop/services/loop-progress.service.spec.ts` with tests using temp directories (follow pattern from task-file-generator.service.spec.ts). Test full workflow: initialize file, append multiple entries, read back, verify format. Use `os.tmpdir()` and `fs.mkdtempSync` for test isolation.",
+ "status": "done",
+ "testStrategy": "Integration tests with real filesystem: create temp directory, initialize progress file, append 3-5 entries with various combinations (with/without taskId), read back and verify full content structure, clean up temp directory in afterEach.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:28:05.277Z"
+ }
+ ],
+ "complexity": 3,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a focused file I/O service with clear implementation.",
+ "updatedAt": "2026-01-08T22:28:05.277Z"
+ },
+ {
+ "id": "5",
+ "title": "Implement Loop Completion Detection",
+ "description": "Create LoopCompletionService in tm-core to parse Claude output for completion markers (<loop-complete>, <loop-blocked>) and determine loop state.",
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-completion.service.ts`:\n\n```typescript\nimport type { LoopCompletionMarker } from '../types.js';\n\nexport interface CompletionCheckResult {\n isComplete: boolean;\n isBlocked: boolean;\n marker?: LoopCompletionMarker;\n rawMatch?: string;\n}\n\nexport class LoopCompletionService {\n private readonly completePattern = /<loop-complete>([^<]+)<\\/loop-complete>/i;\n private readonly blockedPattern = /<loop-blocked>([^<]+)<\\/loop-blocked>/i;\n\n parseOutput(output: string): CompletionCheckResult {\n const completeMatch = output.match(this.completePattern);\n if (completeMatch) {\n return {\n isComplete: true,\n isBlocked: false,\n marker: { type: 'complete', reason: completeMatch[1].trim() },\n rawMatch: completeMatch[0]\n };\n }\n\n const blockedMatch = output.match(this.blockedPattern);\n if (blockedMatch) {\n return {\n isComplete: false,\n isBlocked: true,\n marker: { type: 'blocked', reason: blockedMatch[1].trim() },\n rawMatch: blockedMatch[0]\n };\n }\n\n return { isComplete: false, isBlocked: false };\n }\n\n extractCompletionReason(marker: LoopCompletionMarker): string {\n return marker.reason;\n }\n}\n```\n\nHandle edge cases: multiple markers (use first), malformed markers, case insensitivity.",
+ "testStrategy": "Unit tests for all marker patterns: valid complete markers with various reasons (ALL_TASKS_DONE, COVERAGE_TARGET, ZERO_ERRORS, LOW_DUPLICATION, LOW_ENTROPY), blocked markers with reasons, no markers, malformed markers, multiple markers in output.",
+ "priority": "high",
+ "dependencies": [
+ "1"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Create loop module types with LoopCompletionMarker interface",
+ "description": "Create the types.ts file in packages/tm-core/src/modules/loop/ defining LoopCompletionMarker and related types used by the completion service.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/types.ts` with:\n\n```typescript\nexport type LoopPreset = 'default' | 'test-coverage' | 'linting' | 'duplication' | 'entropy';\n\nexport interface LoopCompletionMarker {\n type: 'complete' | 'blocked';\n reason: string;\n}\n```\n\nThis provides the LoopCompletionMarker type needed by LoopCompletionService.parseOutput() return value. The type distinguishes between completion markers (`<loop-complete>`) and blocked markers (`<loop-blocked>`).",
+ "status": "done",
+ "testStrategy": "Type-only file - no runtime tests needed. TypeScript compiler will validate type correctness when the service imports and uses these types.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:33:15.898Z"
+ },
+ {
+ "id": 2,
+ "title": "Implement LoopCompletionService with regex parsing",
+ "description": "Create the LoopCompletionService class with parseOutput() method that uses regex to detect completion and blocked markers in Claude output.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-completion.service.ts` with the implementation from the task details. Key implementation points:\n\n1. Define CompletionCheckResult interface with isComplete, isBlocked, marker?, and rawMatch? properties\n2. Store regex patterns as private readonly properties using /i flag for case insensitivity\n3. parseOutput() method checks for `<loop-complete>` first, then `<loop-blocked>`, returning first match found\n4. extractCompletionReason() helper method to get reason string from marker\n\nThe regex patterns `/<loop-complete>([^<]+)<\\/loop-complete>/i` and `/<loop-blocked>([^<]+)<\\/loop-blocked>/i` handle the tag content extraction.",
+ "status": "done",
+ "testStrategy": "Unit tests for: valid complete markers with various reasons (ALL_TASKS_DONE, COVERAGE_TARGET, ZERO_ERRORS), valid blocked markers, case insensitivity verification.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:31:45.449Z"
+ },
+ {
+ "id": 3,
+ "title": "Handle edge cases: multiple markers and malformed input",
+ "description": "Ensure the parseOutput() method correctly handles edge cases like multiple markers in output, malformed markers, and empty/null input.",
+ "dependencies": [
+ 2
+ ],
+ "details": "Verify and test edge case handling in LoopCompletionService:\n\n1. **Multiple markers**: The current regex with .match() returns first match - verify this is correct behavior\n2. **Malformed markers**: Unclosed tags like `<loop-complete>reason` should not match (regex already handles this)\n3. **Empty/whitespace content**: `<loop-complete> </loop-complete>` should return trimmed empty reason\n4. **No markers**: Return `{ isComplete: false, isBlocked: false }` \n5. **Null/undefined input**: Add defensive check at start of parseOutput()\n6. **Very long output**: Regex should still work efficiently on large strings\n\nMay need to add input validation: `if (!output) return { isComplete: false, isBlocked: false };`",
+ "status": "done",
+ "testStrategy": "Unit tests for: output with both markers (first wins), malformed/unclosed tags, empty tag content, null/undefined input, output with no markers, large output strings.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:33:15.957Z"
+ },
+ {
+ "id": 4,
+ "title": "Write comprehensive unit tests for LoopCompletionService",
+ "description": "Create unit test file covering all marker patterns, edge cases, and the extractCompletionReason helper method.",
+ "dependencies": [
+ 2,
+ 3
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-completion.service.spec.ts` with test cases:\n\n```typescript\nimport { LoopCompletionService } from './loop-completion.service.js';\n\ndescribe('LoopCompletionService', () => {\n let service: LoopCompletionService;\n beforeEach(() => { service = new LoopCompletionService(); });\n\n describe('parseOutput', () => {\n it('detects <loop-complete> with ALL_TASKS_DONE reason', () => {...});\n it('detects <loop-complete> with COVERAGE_TARGET reason', () => {...});\n it('detects <loop-complete> with ZERO_ERRORS reason', () => {...});\n it('detects <loop-blocked> with reason', () => {...});\n it('returns false for output with no markers', () => {...});\n it('handles case insensitivity', () => {...});\n it('uses first marker when multiple present', () => {...});\n it('ignores malformed/unclosed markers', () => {...});\n it('trims whitespace from reasons', () => {...});\n it('handles empty input', () => {...});\n });\n\n describe('extractCompletionReason', () => {...});\n});\n```",
+ "status": "done",
+ "testStrategy": "Run `npm test -w @tm/core -- --testPathPattern=loop-completion` to execute tests. All tests should pass with 100% coverage of the service.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:33:15.991Z"
+ },
+ {
+ "id": 5,
+ "title": "Export LoopCompletionService from loop module index",
+ "description": "Create the loop module index file to export the LoopCompletionService and types for use by other modules.",
+ "dependencies": [
+ 2
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/index.ts`:\n\n```typescript\nexport * from './types.js';\nexport * from './services/loop-completion.service.js';\n```\n\nAlso create `packages/tm-core/src/modules/loop/services/index.ts`:\n\n```typescript\nexport * from './loop-completion.service.js';\n```\n\nThis follows the existing module structure pattern seen in other tm-core modules (config, git, tasks, etc.) where each module has an index.ts that re-exports its public API. The service and types will be consumable as `import { LoopCompletionService, LoopCompletionMarker } from '@tm/core/modules/loop';`",
+ "status": "done",
+ "testStrategy": "Verify exports work by checking TypeScript compilation and that the module can be imported from the package entrypoint. No dedicated tests needed for re-exports.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:33:16.024Z"
+ }
+ ],
+ "complexity": 3,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a focused regex parsing service with clear implementation.",
+ "updatedAt": "2026-01-08T22:33:16.024Z"
+ },
+ {
+ "id": "6",
+ "title": "Implement Loop Prompt Generator",
+ "description": "Create LoopPromptService in tm-core to generate the full Claude prompt by combining preset content with file context references.",
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-prompt.service.ts`:\n\n```typescript\nimport type { LoopConfig } from '../types.js';\nimport { LoopPresetService } from './loop-preset.service.js';\n\nexport interface PromptGenerationOptions {\n config: LoopConfig;\n iteration: number;\n projectRoot: string;\n}\n\nexport class LoopPromptService {\n private readonly presetService: LoopPresetService;\n\n constructor(presetService: LoopPresetService) {\n this.presetService = presetService;\n }\n\n async generatePrompt(options: PromptGenerationOptions): Promise<string> {\n const { config, iteration, projectRoot } = options;\n \n // Get base prompt from preset or file\n const basePrompt = await this.presetService.resolvePrompt(config.prompt);\n \n // Build context header\n const contextHeader = this.buildContextHeader(config, iteration);\n \n // Combine with file references already in preset\n return `${contextHeader}\\n\\n${basePrompt}`;\n }\n\n private buildContextHeader(config: LoopConfig, iteration: number): string {\n const lines = [\n `# Loop Iteration ${iteration} of ${config.iterations}`,\n ``,\n `## Context`,\n `- Progress file: @${config.progressFile}`,\n `- Tasks file: @.taskmaster/tasks/tasks.json`\n ];\n \n if (config.tag) {\n lines.push(`- Tag filter: ${config.tag}`);\n }\n \n return lines.join('\\n');\n }\n}\n```",
+ "testStrategy": "Unit tests verifying: prompt includes iteration number, includes file references with @ syntax, includes tag when specified, properly combines preset content with header. Snapshot tests for generated prompts from each preset.",
+ "priority": "medium",
+ "dependencies": [
+ "1",
+ "3",
+ "4"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Create LoopPromptService class with constructor and interface definitions",
+ "description": "Create the LoopPromptService class file with TypeScript interface definitions and constructor that accepts LoopPresetService dependency.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-prompt.service.ts` with:\n1. Import statements for LoopConfig type and LoopPresetService\n2. Define PromptGenerationOptions interface with config, iteration, and projectRoot fields\n3. Create LoopPromptService class with private readonly presetService field\n4. Implement constructor that accepts LoopPresetService instance via dependency injection",
+ "status": "done",
+ "testStrategy": "Unit test verifying constructor properly stores presetService reference. Test that service can be instantiated with mock LoopPresetService.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:00:09.920Z"
+ },
+ {
+ "id": 2,
+ "title": "Implement buildContextHeader method for iteration metadata",
+ "description": "Implement the private buildContextHeader method that generates the iteration context section of the prompt with loop metadata.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Add private buildContextHeader method that:\n1. Accepts LoopConfig and iteration number as parameters\n2. Generates header with iteration count (e.g., 'Loop Iteration 3 of 10')\n3. Adds context section with progress file reference using @ syntax\n4. Adds tasks.json file reference\n5. Conditionally includes tag filter if config.tag is specified\n6. Returns formatted string with proper newline separators",
+ "status": "done",
+ "testStrategy": "Unit tests for: header includes correct iteration numbers, header includes file references with @ prefix, header includes tag when config.tag is set, header omits tag line when config.tag is undefined.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:02:17.655Z"
+ },
+ {
+ "id": 3,
+ "title": "Implement generatePrompt async method",
+ "description": "Implement the main generatePrompt async method that combines preset content with context header to produce the full Claude prompt.",
+ "dependencies": [
+ 1,
+ 2
+ ],
+ "details": "Add async generatePrompt method that:\n1. Accepts PromptGenerationOptions parameter\n2. Calls presetService.resolvePrompt() to get base prompt content\n3. Calls buildContextHeader() to get iteration context\n4. Combines context header and base prompt with double newline separator\n5. Returns the complete prompt string",
+ "status": "done",
+ "testStrategy": "Unit test with mock LoopPresetService that returns known prompt. Verify output combines header and base prompt correctly. Test with different iteration numbers and preset values.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:04:58.159Z"
+ },
+ {
+ "id": 4,
+ "title": "Export service from module index and create types",
+ "description": "Export LoopPromptService and PromptGenerationOptions from module index files for external consumption.",
+ "dependencies": [
+ 1,
+ 2,
+ 3
+ ],
+ "details": "1. Create or update `packages/tm-core/src/modules/loop/services/index.ts` to export LoopPromptService and PromptGenerationOptions\n2. Update `packages/tm-core/src/modules/loop/index.ts` to re-export from services\n3. Ensure proper TypeScript type exports for PromptGenerationOptions interface",
+ "status": "done",
+ "testStrategy": "Verify exports are accessible from package entry points. Test that importing { LoopPromptService, PromptGenerationOptions } works from module index.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:06:59.106Z"
+ },
+ {
+ "id": 5,
+ "title": "Write comprehensive unit tests with snapshot tests for generated prompts",
+ "description": "Create unit test file with comprehensive tests for LoopPromptService including snapshot tests for prompt output formats.",
+ "dependencies": [
+ 1,
+ 2,
+ 3,
+ 4
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-prompt.service.spec.ts` with:\n1. Mock LoopPresetService with jest.fn() or vi.fn()\n2. Test generatePrompt includes iteration number in output\n3. Test output includes file references with @ syntax\n4. Test tag is included when specified in config\n5. Test tag is omitted when not specified\n6. Snapshot tests for generated prompts from each preset (default, test-coverage, linting, duplication, entropy)\n7. Test proper combination of header and base prompt content",
+ "status": "done",
+ "testStrategy": "Run `npm run test -w @tm/core` to execute tests. Verify all tests pass. Review snapshot files to ensure prompt formats match expected structure.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:09:45.708Z"
+ }
+ ],
+ "complexity": 3,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a straightforward string composition service.",
+ "updatedAt": "2026-01-08T23:09:45.708Z"
+ },
+ {
+ "id": "7",
+ "title": "Implement Loop Executor Service",
+ "description": "Create LoopExecutorService in tm-core to spawn Claude Code CLI with the generated prompt and capture output for completion detection.",
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-executor.service.ts`:\n\n```typescript\nimport { spawn } from 'node:child_process';\nimport type { LoopIteration } from '../types.js';\nimport { LoopCompletionService, type CompletionCheckResult } from './loop-completion.service.js';\n\nexport interface ExecutionResult {\n iteration: LoopIteration;\n output: string;\n completionCheck: CompletionCheckResult;\n exitCode: number;\n}\n\nexport class LoopExecutorService {\n private readonly completionService: LoopCompletionService;\n private currentProcess: any = null;\n\n constructor(completionService: LoopCompletionService) {\n this.completionService = completionService;\n }\n\n async executeIteration(\n prompt: string,\n iteration: number,\n projectRoot: string\n ): Promise<ExecutionResult> {\n const startTime = Date.now();\n let output = '';\n\n return new Promise((resolve) => {\n // Use claude -p for print mode (non-interactive)\n this.currentProcess = spawn('claude', ['-p', prompt], {\n cwd: projectRoot,\n shell: false,\n stdio: ['ignore', 'pipe', 'pipe']\n });\n\n this.currentProcess.stdout?.on('data', (data: Buffer) => {\n output += data.toString();\n });\n\n this.currentProcess.stderr?.on('data', (data: Buffer) => {\n output += data.toString();\n });\n\n this.currentProcess.on('close', (code: number) => {\n this.currentProcess = null;\n const duration = Date.now() - startTime;\n const completionCheck = this.completionService.parseOutput(output);\n\n const iterationResult: LoopIteration = {\n iteration,\n status: this.determineStatus(code, completionCheck),\n duration,\n message: completionCheck.marker?.reason\n };\n\n resolve({\n iteration: iterationResult,\n output,\n completionCheck,\n exitCode: code\n });\n });\n\n this.currentProcess.on('error', (error: Error) => {\n this.currentProcess = null;\n resolve({\n iteration: {\n iteration,\n status: 'error',\n message: error.message\n },\n output,\n completionCheck: { isComplete: false, isBlocked: false },\n exitCode: 1\n });\n });\n });\n }\n\n private determineStatus(code: number, check: CompletionCheckResult): LoopIteration['status'] {\n if (check.isComplete) return 'complete';\n if (check.isBlocked) return 'blocked';\n if (code !== 0) return 'error';\n return 'success';\n }\n\n async stop(): Promise<void> {\n if (this.currentProcess) {\n this.currentProcess.kill('SIGTERM');\n this.currentProcess = null;\n }\n }\n}\n```\n\nFollow patterns from `packages/tm-core/src/modules/execution/executors/claude-executor.ts`.",
+ "testStrategy": "Unit tests with mocked spawn: successful execution returning output, detecting completion markers in output, handling non-zero exit codes, handling process errors. Integration test (manual/CI) with real Claude Code if available.",
+ "priority": "high",
+ "dependencies": [
+ "1",
+ "5",
+ "6"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Implement basic spawn mechanism with stdio capture",
+ "description": "Create LoopExecutorService with spawn() for Claude CLI following claude-executor.ts patterns, capturing stdout/stderr output.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-executor.service.ts` with:\n\n1. Define `ExecutionResult` interface with fields: `iteration`, `output`, `completionCheck`, `exitCode`\n2. Create `LoopExecutorService` class with constructor accepting `LoopCompletionService` dependency\n3. Implement `executeIteration(prompt: string, iteration: number, projectRoot: string)` method:\n - Use `spawn('claude', ['-p', prompt], { cwd: projectRoot, shell: false, stdio: ['ignore', 'pipe', 'pipe'] })`\n - Attach data handlers to stdout/stderr to accumulate output in a buffer string\n - Store process reference in `this.currentProcess` for lifecycle management\n4. Follow patterns from `packages/tm-core/src/modules/execution/executors/claude-executor.ts` (lines 96-100)",
+ "status": "done",
+ "testStrategy": null,
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:12:39.772Z"
+ },
+ {
+ "id": 2,
+ "title": "Implement output capture and completion detection integration",
+ "description": "Add Promise-based resolution with timing, integrate LoopCompletionService to parse output for completion markers.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Extend `executeIteration()` implementation:\n\n1. Track `startTime = Date.now()` at iteration start\n2. In 'close' event handler:\n - Calculate `duration = Date.now() - startTime`\n - Call `this.completionService.parseOutput(output)` to get `CompletionCheckResult`\n - Build `LoopIteration` object with iteration number, status, duration, and message from marker reason\n - Resolve Promise with `ExecutionResult` containing iteration, output, completionCheck, exitCode\n3. Implement private `determineStatus(code: number, check: CompletionCheckResult)` method:\n - Return 'complete' if `check.isComplete`\n - Return 'blocked' if `check.isBlocked`\n - Return 'error' if `code !== 0`\n - Return 'success' otherwise\n4. Import `LoopCompletionService` and `CompletionCheckResult` from `./loop-completion.service.js`",
+ "status": "done",
+ "testStrategy": null,
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:14:10.517Z"
+ },
+ {
+ "id": 3,
+ "title": "Implement process lifecycle management",
+ "description": "Add stop() method, error handling, process cleanup, and null-safe currentProcess management.",
+ "dependencies": [
+ 1,
+ 2
+ ],
+ "details": "Complete lifecycle management:\n\n1. Implement `async stop(): Promise<void>` method:\n - Check if `this.currentProcess` is truthy\n - Call `this.currentProcess.kill('SIGTERM')`\n - Set `this.currentProcess = null`\n2. Add 'error' event handler in `executeIteration()`:\n - Set `this.currentProcess = null`\n - Resolve with error result: status='error', message=error.message, exitCode=1\n - Include empty completionCheck: `{ isComplete: false, isBlocked: false }`\n3. Ensure `this.currentProcess = null` is set in both 'close' and 'error' handlers before resolving\n4. Export types: `ExecutionResult` interface for consumers\n5. Add proper type for currentProcess (`ChildProcess | null`) avoiding `any`",
+ "status": "done",
+ "testStrategy": null,
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:15:31.790Z"
+ },
+ {
+ "id": 4,
+ "title": "Write unit tests for LoopExecutorService",
+ "description": "Create comprehensive unit tests with mocked spawn for all execution scenarios including success, completion markers, errors, and stop functionality.",
+ "dependencies": [
+ 1,
+ 2,
+ 3
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-executor.service.spec.ts`:\n\n1. Mock `child_process.spawn` using vi.mock\n2. Create mock EventEmitter-based process object with stdout/stderr streams\n3. Test cases:\n - **Successful execution**: spawn returns exit code 0, no completion markers\n - **Completion marker detection**: output contains `<loop-complete>`, verify completionCheck.isComplete=true\n - **Blocked marker detection**: output contains `<loop-blocked>`, verify completionCheck.isBlocked=true\n - **Non-zero exit code**: spawn returns exit code 1, verify status='error'\n - **Process spawn error**: emit 'error' event, verify error result with message\n - **Stop running process**: call stop() while process running, verify SIGTERM sent\n4. Mock LoopCompletionService.parseOutput() to return appropriate CompletionCheckResult\n5. Verify duration timing is captured (use fake timers)\n6. Test that currentProcess is properly cleaned up after completion/error",
+ "status": "done",
+ "testStrategy": "Unit tests with mocked spawn: successful execution returning output, detecting completion markers in output, handling non-zero exit codes, handling process errors, verifying stop() kills process. Use vi.mock for child_process, EventEmitter mocks for process streams.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:16:59.635Z"
+ }
+ ],
+ "complexity": 6,
+ "recommendedSubtasks": 4,
+ "expansionPrompt": "Break down into: 1) Implement basic spawn mechanism with stdio handling following claude-executor.ts patterns, 2) Implement output capture and completion detection integration, 3) Implement process lifecycle management (stop, error handling, cleanup), 4) Write unit tests with mocked spawn for all scenarios (success, completion markers, errors, timeouts)",
+ "updatedAt": "2026-01-08T23:16:59.635Z"
+ },
+ {
+ "id": "8",
+ "title": "Implement Loop Service (Main Orchestrator)",
+ "description": "Create LoopService in tm-core as the main orchestrator that coordinates preset resolution, prompt generation, execution, progress tracking, and completion detection.",
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop.service.ts`:\n\n```typescript\nimport type { LoopConfig, LoopResult, LoopIteration } from '../types.js';\nimport { LoopPresetService } from './loop-preset.service.js';\nimport { LoopProgressService } from './loop-progress.service.js';\nimport { LoopCompletionService } from './loop-completion.service.js';\nimport { LoopPromptService } from './loop-prompt.service.js';\nimport { LoopExecutorService } from './loop-executor.service.js';\n\nexport interface LoopServiceOptions {\n projectRoot: string;\n}\n\nexport class LoopService {\n private readonly projectRoot: string;\n private readonly presetService: LoopPresetService;\n private readonly progressService: LoopProgressService;\n private readonly completionService: LoopCompletionService;\n private readonly promptService: LoopPromptService;\n private readonly executorService: LoopExecutorService;\n private isRunning = false;\n\n constructor(options: LoopServiceOptions) {\n this.projectRoot = options.projectRoot;\n this.presetService = new LoopPresetService();\n this.progressService = new LoopProgressService(options.projectRoot);\n this.completionService = new LoopCompletionService();\n this.promptService = new LoopPromptService(this.presetService);\n this.executorService = new LoopExecutorService(this.completionService);\n }\n\n async run(config: LoopConfig): Promise<LoopResult> {\n this.isRunning = true;\n const iterations: LoopIteration[] = [];\n let tasksCompleted = 0;\n\n // Initialize progress file\n await this.progressService.initializeProgressFile(config.progressFile, {\n preset: config.prompt,\n iterations: config.iterations,\n tag: config.tag\n });\n\n for (let i = 1; i <= config.iterations && this.isRunning; i++) {\n // Generate prompt for this iteration\n const prompt = await this.promptService.generatePrompt({\n config,\n iteration: i,\n projectRoot: this.projectRoot\n });\n\n // Execute iteration\n const result = await this.executorService.executeIteration(\n prompt,\n i,\n this.projectRoot\n );\n\n iterations.push(result.iteration);\n\n // Log progress\n await this.progressService.appendProgress(config.progressFile, {\n timestamp: new Date().toISOString(),\n iteration: i,\n taskId: result.iteration.taskId,\n note: result.iteration.message || 'Iteration completed'\n });\n\n // Check for completion\n if (result.completionCheck.isComplete) {\n return this.buildResult(iterations, tasksCompleted + 1, 'all_complete');\n }\n\n if (result.completionCheck.isBlocked) {\n return this.buildResult(iterations, tasksCompleted, 'blocked');\n }\n\n if (result.iteration.status === 'success') {\n tasksCompleted++;\n }\n\n // Sleep between iterations (except last)\n if (i < config.iterations && config.sleepSeconds > 0) {\n await this.sleep(config.sleepSeconds * 1000);\n }\n }\n\n return this.buildResult(iterations, tasksCompleted, 'max_iterations');\n }\n\n async stop(): Promise<void> {\n this.isRunning = false;\n await this.executorService.stop();\n }\n\n private buildResult(\n iterations: LoopIteration[],\n tasksCompleted: number,\n finalStatus: LoopResult['finalStatus']\n ): LoopResult {\n return {\n iterations,\n totalIterations: iterations.length,\n tasksCompleted,\n finalStatus\n };\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n```",
+ "testStrategy": "Integration tests with mocked executor: running 3 iterations successfully, stopping on completion marker, stopping on blocked marker, hitting max iterations, error handling during iteration. Test progress file gets updated after each iteration.",
+ "priority": "high",
+ "dependencies": [
+ "1",
+ "3",
+ "4",
+ "5",
+ "6",
+ "7"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Implement LoopService constructor with dependency injection for all sub-services",
+ "description": "Create the LoopService class with constructor that accepts LoopServiceOptions and instantiates all required sub-services (LoopPresetService, LoopProgressService, LoopCompletionService, LoopPromptService, LoopExecutorService).",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop.service.ts` with:\n\n1. Define `LoopServiceOptions` interface with `projectRoot: string`\n2. Create `LoopService` class with private readonly fields:\n - `projectRoot: string`\n - `presetService: LoopPresetService`\n - `progressService: LoopProgressService`\n - `completionService: LoopCompletionService`\n - `promptService: LoopPromptService`\n - `executorService: LoopExecutorService`\n - `isRunning: boolean = false`\n3. Constructor instantiates all services with appropriate parameters:\n - `LoopPresetService()` (no params)\n - `LoopProgressService(projectRoot)`\n - `LoopCompletionService()` (no params)\n - `LoopPromptService(presetService)` (DI)\n - `LoopExecutorService(completionService)` (DI)\n4. Export the class and interfaces from index.ts\n\nFollow the same DI pattern as `WorkflowService` in the workflow module.",
+ "status": "done",
+ "testStrategy": "Unit tests verifying: constructor creates all sub-service instances, services are accessible via private fields, options are stored correctly. Test with mock services to verify DI wiring.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:20:04.464Z"
+ },
+ {
+ "id": 2,
+ "title": "Implement main run() loop with iteration tracking and completion detection",
+ "description": "Implement the async run(config: LoopConfig): Promise<LoopResult> method that orchestrates the main loop execution, coordinating prompt generation, execution, progress tracking, and completion detection across iterations.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Implement the `run()` method:\n\n1. Set `this.isRunning = true` at start\n2. Initialize empty `iterations: LoopIteration[]` array and `tasksCompleted = 0` counter\n3. Call `progressService.initializeProgressFile()` with config data (preset, iterations, tag)\n4. Loop from `i = 1` to `config.iterations` while `this.isRunning`:\n a. Generate prompt via `promptService.generatePrompt({ config, iteration: i, projectRoot })`\n b. Execute iteration via `executorService.executeIteration(prompt, i, projectRoot)`\n c. Push `result.iteration` to iterations array\n d. Log progress via `progressService.appendProgress()` with timestamp, iteration, taskId, note\n e. Check completion: if `result.completionCheck.isComplete`, return early with `finalStatus: 'all_complete'`\n f. Check blocked: if `result.completionCheck.isBlocked`, return early with `finalStatus: 'blocked'`\n g. Increment `tasksCompleted` if iteration succeeded\n h. Sleep between iterations (except last) using `config.sleepSeconds`\n5. Return final `LoopResult` with `finalStatus: 'max_iterations'`\n\nUse `buildResult()` private helper to construct LoopResult consistently.",
+ "status": "done",
+ "testStrategy": "Integration tests with mocked executor covering: 3 successful iterations, early exit on completion marker, early exit on blocked marker, hitting max iterations, proper progress logging after each iteration. Verify iterations array and tasksCompleted counter are accurate.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:21:46.801Z"
+ },
+ {
+ "id": 3,
+ "title": "Implement stop() functionality and sleep mechanism",
+ "description": "Implement the async stop(): Promise<void> method to gracefully stop a running loop and the private sleep() helper method for delays between iterations.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Implement stop and sleep functionality:\n\n1. `stop()` method:\n - Set `this.isRunning = false` to signal loop to stop after current iteration\n - Call `await this.executorService.stop()` to abort any running execution\n - This allows graceful shutdown - current iteration completes, then loop exits\n\n2. `sleep()` private method:\n - Signature: `private sleep(ms: number): Promise<void>`\n - Return `new Promise(resolve => setTimeout(resolve, ms))`\n - Called with `config.sleepSeconds * 1000` between iterations\n\n3. Ensure `run()` loop checks `this.isRunning` at start of each iteration\n\nPattern matches the WorkflowOrchestrator's abort pattern where `isAborted` flag prevents further transitions.",
+ "status": "done",
+ "testStrategy": "Unit tests for: stop() sets isRunning to false and calls executorService.stop(), sleep() resolves after specified delay (use vi.useFakeTimers()), run() respects isRunning flag and exits gracefully when stop() called mid-loop.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:24:45.443Z"
+ },
+ {
+ "id": 4,
+ "title": "Write integration tests covering all termination scenarios",
+ "description": "Create comprehensive integration tests for LoopService that mock the executor service and verify all four termination scenarios: completion marker detected, blocked marker detected, max iterations reached, and error during execution.",
+ "dependencies": [
+ 1,
+ 2,
+ 3
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop.service.spec.ts` with integration tests:\n\n1. **Test: Successful 3-iteration run**\n - Mock executor to return success for 3 iterations\n - Verify iterations array has 3 entries\n - Verify tasksCompleted = 3\n - Verify finalStatus = 'max_iterations'\n\n2. **Test: Stop on completion marker**\n - Mock executor to return isComplete=true on iteration 2\n - Verify loop exits early with finalStatus = 'all_complete'\n - Verify only 2 iterations recorded\n\n3. **Test: Stop on blocked marker**\n - Mock executor to return isBlocked=true on iteration 2\n - Verify loop exits early with finalStatus = 'blocked'\n - Verify only 2 iterations recorded\n\n4. **Test: Error handling during iteration**\n - Mock executor to throw error on iteration 2\n - Verify error is caught and finalStatus = 'error'\n - Verify iteration marked as error in results\n\n5. **Test: Progress file updates**\n - Mock progressService.appendProgress\n - Verify called after each iteration with correct data\n\n6. **Test: Sleep between iterations**\n - Use vi.useFakeTimers()\n - Verify sleep called between iterations (not after last)\n\nFollow the testing patterns from `workflow-orchestrator.spec.ts` for mocking and assertions.",
+ "status": "done",
+ "testStrategy": "Self-testing subtask - these ARE the tests. Verify tests pass, cover all edge cases, and follow project conventions. Run with `npm run test -w @tm/core -- --grep 'LoopService'`.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:27:20.723Z"
+ }
+ ],
+ "complexity": 7,
+ "recommendedSubtasks": 4,
+ "expansionPrompt": "Break down into: 1) Implement service constructor with DI for all sub-services, 2) Implement main run() loop with iteration tracking and completion detection, 3) Implement stop() functionality and sleep mechanism, 4) Write integration tests with mocked executor covering all termination scenarios (completion marker, blocked marker, max iterations, error)",
+ "updatedAt": "2026-01-08T23:27:20.723Z"
+ },
+ {
+ "id": "9",
+ "title": "Create Loop Domain Facade",
+ "description": "Create LoopDomain in tm-core as the public API facade for loop operations, following the pattern of other domains (TasksDomain, WorkflowDomain).",
+ "details": "Create `packages/tm-core/src/modules/loop/loop-domain.ts`:\n\n```typescript\nimport type { ConfigManager } from '../config/managers/config-manager.js';\nimport type { TasksDomain } from '../tasks/tasks-domain.js';\nimport { LoopService, type LoopServiceOptions } from './services/loop.service.js';\nimport { LoopPresetService } from './services/loop-preset.service.js';\nimport type { LoopConfig, LoopResult, LoopPreset } from './types.js';\n\nexport class LoopDomain {\n private loopService: LoopService | null = null;\n private readonly projectRoot: string;\n private readonly presetService: LoopPresetService;\n private tasksDomain: TasksDomain | null = null;\n\n constructor(configManager: ConfigManager) {\n this.projectRoot = configManager.getProjectRoot();\n this.presetService = new LoopPresetService();\n }\n\n setTasksDomain(tasksDomain: TasksDomain): void {\n this.tasksDomain = tasksDomain;\n }\n\n // ========== Loop Operations ==========\n\n async run(config: Partial<LoopConfig>): Promise<LoopResult> {\n const fullConfig = this.buildConfig(config);\n this.loopService = new LoopService({ projectRoot: this.projectRoot });\n return this.loopService.run(fullConfig);\n }\n\n async stop(): Promise<void> {\n if (this.loopService) {\n await this.loopService.stop();\n this.loopService = null;\n }\n }\n\n // ========== Preset Operations ==========\n\n isPreset(prompt: string): prompt is LoopPreset {\n return this.presetService.isPreset(prompt);\n }\n\n async resolvePrompt(prompt: LoopPreset | string): Promise<string> {\n return this.presetService.resolvePrompt(prompt);\n }\n\n getAvailablePresets(): LoopPreset[] {\n return ['default', 'test-coverage', 'linting', 'duplication', 'entropy'];\n }\n\n // ========== Task Completion Check ==========\n\n async checkAllTasksComplete(options: { tag?: string }): Promise<boolean> {\n if (!this.tasksDomain) {\n throw new Error('TasksDomain not set');\n }\n const result = await this.tasksDomain.list({ tag: options.tag });\n return result.tasks.every(t => t.status === 'done' || t.status === 'cancelled');\n }\n\n private buildConfig(partial: Partial<LoopConfig>): LoopConfig {\n return {\n iterations: partial.iterations ?? 10,\n prompt: partial.prompt ?? 'default',\n progressFile: partial.progressFile ?? `${this.projectRoot}/.taskmaster/loop-progress.txt`,\n sleepSeconds: partial.sleepSeconds ?? 5,\n onComplete: partial.onComplete,\n tag: partial.tag,\n status: partial.status ?? 'pending'\n };\n }\n}\n```\n\nCreate `packages/tm-core/src/modules/loop/index.ts` exporting all public APIs.",
+ "testStrategy": "Unit tests for config building with defaults, preset detection, available presets list. Integration test for run/stop lifecycle. Test that TasksDomain integration works for completion checking.",
+ "priority": "medium",
+ "dependencies": [
+ "8"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Implement LoopDomain class with config building, preset operations, and task completion checking",
+ "description": "Create the LoopDomain facade class at packages/tm-core/src/modules/loop/loop-domain.ts that follows the WorkflowDomain pattern with ConfigManager injection, lazy-loaded LoopService, preset management, and TasksDomain integration for completion checking.",
+ "dependencies": [],
+ "details": "1. Create `packages/tm-core/src/modules/loop/loop-domain.ts` with:\n - Constructor accepting ConfigManager, storing projectRoot\n - Private fields: loopService (null initially), presetService, tasksDomain (null initially)\n - `setTasksDomain(tasksDomain: TasksDomain)` method for DI\n - `run(config: Partial<LoopConfig>)` that builds full config and creates LoopService\n - `stop()` that calls loopService.stop() and nulls the reference\n - `buildConfig(partial)` private method with defaults: iterations=10, prompt='default', sleepSeconds=5, status='pending', progressFile from projectRoot\n - `isPreset(prompt)` type guard delegating to presetService\n - `resolvePrompt(prompt)` delegating to presetService\n - `getAvailablePresets()` returning static array of preset names\n - `checkAllTasksComplete(options: {tag?: string})` that calls tasksDomain.list() and checks all statuses\n\n2. Follow WorkflowDomain pattern:\n - Lazy service instantiation (create in run(), null in stop())\n - Cross-domain integration via setter injection\n - Thin facade delegating to services\n\n3. Import types from './types.js' and services from './services/'",
+ "status": "done",
+ "testStrategy": "Unit tests in loop-domain.spec.ts: 1) Constructor stores projectRoot from ConfigManager, 2) buildConfig applies defaults correctly with various partial inputs, 3) isPreset/resolvePrompt delegate to PresetService, 4) getAvailablePresets returns correct preset list, 5) checkAllTasksComplete throws when TasksDomain not set, 6) checkAllTasksComplete returns true when all tasks done/cancelled and false otherwise (mock TasksDomain.list), 7) run() creates LoopService and delegates, 8) stop() nulls loopService",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:30:43.124Z"
+ },
+ {
+ "id": 2,
+ "title": "Create index.ts exports and write unit/integration tests for domain facade",
+ "description": "Create the module's public API barrel export file at packages/tm-core/src/modules/loop/index.ts and implement comprehensive unit and integration tests for the LoopDomain facade.",
+ "dependencies": [
+ 1
+ ],
+ "details": "1. Create `packages/tm-core/src/modules/loop/index.ts`:\n ```typescript\n // Domain facade - primary public API\n export { LoopDomain } from './loop-domain.js';\n \n // Types\n export type { LoopConfig, LoopResult, LoopIteration, LoopPreset } from './types.js';\n \n // Services (for advanced usage)\n export { LoopService } from './services/loop.service.js';\n export { LoopPresetService } from './services/loop-preset.service.js';\n ```\n\n2. Create `packages/tm-core/src/modules/loop/loop-domain.spec.ts` with unit tests:\n - Test constructor initializes correctly with mocked ConfigManager\n - Test buildConfig defaults (iterations=10, prompt='default', sleepSeconds=5)\n - Test buildConfig respects partial overrides\n - Test setTasksDomain stores reference\n - Test checkAllTasksComplete with all done/cancelled returns true\n - Test checkAllTasksComplete with pending task returns false\n - Test checkAllTasksComplete throws error when TasksDomain not set\n - Test isPreset/resolvePrompt delegation (mock PresetService)\n - Test run/stop lifecycle (mock LoopService)\n\n3. Create `packages/tm-core/tests/integration/loop/loop-domain.test.ts` for integration:\n - Test full run/stop lifecycle with real services\n - Test preset resolution loads actual preset content\n - Test TasksDomain integration for completion checking",
+ "status": "done",
+ "testStrategy": "Run `npm test -w @tm/core` targeting loop-domain.spec.ts. Unit tests should mock ConfigManager, TasksDomain, LoopService, and LoopPresetService to test facade logic in isolation. Integration tests use real services with filesystem mocks for preset loading. Verify exports compile correctly by importing from index.ts in test file.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:34:08.164Z"
+ }
+ ],
+ "complexity": 4,
+ "recommendedSubtasks": 2,
+ "expansionPrompt": "Break down into: 1) Implement LoopDomain class with config building, preset operations, and task completion checking, 2) Create index.ts exports and write unit/integration tests for domain facade",
+ "updatedAt": "2026-01-08T23:34:08.164Z"
+ },
+ {
+ "id": "10",
+ "title": "Integrate Loop Domain into TmCore",
+ "description": "Add LoopDomain to TmCore facade, wiring it up with TasksDomain for task completion checking.",
+ "details": "Modify `packages/tm-core/src/tm-core.ts`:\n\n1. Import LoopDomain:\n```typescript\nimport { LoopDomain } from './modules/loop/loop-domain.js';\n```\n\n2. Add private property and getter:\n```typescript\nprivate _loop!: LoopDomain;\n\nget loop(): LoopDomain {\n return this._loop;\n}\n```\n\n3. Initialize in `initialize()` method after TasksDomain:\n```typescript\n// Initialize loop domain\nthis._loop = new LoopDomain(this._configManager);\nthis._loop.setTasksDomain(this._tasks);\n```\n\n4. Update `packages/tm-core/src/index.ts` to export loop types:\n```typescript\n// Loop types\nexport type { LoopConfig, LoopResult, LoopIteration, LoopPreset } from './modules/loop/types.js';\nexport { LoopDomain } from './modules/loop/loop-domain.js';\n```",
+ "testStrategy": "Integration test creating TmCore and accessing loop domain. Verify loop.run() works with mocked executor. Verify loop.checkAllTasksComplete() integrates with tasks domain.",
+ "priority": "medium",
+ "dependencies": [
+ "9"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Import LoopDomain into TmCore",
+ "description": "Add the import statement for LoopDomain at the top of tm-core.ts alongside other domain imports.",
+ "dependencies": [],
+ "details": "Add `import { LoopDomain } from './modules/loop/loop-domain.js';` to the imports section in packages/tm-core/src/tm-core.ts, following the existing pattern of other domain imports like TasksDomain, WorkflowDomain, etc.",
+ "status": "done",
+ "testStrategy": "TypeScript compilation will verify the import is correct. The import should resolve after Task 9 creates the loop-domain.ts file.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:35:59.786Z"
+ },
+ {
+ "id": 2,
+ "title": "Add LoopDomain private property and getter",
+ "description": "Add the private _loop property and public getter to TmCore class following the existing pattern.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Add `private _loop!: LoopDomain;` to the private properties section (around line 89) and add the getter `get loop(): LoopDomain { return this._loop; }` to the public getters section (around line 108) in tm-core.ts.",
+ "status": "done",
+ "testStrategy": "TypeScript compilation will verify types. Unit test should verify tmCore.loop returns LoopDomain instance.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:37:17.884Z"
+ },
+ {
+ "id": 3,
+ "title": "Initialize LoopDomain in initialize() method",
+ "description": "Wire up LoopDomain initialization after TasksDomain in the initialize() method with TasksDomain injection.",
+ "dependencies": [
+ 2
+ ],
+ "details": "In the initialize() method (around line 178-179), add after IntegrationDomain initialization: `this._loop = new LoopDomain(this._configManager);` followed by `this._loop.setTasksDomain(this._tasks);` to enable task completion checking integration.",
+ "status": "done",
+ "testStrategy": "Integration test creating TmCore and verifying loop domain is accessible and properly initialized with TasksDomain reference.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:38:57.216Z"
+ },
+ {
+ "id": 4,
+ "title": "Export loop types from index.ts",
+ "description": "Add type exports for LoopConfig, LoopResult, LoopIteration, LoopPreset and LoopDomain class export.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Update packages/tm-core/src/index.ts to export loop types: `export type { LoopConfig, LoopResult, LoopIteration, LoopPreset } from './modules/loop/types.js';` and `export { LoopDomain } from './modules/loop/loop-domain.js';` in the appropriate sections.",
+ "status": "done",
+ "testStrategy": "Verify exports work by importing types from @tm/core in a test file: `import { LoopConfig, LoopDomain } from '@tm/core';`",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:41:30.962Z"
+ },
+ {
+ "id": 5,
+ "title": "Write integration test for loop domain access",
+ "description": "Create integration test verifying TmCore.loop is accessible and works with TasksDomain integration.",
+ "dependencies": [
+ 3,
+ 4
+ ],
+ "details": "Create test that: 1) Creates TmCore instance with createTmCore(), 2) Verifies tmCore.loop is defined and instance of LoopDomain, 3) Verifies loop.checkAllTasksComplete() can be called (integrates with TasksDomain). Test should be in packages/tm-core/tests/integration/ following existing patterns.",
+ "status": "done",
+ "testStrategy": "Run integration tests with `npm test -w @tm/core`. Verify loop domain methods are callable and return expected types.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:43:52.065Z"
+ }
+ ],
+ "complexity": 2,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a straightforward integration task following existing patterns.",
+ "updatedAt": "2026-01-08T23:43:52.065Z"
+ },
+ {
+ "id": "11",
+ "title": "Implement Loop CLI Command",
+ "description": "Create the loop command in apps/cli following the established command pattern with Commander.js, implementing all CLI options specified in the PRD.",
+ "details": "Create `apps/cli/src/commands/loop.command.ts`:\n\n```typescript\nimport { createTmCore, type LoopConfig, type LoopResult } from '@tm/core';\nimport chalk from 'chalk';\nimport { Command } from 'commander';\nimport { exec } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { displayCommandHeader } from '../utils/display-helpers.js';\nimport { displayError } from '../utils/error-handler.js';\nimport { getProjectRoot } from '../utils/project-root.js';\n\nconst execAsync = promisify(exec);\n\nexport interface LoopCommandOptions {\n iterations?: string;\n prompt?: string;\n progressFile?: string;\n sleep?: string;\n onComplete?: string;\n tag?: string;\n status?: string;\n project?: string;\n json?: boolean;\n}\n\nexport class LoopCommand extends Command {\n constructor() {\n super('loop');\n\n this.description('Run Claude Code in a loop, one task per iteration')\n .option('-n, --iterations <number>', 'Maximum iterations', '10')\n .option('-p, --prompt <preset|path>', 'Preset name or path to prompt file', 'default')\n .option('--progress-file <path>', 'Path to progress log')\n .option('--sleep <seconds>', 'Seconds between iterations', '5')\n .option('--on-complete <command>', 'Command to run when complete')\n .option('-t, --tag <tag>', 'Only work on tasks with this tag')\n .option('--status <status>', 'Only work on tasks with this status', 'pending')\n .option('--project <path>', 'Project root directory')\n .option('--json', 'Output results as JSON')\n .action(async (options: LoopCommandOptions) => {\n await this.executeLoop(options);\n });\n }\n\n private async executeLoop(options: LoopCommandOptions): Promise<void> {\n try {\n const projectRoot = getProjectRoot(options.project);\n const tmCore = await createTmCore({ projectPath: projectRoot });\n\n if (!options.json) {\n displayCommandHeader(tmCore, { tag: options.tag || 'master' });\n console.log(chalk.cyan('Starting Task Master Loop...'));\n console.log(chalk.dim(`Preset: ${options.prompt}`));\n console.log(chalk.dim(`Max iterations: ${options.iterations}`));\n console.log();\n }\n\n const config: Partial<LoopConfig> = {\n iterations: parseInt(options.iterations || '10', 10),\n prompt: options.prompt || 'default',\n progressFile: options.progressFile,\n sleepSeconds: parseInt(options.sleep || '5', 10),\n onComplete: options.onComplete,\n tag: options.tag,\n status: options.status\n };\n\n const result = await tmCore.loop.run(config);\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n this.displayResult(result);\n }\n\n // Run on-complete command if specified\n if (options.onComplete && result.finalStatus === 'all_complete') {\n console.log(chalk.dim(`\\nRunning on-complete command: ${options.onComplete}`));\n await execAsync(options.onComplete);\n }\n\n } catch (error) {\n displayError(error as Error);\n process.exit(1);\n }\n }\n\n private displayResult(result: LoopResult): void {\n console.log();\n console.log(chalk.bold('Loop Complete'));\n console.log(chalk.dim('─'.repeat(40)));\n console.log(`Total iterations: ${result.totalIterations}`);\n console.log(`Tasks completed: ${result.tasksCompleted}`);\n console.log(`Final status: ${this.formatStatus(result.finalStatus)}`);\n }\n\n private formatStatus(status: LoopResult['finalStatus']): string {\n switch (status) {\n case 'all_complete': return chalk.green('All tasks complete');\n case 'max_iterations': return chalk.yellow('Max iterations reached');\n case 'blocked': return chalk.red('Blocked');\n case 'error': return chalk.red('Error');\n }\n }\n\n static register(program: Command): LoopCommand {\n const loopCommand = new LoopCommand();\n program.addCommand(loopCommand);\n return loopCommand;\n }\n}\n```",
+ "testStrategy": "Unit tests for option parsing and validation. Integration tests with mocked TmCore for: running with defaults, running with custom preset, running with tag filter, JSON output format, on-complete command execution.",
+ "priority": "high",
+ "dependencies": [
+ "10"
+ ],
+ "status": "in-progress",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Implement LoopCommand class with Commander.js options and static registration",
+ "description": "Create the LoopCommand class extending Commander's Command, configure all CLI options (-n, -p, --progress-file, --sleep, --on-complete, -t, --status, --project, --json), and implement the static register() method following the established pattern from NextCommand.",
+ "dependencies": [],
+ "details": "Create `apps/cli/src/commands/loop.command.ts` with:\n\n1. **LoopCommandOptions interface** defining all typed options:\n - iterations?: string (parsed to number later)\n - prompt?: string (preset name or file path)\n - progressFile?: string\n - sleep?: string (parsed to number)\n - onComplete?: string\n - tag?: string\n - status?: string\n - project?: string\n - json?: boolean\n\n2. **LoopCommand class** extending Command:\n - Constructor configures description and all options via builder pattern\n - Use `.option()` for each flag with proper defaults:\n - `-n, --iterations <number>` default '10'\n - `-p, --prompt <preset|path>` default 'default'\n - `--progress-file <path>` no default (uses core default)\n - `--sleep <seconds>` default '5'\n - `--on-complete <command>` optional\n - `-t, --tag <tag>` optional filter\n - `--status <status>` default 'pending'\n - `--project <path>` for project root override\n - `--json` for JSON output format\n - Action handler calls executeLoop(options)\n\n3. **Static register() method** following pattern:\n ```typescript\n static register(program: Command): LoopCommand {\n const loopCommand = new LoopCommand();\n program.addCommand(loopCommand);\n return loopCommand;\n }\n ```\n\n4. **Register in CommandRegistry** (`apps/cli/src/command-registry.ts`):\n - Add import for LoopCommand\n - Add entry to commands array with name: 'loop', category: 'workflow'\n\n5. **Export from index** (`apps/cli/src/index.ts`) if needed",
+ "status": "done",
+ "testStrategy": "Unit tests for option parsing: verify all options have correct defaults, verify short flags work (-n, -p, -t), verify option types are correctly defined. Test that LoopCommand.register() adds command to program. Test command is discoverable via `program.commands.find(c => c.name() === 'loop')`.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:48:15.038Z"
+ },
+ {
+ "id": 2,
+ "title": "Implement executeLoop() method with display logic and on-complete command execution",
+ "description": "Implement the main executeLoop() private method that initializes TmCore, runs the loop via tmCore.loop.run(), handles both JSON and text output formatting, and executes the on-complete command when all tasks complete.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Implement executeLoop() in LoopCommand with:\n\n1. **Project root resolution**:\n ```typescript\n const projectRoot = getProjectRoot(options.project);\n const tmCore = await createTmCore({ projectPath: projectRoot });\n ```\n\n2. **Display header for non-JSON output**:\n ```typescript\n if (!options.json) {\n displayCommandHeader(tmCore, { tag: options.tag || 'master' });\n console.log(chalk.cyan('Starting Task Master Loop...'));\n console.log(chalk.dim(`Preset: ${options.prompt}`));\n console.log(chalk.dim(`Max iterations: ${options.iterations}`));\n }\n ```\n\n3. **Build LoopConfig from options**:\n ```typescript\n const config: Partial<LoopConfig> = {\n iterations: parseInt(options.iterations || '10', 10),\n prompt: options.prompt || 'default',\n progressFile: options.progressFile,\n sleepSeconds: parseInt(options.sleep || '5', 10),\n onComplete: options.onComplete,\n tag: options.tag,\n status: options.status\n };\n ```\n\n4. **Execute loop via TmCore**:\n ```typescript\n const result = await tmCore.loop.run(config);\n ```\n\n5. **Output handling**:\n - JSON mode: `console.log(JSON.stringify(result, null, 2))`\n - Text mode: call `displayResult(result)` helper method\n\n6. **On-complete command execution** (when specified and all_complete):\n ```typescript\n if (options.onComplete && result.finalStatus === 'all_complete') {\n console.log(chalk.dim(`\\nRunning on-complete command: ${options.onComplete}`));\n await execAsync(options.onComplete);\n }\n ```\n\n7. **Error handling** with try-catch:\n ```typescript\n } catch (error) {\n displayError(error as Error);\n process.exit(1);\n }\n ```\n\n8. **Display helper methods**:\n - `displayResult(result: LoopResult)` - shows completion summary\n - `formatStatus(status)` - color-coded status strings",
+ "status": "done",
+ "testStrategy": "Integration tests with mocked TmCore: 1) Test running with defaults returns expected output format, 2) Test --json flag outputs valid JSON with all LoopResult fields, 3) Test on-complete command is called only when finalStatus is 'all_complete', 4) Test on-complete is NOT called for 'max_iterations', 'blocked', or 'error' statuses, 5) Test error handling shows displayError and exits with code 1.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T23:51:39.149Z"
+ },
+ {
+ "id": 3,
+ "title": "Write unit and integration tests for LoopCommand",
+ "description": "Create comprehensive test suite covering option parsing, validation, display formatting, and integration with mocked TmCore for various loop scenarios including tag filtering and JSON output.",
+ "dependencies": [
+ 1,
+ 2
+ ],
+ "details": "Create test files following project conventions:\n\n**Unit tests** (`apps/cli/src/commands/loop.command.spec.ts`):\n\n1. **Option parsing tests**:\n - Default values: iterations=10, prompt='default', sleep=5, status='pending'\n - Custom values parsed correctly from string to number\n - Short flags work (-n 5, -p custom, -t mytag)\n - Boolean --json flag detection\n\n2. **Validation tests**:\n - Invalid iterations (negative, zero, non-numeric) handled\n - Invalid sleep value handled\n - Valid status values accepted\n\n3. **Display formatting tests**:\n - `formatStatus('all_complete')` returns green text\n - `formatStatus('max_iterations')` returns yellow text\n - `formatStatus('blocked')` returns red text\n - `formatStatus('error')` returns red text\n - `displayResult()` shows correct summary format\n\n**Integration tests** (`apps/cli/tests/integration/commands/loop.spec.ts`):\n\n1. **Mock TmCore** to return controlled LoopResult:\n ```typescript\n vi.mock('@tm/core', () => ({\n createTmCore: vi.fn().mockResolvedValue({\n loop: { run: vi.fn() },\n auth: { getStorageDisplayInfo: vi.fn() }\n })\n }));\n ```\n\n2. **Test scenarios**:\n - Running with defaults returns success\n - Running with --tag filters correctly\n - JSON output contains all required fields\n - On-complete command executed via execAsync mock\n - Error from TmCore calls displayError\n\n3. **Test execAsync mock** for on-complete:\n ```typescript\n vi.mock('node:util', () => ({\n promisify: () => vi.fn().mockResolvedValue({ stdout: '', stderr: '' })\n }));\n ```",
+ "status": "pending",
+ "testStrategy": "Run tests with `npm run test -w @tm/cli -- loop.command`. Verify: all unit tests pass for option parsing and display formatting, integration tests cover the happy path and error scenarios, mocks are properly reset between tests, test coverage includes all branches in executeLoop() and display methods.",
+ "parentId": "undefined"
+ }
+ ],
+ "complexity": 5,
+ "recommendedSubtasks": 3,
+ "expansionPrompt": "Break down into: 1) Implement LoopCommand class extending Commander.Command with all options, 2) Implement executeLoop() with display logic and on-complete command execution, 3) Write unit tests for option parsing/validation and integration tests with mocked TmCore",
+ "updatedAt": "2026-01-08T23:51:39.149Z"
+ },
+ {
+ "id": "12",
+ "title": "Register Loop Command in CLI",
+ "description": "Register the LoopCommand in the command registry and update exports in apps/cli.",
+ "details": "1. Update `apps/cli/src/command-registry.ts`:\n\n```typescript\n// Add import\nimport { LoopCommand } from './commands/loop.command.js';\n\n// Add to commands array in CommandRegistry class\n{\n name: 'loop',\n description: 'Run Claude Code in a loop, one task per iteration',\n commandClass: LoopCommand as any,\n category: 'development'\n}\n```\n\n2. Update `apps/cli/src/index.ts`:\n\n```typescript\n// Add export\nexport { LoopCommand } from './commands/loop.command.js';\n```\n\n3. Verify the command is registered by running:\n```bash\ntask-master --help\n```\n\nThe `loop` command should appear under Development category.",
+ "testStrategy": "Manual test: run `task-master --help` and verify loop command appears. Run `task-master loop --help` and verify all options are documented. Integration test that command registry includes loop command.",
+ "priority": "medium",
+ "dependencies": [
+ "11"
+ ],
+ "status": "pending",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Add LoopCommand import to command-registry.ts",
+ "description": "Import the LoopCommand class from the loop command module at the top of command-registry.ts alongside other command imports.",
+ "dependencies": [],
+ "details": "Add the import statement after line 22 (after StartCommand import): `import { LoopCommand } from './commands/loop.command.js';` This follows the existing import pattern used for all other commands.",
+ "status": "pending",
+ "testStrategy": "TypeScript compilation should succeed without import errors.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 2,
+ "title": "Register LoopCommand in commands array",
+ "description": "Add the loop command entry to the CommandRegistry.commands array with appropriate metadata.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Add the command entry to the commands array in the 'development' category section (after autopilot command around line 91): `{ name: 'loop', description: 'Run Claude Code in a loop, one task per iteration', commandClass: LoopCommand as any, category: 'development' }`",
+ "status": "pending",
+ "testStrategy": "Verify CommandRegistry.hasCommand('loop') returns true.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 3,
+ "title": "Add LoopCommand export to index.ts",
+ "description": "Export the LoopCommand class from the main CLI package entry point for external consumers.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Add the export statement in the Commands section of apps/cli/src/index.ts: `export { LoopCommand } from './commands/loop.command.js';` This should be placed alongside other command exports (around line 16).",
+ "status": "pending",
+ "testStrategy": "Verify the export is accessible via `import { LoopCommand } from '@tm/cli'`.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 4,
+ "title": "Verify loop command appears in CLI help",
+ "description": "Run task-master --help to verify the loop command is properly registered and displayed under the Development category.",
+ "dependencies": [
+ 2
+ ],
+ "details": "Execute `task-master --help` and verify: 1) 'loop' command appears in the output, 2) It's listed under the 'Development' category section alongside 'autopilot', 3) Description shows 'Run Claude Code in a loop, one task per iteration'.",
+ "status": "pending",
+ "testStrategy": "Manual verification: run `task-master --help` and confirm loop command is listed in Development category.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 5,
+ "title": "Verify loop command help output",
+ "description": "Run task-master loop --help to verify all command options are properly documented and accessible.",
+ "dependencies": [
+ 4
+ ],
+ "details": "Execute `task-master loop --help` and verify: 1) Command runs without errors, 2) All CLI options from the LoopCommand implementation are displayed (e.g., -n/--iterations, --prompt, --tag, etc.), 3) Option descriptions are clear and accurate.",
+ "status": "pending",
+ "testStrategy": "Manual verification: run `task-master loop --help` and confirm all options appear with correct descriptions.",
+ "parentId": "undefined"
+ }
+ ],
+ "complexity": 1,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a trivial registration task."
+ },
+ {
+ "id": "13",
+ "title": "Add Loop MCP Tool",
+ "description": "Create MCP tool for loop operations in apps/mcp, following the pattern of existing tools like autopilot.",
+ "details": "Create `apps/mcp/src/tools/loop/index.ts`:\n\n```typescript\nimport { createTmCore, type LoopConfig } from '@tm/core';\nimport { z } from 'zod';\nimport type { FastMCPTool } from '../../shared/types.js';\nimport { resolveProjectRoot } from '../../shared/utils.js';\n\nconst loopStartSchema = z.object({\n projectRoot: z.string().optional(),\n iterations: z.number().optional().default(10),\n prompt: z.string().optional().default('default'),\n progressFile: z.string().optional(),\n sleepSeconds: z.number().optional().default(5),\n tag: z.string().optional(),\n status: z.string().optional().default('pending')\n});\n\nexport const loopStartTool: FastMCPTool = {\n name: 'loop_start',\n description: 'Start a Task Master loop to work through tasks automatically',\n schema: loopStartSchema,\n async execute(args, log) {\n const projectRoot = resolveProjectRoot(args.projectRoot);\n const tmCore = await createTmCore({ projectPath: projectRoot });\n\n log('info', `Starting loop with preset: ${args.prompt}`);\n\n const config: Partial<LoopConfig> = {\n iterations: args.iterations,\n prompt: args.prompt,\n progressFile: args.progressFile,\n sleepSeconds: args.sleepSeconds,\n tag: args.tag,\n status: args.status\n };\n\n const result = await tmCore.loop.run(config);\n\n return {\n success: true,\n result: {\n totalIterations: result.totalIterations,\n tasksCompleted: result.tasksCompleted,\n finalStatus: result.finalStatus,\n iterations: result.iterations\n }\n };\n }\n};\n\nexport const loopPresetsTool: FastMCPTool = {\n name: 'loop_presets',\n description: 'List available loop presets',\n schema: z.object({}),\n async execute(_, log) {\n return {\n success: true,\n presets: ['default', 'test-coverage', 'linting', 'duplication', 'entropy']\n };\n }\n};\n\nexport const loopTools = [loopStartTool, loopPresetsTool];\n```\n\nRegister tools in `apps/mcp/src/index.ts` tool registration.",
+ "testStrategy": "Unit tests for MCP tool execution with mocked TmCore. Verify schema validation rejects invalid inputs. Test that loop_presets returns correct preset list.",
+ "priority": "medium",
+ "dependencies": [
+ "10"
+ ],
+ "status": "pending",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Implement loop_start and loop_presets MCP tools with Zod schemas",
+ "description": "Create the loop MCP tools following the established pattern in apps/mcp/src/tools/, using withToolContext wrapper, Zod schemas, and handleApiResult for response formatting.",
+ "dependencies": [],
+ "details": "Create `apps/mcp/src/tools/loop/` directory with:\n\n1. `start.tool.ts` - loop_start tool:\n - Import `z` from 'zod', `FastMCP` from 'fastmcp', `ToolContext` from shared types, `withToolContext` and `handleApiResult` from shared utils\n - Define `LoopStartSchema` with: `projectRoot: z.string().describe('Absolute path to project root')`, `iterations: z.number().optional().default(10)`, `prompt: z.string().optional().default('default')`, `progressFile: z.string().optional()`, `sleepSeconds: z.number().optional().default(5)`, `tag: z.string().optional()`, `status: z.string().optional().default('pending')`\n - Use `withToolContext('loop-start', async (args, { log, tmCore }) => {...})` wrapper pattern\n - Call `tmCore.loop.run(config)` and return result via `handleApiResult`\n - Add annotations: `{ title: 'Start Loop', destructiveHint: true }`\n\n2. `presets.tool.ts` - loop_presets tool:\n - Simple read-only tool with `readOnlyHint: true`\n - Return hardcoded list: `['default', 'test-coverage', 'linting', 'duplication', 'entropy']`\n - Call `tmCore.loop.getAvailablePresets()` if available, or return static list\n\n3. `index.ts` - Export `registerLoopStartTool` and `registerLoopPresetsTool` functions\n\nFollow exact patterns from `apps/mcp/src/tools/autopilot/start.tool.ts` and `apps/mcp/src/tools/tasks/get-tasks.tool.ts` for structure and error handling.",
+ "status": "pending",
+ "testStrategy": null,
+ "parentId": "undefined"
+ },
+ {
+ "id": 2,
+ "title": "Register loop tools in MCP server and write unit tests",
+ "description": "Add loop tool exports to the MCP package index and create integration tests following the existing test patterns with mocked TmCore responses.",
+ "dependencies": [
+ 1
+ ],
+ "details": "1. **Register tools in MCP exports:**\n - Add `export * from './tools/loop/index.js';` to `apps/mcp/src/index.ts`\n - Ensure the loop tools are included in the tool tier configuration if applicable (check TASK_MASTER_TOOLS env var handling)\n\n2. **Create integration tests** at `apps/mcp/tests/integration/tools/loop.tool.test.ts`:\n - Follow pattern from `apps/mcp/tests/integration/tools/get-tasks.tool.test.ts`\n - Use `callMCPTool` helper to invoke tools via MCP inspector CLI\n - Test `loop_start` with valid config returns success response structure\n - Test `loop_start` with invalid projectRoot returns error\n - Test `loop_presets` returns array of preset names\n - Test schema validation rejects invalid inputs (e.g., negative iterations)\n - Mock or set up test project with tasks.json for integration tests\n\n3. **Create unit tests** at `apps/mcp/src/tools/loop/start.tool.spec.ts`:\n - Mock `createTmCore` to return mock `tmCore` with `loop.run()` method\n - Verify correct parameters passed to `tmCore.loop.run()`\n - Verify response format matches MCPResponse type\n - Test error handling when `tmCore.loop.run()` throws\n\nRun tests with `npm test -w @tm/mcp` to verify all pass.",
+ "status": "pending",
+ "testStrategy": "Integration tests using MCP inspector CLI to verify tool invocation. Unit tests with vi.mock for TmCore to verify parameter passing and response formatting. Test both success and error paths. Verify Zod schema rejects invalid inputs like negative iterations or missing required fields.",
+ "parentId": "undefined"
+ }
+ ],
+ "complexity": 4,
+ "recommendedSubtasks": 2,
+ "expansionPrompt": "Break down into: 1) Implement loop_start and loop_presets tools following autopilot tool patterns with Zod schemas, 2) Register tools in MCP server and write unit tests with mocked TmCore"
+ },
+ {
+ "id": "14",
+ "title": "Write Unit Tests for Loop Module",
+ "description": "Create comprehensive unit test suite for all loop module services in tm-core.",
+ "details": "Create test files in `packages/tm-core/src/modules/loop/`:\n\n1. `services/loop-preset.service.spec.ts`:\n - Test `isPreset()` with valid presets, invalid names, file paths\n - Test `isFilePath()` with various path patterns\n - Test `resolvePrompt()` loading built-in presets\n - Test custom file loading with mock fs\n\n2. `services/loop-progress.service.spec.ts`:\n - Test progress file initialization with correct header\n - Test appending entries preserves format\n - Test reading non-existent file returns empty string\n - Test file existence checks\n\n3. `services/loop-completion.service.spec.ts`:\n - Test parsing `<loop-complete>` with various reasons\n - Test parsing `<loop-blocked>` with various reasons\n - Test output with no markers\n - Test output with multiple markers (first wins)\n - Test case insensitivity\n\n4. `services/loop-prompt.service.spec.ts`:\n - Test prompt generation includes iteration number\n - Test prompt includes file references\n - Test tag inclusion when specified\n\n5. `services/loop.service.spec.ts`:\n - Test full loop execution with mocked executor\n - Test early termination on complete marker\n - Test early termination on blocked marker\n - Test max iterations reached\n - Test progress file updated each iteration\n\nFollow patterns from existing tests in `packages/tm-core/src/modules/workflow/managers/workflow-state-manager.spec.ts`.",
+ "testStrategy": "Run `npm test -w @tm/core` to execute all tests. Aim for >80% coverage on loop module. Use mocks for filesystem operations and external processes.",
+ "priority": "medium",
+ "dependencies": [
+ "8"
+ ],
+ "status": "pending",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Write tests for loop-preset.service.spec.ts",
+ "description": "Create comprehensive unit tests for the LoopPresetService covering preset detection, file path detection, prompt resolution for built-in presets, and custom file loading with mocked filesystem.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-preset.service.spec.ts` with tests for:\n\n1. `isPreset()` tests:\n - Valid presets: 'default', 'test-coverage', 'linting', 'duplication', 'entropy'\n - Invalid names: 'invalid', 'foo', empty string, null/undefined\n - File paths should return false: './prompt.md', '/path/to/file.txt', 'prompts/custom.md'\n\n2. `isFilePath()` tests:\n - Relative paths: './file.md', '../prompt.txt'\n - Absolute paths: '/path/to/prompt.md'\n - Paths with extensions: 'prompt.md', 'file.txt'\n - Windows-style paths: 'C:\\path\\file.md'\n - Should return false for preset names\n\n3. `resolvePrompt()` tests:\n - Each built-in preset returns expected prompt content\n - Verify prompt contains required sections (Files Available, Process, Completion Criteria)\n - Custom file loading with vi.mock('node:fs/promises')\n - Non-existent file throws appropriate error\n\nFollow patterns from `config-loader.service.spec.ts` for fs mocking.",
+ "status": "pending",
+ "testStrategy": "Run `npm test -w @tm/core -- loop-preset` to verify tests pass. Check that all edge cases for preset detection and file path detection are covered. Verify mock filesystem operations work correctly for custom file loading.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 2,
+ "title": "Write tests for loop-progress.service.spec.ts",
+ "description": "Create unit tests for the LoopProgressService covering progress file initialization with headers, entry appending with format preservation, reading non-existent files, and file existence checks.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-progress.service.spec.ts` with tests for:\n\n1. Progress file initialization:\n - Creates file with correct header (iteration info, timestamp)\n - Uses correct default path `.taskmaster/loop-progress.txt`\n - Creates parent directories if needed\n\n2. `appendEntry()` tests:\n - Appends new entry with timestamp\n - Preserves existing content\n - Handles special characters in notes\n - Maintains consistent format between entries\n\n3. `readProgress()` tests:\n - Returns empty string for non-existent file\n - Returns full content of existing file\n - Handles empty file gracefully\n\n4. `fileExists()` tests:\n - Returns true when file exists\n - Returns false when file doesn't exist\n\nMock `node:fs/promises` methods (readFile, writeFile, appendFile, access, mkdir). Follow the beforeEach/afterEach pattern with vi.clearAllMocks() and vi.restoreAllMocks().",
+ "status": "pending",
+ "testStrategy": "Run `npm test -w @tm/core -- loop-progress` to verify tests pass. Ensure all filesystem operations are properly mocked and edge cases like non-existent directories are handled.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 3,
+ "title": "Write tests for loop-completion.service.spec.ts",
+ "description": "Create unit tests for the LoopCompletionService covering parsing of <loop-complete> and <loop-blocked> markers from agent output, handling output without markers, and edge cases like multiple markers.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-completion.service.spec.ts` with tests for:\n\n1. `parseLoopComplete()` tests:\n - Output with `<loop-complete>ALL_TASKS_DONE</loop-complete>` returns { complete: true, reason: 'ALL_TASKS_DONE' }\n - Various reasons: COVERAGE_TARGET, ZERO_ERRORS, LOW_DUPLICATION, LOW_ENTROPY\n - Marker at start, middle, end of output\n - Marker with surrounding whitespace\n\n2. `parseLoopBlocked()` tests:\n - Output with `<loop-blocked>DEPENDENCY_MISSING</loop-blocked>` returns { blocked: true, reason: 'DEPENDENCY_MISSING' }\n - Various block reasons\n - Marker at different positions\n\n3. `parseOutput()` (combined) tests:\n - Output with no markers returns { complete: false, blocked: false }\n - Output with multiple complete markers - first one wins\n - Output with both complete and blocked - complete takes precedence\n - Case insensitivity: `<LOOP-COMPLETE>` should work\n - Nested or malformed markers handled gracefully\n\n4. Edge cases:\n - Empty output string\n - Very long output strings\n - Special characters in reason text",
+ "status": "pending",
+ "testStrategy": "Run `npm test -w @tm/core -- loop-completion` to verify tests pass. Focus on regex edge cases and ensure the parsing logic is robust against malformed input.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 4,
+ "title": "Write tests for loop-prompt.service.spec.ts",
+ "description": "Create unit tests for the LoopPromptService covering prompt generation with iteration numbers, file references inclusion, tag inclusion, and proper template interpolation.",
+ "dependencies": [],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop-prompt.service.spec.ts` with tests for:\n\n1. `generatePrompt()` iteration number tests:\n - Prompt includes current iteration number (e.g., 'Iteration 5 of 10')\n - First iteration (1 of N)\n - Last iteration (N of N)\n\n2. File reference tests:\n - Prompt includes `@.taskmaster/tasks/tasks.json` reference\n - Prompt includes progress file reference with correct path\n - Custom progress file path is included correctly\n\n3. Tag inclusion tests:\n - When tag specified, prompt includes tag filter instruction\n - When no tag, no tag filter in prompt\n - Multiple tags handling (if supported)\n\n4. Template interpolation tests:\n - Base prompt content from preset is included\n - Context variables are interpolated correctly\n - No unresolved template placeholders in output\n\n5. Edge cases:\n - Empty base prompt\n - Very long prompts\n - Special characters in tag names\n\nMock the LoopPresetService for resolving preset content.",
+ "status": "pending",
+ "testStrategy": "Run `npm test -w @tm/core -- loop-prompt` to verify tests pass. Ensure generated prompts contain all required elements and template interpolation works correctly.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 5,
+ "title": "Write tests for loop.service.spec.ts (main orchestrator)",
+ "description": "Create unit tests for the main LoopService orchestrator covering full loop execution with mocked executor, early termination on complete/blocked markers, max iterations reached, and progress file updates per iteration.",
+ "dependencies": [
+ 1,
+ 2,
+ 3,
+ 4
+ ],
+ "details": "Create `packages/tm-core/src/modules/loop/services/loop.service.spec.ts` with tests for:\n\n1. Full loop execution tests:\n - Mock executor (Claude Code subprocess) returns success\n - Verify each iteration calls sub-services in correct order\n - Verify sleep between iterations is called\n - Verify final LoopResult has correct structure\n\n2. Early termination - complete marker:\n - Executor output contains `<loop-complete>ALL_TASKS_DONE</loop-complete>`\n - Loop stops immediately\n - Returns { finalStatus: 'all_complete', tasksCompleted: N }\n - onComplete callback is invoked if provided\n\n3. Early termination - blocked marker:\n - Executor output contains `<loop-blocked>REASON</loop-blocked>`\n - Loop stops immediately\n - Returns { finalStatus: 'blocked', iterations: [...] }\n - Last iteration marked as blocked with reason\n\n4. Max iterations reached:\n - Loop runs exactly N iterations when no termination\n - Returns { finalStatus: 'max_iterations', totalIterations: N }\n\n5. Progress file updates:\n - LoopProgressService.appendEntry called after each iteration\n - Progress includes iteration result summary\n\n6. Error handling:\n - Executor throws error - iteration marked as 'error'\n - Continues to next iteration or stops based on config\n\nMock all sub-services: LoopPresetService, LoopProgressService, LoopCompletionService, LoopPromptService, and the external executor (child_process or similar).",
+ "status": "pending",
+ "testStrategy": "Run `npm test -w @tm/core -- loop.service.spec` to verify tests pass. Ensure all sub-service mocks are properly configured and the orchestration logic is thoroughly tested. Aim for >80% coverage on the main LoopService.",
+ "parentId": "undefined"
+ }
+ ],
+ "complexity": 5,
+ "recommendedSubtasks": 5,
+ "expansionPrompt": "Break down into: 1) Write tests for loop-preset.service.spec.ts, 2) Write tests for loop-progress.service.spec.ts, 3) Write tests for loop-completion.service.spec.ts, 4) Write tests for loop-prompt.service.spec.ts, 5) Write tests for loop.service.spec.ts with mocked sub-services"
+ },
+ {
+ "id": "15",
+ "title": "Write Integration Tests for Loop CLI",
+ "description": "Create integration tests for the loop CLI command in apps/cli.",
+ "details": "Create `apps/cli/tests/integration/commands/loop.command.test.ts`:\n\n```typescript\nimport { execSync } from 'node:child_process';\nimport { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { describe, it, expect, beforeEach, afterEach } from 'vitest';\n\ndescribe('loop command integration', () => {\n const testDir = join(__dirname, 'test-project');\n const tasksDir = join(testDir, '.taskmaster', 'tasks');\n\n beforeEach(() => {\n // Create test project structure\n mkdirSync(tasksDir, { recursive: true });\n writeFileSync(\n join(tasksDir, 'tasks.json'),\n JSON.stringify({ tasks: [], tags: { master: {} } })\n );\n });\n\n afterEach(() => {\n if (existsSync(testDir)) {\n rmSync(testDir, { recursive: true });\n }\n });\n\n it('shows help with --help', () => {\n const output = execSync('task-master loop --help', { encoding: 'utf-8' });\n expect(output).toContain('--iterations');\n expect(output).toContain('--prompt');\n expect(output).toContain('--tag');\n });\n\n it('lists available presets', () => {\n // This could be a separate command or option\n });\n\n // Note: Full loop execution tests require mocking Claude Code\n // or running in a CI environment with Claude available\n});\n```\n\nFollow patterns from existing integration tests in `apps/cli/tests/integration/commands/`.",
+ "testStrategy": "Run integration tests with `npm test -w @tm/cli`. Mock Claude Code execution for CI. Manual testing with real Claude Code for full E2E verification.",
+ "priority": "medium",
+ "dependencies": [
+ "12"
+ ],
+ "status": "pending",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Set up loop command integration test infrastructure",
+ "description": "Create the test file with proper setup following existing integration test patterns in apps/cli/tests/integration/commands/",
+ "dependencies": [],
+ "details": "Create `apps/cli/tests/integration/commands/loop.command.test.ts` with:\n\n1. Standard imports: `execSync` from node:child_process, `fs`, `os`, `path`, vitest functions, and `getCliBinPath` helper\n2. Capture `initialCwd` at module load time for safe directory restoration\n3. `beforeEach` hook that:\n - Creates temp directory with `fs.mkdtempSync(path.join(os.tmpdir(), 'tm-loop-test-'))`\n - Changes to temp directory with `process.chdir(testDir)`\n - Sets `TASKMASTER_SKIP_AUTO_UPDATE=1` environment variable\n - Gets CLI binary path with `getCliBinPath()`\n - Initializes taskmaster with `node \"${binPath}\" init --yes`\n - Creates tasks.json path reference\n4. `afterEach` hook that:\n - Restores working directory to `initialCwd` (with fallback to `os.homedir()` on failure)\n - Cleans up temp directory with `fs.rmSync(testDir, { recursive: true, force: true })`\n - Deletes the environment variable\n5. Helper functions:\n - `writeTasks(tasksData)` to write task data to tasks.json\n - `runLoop(args)` to execute loop command and return `{ output, exitCode }`, handling both success and error cases by capturing stdout/stderr",
+ "status": "pending",
+ "testStrategy": "Verify test infrastructure works by running a simple test that calls `runLoop('--help')` and confirms it returns a valid response with exit code 0.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 2,
+ "title": "Write integration tests for loop command scenarios",
+ "description": "Add test cases for help output, error handling, and basic validation scenarios that don't require Claude Code execution",
+ "dependencies": [
+ 1
+ ],
+ "details": "Add the following test cases to the loop command test file:\n\n1. **Help flag tests:**\n - `it('should show help with --help')` - verify output contains `--iterations`, `--prompt`, `--tag`, `--sleep`, `--progress-file` options\n - `it('should show help with -h shorthand')` - verify same output with short flag\n\n2. **Input validation tests:**\n - `it('should reject invalid iteration count')` - test `--iterations -1` returns non-zero exit code\n - `it('should reject non-numeric iterations')` - test `--iterations abc` returns error\n - `it('should reject invalid prompt file path')` - test with non-existent file path\n\n3. **Project initialization tests:**\n - `it('should fail gracefully when no taskmaster project exists')` - run without init, expect error about missing project\n\n4. **Preset-related tests (if applicable):**\n - `it('should list available presets with --list-presets')` - verify preset names appear in output\n - `it('should accept valid preset name')` - test `--prompt default` is recognized\n\n5. **Tag filtering tests:**\n - `it('should accept --tag flag')` - verify command accepts tag parameter without error\n - `it('should fail with non-existent tag')` - verify error when tag doesn't exist in tasks.json\n\n**Note:** Full loop execution tests that invoke Claude Code should be marked with `.skip` or placed in a separate E2E test file, with a comment explaining they require Claude Code to be available. Example:\n```typescript\nit.skip('should execute loop iterations (requires Claude Code)', () => {\n // This test requires Claude Code to be installed and available\n});\n```",
+ "status": "pending",
+ "testStrategy": "Run `npm test -w @tm/cli -- --grep 'loop command'` to execute only loop command tests. Verify all tests pass without requiring external Claude Code dependency. Tests should complete quickly since they only test CLI argument parsing and validation.",
+ "parentId": "undefined"
+ }
+ ],
+ "complexity": 4,
+ "recommendedSubtasks": 2,
+ "expansionPrompt": "Break down into: 1) Set up test infrastructure following apps/cli/tests/integration patterns with temp directory setup and CLI execution helpers, 2) Write integration tests for help, preset listing, and basic loop execution scenarios"
+ },
+ {
+ "id": "16",
+ "title": "Add Documentation for Loop Command",
+ "description": "Create documentation for the loop command in the docs site (apps/docs) explaining usage, presets, and customization.",
+ "details": "Create `apps/docs/commands/loop.mdx` (or appropriate docs format):\n\n1. Overview section explaining the Ralph Wiggum pattern\n2. Basic usage examples:\n - `task-master loop -n 10`\n - `task-master loop -n 5 --prompt test-coverage`\n - `task-master loop -n 10 --prompt ./custom-prompt.md`\n\n3. Options reference table with all CLI options\n\n4. Built-in presets section:\n - `default` - Task completion workflow\n - `test-coverage` - Write meaningful tests\n - `linting` - Fix lint/type errors\n - `duplication` - Refactor duplicated code\n - `entropy` - Clean up code smells\n\n5. Custom prompt guide:\n - Required structure\n - Completion markers (`<loop-complete>`, `<loop-blocked>`)\n - File references with `@` syntax\n - Progress file usage\n\n6. Progress file format explanation\n\n7. Examples section with real-world use cases\n\nFollow existing docs structure in `apps/docs/`.",
+ "testStrategy": "Documentation review for accuracy and completeness. Test all example commands work as documented. Verify links and cross-references are valid.",
+ "priority": "low",
+ "dependencies": [
+ "12"
+ ],
+ "status": "pending",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Create loop.mdx documentation file with overview and basic usage",
+ "description": "Create the main loop command documentation file (apps/docs/capabilities/loop.mdx) with frontmatter, overview section explaining the Ralph Wiggum pattern, and basic usage examples.",
+ "dependencies": [],
+ "details": "Create `apps/docs/capabilities/loop.mdx` with Mintlify-compatible frontmatter (title: 'Loop Command', description: 'Run Claude Code in autonomous loops'). Include an overview section explaining the Ralph Wiggum pattern (credited to Jeffrey Huntley, popularized by Matt Pocock) - a loop-based approach where each iteration spawns a fresh agent session for better context quality. Add basic usage examples: `task-master loop -n 10`, `task-master loop -n 5 --prompt test-coverage`, `task-master loop -n 10 --prompt ./custom-prompt.md`. Use the existing TDD workflow docs (tdd-workflow/quickstart.mdx) as a style reference.",
+ "status": "pending",
+ "testStrategy": "Verify frontmatter is valid, overview accurately describes the Ralph Wiggum pattern, and basic examples match the PRD command interface.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 2,
+ "title": "Add CLI options reference table",
+ "description": "Add a comprehensive options reference table documenting all CLI options for the loop command including types, defaults, and descriptions.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Add an options table to loop.mdx with columns: Option, Type, Default, Description. Include all options from the PRD: `--iterations, -n` (number, 10), `--prompt, -p` (string, 'default'), `--progress-file` (string, '.taskmaster/loop-progress.txt'), `--sleep` (number, 5), `--on-complete` (string, -), `--tag` (string, -), `--status` (string, 'pending'). Use Mintlify table syntax. Add brief explanations for complex options like how `--prompt` accepts either preset names or file paths.",
+ "status": "pending",
+ "testStrategy": "Verify all options from PRD are documented, types and defaults are accurate, and table renders correctly in Mintlify.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 3,
+ "title": "Document built-in presets section",
+ "description": "Add detailed documentation for all five built-in presets: default, test-coverage, linting, duplication, and entropy workflows.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Create a 'Built-in Presets' section with a summary table listing all presets and their purposes. Then add individual subsections for each preset: `default` (standard task completion workflow), `test-coverage` (write meaningful tests for uncovered code), `linting` (fix lint/type errors one by one), `duplication` (refactor duplicated code using jscpd), `entropy` (clean up code smells like long functions, deep nesting). Include example usage for each preset and describe what constitutes completion criteria. Reference the full preset prompts from the PRD to explain what agents will do.",
+ "status": "pending",
+ "testStrategy": "Verify all 5 presets are documented with accurate descriptions, example commands work, and completion criteria are clearly explained.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 4,
+ "title": "Add custom prompt guide and progress file format",
+ "description": "Document how to create custom prompts including required structure, completion markers, file references, and explain the progress file format.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Add 'Custom Prompts' section explaining: 1) How to specify custom prompts (`--prompt ./path/to/prompt.md`), 2) Required structure with ## Files Available section using `@` syntax for file references, 3) Completion markers that the loop watches for (`<loop-complete>REASON</loop-complete>`, `<loop-blocked>REASON</loop-blocked>`), 4) Best practices for writing effective loop prompts. Add separate 'Progress File' section explaining: the default location (.taskmaster/loop-progress.txt), how agents append notes each iteration, how the @ file reference makes it available to each fresh session, and format examples.",
+ "status": "pending",
+ "testStrategy": "Verify completion markers match PRD spec, file reference syntax is correct, and progress file location matches default option.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 5,
+ "title": "Update docs.json navigation and add real-world examples section",
+ "description": "Add loop command to docs.json navigation structure and create a real-world examples section with practical use cases.",
+ "dependencies": [
+ 1,
+ 2,
+ 3,
+ 4
+ ],
+ "details": "Update `apps/docs/docs.json` to add 'capabilities/loop' to the Technical Capabilities group in the navigation tabs. Add a 'Real-World Examples' section to loop.mdx with practical scenarios: 1) Weekend automation (run loop overnight to clear backlog), 2) Test coverage sprint (get coverage from 60% to 80%), 3) Tech debt day (clean up lint errors across codebase), 4) Code review prep (reduce duplication before PR). Include example commands with realistic flags like `--on-complete 'notify-send \"Loop done!\"'` and `--tag backend`. Cross-link to related docs like command-reference.mdx and tdd-workflow.",
+ "status": "pending",
+ "testStrategy": "Verify docs.json is valid JSON after edit, navigation renders correctly, examples are practical and commands work, and cross-references link to existing pages.",
+ "parentId": "undefined"
+ }
+ ],
+ "complexity": 3,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a focused documentation task with clear structure."
+ },
+ {
+ "id": "17",
+ "title": "Bundle Presets with Package Distribution",
+ "description": "Configure build system to include preset markdown files in the published npm package.",
+ "details": "Update build configuration to include presets:\n\n1. In `packages/tm-core/package.json`, ensure presets directory is included in `files`:\n```json\n{\n \"files\": [\n \"dist/**\",\n \"src/modules/loop/presets/**\"\n ]\n}\n```\n\n2. Update tsdown/tsup configuration if needed to copy asset files:\n```typescript\n// In build config\nexport default {\n // ... existing config\n publicDir: 'src/modules/loop/presets',\n // or use copy plugin\n}\n```\n\n3. Alternative: Use raw-loader or inline the preset content:\n```typescript\n// In loop-preset.service.ts\nconst PRESETS: Record<LoopPreset, string> = {\n 'default': `# Task Master Loop - Default...`,\n 'test-coverage': `# Task Master Loop - Test Coverage...`,\n // etc.\n};\n```\n\n4. Test that presets are accessible after `npm run build`.\n\nFollow patterns from how other assets are bundled in the monorepo.",
+ "testStrategy": "Run `npm run build` and verify presets are included in dist. Run `npm pack` and extract tarball to verify presets are in published package. Test that LoopPresetService can load presets from built package.",
+ "priority": "medium",
+ "dependencies": [
+ "2"
+ ],
+ "status": "done",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Investigate current build setup and determine bundling approach",
+ "description": "Analyze the existing tsdown configuration, package.json files structure, and how assets are bundled to determine the optimal approach for including preset markdown files.",
+ "dependencies": [],
+ "details": "Examine:\n1. Root `tsdown.config.ts` - already uses `copy: ['assets']` to copy root assets\n2. `packages/tm-core/package.json` - currently has `files: ['src', 'README.md', 'CHANGELOG.md']` but package is private and bundled via `noExternal: [/^@tm\\//]`\n3. Root `package.json` - published package with `files: ['dist/**', ...]`\n\nSince @tm/core is bundled into the root package, presets need to either:\n- Option A: Add presets to root `assets/` and use existing `copy` mechanism\n- Option B: Inline preset content as string constants in LoopPresetService\n\nOption B is recommended because:\n- No path resolution issues between dev/prod\n- Works regardless of how package is consumed\n- Simpler testing (no filesystem mocking needed)\n- Follows pattern used by other bundled template content",
+ "status": "done",
+ "testStrategy": "Document findings in a decision record. Verify understanding by checking that `npm run build` produces expected output in `dist/` folder and that `assets/` contents are properly copied.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:49:36.138Z"
+ },
+ {
+ "id": 2,
+ "title": "Implement inlined preset content approach",
+ "description": "Update LoopPresetService to use inlined string constants for preset content instead of filesystem reads, eliminating path resolution complexity.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Create or update `packages/tm-core/src/modules/loop/services/loop-preset.service.ts`:\n\n```typescript\nimport type { LoopPreset } from '../types.js';\n\nconst PRESETS: Record<LoopPreset, string> = {\n 'default': `# Task Master Loop - Default Workflow\\n...`,\n 'test-coverage': `# Task Master Loop - Test Coverage\\n...`,\n 'linting': `# Task Master Loop - Linting\\n...`,\n 'duplication': `# Task Master Loop - Duplication\\n...`,\n 'entropy': `# Task Master Loop - Entropy\\n...`\n};\n\nexport class LoopPresetService {\n isPreset(input: string): input is LoopPreset {\n return input in PRESETS;\n }\n \n getPresetContent(preset: LoopPreset): string {\n return PRESETS[preset];\n }\n}\n```\n\nThis approach:\n- Eliminates need for path resolution at runtime\n- Works identically in dev, build, and published contexts\n- Makes testing straightforward with no mocks needed",
+ "status": "done",
+ "testStrategy": "Unit tests verifying each preset can be retrieved by name, `isPreset()` correctly identifies valid/invalid presets, and `getPresetContent()` returns non-empty strings for all valid presets.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:54:15.152Z"
+ },
+ {
+ "id": 3,
+ "title": "Test preset accessibility in development and after npm pack",
+ "description": "Verify that preset content is accessible in both development mode and after building/packaging for npm distribution.",
+ "dependencies": [
+ 2
+ ],
+ "details": "Testing steps:\n\n1. **Development mode test:**\n - Import LoopPresetService in a test file\n - Verify all presets are accessible via `getPresetContent()`\n - Run `npm run test -w @tm/core` to execute unit tests\n\n2. **Build test:**\n - Run `npm run build` from root\n - Check that tm-core code is properly bundled in `dist/`\n - Verify no runtime errors when importing the built module\n\n3. **Package distribution test:**\n - Run `npm pack` from root to create tarball\n - Extract tarball contents: `tar -xzf task-master-ai-*.tgz`\n - Verify bundled code includes preset strings\n - Test importing from extracted package works\n\n4. **Integration test:**\n - Create integration test that instantiates LoopPresetService\n - Verify it can load all 5 presets without errors\n - Verify preset content contains expected markers (`<loop-complete>`, `<loop-blocked>`)",
+ "status": "done",
+ "testStrategy": "Run `npm run build && npm pack` and extract tarball to verify preset content is embedded. Create integration test in `packages/tm-core/tests/integration/` that loads each preset and validates content structure. Test should pass in CI environment without any filesystem setup.",
+ "parentId": "undefined",
+ "updatedAt": "2026-01-08T22:57:45.565Z"
+ }
+ ],
+ "complexity": 5,
+ "recommendedSubtasks": 3,
+ "expansionPrompt": "Break down into: 1) Investigate current build setup (tsdown config, package.json files) and determine best bundling approach, 2) Implement chosen approach (either copy assets or inline content), 3) Test that presets are accessible in both development and after npm pack",
+ "updatedAt": "2026-01-08T22:57:45.565Z"
+ },
+ {
+ "id": "18",
+ "title": "Add Loop Tool to MCP Tool Tiers",
+ "description": "Register loop tools in the appropriate MCP tool tier (standard or all) for visibility in MCP integrations.",
+ "details": "Update MCP tool tier configuration:\n\n1. Locate tool tier definitions (likely in `apps/mcp/src/` or config files)\n\n2. Add loop tools to 'standard' tier since it's a common workflow tool:\n```typescript\n// Tool tier definitions\nconst TOOL_TIERS = {\n core: [...],\n standard: [\n ...existingStandardTools,\n 'loop_start',\n 'loop_presets'\n ],\n all: [...]\n};\n```\n\n3. Update documentation in `.taskmaster/CLAUDE.md` to include loop tools in the tool tier table.\n\n4. Test with MCP inspector:\n```bash\nnpm run inspector\n```\n\nVerify loop tools appear when `TASK_MASTER_TOOLS=standard` is set.",
+ "testStrategy": "Set TASK_MASTER_TOOLS=standard and verify loop tools are available via MCP. Set TASK_MASTER_TOOLS=core and verify loop tools are NOT available. Run MCP inspector and test tool invocation.",
+ "priority": "low",
+ "dependencies": [
+ "13"
+ ],
+ "status": "pending",
+ "subtasks": [
+ {
+ "id": 1,
+ "title": "Add loop tool registration imports to tool-registry.js",
+ "description": "Import the loop tool registration functions from the appropriate module in mcp-server/src/tools/tool-registry.js.",
+ "dependencies": [],
+ "details": "Add import statements for registerLoopStartTool and registerLoopPresetsTool from their source module (likely './loop-start.js' and './loop-presets.js' or a combined './loop.js'). Follow the existing import pattern used for other tools. The loop tool implementations should be created by dependency task 13.",
+ "status": "pending",
+ "testStrategy": "Verify imports resolve correctly by running npm run build. Check TypeScript/lint errors with npm run typecheck.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 2,
+ "title": "Register loop tools in toolRegistry object",
+ "description": "Add loop_start and loop_presets entries to the toolRegistry object in mcp-server/src/tools/tool-registry.js.",
+ "dependencies": [
+ 1
+ ],
+ "details": "Add entries following the existing pattern:\n```javascript\nloop_start: registerLoopStartTool,\nloop_presets: registerLoopPresetsTool\n```\nPlace them logically near related workflow tools (e.g., near autopilot tools or after research tool).",
+ "status": "pending",
+ "testStrategy": "Run npm run build to verify registration. Unit test that toolRegistry includes 'loop_start' and 'loop_presets' keys.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 3,
+ "title": "Add loop tools to standardTools array",
+ "description": "Add loop_start and loop_presets to the standardTools array since they are common workflow tools.",
+ "dependencies": [
+ 2
+ ],
+ "details": "Update the standardTools array to include the loop tools:\n```javascript\nexport const standardTools = [\n ...coreTools,\n 'initialize_project',\n 'analyze_project_complexity',\n 'expand_all',\n 'add_subtask',\n 'remove_task',\n 'add_task',\n 'complexity_report',\n 'loop_start',\n 'loop_presets'\n];\n```\nUpdate the comment to reflect new count (16 tools instead of 14).",
+ "status": "pending",
+ "testStrategy": "Unit test that standardTools.length increases by 2. Test that standardTools includes 'loop_start' and 'loop_presets'. Verify TASK_MASTER_TOOLS=standard loads loop tools.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 4,
+ "title": "Update MCP tool tier documentation in CLAUDE.md",
+ "description": "Update the tool tier documentation in .taskmaster/CLAUDE.md to include loop tools in the standard tier.",
+ "dependencies": [
+ 3
+ ],
+ "details": "Update the documentation in .taskmaster/CLAUDE.md:\n1. Update the tier table to show 'standard' has 16 tools (not 14)\n2. Update 'Standard adds' line to include loop_start and loop_presets:\n **Standard adds (9 more):** `initialize_project`, `analyze_project_complexity`, `expand_all`, `add_subtask`, `remove_task`, `add_task`, `complexity_report`, `loop_start`, `loop_presets`\n3. Add loop tools to the Essential MCP Tools code block under a new comment section.",
+ "status": "pending",
+ "testStrategy": "Manual review of documentation. Verify tool counts match actual standardTools array length. Check formatting is consistent with existing docs.",
+ "parentId": "undefined"
+ },
+ {
+ "id": 5,
+ "title": "Test loop tools with MCP inspector",
+ "description": "Verify loop tools appear and work correctly with TASK_MASTER_TOOLS=standard via MCP inspector.",
+ "dependencies": [
+ 3
+ ],
+ "details": "Run the following tests:\n1. Set TASK_MASTER_TOOLS=standard and run `npm run inspector`\n2. Verify loop_start and loop_presets tools appear in tool list\n3. Set TASK_MASTER_TOOLS=core and verify loop tools are NOT available\n4. Set TASK_MASTER_TOOLS=all and verify loop tools ARE available\n5. Test invoking loop_presets to verify it returns preset list correctly",
+ "status": "pending",
+ "testStrategy": "Manual testing with MCP inspector CLI. Verify tool visibility changes based on TASK_MASTER_TOOLS env var. Document test results.",
+ "parentId": "undefined"
+ }
+ ],
+ "complexity": 2,
+ "recommendedSubtasks": 0,
+ "expansionPrompt": "No expansion needed - this is a straightforward configuration update."
+ }
+ ],
+ "metadata": {
+ "version": "1.0.0",
+ "lastModified": "2026-01-08T23:51:39.160Z",
+ "taskCount": 18,
+ "completedCount": 11,
+ "tags": [
+ "loop"
+ ]
+ }
}
-}
+}
\ No newline at end of file
diff --git a/apps/cli/src/command-registry.ts b/apps/cli/src/command-registry.ts
index 409aa525..cc8d1ed0 100644
--- a/apps/cli/src/command-registry.ts
+++ b/apps/cli/src/command-registry.ts
@@ -13,6 +13,7 @@ import { ExportCommand, ExportTagCommand } from './commands/export.command.js';
import { GenerateCommand } from './commands/generate.command.js';
// Import all commands
import { ListTasksCommand } from './commands/list.command.js';
+import { LoopCommand } from './commands/loop.command.js';
import { LoginCommand } from './commands/login.command.js';
import { LogoutCommand } from './commands/logout.command.js';
import { NextCommand } from './commands/next.command.js';
@@ -89,6 +90,12 @@ export class CommandRegistry {
commandClass: AutopilotCommand as any,
category: 'development'
},
+ {
+ name: 'loop',
+ description: 'Run Claude Code in a loop, one task per iteration',
+ commandClass: LoopCommand as any,
+ category: 'development'
+ },
// Authentication & Context Commands
{
diff --git a/apps/cli/src/commands/loop.command.spec.ts b/apps/cli/src/commands/loop.command.spec.ts
new file mode 100644
index 00000000..43902e63
--- /dev/null
+++ b/apps/cli/src/commands/loop.command.spec.ts
@@ -0,0 +1,426 @@
+/**
+ * @fileoverview Unit tests for LoopCommand
+ */
+
+import { Command } from 'commander';
+import {
+ type Mock,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi
+} from 'vitest';
+import { LoopCommand } from './loop.command.js';
+
+// Mock @tm/core
+vi.mock('@tm/core', () => ({
+ createTmCore: vi.fn(),
+ PRESET_NAMES: [
+ 'default',
+ 'test-coverage',
+ 'linting',
+ 'duplication',
+ 'entropy'
+ ]
+}));
+
+// Mock display utilities
+vi.mock('../utils/display-helpers.js', () => ({
+ displayCommandHeader: vi.fn()
+}));
+
+vi.mock('../utils/error-handler.js', () => ({
+ displayError: vi.fn()
+}));
+
+vi.mock('../utils/project-root.js', () => ({
+ getProjectRoot: vi.fn().mockReturnValue('/test/project')
+}));
+
+import type { LoopResult } from '@tm/core';
+import { createTmCore } from '@tm/core';
+import { displayCommandHeader } from '../utils/display-helpers.js';
+import { displayError } from '../utils/error-handler.js';
+import { getProjectRoot } from '../utils/project-root.js';
+
+describe('LoopCommand', () => {
+ let loopCommand: LoopCommand;
+ let mockTmCore: any;
+ let mockLoopRun: Mock;
+ let consoleLogSpy: any;
+ let processExitSpy: any;
+
+ const createMockResult = (
+ overrides: Partial<LoopResult> = {}
+ ): LoopResult => ({
+ iterations: [],
+ totalIterations: 3,
+ tasksCompleted: 2,
+ finalStatus: 'max_iterations',
+ ...overrides
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Re-setup mock return values after clearAllMocks
+ (getProjectRoot as Mock).mockReturnValue('/test/project');
+
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ processExitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
+ throw new Error('process.exit called');
+ });
+
+ mockLoopRun = vi.fn().mockResolvedValue(createMockResult());
+ mockTmCore = {
+ loop: {
+ run: mockLoopRun,
+ checkSandboxAuth: vi.fn().mockReturnValue(true),
+ runInteractiveAuth: vi.fn(),
+ resolveIterations: vi.fn().mockImplementation((opts) => {
+ // Mirror the real implementation logic for accurate testing
+ if (opts.userIterations !== undefined) return opts.userIterations;
+ if (opts.preset === 'default' && opts.pendingTaskCount > 0)
+ return opts.pendingTaskCount;
+ return 10;
+ })
+ },
+ tasks: {
+ getStorageType: vi.fn().mockReturnValue('local'),
+ getNext: vi.fn().mockResolvedValue({ id: '1', title: 'Test Task' }),
+ getCount: vi.fn().mockResolvedValue(0)
+ }
+ };
+
+ (createTmCore as Mock).mockResolvedValue(mockTmCore);
+ loopCommand = new LoopCommand();
+ });
+
+ afterEach(() => {
+ consoleLogSpy.mockRestore();
+ processExitSpy.mockRestore();
+ });
+
+ describe('command registration', () => {
+ it('should create command with correct name', () => {
+ expect(loopCommand.name()).toBe('loop');
+ });
+
+ it('should have correct description', () => {
+ expect(loopCommand.description()).toContain('loop');
+ });
+
+ it('should register on parent program via static register()', () => {
+ const program = new Command();
+ const registered = LoopCommand.register(program);
+
+ expect(registered).toBeInstanceOf(LoopCommand);
+ expect(program.commands.find((c) => c.name() === 'loop')).toBe(
+ registered
+ );
+ });
+
+ it('should allow custom name via static register()', () => {
+ const program = new Command();
+ const registered = LoopCommand.register(program, 'custom-loop');
+
+ expect(registered.name()).toBe('custom-loop');
+ });
+ });
+
+ describe('option parsing', () => {
+ it('should have no default for iterations (determined at runtime)', () => {
+ const option = loopCommand.options.find((o) => o.long === '--iterations');
+ expect(option?.defaultValue).toBeUndefined();
+ });
+
+ it('should have default prompt of "default"', () => {
+ const option = loopCommand.options.find((o) => o.long === '--prompt');
+ expect(option?.defaultValue).toBe('default');
+ });
+
+ it('should have -n as short flag for iterations', () => {
+ const option = loopCommand.options.find((o) => o.long === '--iterations');
+ expect(option?.short).toBe('-n');
+ });
+
+ it('should have -p as short flag for prompt', () => {
+ const option = loopCommand.options.find((o) => o.long === '--prompt');
+ expect(option?.short).toBe('-p');
+ });
+
+ it('should have -t as short flag for tag', () => {
+ const option = loopCommand.options.find((o) => o.long === '--tag');
+ expect(option?.short).toBe('-t');
+ });
+
+ it('should have --progress-file option', () => {
+ const option = loopCommand.options.find(
+ (o) => o.long === '--progress-file'
+ );
+ expect(option).toBeDefined();
+ });
+
+ it('should have --project option', () => {
+ const option = loopCommand.options.find((o) => o.long === '--project');
+ expect(option).toBeDefined();
+ });
+ });
+
+ describe('validateIterations', () => {
+ it('should throw error for invalid iterations (non-numeric)', () => {
+ const validateIterations = (loopCommand as any).validateIterations.bind(
+ loopCommand
+ );
+ expect(() => validateIterations('abc')).toThrow('Invalid iterations');
+ });
+
+ it('should throw error for invalid iterations (negative)', () => {
+ const validateIterations = (loopCommand as any).validateIterations.bind(
+ loopCommand
+ );
+ expect(() => validateIterations('-5')).toThrow('Invalid iterations');
+ });
+
+ it('should throw error for invalid iterations (zero)', () => {
+ const validateIterations = (loopCommand as any).validateIterations.bind(
+ loopCommand
+ );
+ expect(() => validateIterations('0')).toThrow('Invalid iterations');
+ });
+
+ it('should allow valid iterations', () => {
+ const validateIterations = (loopCommand as any).validateIterations.bind(
+ loopCommand
+ );
+ expect(() => validateIterations('5')).not.toThrow();
+ });
+ });
+
+ describe('formatStatus', () => {
+ it('should format "all_complete" as green', () => {
+ const formatStatus = (loopCommand as any).formatStatus.bind(loopCommand);
+ const result = formatStatus('all_complete');
+ expect(result).toContain('All tasks complete');
+ });
+
+ it('should format "max_iterations" as yellow', () => {
+ const formatStatus = (loopCommand as any).formatStatus.bind(loopCommand);
+ const result = formatStatus('max_iterations');
+ expect(result).toContain('Max iterations reached');
+ });
+
+ it('should format "blocked" as red', () => {
+ const formatStatus = (loopCommand as any).formatStatus.bind(loopCommand);
+ const result = formatStatus('blocked');
+ expect(result).toContain('Blocked');
+ });
+
+ it('should format "error" as red', () => {
+ const formatStatus = (loopCommand as any).formatStatus.bind(loopCommand);
+ const result = formatStatus('error');
+ expect(result).toContain('Error');
+ });
+ });
+
+ describe('displayResult', () => {
+ it('should display loop completion summary', () => {
+ const displayResult = (loopCommand as any).displayResult.bind(
+ loopCommand
+ );
+ const mockResult: LoopResult = {
+ iterations: [],
+ totalIterations: 5,
+ tasksCompleted: 3,
+ finalStatus: 'max_iterations'
+ };
+
+ displayResult(mockResult);
+
+ expect(consoleLogSpy).toHaveBeenCalled();
+ const allOutput = consoleLogSpy.mock.calls.flat().join(' ');
+ expect(allOutput).toContain('Loop Complete');
+ expect(allOutput).toContain('5');
+ expect(allOutput).toContain('3');
+ });
+ });
+
+ describe('execute integration', () => {
+ it('should call tmCore.loop.run with parsed config', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({
+ iterations: '5',
+ prompt: 'test-coverage',
+ tag: 'feature'
+ });
+
+ expect(mockLoopRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ iterations: 5,
+ prompt: 'test-coverage',
+ tag: 'feature'
+ })
+ );
+ });
+
+ it('should display header', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({});
+
+ expect(displayCommandHeader).toHaveBeenCalled();
+ });
+
+ it('should call displayError on exception', async () => {
+ const error = new Error('Test error');
+ mockLoopRun.mockRejectedValue(error);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+
+ try {
+ await execute({});
+ } catch {
+ // Expected - processExitSpy mock throws to simulate process.exit
+ }
+
+ expect(displayError).toHaveBeenCalledWith(error, { skipExit: true });
+ });
+
+ it('should exit with code 1 on error', async () => {
+ const error = new Error('Test error');
+ mockLoopRun.mockRejectedValue(error);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+
+ try {
+ await execute({});
+ } catch {
+ // Expected - processExitSpy mock throws to simulate process.exit
+ }
+
+ expect(processExitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('should use default values when options not provided and no pending tasks', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+ // Mock empty pending tasks count
+ mockTmCore.tasks.getCount.mockResolvedValue(0);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({});
+
+ expect(mockLoopRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ iterations: 10,
+ prompt: 'default'
+ })
+ );
+ });
+
+ it('should use pending task count as iterations for default preset', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+ // Mock 5 pending items (3 tasks + 2 pending subtasks)
+ mockTmCore.tasks.getCount.mockResolvedValue(5);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({});
+
+ expect(mockLoopRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ iterations: 5,
+ prompt: 'default'
+ })
+ );
+ });
+
+ it('should use explicit iterations even for default preset', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+ // Mock pending tasks (should be ignored when user provides explicit iterations)
+ mockTmCore.tasks.getCount.mockResolvedValue(10);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({ iterations: '3' });
+
+ expect(mockLoopRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ iterations: 3
+ })
+ );
+ });
+
+ it('should default to 10 iterations for non-default presets', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({ prompt: 'test-coverage' });
+
+ // getCount should NOT be called for non-default presets
+ expect(mockTmCore.tasks.getCount).not.toHaveBeenCalled();
+ expect(mockLoopRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ iterations: 10,
+ prompt: 'test-coverage'
+ })
+ );
+ });
+
+ it('should pass progressFile to config when provided', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({ progressFile: '/custom/progress.txt' });
+
+ expect(mockLoopRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ progressFile: '/custom/progress.txt'
+ })
+ );
+ });
+
+ it('should check sandbox auth before running', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({});
+
+ expect(mockTmCore.loop.checkSandboxAuth).toHaveBeenCalled();
+ });
+
+ it('should run interactive auth when sandbox not ready', async () => {
+ mockTmCore.loop.checkSandboxAuth.mockReturnValue(false);
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({});
+
+ expect(mockTmCore.loop.runInteractiveAuth).toHaveBeenCalled();
+ });
+
+ it('should show next task before starting loop', async () => {
+ const result = createMockResult();
+ mockLoopRun.mockResolvedValue(result);
+
+ const execute = (loopCommand as any).execute.bind(loopCommand);
+ await execute({});
+
+ expect(mockTmCore.tasks.getNext).toHaveBeenCalled();
+ const allOutput = consoleLogSpy.mock.calls.flat().join(' ');
+ expect(allOutput).toContain('Next task');
+ expect(allOutput).toContain('Test Task');
+ });
+ });
+});
diff --git a/apps/cli/src/commands/loop.command.ts b/apps/cli/src/commands/loop.command.ts
new file mode 100644
index 00000000..f04f2e8f
--- /dev/null
+++ b/apps/cli/src/commands/loop.command.ts
@@ -0,0 +1,172 @@
+/**
+ * @fileoverview Loop command - thin CLI wrapper over @tm/core's LoopDomain
+ */
+
+import path from 'node:path';
+import {
+ type LoopConfig,
+ type LoopResult,
+ type TmCore,
+ createTmCore,
+ PRESET_NAMES
+} from '@tm/core';
+import chalk from 'chalk';
+import { Command } from 'commander';
+import { displayCommandHeader } from '../utils/display-helpers.js';
+import { displayError } from '../utils/error-handler.js';
+import { getProjectRoot } from '../utils/project-root.js';
+
+export interface LoopCommandOptions {
+ iterations?: string;
+ prompt?: string;
+ progressFile?: string;
+ tag?: string;
+ project?: string;
+}
+
+export class LoopCommand extends Command {
+ private tmCore!: TmCore;
+
+ constructor(name?: string) {
+ super(name || 'loop');
+
+ this.description('Run Claude Code in a loop, one task per iteration')
+ .option('-n, --iterations <number>', 'Maximum iterations')
+ .option(
+ '-p, --prompt <preset|path>',
+ `Preset name (${PRESET_NAMES.join(', ')}) or path to custom prompt file`,
+ 'default'
+ )
+ .option(
+ '--progress-file <path>',
+ 'Path to progress log file',
+ '.taskmaster/progress.txt'
+ )
+ .option('-t, --tag <tag>', 'Only work on tasks with this tag')
+ .option(
+ '--project <path>',
+ 'Project root directory (auto-detected if not provided)'
+ )
+ .action((options: LoopCommandOptions) => this.execute(options));
+ }
+
+ private async execute(options: LoopCommandOptions): Promise<void> {
+ const prompt = options.prompt || 'default';
+ const progressFile = options.progressFile || '.taskmaster/progress.txt';
+
+ try {
+ const projectRoot = path.resolve(getProjectRoot(options.project));
+ this.tmCore = await createTmCore({ projectPath: projectRoot });
+
+ // Get pending task count for default preset iteration resolution
+ const pendingTaskCount =
+ prompt === 'default'
+ ? await this.tmCore.tasks.getCount('pending', options.tag)
+ : undefined;
+
+ // Delegate iteration resolution logic to tm-core
+ const iterations = this.tmCore.loop.resolveIterations({
+ userIterations: options.iterations
+ ? parseInt(options.iterations, 10)
+ : undefined,
+ preset: prompt,
+ pendingTaskCount
+ });
+
+ this.validateIterations(String(iterations));
+
+ displayCommandHeader(this.tmCore, {
+ tag: options.tag || 'master',
+ storageType: this.tmCore.tasks.getStorageType()
+ });
+
+ this.handleSandboxAuth();
+
+ console.log(chalk.cyan('Starting Task Master Loop...'));
+ console.log(chalk.dim(`Preset: ${prompt}`));
+ console.log(chalk.dim(`Max iterations: ${iterations}`));
+
+ // Show next task only for default preset (other presets don't use Task Master tasks)
+ if (prompt === 'default') {
+ const nextTask = await this.tmCore.tasks.getNext(options.tag);
+ if (nextTask) {
+ console.log(
+ chalk.white(
+ `Next task to work on: ${chalk.white(nextTask.id)} - ${nextTask.title}`
+ )
+ );
+ } else {
+ console.log(chalk.yellow('No pending tasks found'));
+ }
+ }
+ console.log();
+
+ const config: Partial<LoopConfig> = {
+ iterations,
+ prompt,
+ progressFile,
+ tag: options.tag
+ };
+
+ const result = await this.tmCore.loop.run(config);
+ this.displayResult(result);
+ } catch (error: unknown) {
+ displayError(error, { skipExit: true });
+ process.exit(1);
+ }
+ }
+
+ private handleSandboxAuth(): void {
+ console.log(chalk.dim('Checking sandbox auth...'));
+ const isAuthed = this.tmCore.loop.checkSandboxAuth();
+
+ if (isAuthed) {
+ console.log(chalk.green('✓ Sandbox ready'));
+ return;
+ }
+
+ console.log(
+ chalk.yellow(
+ 'Sandbox needs authentication. Starting interactive session...'
+ )
+ );
+ console.log(chalk.dim('Please complete auth, then Ctrl+C to continue.\n'));
+
+ this.tmCore.loop.runInteractiveAuth();
+ console.log(chalk.green('✓ Auth complete\n'));
+ }
+
+ private validateIterations(iterations: string): void {
+ const parsed = Number(iterations);
+ if (!Number.isInteger(parsed) || parsed < 1) {
+ throw new Error(
+ `Invalid iterations: ${iterations}. Must be a positive integer.`
+ );
+ }
+ }
+
+ private displayResult(result: LoopResult): void {
+ console.log();
+ console.log(chalk.bold('Loop Complete'));
+ console.log(chalk.dim('─'.repeat(40)));
+ console.log(`Total iterations: ${result.totalIterations}`);
+ console.log(`Tasks completed: ${result.tasksCompleted}`);
+ console.log(`Final status: ${this.formatStatus(result.finalStatus)}`);
+ }
+
+ private formatStatus(status: LoopResult['finalStatus']): string {
+ const statusMap: Record<LoopResult['finalStatus'], string> = {
+ all_complete: chalk.green('All tasks complete'),
+ max_iterations: chalk.yellow('Max iterations reached'),
+ blocked: chalk.red('Blocked'),
+ error: chalk.red('Error')
+ };
+ return statusMap[status];
+ }
+
+ static register(program: Command, name?: string): LoopCommand {
+ const cmd = new LoopCommand(name);
+ program.addCommand(cmd);
+ return cmd;
+ }
+}
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index e4ad3a8a..618749ad 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -14,6 +14,7 @@ export { SetStatusCommand } from './commands/set-status.command.js';
export { ExportCommand } from './commands/export.command.js';
export { TagsCommand } from './commands/tags.command.js';
export { BriefsCommand } from './commands/briefs.command.js';
+export { LoopCommand } from './commands/loop.command.js';
// Command Registry
export {
diff --git a/apps/cli/tests/integration/commands/loop.command.test.ts b/apps/cli/tests/integration/commands/loop.command.test.ts
new file mode 100644
index 00000000..3cda8d9c
--- /dev/null
+++ b/apps/cli/tests/integration/commands/loop.command.test.ts
@@ -0,0 +1,261 @@
+/**
+ * @fileoverview Integration tests for 'task-master loop' command
+ *
+ * Tests the loop command's CLI integration including option parsing,
+ * validation errors, and help text. Note: The loop command spawns
+ * Claude Code which is not available in test environments, so these
+ * tests focus on pre-execution validation and CLI structure.
+ *
+ * @integration
+ */
+
+import { execSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { createTask, createTasksFile } from '@tm/core/testing';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { getCliBinPath } from '../../helpers/test-utils.js';
+
+// Capture initial working directory at module load time
+const initialCwd = process.cwd();
+
+describe('loop command', () => {
+ let testDir: string;
+ let tasksPath: string;
+ let binPath: string;
+
+ beforeEach(() => {
+ testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-loop-test-'));
+ process.chdir(testDir);
+ process.env.TASKMASTER_SKIP_AUTO_UPDATE = '1';
+
+ binPath = getCliBinPath();
+
+ execSync(`node "${binPath}" init --yes`, {
+ stdio: 'pipe',
+ env: { ...process.env, TASKMASTER_SKIP_AUTO_UPDATE: '1' }
+ });
+
+ tasksPath = path.join(testDir, '.taskmaster', 'tasks', 'tasks.json');
+
+ // Use fixture to create initial tasks file with some tasks
+ const initialTasks = createTasksFile({
+ tasks: [
+ createTask({
+ id: 1,
+ title: 'Test Task',
+ description: 'A task for testing loop',
+ status: 'pending'
+ })
+ ]
+ });
+ fs.writeFileSync(tasksPath, JSON.stringify(initialTasks, null, 2));
+ });
+
+ afterEach(() => {
+ try {
+ // Restore to the original working directory captured at module load
+ process.chdir(initialCwd);
+ } catch {
+ // Fallback to home directory if initial directory no longer exists
+ process.chdir(os.homedir());
+ }
+
+ if (testDir && fs.existsSync(testDir)) {
+ fs.rmSync(testDir, { recursive: true, force: true });
+ }
+
+ delete process.env.TASKMASTER_SKIP_AUTO_UPDATE;
+ });
+
+ const runLoop = (args = ''): { output: string; exitCode: number } => {
+ try {
+ const output = execSync(`node "${binPath}" loop ${args}`, {
+ encoding: 'utf-8',
+ stdio: 'pipe',
+ timeout: 5000, // Short timeout since we can't actually run claude
+ env: { ...process.env, TASKMASTER_SKIP_AUTO_UPDATE: '1' }
+ });
+ return { output, exitCode: 0 };
+ } catch (error: any) {
+ return {
+ output: error.stderr?.toString() || error.stdout?.toString() || '',
+ exitCode: error.status || 1
+ };
+ }
+ };
+
+ const runHelp = (): { output: string; exitCode: number } => {
+ try {
+ const output = execSync(`node "${binPath}" loop --help`, {
+ encoding: 'utf-8',
+ stdio: 'pipe',
+ env: { ...process.env, TASKMASTER_SKIP_AUTO_UPDATE: '1' }
+ });
+ return { output, exitCode: 0 };
+ } catch (error: any) {
+ return {
+ output: error.stdout?.toString() || error.stderr?.toString() || '',
+ exitCode: error.status || 1
+ };
+ }
+ };
+
+ describe('command registration', () => {
+ it('should be registered and show in help', () => {
+ const { output, exitCode } = runHelp();
+
+ expect(exitCode).toBe(0);
+ expect(output).toContain('loop');
+ });
+
+ it('should show description in help', () => {
+ const { output, exitCode } = runHelp();
+
+ expect(exitCode).toBe(0);
+ expect(output.toLowerCase()).toContain('claude');
+ expect(output.toLowerCase()).toContain('loop');
+ });
+ });
+
+ describe('option documentation', () => {
+ it('should show -n/--iterations option in help', () => {
+ const { output, exitCode } = runHelp();
+
+ expect(exitCode).toBe(0);
+ expect(output).toContain('-n');
+ expect(output).toContain('--iterations');
+ });
+
+ it('should show -p/--prompt option in help', () => {
+ const { output, exitCode } = runHelp();
+
+ expect(exitCode).toBe(0);
+ expect(output).toContain('-p');
+ expect(output).toContain('--prompt');
+ });
+
+ it('should show -t/--tag option in help', () => {
+ const { output, exitCode } = runHelp();
+
+ expect(exitCode).toBe(0);
+ expect(output).toContain('-t');
+ expect(output).toContain('--tag');
+ });
+
+ it('should show --json option in help', () => {
+ const { output, exitCode } = runHelp();
+
+ expect(exitCode).toBe(0);
+ expect(output).toContain('--json');
+ });
+
+ it('should show --progress-file option in help', () => {
+ const { output, exitCode } = runHelp();
+
+ expect(exitCode).toBe(0);
+ expect(output).toContain('--progress-file');
+ });
+
+ it('should show --project option in help', () => {
+ const { output, exitCode } = runHelp();
+
+ expect(exitCode).toBe(0);
+ expect(output).toContain('--project');
+ });
+ });
+
+ describe('validation errors', () => {
+ it('should reject invalid iterations (non-numeric)', () => {
+ const { output, exitCode } = runLoop('-n abc');
+
+ expect(exitCode).toBe(1);
+ expect(output.toLowerCase()).toContain('invalid');
+ expect(output.toLowerCase()).toContain('iterations');
+ });
+
+ it('should reject invalid iterations (negative)', () => {
+ const { output, exitCode } = runLoop('-n -5');
+
+ expect(exitCode).toBe(1);
+ expect(output.toLowerCase()).toContain('invalid');
+ });
+
+ it('should reject invalid iterations (zero)', () => {
+ const { output, exitCode } = runLoop('-n 0');
+
+ expect(exitCode).toBe(1);
+ expect(output.toLowerCase()).toContain('invalid');
+ expect(output.toLowerCase()).toContain('iterations');
+ });
+ });
+
+ describe('option parsing', () => {
+ it('should accept valid iterations', () => {
+ // Command will fail when trying to run claude, but validation should pass
+ const { output } = runLoop('-n 5');
+
+ // Should NOT contain validation error for iterations
+ expect(output.toLowerCase()).not.toContain('invalid iterations');
+ });
+
+ it('should accept custom prompt preset', () => {
+ const { output } = runLoop('-p test-coverage');
+
+ // Should NOT contain validation error for prompt
+ expect(output.toLowerCase()).not.toContain('invalid prompt');
+ });
+
+ it('should accept tag filter', () => {
+ const { output } = runLoop('-t feature');
+
+ // Should NOT contain validation error for tag
+ expect(output.toLowerCase()).not.toContain('invalid tag');
+ });
+
+ it('should accept progress-file option', () => {
+ const { output } = runLoop('--progress-file /tmp/test-progress.txt');
+
+ // Should NOT contain validation error for progress-file
+ expect(output.toLowerCase()).not.toContain('invalid progress');
+ });
+
+ it('should accept multiple options together', () => {
+ const { output } = runLoop('-n 3 -p default -t test');
+
+ // Should NOT contain validation errors
+ expect(output.toLowerCase()).not.toContain('invalid iterations');
+ });
+ });
+
+ describe('error messages', () => {
+ it('should show helpful error for invalid iterations', () => {
+ const { output, exitCode } = runLoop('-n invalid');
+
+ expect(exitCode).toBe(1);
+ // Should mention what's wrong and what's expected
+ expect(output.toLowerCase()).toContain('iterations');
+ expect(output.toLowerCase()).toContain('positive');
+ });
+ });
+
+ describe('project detection', () => {
+ it('should work in initialized project directory', () => {
+ // The project is already initialized in beforeEach
+ // Command will fail when trying to run claude, but project detection should work
+ const { output } = runLoop('-n 1');
+
+ // Should NOT contain "not a task-master project" or similar
+ expect(output.toLowerCase()).not.toContain('not initialized');
+ expect(output.toLowerCase()).not.toContain('no project');
+ });
+
+ it('should accept --project option for explicit path', () => {
+ const { output } = runLoop(`--project "${testDir}" -n 1`);
+
+ // Should NOT contain validation error for project path
+ expect(output.toLowerCase()).not.toContain('invalid project');
+ });
+ });
+});
diff --git a/apps/docs/capabilities/loop.mdx b/apps/docs/capabilities/loop.mdx
new file mode 100644
index 00000000..da809880
--- /dev/null
+++ b/apps/docs/capabilities/loop.mdx
@@ -0,0 +1,441 @@
+---
+title: Loop Command
+sidebarTitle: "Loop Command"
+description: "Run Claude Code in autonomous loops for batch task completion"
+---
+
+# Loop Command
+
+The `loop` command runs Claude Code in autonomous loops, spawning fresh agent sessions for each iteration. This approach, known as the "Ralph Wiggum pattern" (credited to Jeffrey Huntley, popularized by Matt Pocock), maintains context quality by avoiding long-running sessions that accumulate context fatigue.
+
+## Overview
+
+Instead of a single long-running agent session that degrades over time, the loop command:
+
+1. **Spawns fresh sessions** - Each iteration starts with a clean context
+2. **Uses preset prompts** - Built-in or custom prompts guide each iteration
+3. **Tracks progress** - A progress file persists notes across sessions
+4. **Detects completion** - Special markers signal when work is done or blocked
+
+This pattern is ideal for batch operations like clearing task backlogs, improving test coverage, or fixing lint errors across a codebase.
+
+## Basic Usage
+
+Run 10 iterations with the default task-completion preset:
+
+```bash
+task-master loop -n 10
+```
+
+Run 5 iterations with the test-coverage preset:
+
+```bash
+task-master loop -n 5 --prompt test-coverage
+```
+
+Run iterations with a custom prompt file:
+
+```bash
+task-master loop -n 10 --prompt ./my-custom-prompt.md
+```
+
+Filter to specific task tag:
+
+```bash
+task-master loop -n 10 --tag backend
+```
+
+## How It Works
+
+Each loop iteration:
+
+1. Generates a prompt combining context header + preset content
+2. Spawns `claude -p <prompt>` as a fresh subprocess
+3. Captures output and checks for completion markers
+4. Appends progress notes to the progress file
+5. Sleeps before the next iteration (configurable)
+
+The loop exits early when:
+- An agent outputs `<loop-complete>REASON</loop-complete>` - all work done
+- An agent outputs `<loop-blocked>REASON</loop-blocked>` - cannot proceed
+- Maximum iterations reached
+
+## Progress File
+
+Each iteration's agent has access to a shared progress file (default: `.taskmaster/loop-progress.txt`) via the `@` file reference syntax. Agents append notes about what they completed, allowing subsequent iterations to build on previous work.
+
+Example progress file content:
+
+```
+# Loop Progress - Started 2025-01-09 10:30:00
+# Preset: test-coverage | Iterations: 10
+
+[10:30:45] Iteration 1 (Task 5.2): Added unit tests for UserService
+[10:35:22] Iteration 2 (Task 5.3): Added integration tests for auth flow
+[10:40:18] Iteration 3: All pending test tasks complete
+```
+
+## CLI Options
+
+| Option | Type | Default | Description |
+| ------------------------ | ------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------- |
+| `-n, --iterations` | number | `10` | Maximum number of iterations to run. |
+| `-p, --prompt` | string | `default` | Preset name or path to a custom prompt file. Accepts: `default`, `test-coverage`, `linting`, `duplication`, `entropy`, or a file path like `./my-prompt.md`. |
+| `--progress-file` | string | `.taskmaster/loop-progress.txt` | Path to the progress log file where iteration notes are appended. |
+| `--sleep` | number | `5` | Seconds to wait between iterations. Gives the system time to settle before spawning the next agent. |
+| `--on-complete` | string | - | Shell command to run when all tasks complete (status becomes `all_complete`). Example: `--on-complete 'notify-send "Done!"'` |
+| `-t, --tag` | string | - | Filter to only work on tasks with this tag. |
+| `--status` | string | `pending` | Filter to only work on tasks with this status. |
+| `--project` | string | - | Project root directory. Auto-detected if not provided. |
+| `--json` | flag | - | Output results as JSON instead of formatted text. |
+
+### Option Details
+
+**`--prompt` accepts two types of values:**
+- **Preset names**: Use built-in presets like `default`, `test-coverage`, `linting`, `duplication`, or `entropy`
+- **File paths**: Provide a path to a custom prompt file (e.g., `./my-custom-loop.md`)
+
+**`--on-complete` runs only on success:**
+The shell command only executes when `finalStatus` is `all_complete`, meaning an agent output the `<loop-complete>` marker. It does not run on `max_iterations`, `blocked`, or `error` outcomes.
+
+## Built-in Presets
+
+The loop command includes five built-in presets for common development workflows. Each preset guides agents to complete ONE focused task per iteration.
+
+| Preset | Purpose | Completion Marker |
+| ------ | ------- | ----------------- |
+| `default` | Complete tasks from Task Master backlog | `ALL_TASKS_DONE` |
+| `test-coverage` | Write meaningful tests for uncovered code | `COVERAGE_TARGET` |
+| `linting` | Fix lint and type errors one by one | `ZERO_ERRORS` |
+| `duplication` | Refactor duplicated code into shared utilities | `LOW_DUPLICATION` |
+| `entropy` | Clean up code smells (long functions, deep nesting) | `LOW_ENTROPY` |
+
+### default
+
+The standard task completion workflow. Agents work through your Task Master backlog, completing one task per iteration.
+
+```bash
+task-master loop -n 10 --prompt default
+```
+
+**What it does:**
+1. Runs `task-master next` to get the highest priority available task
+2. Reads task details with `task-master show <id>`
+3. Implements the task with the smallest possible change
+4. Runs tests and type checks to verify quality
+5. Marks the task complete with `task-master set-status --id=<id> --status=done`
+6. Commits work with a descriptive message
+
+**Completion criteria:** All pending tasks are complete.
+
+### test-coverage
+
+Improves test coverage by writing meaningful tests for user-facing behavior - not just chasing coverage numbers.
+
+```bash
+task-master loop -n 10 --prompt test-coverage
+```
+
+**What it does:**
+1. Runs the coverage command (`npm run coverage`, etc.)
+2. Identifies the most important user-facing feature lacking tests
+3. Writes ONE meaningful test validating real behavior
+4. Verifies coverage increased as a side effect
+5. Commits with message: `test(<file>): <describe user behavior tested>`
+
+**Philosophy:** Don't write tests just to increase coverage. Use coverage as a guide to find untested user-facing behavior. Prioritize error handling, CLI commands, API endpoints, and file parsing over internal utilities.
+
+**Completion criteria:** Coverage reaches target or 100%.
+
+### linting
+
+Cleans up lint errors and type errors systematically, one fix per iteration.
+
+```bash
+task-master loop -n 20 --prompt linting
+```
+
+**What it does:**
+1. Runs lint command (`npm run lint`, `eslint .`, etc.)
+2. Runs type check (`tsc --noEmit`, etc.)
+3. Picks ONE error to fix, prioritizing:
+ - Type errors (breaks builds)
+ - Security-related lint errors
+ - Errors in frequently-changed files
+4. Fixes with minimal changes - no surrounding refactoring
+5. Commits with message: `fix(<file>): <describe error fixed>`
+
+**Completion criteria:** Zero lint errors and zero type errors.
+
+### duplication
+
+Finds duplicated code using detection tools and refactors into shared utilities.
+
+```bash
+task-master loop -n 10 --prompt duplication
+```
+
+**What it does:**
+1. Runs duplication detection (`npx jscpd .` or similar)
+2. Reviews the report and picks ONE clone to refactor, prioritizing:
+ - Larger clones (more lines = more maintenance burden)
+ - Clones in frequently-changed files
+ - Clones with slight variations
+3. Extracts duplicated code into a shared utility
+4. Updates all clone locations to use the shared utility
+5. Runs tests to verify behavior is preserved
+
+**Completion criteria:** Duplication below threshold (e.g., <3%).
+
+### entropy
+
+Targets code smells that increase cognitive load and maintenance burden.
+
+```bash
+task-master loop -n 10 --prompt entropy
+```
+
+**Code smells targeted:**
+- Long functions (>60 lines) → extract into smaller functions
+- Deep nesting (>3 levels) → use early returns, extract conditions
+- Large files (>500 lines) → split into focused modules
+- Magic numbers → extract into named constants
+- Complex conditionals → extract into well-named functions
+- God classes → split responsibilities
+
+**What it does:**
+1. Scans codebase for code smells (uses judgment or tools like `complexity-report`)
+2. Picks ONE smell to fix, prioritizing smells in critical paths
+3. Refactors with minimal changes - no over-engineering
+4. Runs tests to verify behavior is preserved
+
+**Completion criteria:** No significant code smells remain.
+
+## Custom Prompts
+
+You can create custom prompt files for specialized workflows that aren't covered by the built-in presets.
+
+### Specifying a Custom Prompt
+
+Pass the file path to the `--prompt` option:
+
+```bash
+task-master loop -n 10 --prompt ./my-custom-loop.md
+```
+
+The path can be absolute or relative to the current directory.
+
+### Required Structure
+
+Custom prompts should follow this structure to work effectively with the loop system:
+
+```markdown
+# Your Loop Title
+
+Brief description of what this loop does.
+
+## Files Available
+
+- @.taskmaster/tasks/tasks.json - Your task backlog
+- @.taskmaster/loop-progress.txt - Progress log from previous iterations
+- @path/to/other/file.ts - Any other files the agent needs
+
+## Process
+
+1. Step one of the workflow
+2. Step two of the workflow
+3. ... more steps
+
+## Important
+
+- Complete ONLY ONE task per session
+- Keep changes small and focused
+- Do NOT start another task after completing one
+- If work is complete, output: <loop-complete>REASON</loop-complete>
+- If blocked, output: <loop-blocked>REASON</loop-blocked>
+```
+
+### File References with @ Syntax
+
+The `@` prefix makes files available to the agent. Claude Code will read these files when processing the prompt:
+
+```markdown
+## Files Available
+
+- @src/index.ts - Main entry point
+- @package.json - Dependencies and scripts
+- @.taskmaster/loop-progress.txt - Progress from previous iterations
+```
+
+Without the `@` prefix, file paths are just text. With `@`, the agent can actually read and reference the file contents.
+
+### Completion Markers
+
+The loop watches for two special markers in agent output:
+
+| Marker | Purpose | Example |
+| ------ | ------- | ------- |
+| `<loop-complete>REASON</loop-complete>` | Signal that all work is done | `<loop-complete>ALL_TESTS_PASSING</loop-complete>` |
+| `<loop-blocked>REASON</loop-blocked>` | Signal that work cannot proceed | `<loop-blocked>MISSING_API_KEY</loop-blocked>` |
+
+When either marker is detected, the loop exits early. The reason text is captured in the final result.
+
+**Example usage in a custom prompt:**
+
+```markdown
+## Important
+
+- If all migrations are complete, output: <loop-complete>MIGRATIONS_DONE</loop-complete>
+- If a migration fails with an unrecoverable error, output: <loop-blocked>MIGRATION_FAILED: describe error</loop-blocked>
+```
+
+### Best Practices
+
+1. **Be specific**: Clearly define what "done" means for your workflow
+2. **One task per iteration**: Instruct agents to complete exactly one unit of work
+3. **Use the progress file**: Reference `@.taskmaster/loop-progress.txt` so agents can see what previous iterations accomplished
+4. **Include quality checks**: Add steps for running tests or type checks before completing
+5. **Define completion criteria**: Tell agents exactly when to output `<loop-complete>`
+6. **Handle edge cases**: Define when to output `<loop-blocked>` to avoid infinite loops
+
+## Progress File
+
+The progress file is a shared log that persists notes across loop iterations. Since each iteration spawns a fresh agent session, this file provides continuity.
+
+### Default Location
+
+```
+.taskmaster/loop-progress.txt
+```
+
+Override with the `--progress-file` option:
+
+```bash
+task-master loop -n 10 --progress-file ./my-progress.txt
+```
+
+### How It Works
+
+1. **Initialization**: The loop creates the progress file at the start with a header
+2. **Each iteration**: Agents read the file via `@` reference and append notes about their work
+3. **Context continuity**: Subsequent agents see what previous iterations accomplished
+
+### File Format
+
+The progress file uses a simple timestamped format:
+
+```
+# Loop Progress - Started 2025-01-09 10:30:00
+# Preset: default | Iterations: 10 | Tag: backend
+
+[10:30:45] Iteration 1 (Task 5.2): Implemented user authentication endpoint
+[10:35:22] Iteration 2 (Task 5.3): Added input validation for login form
+[10:40:18] Iteration 3 (Task 5.4): Fixed edge case in token refresh logic
+[10:45:01] Iteration 4: All pending backend tasks complete
+```
+
+**Format breakdown:**
+- **Header**: Timestamp, preset name, max iterations, optional tag filter
+- **Entries**: `[HH:MM:SS] Iteration N (Task ID): Description`
+- **Task ID**: Optional - included when agent worked on a specific task
+
+### Using Progress in Custom Prompts
+
+Always include the progress file in your `## Files Available` section:
+
+```markdown
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log from previous iterations
+```
+
+And instruct agents to append notes:
+
+```markdown
+## Process
+
+...
+7. Append a brief note to the progress file about what was done
+```
+
+This creates a chain of context that helps each iteration build on previous work.
+
+## Real-World Examples
+
+Here are practical scenarios for using the loop command in your development workflow.
+
+### Weekend Automation
+
+Run a loop overnight or over the weekend to clear your task backlog while you're away:
+
+```bash
+task-master loop -n 50 --prompt default --on-complete 'notify-send "Loop complete!"'
+```
+
+This runs up to 50 iterations, completing tasks one by one. When all tasks are done, you'll get a desktop notification.
+
+### Test Coverage Sprint
+
+Push your test coverage from 60% to 80% systematically:
+
+```bash
+task-master loop -n 20 --prompt test-coverage --on-complete 'echo "Coverage target reached!"'
+```
+
+Each iteration identifies the most important untested user-facing behavior and writes a meaningful test. The agent prioritizes error handling, API endpoints, and CLI commands over internal utilities.
+
+### Tech Debt Day
+
+Dedicate a day to cleaning up lint errors across your codebase:
+
+```bash
+task-master loop -n 30 --prompt linting --sleep 3
+```
+
+With `--sleep 3`, iterations run faster for quick fixes. The agent systematically addresses type errors first (they break builds), then security-related lint errors, then others.
+
+### Code Review Prep
+
+Reduce code duplication before opening a PR:
+
+```bash
+task-master loop -n 10 --prompt duplication --tag backend
+```
+
+The `--tag backend` flag focuses the loop on backend code only. Each iteration finds and refactors one instance of duplicated code into a shared utility.
+
+### Multi-Tag Workflow
+
+Process different parts of your codebase in sequence:
+
+```bash
+# First, handle critical backend tasks
+task-master loop -n 10 --tag backend --status pending
+
+# Then, address frontend tasks
+task-master loop -n 10 --tag frontend --status pending
+```
+
+### Custom Migration Script
+
+For complex migrations, create a custom prompt and run it:
+
+```bash
+# Create custom-migration.md with your specific steps
+task-master loop -n 20 --prompt ./custom-migration.md --progress-file ./migration-progress.txt
+```
+
+Use a separate progress file to track migration-specific notes.
+
+---
+
+<Note>
+**Related documentation:**
+- [CLI Root Commands](/capabilities/cli-root-commands) - Full command reference
+- [TDD Workflow](/tdd-workflow/quickstart) - Structured test-driven development
+- [Task Structure](/capabilities/task-structure) - Understanding task organization
+</Note>
+
+<Tip>
+The loop command is perfect for "overnight automation" - start a loop before leaving and return to a cleaned-up codebase.
+</Tip>
diff --git a/apps/docs/command-reference.mdx b/apps/docs/command-reference.mdx
index 2fe23f81..845c7dfc 100644
--- a/apps/docs/command-reference.mdx
+++ b/apps/docs/command-reference.mdx
@@ -246,4 +246,38 @@ description: "A comprehensive reference of all available Task Master commands"
The TDD workflow enforces RED → GREEN → COMMIT cycles for each subtask. See [AI Agent Integration](/tdd-workflow/ai-agent-integration) for details.
</Accordion>
+
+ <Accordion title="Loop (Autonomous Batch Execution)">
+ ```bash
+ # Run 10 iterations with the default preset
+ task-master loop -n 10
+
+ # Use a specific preset
+ task-master loop -n 10 --prompt test-coverage
+ task-master loop -n 10 --prompt linting
+ task-master loop -n 10 --prompt duplication
+ task-master loop -n 10 --prompt entropy
+
+ # Use a custom prompt file
+ task-master loop -n 10 --prompt ./my-workflow.md
+
+ # Filter to tasks with a specific tag
+ task-master loop -n 10 --tag backend
+
+ # Custom progress file location
+ task-master loop -n 10 --progress-file ./my-progress.txt
+
+ # Output as JSON
+ task-master loop -n 10 --json
+ ```
+
+ **Built-in presets:**
+ - `default` - Complete tasks from Task Master backlog one at a time
+ - `test-coverage` - Write meaningful tests for untested user-facing behavior
+ - `linting` - Fix lint and type errors incrementally
+ - `duplication` - Refactor duplicated code into shared utilities
+ - `entropy` - Clean up code smells (long functions, deep nesting, etc.)
+
+ Each iteration spawns a fresh Claude Code session, avoiding context fatigue. See [Loop Command](/capabilities/loop) for full documentation.
+ </Accordion>
</AccordionGroup>
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 3ac77073..d7f00098 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -50,7 +50,8 @@
"pages": [
"capabilities/mcp",
"capabilities/cli-root-commands",
- "capabilities/task-structure"
+ "capabilities/task-structure",
+ "capabilities/loop"
]
},
{
diff --git a/mcp-server/src/tools/tool-registry.js b/mcp-server/src/tools/tool-registry.js
index d0f2476e..325d514e 100644
--- a/mcp-server/src/tools/tool-registry.js
+++ b/mcp-server/src/tools/tool-registry.js
@@ -118,7 +118,7 @@ export const coreTools = [
];
/**
- * Standard tools array containing the 15 most commonly used tools
+ * Standard tools array containing the 14 most commonly used tools
* Includes all core tools plus frequently used additional tools
*/
export const standardTools = [
diff --git a/packages/tm-core/src/index.ts b/packages/tm-core/src/index.ts
index 4c45e600..06b9f04d 100644
--- a/packages/tm-core/src/index.ts
+++ b/packages/tm-core/src/index.ts
@@ -147,6 +147,15 @@ export type {
TaskComplexityData
} from './modules/reports/types.js';
+// Loop types
+export type {
+ LoopPreset,
+ LoopConfig,
+ LoopIteration,
+ LoopResult
+} from './modules/loop/index.js';
+export { LoopDomain, PRESET_NAMES } from './modules/loop/index.js';
+
// Prompts types
export type {
PromptAction,
diff --git a/packages/tm-core/src/modules/loop/index.ts b/packages/tm-core/src/modules/loop/index.ts
new file mode 100644
index 00000000..ab3a8e16
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/index.ts
@@ -0,0 +1,32 @@
+/**
+ * @fileoverview Loop module exports
+ * Simplified API: LoopDomain (facade), LoopService (logic), Presets (content)
+ */
+
+// Domain facade - primary public API
+export { LoopDomain } from './loop-domain.js';
+
+// Service - for advanced usage
+export { LoopService } from './services/loop.service.js';
+export type { LoopServiceOptions } from './services/loop.service.js';
+
+// Types
+export type {
+ LoopPreset,
+ LoopConfig,
+ LoopIteration,
+ LoopResult
+} from './types.js';
+
+// Presets - content and helpers
+export {
+ PRESETS,
+ PRESET_NAMES,
+ getPreset,
+ isPreset,
+ DEFAULT_PRESET,
+ TEST_COVERAGE_PRESET,
+ LINTING_PRESET,
+ DUPLICATION_PRESET,
+ ENTROPY_PRESET
+} from './presets/index.js';
diff --git a/packages/tm-core/src/modules/loop/loop-domain.spec.ts b/packages/tm-core/src/modules/loop/loop-domain.spec.ts
new file mode 100644
index 00000000..f51f5e1d
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/loop-domain.spec.ts
@@ -0,0 +1,278 @@
+/**
+ * @fileoverview Unit tests for LoopDomain
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { LoopDomain } from './loop-domain.js';
+import type { ConfigManager } from '../config/managers/config-manager.js';
+import type { LoopConfig } from './types.js';
+
+// Mock ConfigManager
+function createMockConfigManager(projectRoot = '/test/project'): ConfigManager {
+ return {
+ getProjectRoot: vi.fn().mockReturnValue(projectRoot)
+ } as unknown as ConfigManager;
+}
+
+describe('LoopDomain', () => {
+ let mockConfigManager: ConfigManager;
+ let loopDomain: LoopDomain;
+
+ beforeEach(() => {
+ mockConfigManager = createMockConfigManager();
+ loopDomain = new LoopDomain(mockConfigManager);
+ });
+
+ describe('constructor', () => {
+ it('should create instance with ConfigManager', () => {
+ expect(loopDomain).toBeInstanceOf(LoopDomain);
+ });
+
+ it('should store projectRoot from ConfigManager', () => {
+ const customManager = createMockConfigManager('/custom/root');
+ const domain = new LoopDomain(customManager);
+ // Verify by checking buildConfig output
+ const config = (domain as any).buildConfig({});
+ expect(config.progressFile).toBe('/custom/root/.taskmaster/progress.txt');
+ });
+
+ it('should call getProjectRoot on ConfigManager', () => {
+ expect(mockConfigManager.getProjectRoot).toHaveBeenCalled();
+ });
+ });
+
+ describe('buildConfig', () => {
+ it('should apply default iterations of 10', () => {
+ const config = (loopDomain as any).buildConfig({});
+ expect(config.iterations).toBe(10);
+ });
+
+ it('should apply default prompt of "default"', () => {
+ const config = (loopDomain as any).buildConfig({});
+ expect(config.prompt).toBe('default');
+ });
+
+ it('should apply default sleepSeconds of 5', () => {
+ const config = (loopDomain as any).buildConfig({});
+ expect(config.sleepSeconds).toBe(5);
+ });
+
+ it('should construct progressFile from projectRoot', () => {
+ const config = (loopDomain as any).buildConfig({});
+ expect(config.progressFile).toBe(
+ '/test/project/.taskmaster/progress.txt'
+ );
+ });
+
+ it('should respect provided iterations', () => {
+ const config = (loopDomain as any).buildConfig({ iterations: 20 });
+ expect(config.iterations).toBe(20);
+ });
+
+ it('should respect provided prompt', () => {
+ const config = (loopDomain as any).buildConfig({
+ prompt: 'test-coverage'
+ });
+ expect(config.prompt).toBe('test-coverage');
+ });
+
+ it('should respect provided sleepSeconds', () => {
+ const config = (loopDomain as any).buildConfig({ sleepSeconds: 10 });
+ expect(config.sleepSeconds).toBe(10);
+ });
+
+ it('should respect provided progressFile', () => {
+ const config = (loopDomain as any).buildConfig({
+ progressFile: '/custom/progress.txt'
+ });
+ expect(config.progressFile).toBe('/custom/progress.txt');
+ });
+
+ it('should respect provided tag', () => {
+ const config = (loopDomain as any).buildConfig({ tag: 'my-tag' });
+ expect(config.tag).toBe('my-tag');
+ });
+
+ it('should handle all options combined', () => {
+ const fullConfig: Partial<LoopConfig> = {
+ iterations: 5,
+ prompt: 'linting',
+ progressFile: '/my/progress.txt',
+ sleepSeconds: 2,
+ tag: 'feature-branch'
+ };
+ const config = (loopDomain as any).buildConfig(fullConfig);
+ expect(config).toEqual(fullConfig);
+ });
+ });
+
+ describe('isPreset', () => {
+ it('should return true for valid preset "default"', () => {
+ expect(loopDomain.isPreset('default')).toBe(true);
+ });
+
+ it('should return true for valid preset "test-coverage"', () => {
+ expect(loopDomain.isPreset('test-coverage')).toBe(true);
+ });
+
+ it('should return true for valid preset "linting"', () => {
+ expect(loopDomain.isPreset('linting')).toBe(true);
+ });
+
+ it('should return true for valid preset "duplication"', () => {
+ expect(loopDomain.isPreset('duplication')).toBe(true);
+ });
+
+ it('should return true for valid preset "entropy"', () => {
+ expect(loopDomain.isPreset('entropy')).toBe(true);
+ });
+
+ it('should return false for invalid preset', () => {
+ expect(loopDomain.isPreset('invalid-preset')).toBe(false);
+ });
+
+ it('should return false for file path', () => {
+ expect(loopDomain.isPreset('/path/to/prompt.md')).toBe(false);
+ });
+
+ it('should return false for empty string', () => {
+ expect(loopDomain.isPreset('')).toBe(false);
+ });
+ });
+
+ describe('getAvailablePresets', () => {
+ it('should return array of all preset names', () => {
+ const presets = loopDomain.getAvailablePresets();
+ expect(presets).toHaveLength(5);
+ expect(presets).toEqual(
+ expect.arrayContaining([
+ 'default',
+ 'test-coverage',
+ 'linting',
+ 'duplication',
+ 'entropy'
+ ])
+ );
+ });
+ });
+
+ describe('resolvePrompt', () => {
+ it('should resolve preset name to content', async () => {
+ const content = await loopDomain.resolvePrompt('default');
+ expect(typeof content).toBe('string');
+ expect(content.length).toBeGreaterThan(0);
+ // Assert on structural property - all presets should contain completion marker
+ expect(content).toContain('<loop-complete>');
+ });
+
+ it('should resolve all preset names', async () => {
+ const presets = loopDomain.getAvailablePresets();
+ for (const preset of presets) {
+ const content = await loopDomain.resolvePrompt(preset);
+ expect(content).toBeTruthy();
+ expect(content.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('should throw for custom path without readFile', async () => {
+ await expect(
+ loopDomain.resolvePrompt('/custom/prompt.md')
+ ).rejects.toThrow('readFile callback');
+ });
+
+ it('should use readFile for custom paths', async () => {
+ const mockReadFile = vi.fn().mockResolvedValue('Custom prompt content');
+ const content = await loopDomain.resolvePrompt(
+ '/custom/prompt.md',
+ mockReadFile
+ );
+ expect(mockReadFile).toHaveBeenCalledWith('/custom/prompt.md');
+ expect(content).toBe('Custom prompt content');
+ });
+ });
+
+ describe('getIsRunning', () => {
+ it('should return false when no loop is running', () => {
+ expect(loopDomain.getIsRunning()).toBe(false);
+ });
+
+ it('should return false after stop() when no loop was started', () => {
+ loopDomain.stop();
+ expect(loopDomain.getIsRunning()).toBe(false);
+ });
+ });
+
+ describe('stop', () => {
+ it('should not throw when called without starting a loop', () => {
+ expect(() => loopDomain.stop()).not.toThrow();
+ });
+
+ it('should be callable multiple times', () => {
+ loopDomain.stop();
+ loopDomain.stop();
+ expect(loopDomain.getIsRunning()).toBe(false);
+ });
+ });
+
+ describe('resolveIterations', () => {
+ it('should return userIterations when provided', () => {
+ const result = loopDomain.resolveIterations({
+ userIterations: 25,
+ preset: 'default',
+ pendingTaskCount: 10
+ });
+ expect(result).toBe(25);
+ });
+
+ it('should return pendingTaskCount for default preset when no userIterations', () => {
+ const result = loopDomain.resolveIterations({
+ preset: 'default',
+ pendingTaskCount: 15
+ });
+ expect(result).toBe(15);
+ });
+
+ it('should return 10 for default preset when pendingTaskCount is 0', () => {
+ const result = loopDomain.resolveIterations({
+ preset: 'default',
+ pendingTaskCount: 0
+ });
+ expect(result).toBe(10);
+ });
+
+ it('should return 10 for default preset when pendingTaskCount is undefined', () => {
+ const result = loopDomain.resolveIterations({
+ preset: 'default'
+ });
+ expect(result).toBe(10);
+ });
+
+ it('should return 10 for non-default presets regardless of pendingTaskCount', () => {
+ const presets = ['test-coverage', 'linting', 'duplication', 'entropy'];
+ for (const preset of presets) {
+ const result = loopDomain.resolveIterations({
+ preset,
+ pendingTaskCount: 50
+ });
+ expect(result).toBe(10);
+ }
+ });
+
+ it('should prioritize userIterations over pendingTaskCount for default preset', () => {
+ const result = loopDomain.resolveIterations({
+ userIterations: 5,
+ preset: 'default',
+ pendingTaskCount: 100
+ });
+ expect(result).toBe(5);
+ });
+
+ it('should prioritize userIterations for non-default presets', () => {
+ const result = loopDomain.resolveIterations({
+ userIterations: 30,
+ preset: 'linting'
+ });
+ expect(result).toBe(30);
+ });
+ });
+});
diff --git a/packages/tm-core/src/modules/loop/loop-domain.ts b/packages/tm-core/src/modules/loop/loop-domain.ts
new file mode 100644
index 00000000..1d284792
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/loop-domain.ts
@@ -0,0 +1,194 @@
+/**
+ * @fileoverview Loop Domain Facade
+ * Public API for loop operations following the pattern of other domains
+ */
+
+import path from 'node:path';
+import { getLogger } from '../../common/logger/index.js';
+import type { ConfigManager } from '../config/managers/config-manager.js';
+import {
+ PRESET_NAMES,
+ isPreset as checkIsPreset,
+ getPreset
+} from './presets/index.js';
+import { LoopService } from './services/loop.service.js';
+import type { LoopConfig, LoopPreset, LoopResult } from './types.js';
+
+/**
+ * Loop Domain - Unified API for loop operations
+ * Coordinates LoopService with lazy instantiation
+ */
+export class LoopDomain {
+ private readonly logger = getLogger('LoopDomain');
+ private loopService: LoopService | null = null;
+ private readonly projectRoot: string;
+
+ constructor(configManager: ConfigManager) {
+ this.projectRoot = configManager.getProjectRoot();
+ }
+
+ // ========== Sandbox Auth Operations ==========
+
+ /**
+ * Check if Docker sandbox auth is ready
+ * @returns true if ready, false if auth needed
+ */
+ checkSandboxAuth(): boolean {
+ const service = new LoopService({ projectRoot: this.projectRoot });
+ return service.checkSandboxAuth();
+ }
+
+ /**
+ * Run Docker sandbox session for user authentication
+ * Blocks until user completes auth
+ */
+ runInteractiveAuth(): void {
+ const service = new LoopService({ projectRoot: this.projectRoot });
+ service.runInteractiveAuth();
+ }
+
+ // ========== Loop Operations ==========
+
+ /**
+ * Run a loop with the given configuration
+ * Creates a new LoopService instance and runs it
+ * @param config - Partial loop configuration (defaults will be applied)
+ * @returns Promise resolving to the loop result
+ * @throws Error if a loop is already running
+ */
+ async run(config: Partial<LoopConfig>): Promise<LoopResult> {
+ // Prevent orphaning a previous running LoopService
+ if (this.loopService?.isRunning) {
+ try {
+ this.loopService.stop();
+ } catch (error) {
+ // Log but don't block - stopping previous service is best-effort cleanup
+ this.logger.warn('Failed to stop previous loop service:', error);
+ }
+ }
+
+ const fullConfig = this.buildConfig(config);
+ this.loopService = new LoopService({ projectRoot: this.projectRoot });
+ return this.loopService.run(fullConfig);
+ }
+
+ /**
+ * Stop the currently running loop
+ * Signals the loop to stop and nulls the service reference
+ */
+ stop(): void {
+ if (this.loopService) {
+ this.loopService.stop();
+ this.loopService = null;
+ }
+ }
+
+ /**
+ * Check if a loop is currently running
+ */
+ getIsRunning(): boolean {
+ return this.loopService?.isRunning ?? false;
+ }
+
+ // ========== Preset Operations ==========
+
+ /**
+ * Type guard to check if a string is a valid preset name
+ * @param prompt - The string to check
+ * @returns True if the prompt is a valid LoopPreset
+ */
+ isPreset(prompt: string): prompt is LoopPreset {
+ return checkIsPreset(prompt);
+ }
+
+ /**
+ * Resolve a prompt string to its content
+ * For preset names, returns the inlined content
+ * For file paths, reads the file (requires readFile callback)
+ * @param prompt - Either a preset name or a file path
+ * @param readFile - Optional async function to read file content
+ * @returns Promise resolving to the prompt content string
+ */
+ async resolvePrompt(
+ prompt: LoopPreset | string,
+ readFile?: (path: string) => Promise<string>
+ ): Promise<string> {
+ if (checkIsPreset(prompt)) {
+ return getPreset(prompt);
+ }
+ if (!readFile) {
+ throw new Error(
+ `Custom prompt file requires readFile callback: ${prompt}`
+ );
+ }
+ return readFile(prompt);
+ }
+
+ /**
+ * Get all available preset names
+ * @returns Array of available preset names
+ */
+ getAvailablePresets(): LoopPreset[] {
+ return [...PRESET_NAMES];
+ }
+
+ // ========== Iteration Resolution ==========
+
+ /**
+ * Resolve the number of iterations to use based on preset and task count.
+ * Business logic for determining iterations:
+ * - If user provided explicit iterations, use that
+ * - If preset is 'default' and pendingTaskCount > 0, use pending task count
+ * - Otherwise, default to 10
+ *
+ * @param options - Options for resolving iterations
+ * @param options.userIterations - User-provided iterations (takes priority)
+ * @param options.preset - The preset name being used
+ * @param options.pendingTaskCount - Count of pending tasks + subtasks (for default preset)
+ * @returns The resolved number of iterations
+ */
+ resolveIterations(options: {
+ userIterations?: number;
+ preset: string;
+ pendingTaskCount?: number;
+ }): number {
+ const { userIterations, preset, pendingTaskCount } = options;
+
+ // User explicitly provided iterations - use their value
+ if (userIterations !== undefined) {
+ return userIterations;
+ }
+
+ // For default preset, use pending task count if available
+ if (
+ preset === 'default' &&
+ pendingTaskCount !== undefined &&
+ pendingTaskCount > 0
+ ) {
+ return pendingTaskCount;
+ }
+
+ // Default for non-default presets or when no pending tasks
+ return 10;
+ }
+
+ // ========== Internal Helpers ==========
+
+ /**
+ * Build a complete LoopConfig from partial input
+ * Applies sensible defaults for any missing fields
+ * @param partial - Partial configuration to merge with defaults
+ * @returns Complete LoopConfig with all required fields
+ */
+ private buildConfig(partial: Partial<LoopConfig>): LoopConfig {
+ return {
+ iterations: partial.iterations ?? 10,
+ prompt: partial.prompt ?? 'default',
+ progressFile:
+ partial.progressFile ??
+ path.join(this.projectRoot, '.taskmaster', 'progress.txt'),
+ sleepSeconds: partial.sleepSeconds ?? 5,
+ tag: partial.tag
+ };
+ }
+}
diff --git a/packages/tm-core/src/modules/loop/presets/__snapshots__/presets.spec.ts.snap b/packages/tm-core/src/modules/loop/presets/__snapshots__/presets.spec.ts.snap
new file mode 100644
index 00000000..7a0e6195
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/presets/__snapshots__/presets.spec.ts.snap
@@ -0,0 +1,177 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`Preset Snapshots > default preset matches snapshot 1`] = `
+"SETUP: If task-master command not found, run: npm i -g task-master-ai
+
+TASK: Implement ONE task/subtask from the Task Master backlog.
+
+PROCESS:
+1. Run task-master next (or use MCP) to get the next available task/subtask.
+2. Read task details with task-master show <id>.
+3. Implement following codebase patterns.
+4. Write tests alongside implementation.
+5. Run type check (e.g., \`npm run typecheck\`, \`tsc --noEmit\`).
+6. Run tests (e.g., \`npm test\`, \`npm run test\`).
+7. Mark complete: task-master set-status --id=<id> --status=done
+8. Commit with message: feat(<scope>): <what was implemented>
+9. Append super-concise notes to progress file: task ID, what was done, any learnings.
+
+IMPORTANT:
+- Complete ONLY ONE task per iteration.
+- Keep changes small and focused.
+- Do NOT start another task after completing one.
+- If all tasks are done, output <loop-complete>ALL_DONE</loop-complete>.
+- If blocked, output <loop-blocked>REASON</loop-blocked>.
+"
+`;
+
+exports[`Preset Snapshots > duplication preset matches snapshot 1`] = `
+"# Task Master Loop - Duplication
+
+Find duplicated code and refactor into shared utilities. ONE refactor per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (clones refactored, duplication %)
+
+## Process
+
+1. Run duplication detection (\`npx jscpd .\`, or similar tool)
+2. Review the report and pick ONE clone to refactor - prioritize:
+ - Larger clones (more lines = more maintenance burden)
+ - Clones in frequently-changed files
+ - Clones with slight variations (consolidate logic)
+3. Extract the duplicated code into a shared utility/function
+4. Update all clone locations to use the shared utility
+5. Run tests to ensure behavior is preserved
+6. Commit with message: \`refactor(<file>): extract <utility> to reduce duplication\`
+7. Append to progress file: what was refactored, new duplication %
+
+## Important
+
+- Complete ONLY ONE refactor per session
+- Keep changes focused on the specific duplication
+- Do NOT start another refactor after completing one
+
+## Completion Criteria
+
+- If duplication below threshold (e.g., <3%), output: <loop-complete>LOW_DUPLICATION</loop-complete>
+"
+`;
+
+exports[`Preset Snapshots > entropy preset matches snapshot 1`] = `
+"# Task Master Loop - Entropy (Code Smells)
+
+Find code smells and clean them up. ONE cleanup per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (smells fixed, areas cleaned)
+
+## Code Smells to Target
+
+- Long functions (>60 lines) - extract into smaller functions
+- Deep nesting (>3 levels) - use early returns, extract conditions
+- Large files (>500 lines) - split into focused modules
+- Magic numbers - extract into named constants
+- Complex conditionals - extract into well-named functions
+- God classes - split responsibilities
+
+## Process
+
+1. Scan the codebase for code smells (use your judgment or tools like \`complexity-report\`)
+2. Pick ONE smell to fix - prioritize:
+ - Smells in frequently-changed files
+ - Smells that hurt readability the most
+ - Smells in critical paths (authentication, payments, etc.)
+3. Refactor with minimal changes - don't over-engineer
+4. Run tests to ensure behavior is preserved
+5. Commit with message: \`refactor(<file>): <describe the cleanup>\`
+6. Append to progress file: what was cleaned, smell type
+
+## Important
+
+- Complete ONLY ONE cleanup per session
+- Keep refactoring focused and minimal
+- Do NOT start another cleanup after completing one
+
+## Completion Criteria
+
+- If no significant smells remain, output: <loop-complete>LOW_ENTROPY</loop-complete>
+"
+`;
+
+exports[`Preset Snapshots > linting preset matches snapshot 1`] = `
+"# Task Master Loop - Linting
+
+Fix lint errors and type errors one by one. ONE fix per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (errors fixed, remaining count)
+
+## Process
+
+1. Run lint command (\`pnpm lint\`, \`npm run lint\`, \`eslint .\`, etc.)
+2. Run type check (\`pnpm typecheck\`, \`tsc --noEmit\`, etc.)
+3. Pick ONE error to fix - prioritize:
+ - Type errors (breaks builds)
+ - Security-related lint errors
+ - Errors in frequently-changed files
+4. Fix the error with minimal changes - don't refactor surrounding code
+5. Run lint/typecheck again to verify the fix doesn't introduce new errors
+6. Commit with message: \`fix(<file>): <describe the lint/type error fixed>\`
+7. Append to progress file: error fixed, remaining error count
+
+## Important
+
+- Complete ONLY ONE fix per session
+- Keep changes minimal and focused
+- Do NOT start another fix after completing one
+
+## Completion Criteria
+
+- If zero lint errors and zero type errors, output: <loop-complete>ZERO_ERRORS</loop-complete>
+"
+`;
+
+exports[`Preset Snapshots > test-coverage preset matches snapshot 1`] = `
+"# Task Master Loop - Test Coverage
+
+Find uncovered code and write meaningful tests. ONE test per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (coverage %, what was tested)
+
+## What Makes a Great Test
+
+A great test covers behavior users depend on. It tests a feature that, if broken,
+would frustrate or block users. It validates real workflows - not implementation details.
+
+Do NOT write tests just to increase coverage. Use coverage as a guide to find
+UNTESTED USER-FACING BEHAVIOR. If code is not worth testing (boilerplate, unreachable
+branches, internal plumbing), add ignore comments instead of low-value tests.
+
+## Process
+
+1. Run coverage command (\`pnpm coverage\`, \`npm run coverage\`, etc.)
+2. Identify the most important USER-FACING FEATURE that lacks tests
+ - Prioritize: error handling users hit, CLI commands, API endpoints, file parsing
+ - Deprioritize: internal utilities, edge cases users won't encounter, boilerplate
+3. Write ONE meaningful test that validates the feature works correctly
+4. Run coverage again - it should increase as a side effect of testing real behavior
+5. Commit with message: \`test(<file>): <describe the user behavior being tested>\`
+6. Append to progress file: what you tested, new coverage %, learnings
+
+## Important
+
+- Complete ONLY ONE test per session
+- Keep tests focused on user-facing behavior
+- Do NOT start another test after completing one
+
+## Completion Criteria
+
+- If coverage reaches target (or 100%), output: <loop-complete>COVERAGE_TARGET</loop-complete>
+"
+`;
diff --git a/packages/tm-core/src/modules/loop/presets/default.ts b/packages/tm-core/src/modules/loop/presets/default.ts
new file mode 100644
index 00000000..6660600e
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/presets/default.ts
@@ -0,0 +1,26 @@
+/**
+ * Default preset for Task Master loop - general task completion
+ * Matches the structure of scripts/loop.sh prompt
+ */
+export const DEFAULT_PRESET = `SETUP: If task-master command not found, run: npm i -g task-master-ai
+
+TASK: Implement ONE task/subtask from the Task Master backlog.
+
+PROCESS:
+1. Run task-master next (or use MCP) to get the next available task/subtask.
+2. Read task details with task-master show <id>.
+3. Implement following codebase patterns.
+4. Write tests alongside implementation.
+5. Run type check (e.g., \`npm run typecheck\`, \`tsc --noEmit\`).
+6. Run tests (e.g., \`npm test\`, \`npm run test\`).
+7. Mark complete: task-master set-status --id=<id> --status=done
+8. Commit with message: feat(<scope>): <what was implemented>
+9. Append super-concise notes to progress file: task ID, what was done, any learnings.
+
+IMPORTANT:
+- Complete ONLY ONE task per iteration.
+- Keep changes small and focused.
+- Do NOT start another task after completing one.
+- If all tasks are done, output <loop-complete>ALL_DONE</loop-complete>.
+- If blocked, output <loop-blocked>REASON</loop-blocked>.
+`;
diff --git a/packages/tm-core/src/modules/loop/presets/duplication.ts b/packages/tm-core/src/modules/loop/presets/duplication.ts
new file mode 100644
index 00000000..b523b5ed
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/presets/duplication.ts
@@ -0,0 +1,34 @@
+/**
+ * Duplication preset for Task Master loop - code deduplication
+ */
+export const DUPLICATION_PRESET = `# Task Master Loop - Duplication
+
+Find duplicated code and refactor into shared utilities. ONE refactor per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (clones refactored, duplication %)
+
+## Process
+
+1. Run duplication detection (\`npx jscpd .\`, or similar tool)
+2. Review the report and pick ONE clone to refactor - prioritize:
+ - Larger clones (more lines = more maintenance burden)
+ - Clones in frequently-changed files
+ - Clones with slight variations (consolidate logic)
+3. Extract the duplicated code into a shared utility/function
+4. Update all clone locations to use the shared utility
+5. Run tests to ensure behavior is preserved
+6. Commit with message: \`refactor(<file>): extract <utility> to reduce duplication\`
+7. Append to progress file: what was refactored, new duplication %
+
+## Important
+
+- Complete ONLY ONE refactor per session
+- Keep changes focused on the specific duplication
+- Do NOT start another refactor after completing one
+
+## Completion Criteria
+
+- If duplication below threshold (e.g., <3%), output: <loop-complete>LOW_DUPLICATION</loop-complete>
+`;
diff --git a/packages/tm-core/src/modules/loop/presets/entropy.ts b/packages/tm-core/src/modules/loop/presets/entropy.ts
new file mode 100644
index 00000000..d7b6cd25
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/presets/entropy.ts
@@ -0,0 +1,43 @@
+/**
+ * @fileoverview Entropy (Code Smells) preset for loop module
+ */
+
+export const ENTROPY_PRESET = `# Task Master Loop - Entropy (Code Smells)
+
+Find code smells and clean them up. ONE cleanup per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (smells fixed, areas cleaned)
+
+## Code Smells to Target
+
+- Long functions (>60 lines) - extract into smaller functions
+- Deep nesting (>3 levels) - use early returns, extract conditions
+- Large files (>500 lines) - split into focused modules
+- Magic numbers - extract into named constants
+- Complex conditionals - extract into well-named functions
+- God classes - split responsibilities
+
+## Process
+
+1. Scan the codebase for code smells (use your judgment or tools like \`complexity-report\`)
+2. Pick ONE smell to fix - prioritize:
+ - Smells in frequently-changed files
+ - Smells that hurt readability the most
+ - Smells in critical paths (authentication, payments, etc.)
+3. Refactor with minimal changes - don't over-engineer
+4. Run tests to ensure behavior is preserved
+5. Commit with message: \`refactor(<file>): <describe the cleanup>\`
+6. Append to progress file: what was cleaned, smell type
+
+## Important
+
+- Complete ONLY ONE cleanup per session
+- Keep refactoring focused and minimal
+- Do NOT start another cleanup after completing one
+
+## Completion Criteria
+
+- If no significant smells remain, output: <loop-complete>LOW_ENTROPY</loop-complete>
+`;
diff --git a/packages/tm-core/src/modules/loop/presets/index.ts b/packages/tm-core/src/modules/loop/presets/index.ts
new file mode 100644
index 00000000..c4a35acf
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/presets/index.ts
@@ -0,0 +1,52 @@
+/**
+ * @fileoverview Preset exports for loop module
+ * Simple re-exports from individual preset files with helper functions
+ */
+
+import { DEFAULT_PRESET } from './default.js';
+import { TEST_COVERAGE_PRESET } from './test-coverage.js';
+import { LINTING_PRESET } from './linting.js';
+import { DUPLICATION_PRESET } from './duplication.js';
+import { ENTROPY_PRESET } from './entropy.js';
+import type { LoopPreset } from '../types.js';
+
+/**
+ * Record of all preset names to their content
+ */
+export const PRESETS: Record<LoopPreset, string> = {
+ default: DEFAULT_PRESET,
+ 'test-coverage': TEST_COVERAGE_PRESET,
+ linting: LINTING_PRESET,
+ duplication: DUPLICATION_PRESET,
+ entropy: ENTROPY_PRESET
+};
+
+/**
+ * Array of all available preset names
+ */
+export const PRESET_NAMES = Object.keys(PRESETS) as LoopPreset[];
+
+/**
+ * Get the content of a preset by name
+ * @param name - The preset name
+ * @returns The preset content string
+ */
+export function getPreset(name: LoopPreset): string {
+ return PRESETS[name];
+}
+
+/**
+ * Type guard to check if a value is a valid preset name
+ * @param value - The value to check
+ * @returns True if the value is a valid LoopPreset
+ */
+export function isPreset(value: string): value is LoopPreset {
+ return value in PRESETS;
+}
+
+// Re-export individual presets for direct access
+export { DEFAULT_PRESET } from './default.js';
+export { TEST_COVERAGE_PRESET } from './test-coverage.js';
+export { LINTING_PRESET } from './linting.js';
+export { DUPLICATION_PRESET } from './duplication.js';
+export { ENTROPY_PRESET } from './entropy.js';
diff --git a/packages/tm-core/src/modules/loop/presets/linting.ts b/packages/tm-core/src/modules/loop/presets/linting.ts
new file mode 100644
index 00000000..d33df6f0
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/presets/linting.ts
@@ -0,0 +1,34 @@
+/**
+ * Linting preset for Task Master loop - fix lint and type errors
+ */
+export const LINTING_PRESET = `# Task Master Loop - Linting
+
+Fix lint errors and type errors one by one. ONE fix per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (errors fixed, remaining count)
+
+## Process
+
+1. Run lint command (\`pnpm lint\`, \`npm run lint\`, \`eslint .\`, etc.)
+2. Run type check (\`pnpm typecheck\`, \`tsc --noEmit\`, etc.)
+3. Pick ONE error to fix - prioritize:
+ - Type errors (breaks builds)
+ - Security-related lint errors
+ - Errors in frequently-changed files
+4. Fix the error with minimal changes - don't refactor surrounding code
+5. Run lint/typecheck again to verify the fix doesn't introduce new errors
+6. Commit with message: \`fix(<file>): <describe the lint/type error fixed>\`
+7. Append to progress file: error fixed, remaining error count
+
+## Important
+
+- Complete ONLY ONE fix per session
+- Keep changes minimal and focused
+- Do NOT start another fix after completing one
+
+## Completion Criteria
+
+- If zero lint errors and zero type errors, output: <loop-complete>ZERO_ERRORS</loop-complete>
+`;
diff --git a/packages/tm-core/src/modules/loop/presets/presets.spec.ts b/packages/tm-core/src/modules/loop/presets/presets.spec.ts
new file mode 100644
index 00000000..12eac09f
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/presets/presets.spec.ts
@@ -0,0 +1,284 @@
+/**
+ * @fileoverview Tests for preset exports and preset content structure
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ PRESETS,
+ PRESET_NAMES,
+ getPreset,
+ isPreset,
+ DEFAULT_PRESET,
+ TEST_COVERAGE_PRESET,
+ LINTING_PRESET,
+ DUPLICATION_PRESET,
+ ENTROPY_PRESET
+} from './index.js';
+
+describe('Preset Exports', () => {
+ describe('PRESET_NAMES', () => {
+ it('contains all 5 preset names', () => {
+ expect(PRESET_NAMES).toHaveLength(5);
+ });
+
+ it('includes default preset', () => {
+ expect(PRESET_NAMES).toContain('default');
+ });
+
+ it('includes test-coverage preset', () => {
+ expect(PRESET_NAMES).toContain('test-coverage');
+ });
+
+ it('includes linting preset', () => {
+ expect(PRESET_NAMES).toContain('linting');
+ });
+
+ it('includes duplication preset', () => {
+ expect(PRESET_NAMES).toContain('duplication');
+ });
+
+ it('includes entropy preset', () => {
+ expect(PRESET_NAMES).toContain('entropy');
+ });
+ });
+
+ describe('PRESETS record', () => {
+ it('has entries for all preset names', () => {
+ for (const name of PRESET_NAMES) {
+ expect(PRESETS[name]).toBeDefined();
+ expect(typeof PRESETS[name]).toBe('string');
+ }
+ });
+
+ it('has non-empty content for each preset', () => {
+ for (const name of PRESET_NAMES) {
+ expect(PRESETS[name].length).toBeGreaterThan(0);
+ }
+ });
+ });
+
+ describe('getPreset', () => {
+ it('returns content for default preset', () => {
+ const content = getPreset('default');
+ expect(content).toBeTruthy();
+ expect(typeof content).toBe('string');
+ expect(content.length).toBeGreaterThan(0);
+ });
+
+ it('returns content for test-coverage preset', () => {
+ const content = getPreset('test-coverage');
+ expect(content).toBeTruthy();
+ expect(content.length).toBeGreaterThan(0);
+ });
+
+ it('returns content for linting preset', () => {
+ const content = getPreset('linting');
+ expect(content).toBeTruthy();
+ expect(content.length).toBeGreaterThan(0);
+ });
+
+ it('returns content for duplication preset', () => {
+ const content = getPreset('duplication');
+ expect(content).toBeTruthy();
+ expect(content.length).toBeGreaterThan(0);
+ });
+
+ it('returns content for entropy preset', () => {
+ const content = getPreset('entropy');
+ expect(content).toBeTruthy();
+ expect(content.length).toBeGreaterThan(0);
+ });
+
+ it('returns same content as PRESETS record', () => {
+ for (const name of PRESET_NAMES) {
+ expect(getPreset(name)).toBe(PRESETS[name]);
+ }
+ });
+ });
+
+ describe('isPreset', () => {
+ it('returns true for valid preset names', () => {
+ expect(isPreset('default')).toBe(true);
+ expect(isPreset('test-coverage')).toBe(true);
+ expect(isPreset('linting')).toBe(true);
+ expect(isPreset('duplication')).toBe(true);
+ expect(isPreset('entropy')).toBe(true);
+ });
+
+ it('returns false for invalid preset names', () => {
+ expect(isPreset('invalid')).toBe(false);
+ expect(isPreset('custom')).toBe(false);
+ expect(isPreset('')).toBe(false);
+ });
+
+ it('returns false for file paths', () => {
+ expect(isPreset('/path/to/preset.md')).toBe(false);
+ expect(isPreset('./custom-preset.md')).toBe(false);
+ expect(isPreset('presets/default.md')).toBe(false);
+ });
+
+ it('returns false for preset names with different casing', () => {
+ expect(isPreset('Default')).toBe(false);
+ expect(isPreset('DEFAULT')).toBe(false);
+ expect(isPreset('Test-Coverage')).toBe(false);
+ });
+ });
+
+ describe('Individual preset constants', () => {
+ it('exports DEFAULT_PRESET', () => {
+ expect(DEFAULT_PRESET).toBeDefined();
+ expect(typeof DEFAULT_PRESET).toBe('string');
+ expect(DEFAULT_PRESET.length).toBeGreaterThan(0);
+ });
+
+ it('exports TEST_COVERAGE_PRESET', () => {
+ expect(TEST_COVERAGE_PRESET).toBeDefined();
+ expect(typeof TEST_COVERAGE_PRESET).toBe('string');
+ expect(TEST_COVERAGE_PRESET.length).toBeGreaterThan(0);
+ });
+
+ it('exports LINTING_PRESET', () => {
+ expect(LINTING_PRESET).toBeDefined();
+ expect(typeof LINTING_PRESET).toBe('string');
+ expect(LINTING_PRESET.length).toBeGreaterThan(0);
+ });
+
+ it('exports DUPLICATION_PRESET', () => {
+ expect(DUPLICATION_PRESET).toBeDefined();
+ expect(typeof DUPLICATION_PRESET).toBe('string');
+ expect(DUPLICATION_PRESET.length).toBeGreaterThan(0);
+ });
+
+ it('exports ENTROPY_PRESET', () => {
+ expect(ENTROPY_PRESET).toBeDefined();
+ expect(typeof ENTROPY_PRESET).toBe('string');
+ expect(ENTROPY_PRESET.length).toBeGreaterThan(0);
+ });
+
+ it('individual constants match PRESETS record', () => {
+ expect(DEFAULT_PRESET).toBe(PRESETS['default']);
+ expect(TEST_COVERAGE_PRESET).toBe(PRESETS['test-coverage']);
+ expect(LINTING_PRESET).toBe(PRESETS['linting']);
+ expect(DUPLICATION_PRESET).toBe(PRESETS['duplication']);
+ expect(ENTROPY_PRESET).toBe(PRESETS['entropy']);
+ });
+ });
+});
+
+describe('Preset Snapshots', () => {
+ it('default preset matches snapshot', () => {
+ expect(DEFAULT_PRESET).toMatchSnapshot();
+ });
+
+ it('test-coverage preset matches snapshot', () => {
+ expect(TEST_COVERAGE_PRESET).toMatchSnapshot();
+ });
+
+ it('linting preset matches snapshot', () => {
+ expect(LINTING_PRESET).toMatchSnapshot();
+ });
+
+ it('duplication preset matches snapshot', () => {
+ expect(DUPLICATION_PRESET).toMatchSnapshot();
+ });
+
+ it('entropy preset matches snapshot', () => {
+ expect(ENTROPY_PRESET).toMatchSnapshot();
+ });
+});
+
+describe('Preset Structure Validation', () => {
+ describe('all presets contain required elements', () => {
+ it.each(PRESET_NAMES)('%s contains <loop-complete> marker', (preset) => {
+ const content = getPreset(preset);
+ expect(content).toMatch(/<loop-complete>/);
+ });
+
+ it.each(PRESET_NAMES.filter((p) => p !== 'default'))(
+ '%s contains @ file reference pattern',
+ (preset) => {
+ const content = getPreset(preset);
+ // Check for @ file reference pattern (e.g., @.taskmaster/ or @./)
+ // Note: default preset uses context header injection instead
+ expect(content).toMatch(/@\.taskmaster\/|@\.\//);
+ }
+ );
+
+ it.each(PRESET_NAMES)('%s contains numbered process steps', (preset) => {
+ const content = getPreset(preset);
+ // Check for numbered steps (e.g., "1. ", "2. ")
+ expect(content).toMatch(/^\d+\./m);
+ });
+
+ it.each(PRESET_NAMES)(
+ '%s contains Important or Completion section',
+ (preset) => {
+ const content = getPreset(preset);
+ // Check for Important section (markdown or plain text) or Completion section
+ expect(content).toMatch(/## Important|## Completion|^IMPORTANT:/im);
+ }
+ );
+ });
+
+ describe('default preset specific requirements', () => {
+ it('contains <loop-blocked> marker', () => {
+ expect(DEFAULT_PRESET).toMatch(/<loop-blocked>/);
+ });
+
+ it('contains both loop markers', () => {
+ expect(DEFAULT_PRESET).toMatch(/<loop-complete>.*<\/loop-complete>/);
+ expect(DEFAULT_PRESET).toMatch(/<loop-blocked>.*<\/loop-blocked>/);
+ });
+ });
+});
+
+describe('Preset Content Consistency', () => {
+ it.each(PRESET_NAMES)(
+ '%s mentions single-task-per-iteration constraint',
+ (preset) => {
+ const content = getPreset(preset);
+ // Check for variations of the single-task constraint
+ const hasConstraint =
+ content.toLowerCase().includes('one task') ||
+ content.toLowerCase().includes('one test') ||
+ content.toLowerCase().includes('one fix') ||
+ content.toLowerCase().includes('one refactor') ||
+ content.toLowerCase().includes('one cleanup') ||
+ content.toLowerCase().includes('only one');
+ expect(hasConstraint).toBe(true);
+ }
+ );
+
+ it.each(PRESET_NAMES)('%s has progress file reference', (preset) => {
+ const content = getPreset(preset);
+ // All presets should reference the progress file
+ expect(content).toMatch(/loop-progress|progress/i);
+ });
+
+ it('specialized presets have markdown headers', () => {
+ // Default preset uses plain text sections (SETUP:, TASK:, PROCESS:, IMPORTANT:)
+ // Other presets use markdown headers
+ for (const preset of PRESET_NAMES.filter((p) => p !== 'default')) {
+ const content = getPreset(preset);
+ // Check for at least one markdown header
+ expect(content).toMatch(/^#+ /m);
+ }
+ });
+
+ it('all presets have process section', () => {
+ for (const preset of PRESET_NAMES) {
+ const content = getPreset(preset);
+ // Check for Process header (markdown ## or plain text PROCESS:)
+ expect(content).toMatch(/## Process|^PROCESS:/m);
+ }
+ });
+
+ it('specialized presets have files available section', () => {
+ // Default preset doesn't have files available section - context is injected at runtime
+ for (const preset of PRESET_NAMES.filter((p) => p !== 'default')) {
+ const content = getPreset(preset);
+ // Check for Files Available header
+ expect(content).toMatch(/## Files Available/);
+ }
+ });
+});
diff --git a/packages/tm-core/src/modules/loop/presets/test-coverage.ts b/packages/tm-core/src/modules/loop/presets/test-coverage.ts
new file mode 100644
index 00000000..3a2c625a
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/presets/test-coverage.ts
@@ -0,0 +1,41 @@
+/**
+ * Test coverage preset for Task Master loop - writing meaningful tests
+ */
+export const TEST_COVERAGE_PRESET = `# Task Master Loop - Test Coverage
+
+Find uncovered code and write meaningful tests. ONE test per session.
+
+## Files Available
+
+- @.taskmaster/loop-progress.txt - Progress log (coverage %, what was tested)
+
+## What Makes a Great Test
+
+A great test covers behavior users depend on. It tests a feature that, if broken,
+would frustrate or block users. It validates real workflows - not implementation details.
+
+Do NOT write tests just to increase coverage. Use coverage as a guide to find
+UNTESTED USER-FACING BEHAVIOR. If code is not worth testing (boilerplate, unreachable
+branches, internal plumbing), add ignore comments instead of low-value tests.
+
+## Process
+
+1. Run coverage command (\`pnpm coverage\`, \`npm run coverage\`, etc.)
+2. Identify the most important USER-FACING FEATURE that lacks tests
+ - Prioritize: error handling users hit, CLI commands, API endpoints, file parsing
+ - Deprioritize: internal utilities, edge cases users won't encounter, boilerplate
+3. Write ONE meaningful test that validates the feature works correctly
+4. Run coverage again - it should increase as a side effect of testing real behavior
+5. Commit with message: \`test(<file>): <describe the user behavior being tested>\`
+6. Append to progress file: what you tested, new coverage %, learnings
+
+## Important
+
+- Complete ONLY ONE test per session
+- Keep tests focused on user-facing behavior
+- Do NOT start another test after completing one
+
+## Completion Criteria
+
+- If coverage reaches target (or 100%), output: <loop-complete>COVERAGE_TARGET</loop-complete>
+`;
diff --git a/packages/tm-core/src/modules/loop/services/index.ts b/packages/tm-core/src/modules/loop/services/index.ts
new file mode 100644
index 00000000..d2b45cea
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/services/index.ts
@@ -0,0 +1,6 @@
+/**
+ * @fileoverview Loop services barrel export
+ */
+
+export { LoopService } from './loop.service.js';
+export type { LoopServiceOptions } from './loop.service.js';
diff --git a/packages/tm-core/src/modules/loop/services/loop.service.spec.ts b/packages/tm-core/src/modules/loop/services/loop.service.spec.ts
new file mode 100644
index 00000000..a211bd1e
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/services/loop.service.spec.ts
@@ -0,0 +1,703 @@
+/**
+ * @fileoverview Unit tests for simplified LoopService
+ * Tests the synchronous spawnSync-based implementation
+ */
+
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance
+} from 'vitest';
+import { LoopService, type LoopServiceOptions } from './loop.service.js';
+import * as childProcess from 'node:child_process';
+import * as fsPromises from 'node:fs/promises';
+
+// Mock child_process and fs/promises
+vi.mock('node:child_process');
+vi.mock('node:fs/promises');
+
+describe('LoopService', () => {
+ const defaultOptions: LoopServiceOptions = {
+ projectRoot: '/test/project'
+ };
+
+ let mockSpawnSync: MockInstance;
+
+ beforeEach(() => {
+ vi.resetAllMocks();
+ // Default fs mocks
+ vi.mocked(fsPromises.mkdir).mockResolvedValue(undefined);
+ vi.mocked(fsPromises.writeFile).mockResolvedValue(undefined);
+ vi.mocked(fsPromises.appendFile).mockResolvedValue(undefined);
+
+ // Default spawnSync mock
+ mockSpawnSync = vi.mocked(childProcess.spawnSync);
+
+ // Suppress console output in tests
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ describe('constructor', () => {
+ it('should create a LoopService instance with required options', () => {
+ const service = new LoopService(defaultOptions);
+ expect(service).toBeInstanceOf(LoopService);
+ });
+
+ it('should store projectRoot from options', () => {
+ const service = new LoopService(defaultOptions);
+ expect(service.getProjectRoot()).toBe('/test/project');
+ });
+
+ it('should initialize isRunning to false', () => {
+ const service = new LoopService(defaultOptions);
+ expect(service.isRunning).toBe(false);
+ });
+ });
+
+ describe('service instantiation with different project roots', () => {
+ it('should work with absolute path', () => {
+ const service = new LoopService({
+ projectRoot: '/absolute/path/to/project'
+ });
+ expect(service.getProjectRoot()).toBe('/absolute/path/to/project');
+ });
+
+ it('should work with Windows-style path', () => {
+ const service = new LoopService({
+ projectRoot: 'C:\\Users\\test\\project'
+ });
+ expect(service.getProjectRoot()).toBe('C:\\Users\\test\\project');
+ });
+
+ it('should work with empty projectRoot', () => {
+ const service = new LoopService({ projectRoot: '' });
+ expect(service.getProjectRoot()).toBe('');
+ });
+ });
+
+ describe('service instance isolation', () => {
+ it('should create independent instances', () => {
+ const service1 = new LoopService(defaultOptions);
+ const service2 = new LoopService(defaultOptions);
+ expect(service1).not.toBe(service2);
+ });
+
+ it('should maintain independent state between instances', () => {
+ const service1 = new LoopService({ projectRoot: '/project1' });
+ const service2 = new LoopService({ projectRoot: '/project2' });
+
+ expect(service1.getProjectRoot()).toBe('/project1');
+ expect(service2.getProjectRoot()).toBe('/project2');
+ });
+ });
+
+ describe('stop()', () => {
+ it('should set isRunning to false', () => {
+ const service = new LoopService(defaultOptions);
+ // Access private field via any cast for testing
+ (service as unknown as { _isRunning: boolean })._isRunning = true;
+ expect(service.isRunning).toBe(true);
+
+ service.stop();
+
+ expect(service.isRunning).toBe(false);
+ });
+
+ it('should be safe to call multiple times', () => {
+ const service = new LoopService(defaultOptions);
+ service.stop();
+ service.stop();
+ service.stop();
+
+ expect(service.isRunning).toBe(false);
+ });
+ });
+
+ describe('checkSandboxAuth()', () => {
+ it('should return true when output contains ok', () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: 'OK',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const service = new LoopService(defaultOptions);
+ const result = service.checkSandboxAuth();
+
+ expect(result).toBe(true);
+ expect(mockSpawnSync).toHaveBeenCalledWith(
+ 'docker',
+ ['sandbox', 'run', 'claude', '-p', 'Say OK'],
+ expect.objectContaining({
+ cwd: '/test/project',
+ timeout: 30000
+ })
+ );
+ });
+
+ it('should return false when output does not contain ok', () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: 'Error: not authenticated',
+ stderr: '',
+ status: 1,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const service = new LoopService(defaultOptions);
+ const result = service.checkSandboxAuth();
+
+ expect(result).toBe(false);
+ });
+
+ it('should check stderr as well as stdout', () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: 'OK response',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const service = new LoopService(defaultOptions);
+ const result = service.checkSandboxAuth();
+
+ expect(result).toBe(true);
+ });
+ });
+
+ describe('runInteractiveAuth()', () => {
+ it('should spawn interactive docker session', () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const service = new LoopService(defaultOptions);
+ service.runInteractiveAuth();
+
+ expect(mockSpawnSync).toHaveBeenCalledWith(
+ 'docker',
+ expect.arrayContaining(['sandbox', 'run', 'claude']),
+ expect.objectContaining({
+ cwd: '/test/project',
+ stdio: 'inherit'
+ })
+ );
+ });
+ });
+
+ describe('run()', () => {
+ let service: LoopService;
+
+ beforeEach(() => {
+ service = new LoopService(defaultOptions);
+ });
+
+ describe('successful iteration run', () => {
+ it('should run a single iteration successfully', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: 'Task completed',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const result = await service.run({
+ prompt: 'default',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(result.totalIterations).toBe(1);
+ expect(result.tasksCompleted).toBe(1);
+ expect(result.finalStatus).toBe('max_iterations');
+ });
+
+ it('should run multiple iterations', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: 'Done',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const result = await service.run({
+ prompt: 'default',
+ iterations: 3,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(result.totalIterations).toBe(3);
+ expect(result.tasksCompleted).toBe(3);
+ expect(mockSpawnSync).toHaveBeenCalledTimes(3);
+ });
+
+ it('should call spawnSync with docker sandbox run claude -p', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: 'Done',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ await service.run({
+ prompt: 'default',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(mockSpawnSync).toHaveBeenCalledWith(
+ 'docker',
+ expect.arrayContaining([
+ 'sandbox',
+ 'run',
+ 'claude',
+ '-p',
+ expect.any(String)
+ ]),
+ expect.objectContaining({
+ cwd: '/test/project'
+ })
+ );
+ });
+ });
+
+ describe('completion marker detection', () => {
+ it('should detect loop-complete marker and exit early', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '<loop-complete>ALL_DONE</loop-complete>',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const result = await service.run({
+ prompt: 'default',
+ iterations: 5,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(result.totalIterations).toBe(1);
+ expect(result.finalStatus).toBe('all_complete');
+ });
+
+ it('should detect loop-blocked marker and exit early', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '<loop-blocked>Missing API key</loop-blocked>',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const result = await service.run({
+ prompt: 'default',
+ iterations: 5,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(result.totalIterations).toBe(1);
+ expect(result.finalStatus).toBe('blocked');
+ });
+ });
+
+ describe('error handling', () => {
+ it('should handle non-zero exit code', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: 'Error occurred',
+ status: 1,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ const result = await service.run({
+ prompt: 'default',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(result.iterations[0].status).toBe('error');
+ expect(result.tasksCompleted).toBe(0);
+ });
+
+ it('should handle null status as error', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: '',
+ status: null,
+ signal: 'SIGTERM',
+ pid: 123,
+ output: []
+ });
+
+ const result = await service.run({
+ prompt: 'default',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(result.iterations[0].status).toBe('error');
+ });
+ });
+
+ describe('progress file operations', () => {
+ it('should initialize progress file at start', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ await service.run({
+ prompt: 'default',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(fsPromises.mkdir).toHaveBeenCalledWith('/test', {
+ recursive: true
+ });
+ expect(fsPromises.writeFile).toHaveBeenCalledWith(
+ '/test/progress.txt',
+ expect.stringContaining('# Task Master Loop Progress'),
+ 'utf-8'
+ );
+ });
+
+ it('should append final summary at end', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ await service.run({
+ prompt: 'default',
+ iterations: 2,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(fsPromises.appendFile).toHaveBeenCalledWith(
+ '/test/progress.txt',
+ expect.stringContaining('# Loop Complete'),
+ 'utf-8'
+ );
+ });
+ });
+
+ describe('preset resolution', () => {
+ it('should resolve built-in preset names', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ await service.run({
+ prompt: 'test-coverage',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ // Verify spawn was called with prompt containing iteration info
+ const spawnCall = mockSpawnSync.mock.calls[0];
+ // Args are ['sandbox', 'run', 'claude', '-p', prompt]
+ const promptArg = spawnCall[1][4];
+ expect(promptArg).toContain('iteration 1 of 1');
+ });
+
+ it('should load custom prompt from file', async () => {
+ vi.mocked(fsPromises.readFile).mockResolvedValue(
+ 'Custom prompt content'
+ );
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ await service.run({
+ prompt: '/custom/prompt.md',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(fsPromises.readFile).toHaveBeenCalledWith(
+ '/custom/prompt.md',
+ 'utf-8'
+ );
+ });
+
+ it('should throw on empty custom prompt file', async () => {
+ vi.mocked(fsPromises.readFile).mockResolvedValue(' ');
+
+ await expect(
+ service.run({
+ prompt: '/custom/empty.md',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ })
+ ).rejects.toThrow('empty');
+ });
+ });
+ });
+
+ describe('parseCompletion (inlined)', () => {
+ let service: LoopService;
+ let parseCompletion: (
+ output: string,
+ exitCode: number
+ ) => { status: string; message?: string };
+
+ beforeEach(() => {
+ service = new LoopService(defaultOptions);
+ // Access private method
+ parseCompletion = (
+ service as unknown as {
+ parseCompletion: typeof parseCompletion;
+ }
+ ).parseCompletion.bind(service);
+ });
+
+ it('should detect complete marker', () => {
+ const result = parseCompletion(
+ '<loop-complete>ALL DONE</loop-complete>',
+ 0
+ );
+ expect(result.status).toBe('complete');
+ expect(result.message).toBe('ALL DONE');
+ });
+
+ it('should detect blocked marker', () => {
+ const result = parseCompletion('<loop-blocked>STUCK</loop-blocked>', 0);
+ expect(result.status).toBe('blocked');
+ expect(result.message).toBe('STUCK');
+ });
+
+ it('should return error on non-zero exit code', () => {
+ const result = parseCompletion('Some output', 1);
+ expect(result.status).toBe('error');
+ expect(result.message).toBe('Exit code 1');
+ });
+
+ it('should return success on zero exit code without markers', () => {
+ const result = parseCompletion('Regular output', 0);
+ expect(result.status).toBe('success');
+ });
+
+ it('should be case-insensitive for markers', () => {
+ const result = parseCompletion('<LOOP-COMPLETE>DONE</LOOP-COMPLETE>', 0);
+ expect(result.status).toBe('complete');
+ });
+
+ it('should trim whitespace from reason', () => {
+ const result = parseCompletion(
+ '<loop-complete> trimmed </loop-complete>',
+ 0
+ );
+ expect(result.message).toBe('trimmed');
+ });
+ });
+
+ describe('isPreset (inlined)', () => {
+ let service: LoopService;
+ let isPreset: (name: string) => boolean;
+
+ beforeEach(() => {
+ service = new LoopService(defaultOptions);
+ isPreset = (
+ service as unknown as { isPreset: (n: string) => boolean }
+ ).isPreset.bind(service);
+ });
+
+ it('should return true for default preset', () => {
+ expect(isPreset('default')).toBe(true);
+ });
+
+ it('should return true for test-coverage preset', () => {
+ expect(isPreset('test-coverage')).toBe(true);
+ });
+
+ it('should return true for linting preset', () => {
+ expect(isPreset('linting')).toBe(true);
+ });
+
+ it('should return true for duplication preset', () => {
+ expect(isPreset('duplication')).toBe(true);
+ });
+
+ it('should return true for entropy preset', () => {
+ expect(isPreset('entropy')).toBe(true);
+ });
+
+ it('should return false for unknown preset', () => {
+ expect(isPreset('unknown')).toBe(false);
+ });
+
+ it('should return false for file paths', () => {
+ expect(isPreset('/path/to/file.md')).toBe(false);
+ });
+ });
+
+ describe('buildContextHeader (inlined)', () => {
+ let service: LoopService;
+ let buildContextHeader: (
+ config: { iterations: number; progressFile: string; tag?: string },
+ iteration: number
+ ) => string;
+
+ beforeEach(() => {
+ service = new LoopService(defaultOptions);
+ buildContextHeader = (
+ service as unknown as {
+ buildContextHeader: typeof buildContextHeader;
+ }
+ ).buildContextHeader.bind(service);
+ });
+
+ it('should include iteration info', () => {
+ const header = buildContextHeader(
+ { iterations: 5, progressFile: '/test/progress.txt' },
+ 2
+ );
+ expect(header).toContain('iteration 2 of 5');
+ });
+
+ it('should include progress file reference', () => {
+ const header = buildContextHeader(
+ { iterations: 1, progressFile: '/test/progress.txt' },
+ 1
+ );
+ expect(header).toContain('@/test/progress.txt');
+ });
+
+ it('should include tasks file reference', () => {
+ const header = buildContextHeader(
+ { iterations: 1, progressFile: '/test/progress.txt' },
+ 1
+ );
+ expect(header).toContain('@.taskmaster/tasks/tasks.json');
+ });
+
+ it('should include tag filter when provided', () => {
+ const header = buildContextHeader(
+ { iterations: 1, progressFile: '/test/progress.txt', tag: 'feature-x' },
+ 1
+ );
+ expect(header).toContain('tag: feature-x');
+ });
+
+ it('should not include tag when not provided', () => {
+ const header = buildContextHeader(
+ { iterations: 1, progressFile: '/test/progress.txt' },
+ 1
+ );
+ expect(header).not.toContain('tag:');
+ });
+ });
+
+ describe('integration: stop during run', () => {
+ let service: LoopService;
+
+ beforeEach(() => {
+ service = new LoopService(defaultOptions);
+ });
+
+ it('should set isRunning to true during run', async () => {
+ let capturedIsRunning = false;
+ mockSpawnSync.mockImplementation(() => {
+ capturedIsRunning = service.isRunning;
+ return {
+ stdout: '',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ };
+ });
+
+ await service.run({
+ prompt: 'default',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(capturedIsRunning).toBe(true);
+ });
+
+ it('should set isRunning to false on completion', async () => {
+ mockSpawnSync.mockReturnValue({
+ stdout: '',
+ stderr: '',
+ status: 0,
+ signal: null,
+ pid: 123,
+ output: []
+ });
+
+ await service.run({
+ prompt: 'default',
+ iterations: 1,
+ sleepSeconds: 0,
+ progressFile: '/test/progress.txt'
+ });
+
+ expect(service.isRunning).toBe(false);
+ });
+ });
+});
diff --git a/packages/tm-core/src/modules/loop/services/loop.service.ts b/packages/tm-core/src/modules/loop/services/loop.service.ts
new file mode 100644
index 00000000..a58524b8
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/services/loop.service.ts
@@ -0,0 +1,251 @@
+/**
+ * @fileoverview Loop Service - Orchestrates running Claude Code in Docker sandbox iterations
+ */
+
+import { spawnSync } from 'node:child_process';
+import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { PRESETS, isPreset as checkIsPreset } from '../presets/index.js';
+import type {
+ LoopConfig,
+ LoopIteration,
+ LoopPreset,
+ LoopResult
+} from '../types.js';
+
+export interface LoopServiceOptions {
+ projectRoot: string;
+}
+
+export class LoopService {
+ private readonly projectRoot: string;
+ private _isRunning = false;
+
+ constructor(options: LoopServiceOptions) {
+ this.projectRoot = options.projectRoot;
+ }
+
+ getProjectRoot(): string {
+ return this.projectRoot;
+ }
+
+ get isRunning(): boolean {
+ return this._isRunning;
+ }
+
+ /** Check if Docker sandbox auth is ready */
+ checkSandboxAuth(): boolean {
+ const result = spawnSync(
+ 'docker',
+ ['sandbox', 'run', 'claude', '-p', 'Say OK'],
+ {
+ cwd: this.projectRoot,
+ timeout: 30000,
+ encoding: 'utf-8',
+ stdio: ['inherit', 'pipe', 'pipe'] // stdin from terminal, capture stdout/stderr
+ }
+ );
+ const output = (result.stdout || '') + (result.stderr || '');
+ return output.toLowerCase().includes('ok');
+ }
+
+ /** Run interactive Docker sandbox session for user authentication */
+ runInteractiveAuth(): void {
+ spawnSync(
+ 'docker',
+ [
+ 'sandbox',
+ 'run',
+ 'claude',
+ "You're authenticated! Press Ctrl+C to continue."
+ ],
+ {
+ cwd: this.projectRoot,
+ stdio: 'inherit'
+ }
+ );
+ }
+
+ /** Run a loop with the given configuration */
+ async run(config: LoopConfig): Promise<LoopResult> {
+ this._isRunning = true;
+ const iterations: LoopIteration[] = [];
+ let tasksCompleted = 0;
+
+ await this.initProgressFile(config);
+
+ for (let i = 1; i <= config.iterations && this._isRunning; i++) {
+ // Show iteration header
+ console.log();
+ console.log(`━━━ Iteration ${i} of ${config.iterations} ━━━`);
+
+ const prompt = await this.buildPrompt(config, i);
+ const iteration = this.executeIteration(prompt, i);
+ iterations.push(iteration);
+
+ // Check for early exit conditions
+ if (iteration.status === 'complete') {
+ return this.finalize(
+ config,
+ iterations,
+ tasksCompleted + 1,
+ 'all_complete'
+ );
+ }
+ if (iteration.status === 'blocked') {
+ return this.finalize(config, iterations, tasksCompleted, 'blocked');
+ }
+ if (iteration.status === 'success') {
+ tasksCompleted++;
+ }
+
+ // Sleep between iterations (except last)
+ if (i < config.iterations && config.sleepSeconds > 0) {
+ await new Promise((r) => setTimeout(r, config.sleepSeconds * 1000));
+ }
+ }
+
+ return this.finalize(config, iterations, tasksCompleted, 'max_iterations');
+ }
+
+ /** Stop the loop after current iteration completes */
+ stop(): void {
+ this._isRunning = false;
+ }
+
+ // ========== Private Helpers ==========
+
+ private async finalize(
+ config: LoopConfig,
+ iterations: LoopIteration[],
+ tasksCompleted: number,
+ finalStatus: LoopResult['finalStatus']
+ ): Promise<LoopResult> {
+ this._isRunning = false;
+ const result: LoopResult = {
+ iterations,
+ totalIterations: iterations.length,
+ tasksCompleted,
+ finalStatus
+ };
+ await this.appendFinalSummary(config.progressFile, result);
+ return result;
+ }
+
+ private async initProgressFile(config: LoopConfig): Promise<void> {
+ await mkdir(path.dirname(config.progressFile), { recursive: true });
+ const tagLine = config.tag ? `# Tag: ${config.tag}\n` : '';
+ await writeFile(
+ config.progressFile,
+ `# Task Master Loop Progress
+# Started: ${new Date().toISOString()}
+# Preset: ${config.prompt}
+# Max Iterations: ${config.iterations}
+${tagLine}
+---
+
+`,
+ 'utf-8'
+ );
+ }
+
+ private async appendFinalSummary(
+ file: string,
+ result: LoopResult
+ ): Promise<void> {
+ await appendFile(
+ file,
+ `
+---
+# Loop Complete: ${new Date().toISOString()}
+- Total iterations: ${result.totalIterations}
+- Tasks completed: ${result.tasksCompleted}
+- Final status: ${result.finalStatus}
+`,
+ 'utf-8'
+ );
+ }
+
+ private isPreset(name: string): name is LoopPreset {
+ return checkIsPreset(name);
+ }
+
+ private async resolvePrompt(prompt: string): Promise<string> {
+ if (this.isPreset(prompt)) {
+ return PRESETS[prompt];
+ }
+ const content = await readFile(prompt, 'utf-8');
+ if (!content.trim()) {
+ throw new Error(`Custom prompt file '${prompt}' is empty`);
+ }
+ return content;
+ }
+
+ private buildContextHeader(config: LoopConfig, iteration: number): string {
+ const tagInfo = config.tag ? ` (tag: ${config.tag})` : '';
+ return `@${config.progressFile} @.taskmaster/tasks/tasks.json @CLAUDE.md
+
+Loop iteration ${iteration} of ${config.iterations}${tagInfo}`;
+ }
+
+ private async buildPrompt(
+ config: LoopConfig,
+ iteration: number
+ ): Promise<string> {
+ const basePrompt = await this.resolvePrompt(config.prompt);
+ return `${this.buildContextHeader(config, iteration)}\n\n${basePrompt}`;
+ }
+
+ private parseCompletion(
+ output: string,
+ exitCode: number
+ ): { status: LoopIteration['status']; message?: string } {
+ const completeMatch = output.match(
+ /<loop-complete>([^<]*)<\/loop-complete>/i
+ );
+ if (completeMatch)
+ return { status: 'complete', message: completeMatch[1].trim() };
+
+ const blockedMatch = output.match(/<loop-blocked>([^<]*)<\/loop-blocked>/i);
+ if (blockedMatch)
+ return { status: 'blocked', message: blockedMatch[1].trim() };
+
+ if (exitCode !== 0)
+ return { status: 'error', message: `Exit code ${exitCode}` };
+ return { status: 'success' };
+ }
+
+ private executeIteration(
+ prompt: string,
+ iterationNum: number
+ ): LoopIteration {
+ const startTime = Date.now();
+
+ const result = spawnSync(
+ 'docker',
+ ['sandbox', 'run', 'claude', '-p', prompt],
+ {
+ cwd: this.projectRoot,
+ encoding: 'utf-8',
+ maxBuffer: 50 * 1024 * 1024, // 50MB buffer
+ stdio: ['inherit', 'pipe', 'pipe']
+ }
+ );
+
+ const output = (result.stdout || '') + (result.stderr || '');
+
+ // Print output to console (spawnSync with pipe captures but doesn't display)
+ if (output) console.log(output);
+
+ const { status, message } = this.parseCompletion(
+ output,
+ result.status ?? 1
+ );
+ return {
+ iteration: iterationNum,
+ status,
+ duration: Date.now() - startTime,
+ message
+ };
+ }
+}
diff --git a/packages/tm-core/src/modules/loop/types.spec.ts b/packages/tm-core/src/modules/loop/types.spec.ts
new file mode 100644
index 00000000..d8c485a7
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/types.spec.ts
@@ -0,0 +1,159 @@
+/**
+ * @fileoverview Tests for loop module type definitions
+ */
+
+import { describe, it, expect } from 'vitest';
+import type {
+ LoopPreset,
+ LoopConfig,
+ LoopIteration,
+ LoopResult
+} from './types.js';
+
+// Also verify types are exported from the barrel
+import type {
+ LoopPreset as BarrelLoopPreset,
+ LoopConfig as BarrelLoopConfig,
+ LoopIteration as BarrelLoopIteration,
+ LoopResult as BarrelLoopResult
+} from './index.js';
+
+describe('Loop Types', () => {
+ describe('LoopPreset', () => {
+ it('accepts valid preset values', () => {
+ // TypeScript compile-time check - these should all be valid
+ const presets: LoopPreset[] = [
+ 'default',
+ 'test-coverage',
+ 'linting',
+ 'duplication',
+ 'entropy'
+ ];
+ expect(presets).toHaveLength(5);
+ });
+ });
+
+ describe('LoopConfig', () => {
+ it('accepts valid config with required fields', () => {
+ const config: LoopConfig = {
+ iterations: 10,
+ prompt: 'default',
+ progressFile: '/path/to/progress.txt',
+ sleepSeconds: 5
+ };
+ expect(config.iterations).toBe(10);
+ expect(config.prompt).toBe('default');
+ expect(config.progressFile).toBe('/path/to/progress.txt');
+ expect(config.sleepSeconds).toBe(5);
+ });
+
+ it('accepts config with all optional fields', () => {
+ const config: LoopConfig = {
+ iterations: 5,
+ prompt: 'test-coverage',
+ progressFile: '/progress.txt',
+ sleepSeconds: 3,
+ tag: 'feature-branch'
+ };
+ expect(config.tag).toBe('feature-branch');
+ });
+
+ it('accepts custom prompt string', () => {
+ const config: LoopConfig = {
+ iterations: 1,
+ prompt: '/path/to/custom-prompt.txt',
+ progressFile: '/progress.txt',
+ sleepSeconds: 0
+ };
+ expect(config.prompt).toBe('/path/to/custom-prompt.txt');
+ });
+ });
+
+ describe('LoopIteration', () => {
+ it('accepts valid iteration with minimal fields', () => {
+ const iteration: LoopIteration = {
+ iteration: 1,
+ status: 'success'
+ };
+ expect(iteration.iteration).toBe(1);
+ expect(iteration.status).toBe('success');
+ });
+
+ it('accepts iteration with all fields', () => {
+ const iteration: LoopIteration = {
+ iteration: 3,
+ taskId: '1.2',
+ status: 'blocked',
+ message: 'Waiting on external API',
+ duration: 45000
+ };
+ expect(iteration.taskId).toBe('1.2');
+ expect(iteration.message).toBe('Waiting on external API');
+ expect(iteration.duration).toBe(45000);
+ });
+
+ it('accepts all status values', () => {
+ const statuses: LoopIteration['status'][] = [
+ 'success',
+ 'blocked',
+ 'error',
+ 'complete'
+ ];
+ expect(statuses).toHaveLength(4);
+ });
+ });
+
+ describe('LoopResult', () => {
+ it('accepts valid loop result', () => {
+ const result: LoopResult = {
+ iterations: [
+ { iteration: 1, status: 'success', taskId: '1' },
+ { iteration: 2, status: 'success', taskId: '2' }
+ ],
+ totalIterations: 2,
+ tasksCompleted: 2,
+ finalStatus: 'all_complete'
+ };
+ expect(result.iterations).toHaveLength(2);
+ expect(result.totalIterations).toBe(2);
+ expect(result.tasksCompleted).toBe(2);
+ expect(result.finalStatus).toBe('all_complete');
+ });
+
+ it('accepts all final status values', () => {
+ const statuses: LoopResult['finalStatus'][] = [
+ 'all_complete',
+ 'max_iterations',
+ 'blocked',
+ 'error'
+ ];
+ expect(statuses).toHaveLength(4);
+ });
+ });
+
+ describe('Barrel exports from index.ts', () => {
+ it('exports all types from barrel', () => {
+ // Verify types are accessible from barrel export
+ const preset: BarrelLoopPreset = 'default';
+ const config: BarrelLoopConfig = {
+ iterations: 5,
+ prompt: preset,
+ progressFile: '/progress.txt',
+ sleepSeconds: 2
+ };
+ const iteration: BarrelLoopIteration = {
+ iteration: 1,
+ status: 'success'
+ };
+ const result: BarrelLoopResult = {
+ iterations: [iteration],
+ totalIterations: 1,
+ tasksCompleted: 1,
+ finalStatus: 'all_complete'
+ };
+
+ expect(config.prompt).toBe('default');
+ expect(result.iterations).toHaveLength(1);
+ });
+ });
+});
diff --git a/packages/tm-core/src/modules/loop/types.ts b/packages/tm-core/src/modules/loop/types.ts
new file mode 100644
index 00000000..901276e8
--- /dev/null
+++ b/packages/tm-core/src/modules/loop/types.ts
@@ -0,0 +1,59 @@
+/**
+ * @fileoverview Type definitions for the loop module
+ */
+
+/**
+ * Available preset loop prompts
+ */
+export type LoopPreset =
+ | 'default'
+ | 'test-coverage'
+ | 'linting'
+ | 'duplication'
+ | 'entropy';
+
+/**
+ * Configuration options for a loop execution
+ */
+export interface LoopConfig {
+ /** Number of iterations to run */
+ iterations: number;
+ /** Preset name or custom prompt file path */
+ prompt: LoopPreset | string;
+ /** Path to the progress file */
+ progressFile: string;
+ /** Seconds to sleep between iterations */
+ sleepSeconds: number;
+ /** Tag context to operate on (optional) */
+ tag?: string;
+}
+
+/**
+ * Result of a single loop iteration
+ */
+export interface LoopIteration {
+ /** Iteration number (1-indexed) */
+ iteration: number;
+ /** ID of the task worked on (if any) */
+ taskId?: string;
+ /** Status of this iteration */
+ status: 'success' | 'blocked' | 'error' | 'complete';
+ /** Optional message describing the result */
+ message?: string;
+ /** Duration of this iteration in milliseconds */
+ duration?: number;
+}
+
+/**
+ * Overall result of a loop execution
+ */
+export interface LoopResult {
+ /** Array of iteration results */
+ iterations: LoopIteration[];
+ /** Total number of iterations executed */
+ totalIterations: number;
+ /** Number of tasks completed successfully */
+ tasksCompleted: number;
+ /** Final status of the loop */
+ finalStatus: 'all_complete' | 'max_iterations' | 'blocked' | 'error';
+}
diff --git a/packages/tm-core/src/modules/tasks/tasks-domain.ts b/packages/tm-core/src/modules/tasks/tasks-domain.ts
index 534487df..a74ca46f 100644
--- a/packages/tm-core/src/modules/tasks/tasks-domain.ts
+++ b/packages/tm-core/src/modules/tasks/tasks-domain.ts
@@ -154,6 +154,40 @@ export class TasksDomain {
return this.taskService.getNextTask(tag);
}
+ /**
+ * Get count of tasks and their subtasks matching a status
+ * Useful for determining work remaining, progress tracking, or setting loop iterations
+ *
+ * @param status - Task status to count (e.g., 'pending', 'done', 'in-progress')
+ * @param tag - Optional tag to filter tasks
+ * @returns Total count of matching tasks + matching subtasks
+ */
+ async getCount(status: TaskStatus, tag?: string): Promise<number> {
+ // Fetch ALL tasks to ensure we count subtasks across all parent tasks
+ // (a parent task may have different status than its subtasks)
+ const result = await this.list({ tag });
+
+ let count = 0;
+ for (const task of result.tasks) {
+ // Count the task if it matches the status
+ if (task.status === status) {
+ count++;
+ }
+
+ // Count subtasks with matching status
+ if (task.subtasks && task.subtasks.length > 0) {
+ for (const subtask of task.subtasks) {
+ // For pending, also count subtasks without status (default to pending)
+ if (subtask.status === status || (status === 'pending' && !subtask.status)) {
+ count++;
+ }
+ }
+ }
+ }
+
+ return count;
+ }
+
// ========== Task Status Management ==========
/**
diff --git a/packages/tm-core/src/tm-core.ts b/packages/tm-core/src/tm-core.ts
index 510da421..b80ba204 100644
--- a/packages/tm-core/src/tm-core.ts
+++ b/packages/tm-core/src/tm-core.ts
@@ -9,6 +9,7 @@ import { ConfigDomain } from './modules/config/config-domain.js';
import { ConfigManager } from './modules/config/managers/config-manager.js';
import { GitDomain } from './modules/git/git-domain.js';
import { IntegrationDomain } from './modules/integration/integration-domain.js';
+import { LoopDomain } from './modules/loop/loop-domain.js';
import { TasksDomain } from './modules/tasks/tasks-domain.js';
import { WorkflowDomain } from './modules/workflow/workflow-domain.js';
@@ -87,6 +88,7 @@ export class TmCore {
private _git!: GitDomain;
private _config!: ConfigDomain;
private _integration!: IntegrationDomain;
+ private _loop!: LoopDomain;
// Public readonly getters
get tasks(): TasksDomain {
@@ -107,6 +109,9 @@ export class TmCore {
get integration(): IntegrationDomain {
return this._integration;
}
+ get loop(): LoopDomain {
+ return this._loop;
+ }
get logger(): Logger {
return this._logger;
}
@@ -176,6 +181,7 @@ export class TmCore {
this._git = new GitDomain(this._projectPath);
this._config = new ConfigDomain(this._configManager);
this._integration = new IntegrationDomain(this._configManager);
+ this._loop = new LoopDomain(this._configManager);
// Initialize domains that need async setup
await this._tasks.initialize();
diff --git a/packages/tm-core/tests/integration/loop/loop-core-exports.test.ts b/packages/tm-core/tests/integration/loop/loop-core-exports.test.ts
new file mode 100644
index 00000000..95e7709b
--- /dev/null
+++ b/packages/tm-core/tests/integration/loop/loop-core-exports.test.ts
@@ -0,0 +1,155 @@
+/**
+ * @fileoverview Integration tests for loop type exports from @tm/core
+ *
+ * Verifies that all loop types and the LoopDomain class are correctly
+ * exported from the main @tm/core index.ts entry point.
+ *
+ * @integration
+ */
+
+import { describe, expect, it } from 'vitest';
+
+// Import types and class from @tm/core main entry point
+import {
+ LoopDomain,
+ type LoopPreset,
+ type LoopConfig,
+ type LoopIteration,
+ type LoopResult
+} from '../../../src/index.js';
+import type { ConfigManager } from '../../../src/modules/config/managers/config-manager.js';
+
+// Helper to create mock ConfigManager
+function createMockConfigManager(projectRoot = '/test/project'): ConfigManager {
+ return {
+ getProjectRoot: () => projectRoot
+ } as unknown as ConfigManager;
+}
+
+describe('Loop Exports from @tm/core', () => {
+ describe('LoopDomain Class Export', () => {
+ it('should export LoopDomain class', () => {
+ expect(LoopDomain).toBeDefined();
+ expect(typeof LoopDomain).toBe('function');
+ });
+
+ it('should be constructible', () => {
+ const mockConfigManager = createMockConfigManager();
+ const domain = new LoopDomain(mockConfigManager);
+ expect(domain).toBeInstanceOf(LoopDomain);
+ });
+ });
+
+ describe('Loop Type Exports', () => {
+ it('should export LoopPreset type (compile-time verification)', () => {
+ // TypeScript compilation verifies these types exist
+ const preset: LoopPreset = 'default';
+ expect(preset).toBe('default');
+
+ // Verify all valid presets
+ const validPresets: LoopPreset[] = [
+ 'default',
+ 'test-coverage',
+ 'linting',
+ 'duplication',
+ 'entropy'
+ ];
+ expect(validPresets).toHaveLength(5);
+ });
+
+ it('should export LoopConfig type (compile-time verification)', () => {
+ const config: LoopConfig = {
+ iterations: 10,
+ prompt: 'default',
+ sleepSeconds: 5,
+ progressFile: '/path/to/progress.txt'
+ };
+ expect(config.iterations).toBe(10);
+ expect(config.prompt).toBe('default');
+ expect(config.sleepSeconds).toBe(5);
+ expect(config.progressFile).toBe('/path/to/progress.txt');
+ });
+
+ it('should export LoopConfig type with optional fields', () => {
+ const configWithTag: LoopConfig = {
+ iterations: 5,
+ prompt: '/custom/prompt.md',
+ sleepSeconds: 10,
+ progressFile: '/progress.txt',
+ tag: 'feature-branch'
+ };
+ expect(configWithTag.tag).toBe('feature-branch');
+ });
+
+ it('should export LoopIteration type (compile-time verification)', () => {
+ const iteration: LoopIteration = {
+ iteration: 1,
+ status: 'success',
+ taskId: 'task-1',
+ message: 'Task completed successfully',
+ duration: 1000
+ };
+ expect(iteration.iteration).toBe(1);
+ expect(iteration.status).toBe('success');
+ expect(iteration.taskId).toBe('task-1');
+ });
+
+ it('should export LoopIteration with all status values', () => {
+ const statuses: LoopIteration['status'][] = [
+ 'success',
+ 'complete',
+ 'blocked',
+ 'error'
+ ];
+ expect(statuses).toContain('success');
+ expect(statuses).toContain('complete');
+ expect(statuses).toContain('blocked');
+ expect(statuses).toContain('error');
+ });
+
+ it('should export LoopResult type (compile-time verification)', () => {
+ const result: LoopResult = {
+ totalIterations: 3,
+ tasksCompleted: 5,
+ finalStatus: 'all_complete',
+ iterations: []
+ };
+ expect(result.totalIterations).toBe(3);
+ expect(result.finalStatus).toBe('all_complete');
+ expect(result.tasksCompleted).toBe(5);
+ });
+
+ it('should export LoopResult with all finalStatus values', () => {
+ const finalStatuses: LoopResult['finalStatus'][] = [
+ 'all_complete',
+ 'max_iterations',
+ 'blocked',
+ 'error'
+ ];
+ expect(finalStatuses).toContain('all_complete');
+ expect(finalStatuses).toContain('max_iterations');
+ expect(finalStatuses).toContain('blocked');
+ expect(finalStatuses).toContain('error');
+ });
+ });
+
+ describe('Export Usability', () => {
+ it('should support typical import patterns', () => {
+ // This test verifies that the imports at the top of this file work
+ // If the imports fail, this test file won't even compile
+ expect(true).toBe(true);
+ });
+
+ it('should allow creating LoopDomain with valid config access', () => {
+ const mockConfigManager = createMockConfigManager();
+ const domain = new LoopDomain(mockConfigManager);
+
+ // Verify domain has expected methods
+ expect(typeof domain.isPreset).toBe('function');
+ expect(typeof domain.resolvePrompt).toBe('function');
+ expect(typeof domain.getAvailablePresets).toBe('function');
+ expect(typeof domain.getIsRunning).toBe('function');
+ expect(typeof domain.stop).toBe('function');
+ });
+ });
+});
diff --git a/packages/tm-core/tests/integration/loop/loop-domain.test.ts b/packages/tm-core/tests/integration/loop/loop-domain.test.ts
new file mode 100644
index 00000000..b3007e2d
--- /dev/null
+++ b/packages/tm-core/tests/integration/loop/loop-domain.test.ts
@@ -0,0 +1,218 @@
+/**
+ * @fileoverview Integration tests for LoopDomain facade
+ *
+ * Tests the LoopDomain public API and its integration with:
+ * - Preset resolution (using simplified preset exports)
+ * - Index.ts barrel export accessibility
+ *
+ * @integration
+ */
+
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import {
+ LoopDomain,
+ PRESET_NAMES,
+ PRESETS,
+ getPreset,
+ isPreset,
+ type LoopPreset
+} from '../../../src/modules/loop/index.js';
+import type { ConfigManager } from '../../../src/modules/config/managers/config-manager.js';
+
+// Mock ConfigManager factory
+function createMockConfigManager(projectRoot = '/test/project'): ConfigManager {
+ return {
+ getProjectRoot: vi.fn().mockReturnValue(projectRoot)
+ } as unknown as ConfigManager;
+}
+
+describe('LoopDomain Integration', () => {
+ describe('Barrel Export Accessibility', () => {
+ it('should export LoopDomain from index.ts', () => {
+ expect(LoopDomain).toBeDefined();
+ expect(typeof LoopDomain).toBe('function');
+ });
+
+ it('should be constructible with ConfigManager', () => {
+ const configManager = createMockConfigManager();
+ const domain = new LoopDomain(configManager);
+ expect(domain).toBeInstanceOf(LoopDomain);
+ });
+
+ it('should export preset utilities alongside LoopDomain', () => {
+ expect(PRESET_NAMES).toBeDefined();
+ expect(PRESETS).toBeDefined();
+ expect(getPreset).toBeDefined();
+ expect(isPreset).toBeDefined();
+ });
+ });
+
+ describe('Preset Resolution with Real Presets', () => {
+ let domain: LoopDomain;
+
+ beforeEach(() => {
+ const configManager = createMockConfigManager();
+ domain = new LoopDomain(configManager);
+ });
+
+ it('should resolve all presets', async () => {
+ const expectedPresets: LoopPreset[] = [
+ 'default',
+ 'test-coverage',
+ 'linting',
+ 'duplication',
+ 'entropy'
+ ];
+
+ for (const preset of expectedPresets) {
+ const content = await domain.resolvePrompt(preset);
+ expect(content).toBeTruthy();
+ expect(content.length).toBeGreaterThan(100);
+ expect(content).toContain('<loop-complete>');
+ }
+ });
+
+ it('should return consistent content between isPreset and resolvePrompt', async () => {
+ const presets = domain.getAvailablePresets();
+
+ for (const preset of presets) {
+ expect(domain.isPreset(preset)).toBe(true);
+ const content = await domain.resolvePrompt(preset);
+ expect(content).toBeTruthy();
+ }
+ });
+
+ it('should correctly identify non-presets', () => {
+ expect(domain.isPreset('/path/to/custom.md')).toBe(false);
+ expect(domain.isPreset('my-custom-preset')).toBe(false);
+ expect(domain.isPreset('')).toBe(false);
+ });
+
+ it('should match preset content with getPreset utility', async () => {
+ for (const preset of PRESET_NAMES) {
+ const fromDomain = await domain.resolvePrompt(preset);
+ const fromUtility = getPreset(preset);
+ expect(fromDomain).toBe(fromUtility);
+ }
+ });
+ });
+
+ describe('Config Building Integration', () => {
+ it('should build config with correct projectRoot in progressFile', () => {
+ const configManager = createMockConfigManager('/my/custom/project');
+ const domain = new LoopDomain(configManager);
+
+ // Access private buildConfig via run preparation
+ // Test indirectly by checking the domain was created with correct projectRoot
+ expect(domain.getAvailablePresets()).toHaveLength(5);
+
+ // Verify preset resolution still works
+ expect(domain.isPreset('default')).toBe(true);
+ });
+
+ it('should handle multiple LoopDomain instances independently', () => {
+ const domain1 = new LoopDomain(createMockConfigManager('/project1'));
+ const domain2 = new LoopDomain(createMockConfigManager('/project2'));
+
+ // Both should work independently
+ expect(domain1.isPreset('default')).toBe(true);
+ expect(domain2.isPreset('default')).toBe(true);
+
+ // Each should have its own preset values
+ expect(domain1.getAvailablePresets()).toEqual(
+ domain2.getAvailablePresets()
+ );
+ });
+ });
+
+ describe('Run/Stop Lifecycle', () => {
+ let domain: LoopDomain;
+
+ beforeEach(() => {
+ domain = new LoopDomain(createMockConfigManager());
+ });
+
+ it('should report not running initially', () => {
+ expect(domain.getIsRunning()).toBe(false);
+ });
+
+ it('should handle stop when no loop is running', () => {
+ expect(() => domain.stop()).not.toThrow();
+ expect(domain.getIsRunning()).toBe(false);
+ });
+
+ it('should allow multiple stop calls without error', () => {
+ domain.stop();
+ domain.stop();
+ domain.stop();
+ expect(domain.getIsRunning()).toBe(false);
+ });
+ });
+
+ describe('Preset Content with Completion Markers', () => {
+ let domain: LoopDomain;
+
+ beforeEach(() => {
+ domain = new LoopDomain(createMockConfigManager());
+ });
+
+ it('should resolve presets with detectable completion markers', async () => {
+ for (const preset of domain.getAvailablePresets()) {
+ const content = await domain.resolvePrompt(preset);
+
+ // All presets should have a <loop-complete> marker
+ expect(content).toContain('<loop-complete>');
+
+ // Extract the marker from content
+ const match = content.match(/<loop-complete>([^<]+)<\/loop-complete>/);
+ expect(match).toBeTruthy();
+ expect(match![1].length).toBeGreaterThan(0);
+ }
+ });
+
+ it('should resolve default preset with both complete and blocked markers', async () => {
+ const content = await domain.resolvePrompt('default');
+
+ expect(content).toContain('<loop-complete>');
+ expect(content).toContain('<loop-blocked>');
+ });
+ });
+
+ describe('Custom Prompt File Resolution', () => {
+ let domain: LoopDomain;
+
+ beforeEach(() => {
+ domain = new LoopDomain(createMockConfigManager());
+ });
+
+ it('should resolve custom file path with provided readFile callback', async () => {
+ const customContent =
+ '# My Custom Loop Prompt\n<loop-complete>CUSTOM</loop-complete>';
+ const mockReadFile = vi.fn().mockResolvedValue(customContent);
+
+ const content = await domain.resolvePrompt(
+ '/path/to/custom.md',
+ mockReadFile
+ );
+
+ expect(mockReadFile).toHaveBeenCalledWith('/path/to/custom.md');
+ expect(content).toBe(customContent);
+ });
+
+ it('should throw for custom path without readFile callback', async () => {
+ await expect(domain.resolvePrompt('/path/to/custom.md')).rejects.toThrow(
+ 'Custom prompt file requires readFile callback'
+ );
+ });
+
+ it('should propagate readFile errors', async () => {
+ const mockReadFile = vi
+ .fn()
+ .mockRejectedValue(new Error('File not found'));
+
+ await expect(
+ domain.resolvePrompt('/nonexistent/file.md', mockReadFile)
+ ).rejects.toThrow('File not found');
+ });
+ });
+});
diff --git a/packages/tm-core/tests/integration/loop/loop-preset-accessibility.test.ts b/packages/tm-core/tests/integration/loop/loop-preset-accessibility.test.ts
new file mode 100644
index 00000000..a6644f60
--- /dev/null
+++ b/packages/tm-core/tests/integration/loop/loop-preset-accessibility.test.ts
@@ -0,0 +1,243 @@
+/**
+ * @fileoverview Integration tests for preset accessibility
+ *
+ * Tests that preset content is accessible without filesystem dependencies,
+ * validating that the inlined preset approach works correctly for both
+ * development and bundled distribution contexts.
+ *
+ * These tests verify:
+ * - All 5 presets can be loaded without filesystem access
+ * - Preset content contains required markers for loop completion detection
+ * - Preset content structure is valid and usable by the loop system
+ *
+ * @integration
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ PRESETS,
+ PRESET_NAMES,
+ getPreset,
+ isPreset,
+ type LoopPreset
+} from '../../../src/modules/loop/index.js';
+
+describe('Preset Accessibility Integration', () => {
+ describe('Preset Accessibility', () => {
+ it('should load all 5 presets without filesystem access', () => {
+ // This test verifies that presets are inlined and don't require fs
+ expect(PRESET_NAMES).toHaveLength(5);
+
+ for (const presetName of PRESET_NAMES) {
+ const content = getPreset(presetName);
+ expect(content).toBeTruthy();
+ expect(typeof content).toBe('string');
+ expect(content.length).toBeGreaterThan(100);
+ }
+ });
+
+ it('should have all expected preset names available', () => {
+ const expectedPresets: LoopPreset[] = [
+ 'default',
+ 'test-coverage',
+ 'linting',
+ 'duplication',
+ 'entropy'
+ ];
+
+ for (const preset of expectedPresets) {
+ expect(isPreset(preset)).toBe(true);
+ }
+ });
+
+ it('should have PRESETS record with all presets', () => {
+ expect(Object.keys(PRESETS)).toHaveLength(5);
+ expect(PRESETS['default']).toBeTruthy();
+ expect(PRESETS['test-coverage']).toBeTruthy();
+ expect(PRESETS['linting']).toBeTruthy();
+ expect(PRESETS['duplication']).toBeTruthy();
+ expect(PRESETS['entropy']).toBeTruthy();
+ });
+
+ it('should have getPreset return same content as PRESETS record', () => {
+ for (const presetName of PRESET_NAMES) {
+ expect(getPreset(presetName)).toBe(PRESETS[presetName]);
+ }
+ });
+ });
+
+ describe('Preset Content Structure', () => {
+ it('all presets should contain loop-complete marker', () => {
+ for (const presetName of PRESET_NAMES) {
+ const content = getPreset(presetName);
+ expect(content).toContain('<loop-complete>');
+ }
+ });
+
+ it('default preset should contain both complete and blocked markers', () => {
+ const content = getPreset('default');
+ expect(content).toContain('<loop-complete>');
+ expect(content).toContain('<loop-blocked>');
+ });
+
+ it('all presets should reference progress file', () => {
+ for (const presetName of PRESET_NAMES) {
+ const content = getPreset(presetName);
+ // Default uses "progress file", others use "loop-progress"
+ expect(content).toMatch(/loop-progress|progress file/i);
+ }
+ });
+
+ it('all presets should emphasize single-task constraint', () => {
+ for (const presetName of PRESET_NAMES) {
+ const content = getPreset(presetName);
+ // All presets should mention completing ONE task/test/fix per session
+ expect(content).toMatch(/\bONE\b/i);
+ }
+ });
+
+ it('each preset should have unique completion reason', () => {
+ const completionReasons = new Set<string>();
+
+ for (const presetName of PRESET_NAMES) {
+ const content = getPreset(presetName);
+ // Extract the completion reason from <loop-complete>REASON</loop-complete>
+ const match = content.match(/<loop-complete>([^<]+)<\/loop-complete>/);
+ expect(match).toBeTruthy();
+ if (match) {
+ completionReasons.add(match[1]);
+ }
+ }
+
+ // All presets should have unique completion reasons
+ expect(completionReasons.size).toBe(PRESET_NAMES.length);
+ });
+ });
+
+ describe('Completion Marker Detection', () => {
+ // Simple regex-based completion marker detection (inlined from deleted LoopCompletionService)
+ const parseOutput = (output: string) => {
+ const completeMatch = output.match(
+ /<loop-complete>([^<]*)<\/loop-complete>/i
+ );
+ const blockedMatch = output.match(
+ /<loop-blocked>([^<]*)<\/loop-blocked>/i
+ );
+
+ return {
+ isComplete: !!completeMatch,
+ isBlocked: !!blockedMatch,
+ marker: completeMatch
+ ? { type: 'complete' as const, reason: completeMatch[1] }
+ : blockedMatch
+ ? { type: 'blocked' as const, reason: blockedMatch[1] }
+ : null
+ };
+ };
+
+ it('should detect completion markers from preset content', () => {
+ // Simulate agent output containing the completion marker from default preset
+ const agentOutput = `
+I have completed all the tasks in the backlog. There are no more pending tasks to work on.
+
+<loop-complete>ALL_TASKS_DONE</loop-complete>
+`;
+
+ const result = parseOutput(agentOutput);
+ expect(result.isComplete).toBe(true);
+ expect(result.marker?.type).toBe('complete');
+ expect(result.marker?.reason).toBe('ALL_TASKS_DONE');
+ });
+
+ it('should detect blocked marker from default preset', () => {
+ const agentOutput = `
+I cannot proceed because the API key is not configured.
+
+<loop-blocked>MISSING_API_KEY</loop-blocked>
+`;
+
+ const result = parseOutput(agentOutput);
+ expect(result.isBlocked).toBe(true);
+ expect(result.marker?.type).toBe('blocked');
+ expect(result.marker?.reason).toBe('MISSING_API_KEY');
+ });
+
+ it('should detect test-coverage preset completion marker', () => {
+ const agentOutput = `
+Coverage has reached 95% which exceeds our target of 80%.
+
+<loop-complete>COVERAGE_TARGET</loop-complete>
+`;
+
+ const result = parseOutput(agentOutput);
+ expect(result.isComplete).toBe(true);
+ expect(result.marker?.reason).toBe('COVERAGE_TARGET');
+ });
+
+ it('should detect linting preset completion marker', () => {
+ const agentOutput = `
+All lint errors and type errors have been fixed.
+
+<loop-complete>ZERO_ERRORS</loop-complete>
+`;
+
+ const result = parseOutput(agentOutput);
+ expect(result.isComplete).toBe(true);
+ expect(result.marker?.reason).toBe('ZERO_ERRORS');
+ });
+
+ it('should detect duplication preset completion marker', () => {
+ const agentOutput = `
+Code duplication is now at 2.5%, below the 3% threshold.
+
+<loop-complete>LOW_DUPLICATION</loop-complete>
+`;
+
+ const result = parseOutput(agentOutput);
+ expect(result.isComplete).toBe(true);
+ expect(result.marker?.reason).toBe('LOW_DUPLICATION');
+ });
+
+ it('should detect entropy preset completion marker', () => {
+ const agentOutput = `
+No significant code smells remain in the codebase.
+
+<loop-complete>LOW_ENTROPY</loop-complete>
+`;
+
+ const result = parseOutput(agentOutput);
+ expect(result.isComplete).toBe(true);
+ expect(result.marker?.reason).toBe('LOW_ENTROPY');
+ });
+ });
+
+ describe('isPreset Consistency', () => {
+ it('should return true for valid presets', () => {
+ const validPresets = [
+ 'default',
+ 'test-coverage',
+ 'linting',
+ 'duplication',
+ 'entropy'
+ ];
+
+ for (const name of validPresets) {
+ expect(isPreset(name)).toBe(true);
+ }
+ });
+
+ it('should return false for invalid presets', () => {
+ const invalidPresets = [
+ 'invalid',
+ 'custom',
+ '',
+ 'DEFAULT',
+ 'Test-Coverage'
+ ];
+
+ for (const name of invalidPresets) {
+ expect(isPreset(name)).toBe(false);
+ }
+ });
+ });
+});
diff --git a/packages/tm-core/tests/integration/loop/loop-tmcore-access.test.ts b/packages/tm-core/tests/integration/loop/loop-tmcore-access.test.ts
new file mode 100644
index 00000000..97421c92
--- /dev/null
+++ b/packages/tm-core/tests/integration/loop/loop-tmcore-access.test.ts
@@ -0,0 +1,157 @@
+/**
+ * @fileoverview Integration tests for LoopDomain access via TmCore
+ *
+ * Verifies that LoopDomain is properly accessible through TmCore.loop
+ * and methods work correctly.
+ *
+ * @integration
+ */
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Mock the logger to reduce noise in tests
+vi.mock('../../../src/common/logger/index.js', () => {
+ const mockLogger = {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ child: vi.fn().mockReturnThis()
+ };
+ return {
+ createLogger: () => mockLogger,
+ getLogger: () => mockLogger
+ };
+});
+
+import { createTmCore, TmCore, LoopDomain } from '../../../src/index.js';
+
+describe('LoopDomain Access via TmCore', () => {
+ let testProjectDir: string;
+ let tmCore: TmCore | null = null;
+
+ beforeEach(() => {
+ // Create temp project directory for isolation
+ testProjectDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'tm-loop-access-test-')
+ );
+
+ // Create minimal taskmaster config structure
+ const taskmasterDir = path.join(testProjectDir, '.taskmaster');
+ const tasksDir = path.join(taskmasterDir, 'tasks');
+ fs.mkdirSync(tasksDir, { recursive: true });
+
+ // Create empty tasks.json for TasksDomain initialization
+ fs.writeFileSync(
+ path.join(tasksDir, 'tasks.json'),
+ JSON.stringify({
+ tasks: [],
+ tags: { default: { tasks: [] } },
+ activeTag: 'default'
+ }),
+ 'utf-8'
+ );
+
+ // Create config.json
+ fs.writeFileSync(
+ path.join(taskmasterDir, 'config.json'),
+ JSON.stringify({
+ models: {
+ main: { id: 'test-model', provider: 'test' },
+ research: { id: 'test-model', provider: 'test' },
+ fallback: { id: 'test-model', provider: 'test' }
+ }
+ }),
+ 'utf-8'
+ );
+ });
+
+ afterEach(async () => {
+ // Clean up TmCore
+ if (tmCore) {
+ await tmCore.close();
+ tmCore = null;
+ }
+
+ // Clean up temp directory
+ if (testProjectDir) {
+ fs.rmSync(testProjectDir, { recursive: true, force: true });
+ }
+ });
+
+ describe('TmCore.loop Accessor', () => {
+ it('should have loop property accessible after createTmCore()', async () => {
+ tmCore = await createTmCore({ projectPath: testProjectDir });
+
+ expect(tmCore.loop).toBeDefined();
+ });
+
+ it('should return LoopDomain instance', async () => {
+ tmCore = await createTmCore({ projectPath: testProjectDir });
+
+ expect(tmCore.loop).toBeInstanceOf(LoopDomain);
+ });
+
+ it('should have expected LoopDomain methods', async () => {
+ tmCore = await createTmCore({ projectPath: testProjectDir });
+
+ expect(typeof tmCore.loop.isPreset).toBe('function');
+ expect(typeof tmCore.loop.resolvePrompt).toBe('function');
+ expect(typeof tmCore.loop.getAvailablePresets).toBe('function');
+ expect(typeof tmCore.loop.getIsRunning).toBe('function');
+ expect(typeof tmCore.loop.stop).toBe('function');
+ });
+ });
+
+ describe('Preset Resolution via TmCore', () => {
+ it('should resolve preset content through TmCore.loop', async () => {
+ tmCore = await createTmCore({ projectPath: testProjectDir });
+
+ const content = await tmCore.loop.resolvePrompt('default');
+
+ expect(content).toBeTruthy();
+ expect(content.length).toBeGreaterThan(100);
+ expect(content).toContain('<loop-complete>');
+ });
+
+ it('should identify valid presets', async () => {
+ tmCore = await createTmCore({ projectPath: testProjectDir });
+
+ expect(tmCore.loop.isPreset('default')).toBe(true);
+ expect(tmCore.loop.isPreset('test-coverage')).toBe(true);
+ expect(tmCore.loop.isPreset('/some/file/path.md')).toBe(false);
+ });
+
+ it('should list all available presets', async () => {
+ tmCore = await createTmCore({ projectPath: testProjectDir });
+
+ const presets = tmCore.loop.getAvailablePresets();
+
+ expect(presets).toContain('default');
+ expect(presets).toContain('test-coverage');
+ expect(presets).toContain('linting');
+ expect(presets).toContain('duplication');
+ expect(presets).toContain('entropy');
+ expect(presets).toHaveLength(5);
+ });
+ });
+
+ describe('Loop Lifecycle via TmCore', () => {
+ it('should report not running initially', async () => {
+ tmCore = await createTmCore({ projectPath: testProjectDir });
+
+ expect(tmCore.loop.getIsRunning()).toBe(false);
+ });
+
+ it('should handle stop() when not running', async () => {
+ tmCore = await createTmCore({ projectPath: testProjectDir });
+
+ // stop() is now synchronous and should not throw
+ expect(() => tmCore!.loop.stop()).not.toThrow();
+ expect(tmCore.loop.getIsRunning()).toBe(false);
+ });
+ });
+});
diff --git a/scripts/loop.sh b/scripts/loop.sh
new file mode 100755
index 00000000..b98ad9c8
--- /dev/null
+++ b/scripts/loop.sh
@@ -0,0 +1,70 @@
+#!/bin/bash
+# Keeping here for reference, but using the new task-master loop command instead
+set -e
+
+if [ -z "$1" ]; then
+ echo "Usage: $0 <iterations>"
+ exit 1
+fi
+
+# Cold start check - test if sandbox auth is ready
+echo "Checking sandbox auth..."
+test_result=$(docker sandbox run claude -p "Say OK" 2>&1) || true
+
+if [[ "$test_result" == *"OK"* ]]; then
+ echo "✓ Sandbox ready"
+else
+ echo "Sandbox needs authentication. Starting interactive session..."
+ echo "Please complete auth, then ctrl+c to continue."
+ echo ""
+ docker sandbox run claude "cool you're in! you can now exit (ctrl + c) so we can continue the loop"
+ echo ""
+ echo "✓ Auth complete"
+fi
+echo ""
+
+for ((i=1; i<=$1; i++)); do
+ echo ""
+ echo "━━━ Iteration $i of $1 ━━━"
+
+ result=$(docker sandbox run claude -p "@.taskmaster/tasks/tasks.json @.taskmaster/loop-progress.txt @CLAUDE.md \
+SETUP: If task-master command not found, run: npm i -g task-master-ai \
+\
+TASK: Implement ONE task/subtask for the tm loop feature. \
+\
+PROCESS: \
+1. Run task-master next (or use MCP) to get the next available task/subtask. \
+2. Read task details with task-master show <id>. \
+3. Implement following codebase patterns (CLI in apps/cli/src/commands/, core in packages/tm-core/src/modules/). \
+4. Write tests alongside implementation. \
+5. Run npm run turbo:typecheck to verify types. \
+6. Run npm test -w <package> to verify tests pass. \
+7. Mark complete: task-master set-status --id=<id> --status=done \
+8. Commit with message: feat(loop): <what was implemented> (do NOT include loop-progress.txt in commit) \
+9. Append super-concise notes to .taskmaster/loop-progress.txt: task ID, what was done, any learnings. \
+\
+IMPORTANT: \
+- Complete ONLY ONE task per iteration. \
+- Keep changes small and focused. \
+- Do NOT start another task after completing one. \
+- If all tasks are done, output <loop-complete>ALL_DONE</loop-complete>. \
+- If blocked, output <loop-blocked>REASON</loop-blocked>. \
+")
+
+ echo "$result"
+
+ # Strict match - require exact format with content
+ if [[ "$result" =~ \<loop-complete\>ALL_DONE\</loop-complete\> ]]; then
+ echo ""
+ echo "All tasks complete after $i iterations."
+ exit 0
+ fi
+
+ if [[ "$result" =~ \<loop-blocked\>.+\</loop-blocked\> ]]; then
+ echo ""
+ echo "Blocked at iteration $i."
+ exit 1
+ fi
+done
+
+echo "Max iterations ($1) reached."
diff --git a/tests/unit/mcp-server/tools/tool-registry.test.js b/tests/unit/mcp-server/tools/tool-registry.test.js
new file mode 100644
index 00000000..a83bd83c
--- /dev/null
+++ b/tests/unit/mcp-server/tools/tool-registry.test.js
@@ -0,0 +1,131 @@
+/**
+ * tool-registry.test.js
+ * Tests for tool registry - verifies tools are correctly registered in tiers
+ */
+
+import {
+ coreTools,
+ getAvailableTools,
+ getToolCategories,
+ getToolCounts,
+ getToolRegistration,
+ isValidTool,
+ standardTools,
+ toolRegistry
+} from '../../../../mcp-server/src/tools/tool-registry.js';
+
+describe('tool-registry', () => {
+ describe('tool tier structure', () => {
+ it('should have exactly 7 core tools', () => {
+ expect(coreTools.length).toBe(7);
+ });
+
+ it('should have exactly 14 standard tools', () => {
+ expect(standardTools.length).toBe(14);
+ });
+
+ it('should have standardTools include all coreTools', () => {
+ coreTools.forEach((tool) => {
+ expect(standardTools).toContain(tool);
+ });
+ });
+
+ it('should have all standardTools registered in toolRegistry', () => {
+ standardTools.forEach((tool) => {
+ expect(toolRegistry[tool]).toBeDefined();
+ });
+ });
+ });
+
+ describe('getAvailableTools', () => {
+ it('should return all registered tool names', () => {
+ const tools = getAvailableTools();
+ expect(Array.isArray(tools)).toBe(true);
+ });
+ });
+
+ describe('getToolCounts', () => {
+ it('should return correct counts', () => {
+ const counts = getToolCounts();
+ expect(counts.core).toBe(7);
+ expect(counts.standard).toBe(14);
+ expect(counts.total).toBeGreaterThanOrEqual(14);
+ });
+ });
+
+ describe('getToolCategories', () => {
+ it('should return categories with core tools', () => {
+ const categories = getToolCategories();
+ expect(categories.core).toContain('get_tasks');
+ expect(categories.core).toContain('next_task');
+ });
+
+ it('should return categories with standard tools', () => {
+ const categories = getToolCategories();
+ expect(categories.standard).toContain('get_tasks');
+ expect(categories.standard).toContain('add_task');
+ });
+
+ it('should return categories with all tools', () => {
+ const categories = getToolCategories();
+ expect(categories.all.length).toBeGreaterThanOrEqual(
+ categories.standard.length
+ );
+ });
+ });
+
+ describe('getToolRegistration', () => {
+ it('should return registration function for get_tasks', () => {
+ const registration = getToolRegistration('get_tasks');
+ expect(registration).toBeDefined();
+ expect(typeof registration).toBe('function');
+ });
+
+ it('should return registration function for add_task', () => {
+ const registration = getToolRegistration('add_task');
+ expect(registration).toBeDefined();
+ expect(typeof registration).toBe('function');
+ });
+
+ it('should return null for unknown tool', () => {
+ const registration = getToolRegistration('unknown_tool');
+ expect(registration).toBeNull();
+ });
+ });
+
+ describe('isValidTool', () => {
+ it('should return true for get_tasks', () => {
+ expect(isValidTool('get_tasks')).toBe(true);
+ });
+
+ it('should return true for add_task', () => {
+ expect(isValidTool('add_task')).toBe(true);
+ });
+
+ it('should return false for unknown tool', () => {
+ expect(isValidTool('unknown_tool')).toBe(false);
+ });
+ });
+
+ describe('TASK_MASTER_TOOLS behavior simulation', () => {
+ it('should allow filtering to core tools only', () => {
+ const coreToolSet = new Set(coreTools);
+ expect(coreToolSet.has('get_tasks')).toBe(true);
+ expect(coreToolSet.has('next_task')).toBe(true);
+ });
+
+ it('should allow filtering to standard tools', () => {
+ const standardToolSet = new Set(standardTools);
+ expect(standardToolSet.has('get_tasks')).toBe(true);
+ expect(standardToolSet.has('next_task')).toBe(true);
+ expect(standardToolSet.has('add_task')).toBe(true);
+ });
+
+ it('should include all tools when using getAvailableTools', () => {
+ const allTools = getAvailableTools();
+ const allToolSet = new Set(allTools);
+ expect(allToolSet.has('get_tasks')).toBe(true);
+ expect(allToolSet.has('add_task')).toBe(true);
+ });
+ });
+});