Files
2025-11-29 18:48:31 +08:00

19 KiB

name, description
name description
mermaid-diagrams Create sequence diagrams for message flows and temporal interactions, architecture diagrams for cloud/CI-CD infrastructure relationships, or flowchart diagrams for process flows and decision logic. Automatically validates all diagrams with mermaid-cli and applies self-healing fixes. Use for documenting API interactions, system workflows, microservices communication, cloud service architectures, or process documentation.

Mermaid Diagrams

Create professional diagrams using Mermaid syntax for documentation, design discussions, and system architecture planning. This skill covers three primary diagram types:

  • Sequence Diagrams: Show temporal interactions and message flows between actors, services, or processes
  • Architecture Diagrams: Visualize relationships between services and resources in cloud or CI/CD deployments
  • Flowchart Diagrams: Illustrate processes, decision trees, algorithms, and workflow logic

🚀 Automatic Validation Workflow

IMPORTANT: All diagrams generated by this skill are automatically validated with mermaid-cli. This ensures error-free diagrams that render correctly every time.

Mandatory Workflow Steps

When creating diagrams, ALWAYS follow this exact workflow:

  1. Generate Diagram Content (based on user requirements)
  2. AUTOMATICALLY VALIDATE using mermaid-cli (mandatory step)
  3. APPLY SELF-HEALING FIXES if validation fails (automatic)
  4. CONFIRM VALIDATION SUCCESS before presenting to user
  5. DELIVER VALIDATED DIAGRAM to user

NEVER skip validation or present unvalidated diagrams to users.

Sequence Diagrams

Sequence diagrams are interaction diagrams that show how processes operate with one another and in what order. They visualize temporal interactions between participants, making them ideal for documenting API flows, system integrations, user interactions, and distributed system communications.

Quick Instructions

  1. Define participants: Use actor (humans) or participant with type attributes
  2. Add messages: ->> (sync), -->> (response), -) (async)
  3. Show activations: Append +/- to arrows (A->>+B, B-->>-A)
  4. Control structures: alt/else, loop, par, critical for complex flows

→ For detailed syntax, see sequence-diagrams-reference.md

🔍 Automatic Validation Process

After generating any sequence diagram, you MUST:

  1. Create temp files:

    echo "YOUR_SEQUENCE_DIAGRAM_HERE" > /tmp/mermaid_validate.mmd
    
  2. Run enhanced validation (your bash script approach):

    mmdc -i /tmp/mermaid_validate.mmd -o /tmp/mermaid_validate.svg 2>/tmp/mermaid_validate.err
    rc=$?
    if [ $rc -ne 0 ]; then
      echo "🛑 mmdc failed (exit code $rc)."; cat /tmp/mermaid_validate.err; exit 1
    fi
    
    # Check SVG for error markers that mmdc might miss
    if grep -q -i 'Syntax error in graph\|mermaidError\|errorText\|Parse error' /tmp/mermaid_validate.svg; then
      echo "🛑 Mermaid syntax error found in output SVG"
      exit 1
    fi
    
    # Verify SVG actually contains diagram content (not just error text)
    if ! grep -q '<svg.*width.*height' /tmp/mermaid_validate.svg; then
      echo "🛑 SVG output appears invalid or empty"
      exit 1
    fi
    
    echo "✅ Diagram appears valid"
    
  3. If validation fails, apply fixes:

    • Check participant syntax: ensure participant or actor keywords used correctly
    • Verify arrow syntax: ->>, -->>, -) patterns are correct
    • Validate control structures: alt, loop, par blocks are properly closed
    • Review error details in /tmp/mermaid_validate.err for specific issues
  4. Re-validate until successful: (repeat step 2)

  5. Cleanup and confirm:

    rm -f /tmp/mermaid_validate.mmd /tmp/mermaid_validate.svg /tmp/mermaid_validate.err
    

VALIDATION MUST PASS BEFORE PRESENTING TO USER!

⚠️ CRITICAL: Key Syntax Differences

NEVER MIX THESE SYNTAXES! Each diagram type has completely different keywords. Mixing them will break your diagram.

Sequence Diagrams:

sequenceDiagram
    actor User
    participant API@{ "type": "control" }
    participant DB@{ "type": "database" }
  • Use actor for humans (stick figure icon)
  • Use participant with type attributes for systems
  • ✓ Use: participant, actor
  • ✗ NEVER use: service, database, group

Architecture Diagrams:

architecture-beta
    service api(server)[API]
    database db(database)[Database]
    group backend(cloud)[Backend]
  • Use service for components
  • Use database as a keyword (NOT participant!)
  • Use group for organizing services
  • ✓ Use: service, database, group
  • ✗ NEVER use: participant, actor

Minimal Example

sequenceDiagram
    actor User
    participant API@{ "type": "control" }
    participant DB@{ "type": "database" }

    User->>+API: Request data
    API->>+DB: Query
    DB-->>-API: Result
    API-->>-User: Response

Guidelines

  • Limit to 5-7 participants per diagram for clarity
  • Use activations (+/-) to show processing periods
  • Apply control structures (alt, loop, par) for complex flows

→ See sequence-diagrams-reference.md for detailed patterns and best practices


Architecture Diagrams

Architecture diagrams show relationships between services and resources commonly found within cloud or CI/CD deployments. Services (nodes) are connected by edges, and related services can be placed within groups to illustrate organization.

Quick Instructions

  1. Start with architecture-beta keyword
  2. Define groups: group {id}({icon})[{label}]
  3. Add services: service {id}({icon})[{label}] in {group}
  4. Connect edges: {id}:{T|B|L|R} -- {T|B|L|R}:{id}
  5. Add arrows: --> (single) or <--> (bidirectional)

CRITICAL Syntax Rules:

  • IDs: Use simple alphanumeric (e.g., api, db1, auth_service) - NO spaces or special chars
  • Labels: AVOID special characters that break parsing:
    • NO hyphens (Gen-AI, Cross-Account)
    • NO colons (AWS Account: prod)
    • NO special punctuation
    • ✓ Use spaces: [Gen AI] instead of [Gen-AI]
    • ✓ Use simple words: [Cross Account IAM Role] instead of [Cross-Account IAM Role]

Default icons: cloud, database, disk, internet, server

→ For extended icons and advanced features, see architecture-diagram-reference.md

🔍 Automatic Validation Process

After generating any architecture diagram, you MUST:

  1. Create temp files:

    echo "YOUR_ARCHITECTURE_DIAGRAM_HERE" > /tmp/mermaid_validate.mmd
    
  2. Run enhanced validation (your bash script approach):

    mmdc -i /tmp/mermaid_validate.mmd -o /tmp/mermaid_validate.svg 2>/tmp/mermaid_validate.err
    rc=$?
    if [ $rc -ne 0 ]; then
      echo "🛑 mmdc failed (exit code $rc)."; cat /tmp/mermaid_validate.err; exit 1
    fi
    
    # Check SVG for error markers that mmdc might miss
    if grep -q -i 'Syntax error in graph\|mermaidError\|errorText\|Parse error' /tmp/mermaid_validate.svg; then
      echo "🛑 Mermaid syntax error found in output SVG"
      exit 1
    fi
    
    # Verify SVG actually contains diagram content (not just error text)
    if ! grep -q '<svg.*width.*height' /tmp/mermaid_validate.svg; then
      echo "🛑 SVG output appears invalid or empty"
      exit 1
    fi
    
    echo "✅ Diagram appears valid"
    
  3. If validation fails, apply automatic fixes:

    • Fix hyphens in labels: [Gen-AI][Gen AI]
    • Remove colons: [API:prod][API Prod]
    • Remove special characters: keep only alphanumeric, spaces, underscores
    • Fix IDs: ensure no spaces in service/group IDs (use underscores)
    • Review error details in /tmp/mermaid_validate.err for specific issues
  4. Re-validate until successful: (repeat step 2)

  5. Cleanup and confirm:

    rm -f /tmp/mermaid_validate.mmd /tmp/mermaid_validate.svg /tmp/mermaid_validate.err
    

VALIDATION MUST PASS BEFORE PRESENTING TO USER!

Minimal Example

architecture-beta
    group stg_aitools(cloud)[AWS Stg AI Tools]
    group stg_genai(cloud)[AWS Stg Gen AI]

    service litellm(server)[LiteLLM Service] in stg_aitools
    service rds(database)[RDS PostgreSQL] in stg_aitools
    service redis(disk)[Redis Cache] in stg_aitools
    service bedrock(server)[AWS Bedrock] in stg_genai
    service iam_role(server)[Cross Account IAM Role] in stg_genai

    litellm:R --> L:rds
    litellm:B --> T:redis
    litellm:R --> L:iam_role
    iam_role:B --> T:bedrock

Note: No hyphens in labels! Use spaces instead (Gen AI not Gen-AI)

Guidelines

  • Group related services with group declarations
  • Use clear directional indicators (T/B/L/R) and arrows (-->)
  • Limit to 8-12 services per diagram for clarity

→ See architecture-diagram-reference.md for icons, junctions, and complex patterns


Flowchart Diagrams

Flowchart diagrams visualize processes, decision logic, algorithms, and workflows using nodes (shapes) and edges (arrows). They're ideal for documenting business processes, algorithm logic, decision trees, and step-by-step workflows.

Quick Instructions

  1. Start with flowchart keyword and direction: flowchart TD (Top Down), LR (Left Right)
  2. Define nodes with shapes: [Process], {Decision}, (Start/End), [(Database)]
  3. Connect with arrows: --> (standard), -.-> (dotted), ==> (thick)
  4. Add text to arrows: -->|label| or -- label -->
  5. Group related nodes: use subgraph blocks
  6. Apply styling: style id fill:#color,stroke:#color

→ For detailed syntax, see flowchart-diagram-reference.md

🔍 Automatic Validation Process

After generating any flowchart diagram, you MUST:

  1. Create temp files:

    echo "YOUR_FLOWCHART_DIAGRAM_HERE" > /tmp/mermaid_validate.mmd
    
  2. Run enhanced validation (your bash script approach):

    mmdc -i /tmp/mermaid_validate.mmd -o /tmp/mermaid_validate.svg 2>/tmp/mermaid_validate.err
    rc=$?
    if [ $rc -ne 0 ]; then
      echo "🛑 mmdc failed (exit code $rc)."; cat /tmp/mermaid_validate.err; exit 1
    fi
    
    # Check SVG for error markers that mmdc might miss
    if grep -q -i 'Syntax error in graph\|mermaidError\|errorText\|Parse error' /tmp/mermaid_validate.svg; then
      echo "🛑 Mermaid syntax error found in output SVG"
      exit 1
    fi
    
    # Verify SVG actually contains diagram content (not just error text)
    if ! grep -q '<svg.*width.*height' /tmp/mermaid_validate.svg; then
      echo "🛑 SVG output appears invalid or empty"
      exit 1
    fi
    
    echo "✅ Diagram appears valid"
    
  3. If validation fails, apply fixes:

    • Check node shape syntax: ensure brackets/braces are balanced
    • Verify arrow syntax: -->, -.->, ==> patterns are correct
    • Validate subgraph blocks: ensure subgraph has matching end
    • Avoid reserved words: capitalize "end" or wrap in quotes
    • Review error details in /tmp/mermaid_validate.err for specific issues
  4. Re-validate until successful: (repeat step 2)

  5. Cleanup and confirm:

    rm -f /tmp/mermaid_validate.mmd /tmp/mermaid_validate.svg /tmp/mermaid_validate.err
    

VALIDATION MUST PASS BEFORE PRESENTING TO USER!

Minimal Example

flowchart TD
    Start([Start Process]) --> Input[/Enter Data/]
    Input --> Validate{Valid Data?}

    Validate -->|Yes| Process[Process Data]
    Validate -->|No| Error[Display Error]

    Error --> Input
    Process --> DB[(Save to Database)]
    DB --> End([End])

Guidelines

  • Limit to 10-15 nodes per diagram for clarity
  • Use standard shapes: diamonds for decisions, cylinders for databases
  • Label arrows to clarify flow logic
  • Group related processes with subgraph for organization

→ See flowchart-diagram-reference.md for all node shapes, arrow types, subgraphs, and styling options


When to Use Each Diagram Type

Use Sequence Diagrams When:

  • Documenting temporal interactions and message ordering
  • Showing API request/response flows
  • Illustrating authentication or authorization flows
  • Explaining microservices communication patterns
  • Demonstrating error handling and conditional logic
  • Visualizing actor interactions over time

Use Architecture Diagrams When:

  • Showing infrastructure relationships and deployment structure
  • Documenting cloud service architecture
  • Illustrating CI/CD pipeline components
  • Visualizing system topology and service organization
  • Explaining resource dependencies (databases, storage, networks)
  • Presenting high-level system design

Use Flowchart Diagrams When:

  • Documenting business processes and workflows
  • Illustrating decision logic and conditional branches
  • Visualizing algorithm steps and computation flow
  • Showing approval workflows or multi-step procedures
  • Explaining error handling paths and retry logic
  • Creating troubleshooting guides and decision trees

Common Best Practices

For Both Diagram Types:

  1. Start simple: Begin with basic structures, then add complexity as needed
  2. Use consistent naming: Follow your project's naming conventions
  3. Keep it focused: If a diagram becomes unclear, split it into multiple diagrams
  4. Test readability: Ensure diagrams are readable at typical documentation sizes
  5. Version control: Treat diagrams as code—review changes and maintain them alongside implementation
  6. Document assumptions: Use notes or descriptions to clarify business rules or technical constraints

Diagram Size Guidelines:

  • Sequence: Limit to 5-7 participants per diagram
  • Architecture: Limit to 8-12 services per diagram
  • Flowchart: Limit to 10-15 nodes per diagram
  • For larger systems, create multiple diagrams focusing on specific subsystems or layers

When Diagrams Conflict:

  • For runtime behavior → use sequence diagrams
  • For deployment structure → use architecture diagrams
  • For process/decision flows → use flowchart diagrams
  • For complex systems, use combinations: architecture for infrastructure, sequence for interactions, flowcharts for business logic

Common Mistakes

Common Syntax Mistakes

Architecture diagrams: NEVER use these patterns:

  1. Hyphens in labels (breaks parsing):

    • [Gen-AI], [Cross-Account], [AI-Tools]
    • [Gen AI], [Cross Account], [AI Tools]
  2. Special characters in labels:

    • [AWS Account: prod] (colons)
    • [DB@prod] (at symbols)
    • [AWS Account Prod] (simple words)
  3. Invalid keywords in sequence diagrams:

    • database DB, service API
    • participant DB@{ "type": "database" }
  4. Unbalanced brackets in flowchart nodes:

    • A[Text, B{Decision, C(Start
    • A[Text], B{Decision}, C(Start)
  5. Reserved words in flowcharts:

    • end (breaks diagram)
    • End, END, or "end"

→ See examples above for correct syntax patterns

🔧 Validation Tip: These errors are automatically caught and fixed by the mandatory validation process. See the Automatic Validation Workflow section.


Troubleshooting

Sequence Diagrams:

  • "end" keyword breaks diagram: Wrap in quotes "end" or parentheses (end)
  • Participant not appearing: Explicitly declare with participant Name before first use
  • Arrow not rendering: Verify syntax (->>, -->>, ->, -->, -))

Architecture Diagrams:

  • Parsing errors with labels: Avoid colons (:) and complex punctuation in labels
    • Wrong: [AWS Account: prod api]
    • ✓ Correct: [AWS Account Prod API]
  • Invalid ID errors: Use simple alphanumeric IDs without spaces
    • Wrong: group stg ai-tools (space in ID)
    • ✓ Correct: group stg_aitools or group aitools_stg
  • Service not in group: Ensure group is declared before service, use in {group_id}
  • Edge not connecting: Verify both services exist and direction indicators are valid (T/B/L/R)
  • Icon not displaying: Check icon name spelling or use default icons

Flowchart Diagrams:

  • Unbalanced brackets: Ensure all node shapes have matching opening/closing brackets
    • Wrong: A[Process, B{Decision
    • ✓ Correct: A[Process], B{Decision}
  • Reserved word "end": Capitalize or quote it to avoid breaking diagram
    • Wrong: flowchart TD\n A --> end
    • ✓ Correct: flowchart TD\n A --> End
  • Arrow syntax errors: Verify arrow patterns (-->, -.->, ==>)
  • Subgraph not closed: Ensure every subgraph has matching end
  • Node not appearing: Check node ID is defined before use in connections

Validation & mmdc Issues:

  • mmdc not found: Install mermaid-cli with npm install -g @mermaid-js/mermaid-cli
  • Permission errors: Check write permissions to /tmp directory
  • Silent failures: Enhanced validation now checks both exit codes AND SVG content for embedded errors
  • False positive validation: The new validation catches cases where mmdc returns success but SVG contains syntax errors
  • Error file analysis: Check /tmp/mermaid_validate.err for detailed error messages when validation fails
  • SVG validation failures: Diagrams with embedded syntax errors are now detected via SVG content scanning
  • Persistent syntax errors: Use the Automatic Validation Workflow to automatically detect and fix common issues

Enhanced Validation Features:

  • Dual-layer validation: Checks both mmdc exit codes AND SVG output for error markers
  • Error pattern detection: Scans for 'Syntax error in graph', 'mermaidError', 'errorText', 'Parse error' in SVG
  • SVG integrity check: Verifies output contains valid SVG structure with width/height attributes
  • Detailed error reporting: Captures mmdc stderr output for specific syntax issues

Reference Documentation

For complete syntax, advanced features, and more examples:


This skill enables you to create professional diagrams for documentation, design discussions, API specifications, system architecture planning, and process documentation. Choose the appropriate diagram type based on whether you're documenting temporal interactions (sequence), structural relationships (architecture), or process flows (flowchart).