# Task ID: 41
# Title: Implement Visual Task Dependency Graph in Terminal
# Status: pending
# Dependencies: None
# Priority: medium
# Description: Create a feature that renders task dependencies as a visual graph using ASCII/Unicode characters in the terminal, with color-coded nodes representing tasks and connecting lines showing dependency relationships.
# Details:
This implementation should include:

1. Create a new command `graph` or `visualize` that displays the dependency graph.

2. Design an ASCII/Unicode-based graph rendering system that:
   - Represents each task as a node with its ID and abbreviated title
   - Shows dependencies as directional lines between nodes (→, ↑, ↓, etc.)
   - Uses color coding for different task statuses (e.g., green for completed, yellow for in-progress, red for blocked)
   - Handles complex dependency chains with proper spacing and alignment

3. Implement layout algorithms to:
   - Minimize crossing lines for better readability
   - Properly space nodes to avoid overlapping
   - Support both vertical and horizontal graph orientations (as a configurable option)

4. Add detection and highlighting of circular dependencies with a distinct color/pattern

5. Include a legend explaining the color coding and symbols used

6. Ensure the graph is responsive to terminal width, with options to:
   - Automatically scale to fit the current terminal size
   - Allow zooming in/out of specific sections for large graphs
   - Support pagination or scrolling for very large dependency networks

7. Add options to filter the graph by:
   - Specific task IDs or ranges
   - Task status
   - Dependency depth (e.g., show only direct dependencies or N levels deep)

8. Ensure accessibility by using distinct patterns in addition to colors for users with color vision deficiencies

9. Optimize performance for projects with many tasks and complex dependency relationships

# Test Strategy:
1. Unit Tests:
   - Test the graph generation algorithm with various dependency structures
   - Verify correct node placement and connection rendering
   - Test circular dependency detection
   - Verify color coding matches task statuses

2. Integration Tests:
   - Test the command with projects of varying sizes (small, medium, large)
   - Verify correct handling of different terminal sizes
   - Test all filtering options

3. Visual Verification:
   - Create test cases with predefined dependency structures and verify the visual output matches expected patterns
   - Test with terminals of different sizes, including very narrow terminals
   - Verify readability of complex graphs

4. Edge Cases:
   - Test with no dependencies (single nodes only)
   - Test with circular dependencies
   - Test with very deep dependency chains
   - Test with wide dependency networks (many parallel tasks)
   - Test with the maximum supported number of tasks

5. Usability Testing:
   - Have team members use the feature and provide feedback on readability and usefulness
   - Test in different terminal emulators to ensure compatibility
   - Verify the feature works in terminals with limited color support

6. Performance Testing:
   - Measure rendering time for large projects
   - Ensure reasonable performance with 100+ interconnected tasks

# Subtasks:
## 1. CLI Command Setup [pending]
### Dependencies: None
### Description: Design and implement the command-line interface for the dependency graph tool, including argument parsing and help documentation.
### Details:
Define commands for input file specification, output options, filtering, and other user-configurable parameters.
<info added on 2025-05-23T21:02:26.442Z>
Implement a new 'diagram' command (with 'graph' alias) in commands.js following the Commander.js pattern. The command should:

1. Import diagram-generator.js module functions for generating visual representations
2. Support multiple visualization types with --type option:
   - dependencies: show task dependency relationships
   - subtasks: show task/subtask hierarchy
   - flow: show task workflow
   - gantt: show timeline visualization

3. Include the following options:
   - --task <id>: Filter diagram to show only specified task and its relationships
   - --mermaid: Output raw Mermaid markdown for external rendering
   - --visual: Render diagram directly in terminal
   - --format <format>: Output format (text, svg, png)

4. Implement proper error handling and validation:
   - Validate task IDs using existing taskExists() function
   - Handle invalid option combinations
   - Provide descriptive error messages

5. Integrate with UI components:
   - Use ui.js display functions for consistent output formatting
   - Apply chalk coloring for terminal output
   - Use boxen formatting consistent with other commands

6. Handle file operations:
   - Resolve file paths using findProjectRoot() pattern
   - Support saving diagrams to files when appropriate

7. Include comprehensive help text following the established pattern in other commands
</info added on 2025-05-23T21:02:26.442Z>

## 2. Graph Layout Algorithms [pending]
### Dependencies: 41.1
### Description: Develop or integrate algorithms to compute optimal node and edge placement for clear and readable graph layouts in a terminal environment.
### Details:
Consider topological sorting, hierarchical, and force-directed layouts suitable for ASCII/Unicode rendering.
<info added on 2025-05-23T21:02:49.434Z>
Create a new diagram-generator.js module in the scripts/modules/ directory following Task Master's module architecture pattern. The module should include:

1. Core functions for generating Mermaid diagrams:
   - generateDependencyGraph(tasks, options) - creates flowchart showing task dependencies
   - generateSubtaskDiagram(task, options) - creates hierarchy diagram for subtasks
   - generateProjectFlow(tasks, options) - creates overall project workflow
   - generateGanttChart(tasks, options) - creates timeline visualization

2. Integration with existing Task Master data structures:
   - Use the same task object format from task-manager.js
   - Leverage dependency analysis from dependency-manager.js
   - Support complexity scores from analyze-complexity functionality
   - Handle both main tasks and subtasks with proper ID notation (parentId.subtaskId)

3. Layout algorithm considerations for Mermaid:
   - Topological sorting for dependency flows
   - Hierarchical layouts for subtask trees
   - Circular dependency detection and highlighting
   - Terminal width-aware formatting for ASCII fallback

4. Export functions following the existing module pattern at the bottom of the file
</info added on 2025-05-23T21:02:49.434Z>

## 3. ASCII/Unicode Rendering Engine [pending]
### Dependencies: 41.2
### Description: Implement rendering logic to display the dependency graph using ASCII and Unicode characters in the terminal.
### Details:
Support for various node and edge styles, and ensure compatibility with different terminal types.
<info added on 2025-05-23T21:03:10.001Z>
Extend ui.js with diagram display functions that integrate with Task Master's existing UI patterns:

1. Implement core diagram display functions:
   - displayTaskDiagram(tasksPath, diagramType, options) as the main entry point
   - displayMermaidCode(mermaidCode, title) for formatted code output with boxen
   - displayDiagramLegend() to explain symbols and colors

2. Ensure UI consistency by:
   - Using established chalk color schemes (blue/green/yellow/red)
   - Applying boxen for consistent component formatting
   - Following existing display function patterns (displayTaskById, displayComplexityReport)
   - Utilizing cli-table3 for any diagram metadata tables

3. Address terminal rendering challenges:
   - Implement ASCII/Unicode fallback when Mermaid rendering isn't available
   - Respect terminal width constraints using process.stdout.columns
   - Integrate with loading indicators via startLoadingIndicator/stopLoadingIndicator

4. Update task file generation to include Mermaid diagram sections in individual task files

5. Support both CLI and MCP output formats through the outputFormat parameter
</info added on 2025-05-23T21:03:10.001Z>

## 4. Color Coding Support [pending]
### Dependencies: 41.3
### Description: Add color coding to nodes and edges to visually distinguish types, statuses, or other attributes in the graph.
### Details:
Use ANSI escape codes for color; provide options for colorblind-friendly palettes.
<info added on 2025-05-23T21:03:35.762Z>
Integrate color coding with Task Master's existing status system:

1. Extend getStatusWithColor() in ui.js to support diagram contexts:
   - Add 'diagram' parameter to determine rendering context
   - Modify color intensity for better visibility in graph elements

2. Implement Task Master's established color scheme using ANSI codes:
   - Green (\x1b[32m) for 'done'/'completed' tasks
   - Yellow (\x1b[33m) for 'pending' tasks
   - Orange (\x1b[38;5;208m) for 'in-progress' tasks
   - Red (\x1b[31m) for 'blocked' tasks
   - Gray (\x1b[90m) for 'deferred'/'cancelled' tasks
   - Magenta (\x1b[35m) for 'review' tasks

3. Create diagram-specific color functions:
   - getDependencyLineColor(fromTaskStatus, toTaskStatus) - color dependency arrows based on relationship status
   - getNodeBorderColor(task) - style node borders using priority/complexity indicators
   - getSubtaskGroupColor(parentTask) - visually group related subtasks

4. Integrate complexity visualization:
   - Use getComplexityWithColor() for node background or border thickness
   - Map complexity scores to visual weight in the graph

5. Ensure accessibility:
   - Add text-based indicators (symbols like ✓, ⚠, ⏳) alongside colors
   - Implement colorblind-friendly palettes as user-selectable option
   - Include shape variations for different statuses

6. Follow existing ANSI patterns:
   - Maintain consistency with terminal UI color usage
   - Reuse color constants from the codebase

7. Support graceful degradation:
   - Check terminal capabilities using existing detection
   - Provide monochrome fallbacks with distinctive patterns
   - Use bold/underline as alternatives when colors unavailable
</info added on 2025-05-23T21:03:35.762Z>

## 5. Circular Dependency Detection [pending]
### Dependencies: 41.2
### Description: Implement algorithms to detect and highlight circular dependencies within the graph.
### Details:
Clearly mark cycles in the rendered output and provide warnings or errors as appropriate.
<info added on 2025-05-23T21:04:20.125Z>
Integrate with Task Master's existing circular dependency detection:

1. Import the dependency detection logic from dependency-manager.js module
2. Utilize the findCycles function from utils.js or dependency-manager.js
3. Extend validateDependenciesCommand functionality to highlight cycles in diagrams

Visual representation in Mermaid diagrams:
- Apply red/bold styling to nodes involved in dependency cycles
- Add warning annotations to cyclic edges
- Implement cycle path highlighting with distinctive line styles

Integration with validation workflow:
- Execute dependency validation before diagram generation
- Display cycle warnings consistent with existing CLI error messaging
- Utilize chalk.red and boxen for error highlighting following established patterns

Add diagram legend entries that explain cycle notation and warnings

Ensure detection of cycles in both:
- Main task dependencies
- Subtask dependencies within parent tasks

Follow Task Master's error handling patterns for graceful cycle reporting and user notification
</info added on 2025-05-23T21:04:20.125Z>

## 6. Filtering and Search Functionality [pending]
### Dependencies: 41.1, 41.2
### Description: Enable users to filter nodes and edges by criteria such as name, type, or dependency depth.
### Details:
Support command-line flags for filtering and interactive search if feasible.
<info added on 2025-05-23T21:04:57.811Z>
Implement MCP tool integration for task dependency visualization:

1. Create task_diagram.js in mcp-server/src/tools/ following existing tool patterns
2. Implement taskDiagramDirect.js in mcp-server/src/core/direct-functions/
3. Use Zod schema for parameter validation:
   - diagramType (dependencies, subtasks, flow, gantt)
   - taskId (optional string)
   - format (mermaid, text, json)
   - includeComplexity (boolean)

4. Structure response data with:
   - mermaidCode for client-side rendering
   - metadata (nodeCount, edgeCount, cycleWarnings)
   - support for both task-specific and project-wide diagrams

5. Integrate with session management and project root handling
6. Implement error handling using handleApiResult pattern
7. Register the tool in tools/index.js

Maintain compatibility with existing command-line flags for filtering and interactive search.
</info added on 2025-05-23T21:04:57.811Z>

## 7. Accessibility Features [pending]
### Dependencies: 41.3, 41.4
### Description: Ensure the tool is accessible, including support for screen readers, high-contrast modes, and keyboard navigation.
### Details:
Provide alternative text output and ensure color is not the sole means of conveying information.
<info added on 2025-05-23T21:05:54.584Z>
# Accessibility and Export Integration

## Accessibility Features
- Provide alternative text output for visual elements
- Ensure color is not the sole means of conveying information
- Support keyboard navigation through the dependency graph
- Add screen reader compatible node descriptions

## Export Integration
- Extend generateTaskFiles function in task-manager.js to include Mermaid diagram sections
- Add Mermaid code blocks to task markdown files under ## Diagrams header
- Follow existing task file generation patterns and markdown structure
- Support multiple diagram types per task file:
  * Task dependencies (prerequisite relationships)
  * Subtask hierarchy visualization
  * Task flow context in project workflow
- Integrate with existing fs module file writing operations
- Add diagram export options to the generate command in commands.js
- Support SVG and PNG export using Mermaid CLI when available
- Implement error handling for diagram generation failures
- Reference exported diagrams in task markdown with proper paths
- Update CLI generate command with options like --include-diagrams
</info added on 2025-05-23T21:05:54.584Z>

## 8. Performance Optimization [pending]
### Dependencies: 41.2, 41.3, 41.4, 41.5, 41.6
### Description: Profile and optimize the tool for large graphs to ensure responsive rendering and low memory usage.
### Details:
Implement lazy loading, efficient data structures, and parallel processing where appropriate.
<info added on 2025-05-23T21:06:14.533Z>
# Mermaid Library Integration and Terminal-Specific Handling

## Package Dependencies
- Add mermaid package as an optional dependency in package.json for generating raw Mermaid diagram code
- Consider mermaid-cli for SVG/PNG conversion capabilities
- Evaluate terminal-image or similar libraries for terminals with image support
- Explore ascii-art-ansi or box-drawing character libraries for text-only terminals

## Terminal Capability Detection
- Leverage existing terminal detection from ui.js to assess rendering capabilities
- Implement detection for:
  - iTerm2 and other terminals with image protocol support
  - Terminals with Unicode/extended character support
  - Basic terminals requiring pure ASCII output

## Rendering Strategy with Fallbacks
1. Primary: Generate raw Mermaid code for user copy/paste
2. Secondary: Render simplified ASCII tree/flow representation using box characters
3. Tertiary: Present dependencies in tabular format for minimal terminals

## Implementation Approach
- Use dynamic imports for optional rendering libraries to maintain lightweight core
- Implement graceful degradation when optional packages aren't available
- Follow Task Master's philosophy of minimal dependencies
- Ensure performance optimization through lazy loading where appropriate
- Design modular rendering components that can be swapped based on terminal capabilities
</info added on 2025-05-23T21:06:14.533Z>

## 9. Documentation [pending]
### Dependencies: 41.1, 41.2, 41.3, 41.4, 41.5, 41.6, 41.7, 41.8
### Description: Write comprehensive user and developer documentation covering installation, usage, configuration, and extension.
### Details:
Include examples, troubleshooting, and contribution guidelines.

## 10. Testing and Validation [pending]
### Dependencies: 41.1, 41.2, 41.3, 41.4, 41.5, 41.6, 41.7, 41.8, 41.9
### Description: Develop automated tests for all major features, including CLI parsing, layout correctness, rendering, color coding, filtering, and cycle detection.
### Details:
Include unit, integration, and regression tests; validate accessibility and performance claims.
<info added on 2025-05-23T21:08:36.329Z>
# Documentation Tasks for Visual Task Dependency Graph

## User Documentation
1. Update README.md with diagram command documentation following existing command reference format
2. Add examples to CLI command help text in commands.js matching patterns from other commands
3. Create docs/diagrams.md with detailed usage guide including:
   - Command examples for each diagram type
   - Mermaid code samples and output
   - Terminal compatibility notes
   - Integration with task workflow examples
   - Troubleshooting section for common diagram rendering issues
   - Accessibility features and terminal fallback options

## Developer Documentation
1. Update MCP tool documentation to include the new task_diagram tool
2. Add JSDoc comments to all new functions following existing code standards
3. Create contributor documentation for extending diagram types
4. Update API documentation for any new MCP interface endpoints

## Integration Documentation
1. Document integration with existing commands (analyze-complexity, generate, etc.)
2. Provide examples showing how diagrams complement other Task Master features
</info added on 2025-05-23T21:08:36.329Z>

