Skip to main content

When to Use This Skill

✅ Use when:

  • Fixing Mermaid diagrams that fail to render on GitHub
  • Automating syntax repairs across multiple diagram files
  • Ensuring GitHub Mermaid compatibility for documentation
  • Batch processing repository-wide diagram fixes
  • Implementing idempotent repair patterns with rollback support
  • Validating diagram syntax before commits

❌ Don't use when:

  • Diagrams already render correctly on GitHub
  • Creating new diagrams from scratch (use diagram creation tools)
  • Only need to view/preview diagrams locally
  • Syntax errors are outside Mermaid specification
  • Manual diagram editing is preferred over automation

Core Capabilities

  • Syntax Detection: Identify 9 common Mermaid syntax issues:
    • Line breaks (<br/>, <br>, <br />)
    • Forward slashes in labels ([/text]) - CRITICAL
    • Raw ampersands (&) in node labels - CRITICAL
    • Over-encoded ampersands (&amp;amp;...)
    • Excessive quotes from repeated fixes
    • Cylinder node quote counting
    • Double braces ({{, }})
    • Gantt dateFormat X (Unix timestamp)
    • Pie chart title parentheses
  • Idempotent Repairs: Pattern matching that prevents re-application of fixes
  • Repository-Wide Processing: Batch processing of all .mmd files with progress tracking
  • Safety Verification: Backup creation, dry-run mode, and automatic rollback on failure
  • Git Integration: Automated commit workflows for diagram fixes
  • GitHub Compatibility: Ensures diagrams render correctly on GitHub

Skill Type

Mermaid diagram syntax fixing and GitHub compatibility automation.

Description

Complete Mermaid diagram fixing capability for GitHub compatibility through idempotent pattern matching, automated syntax repair, and repository-wide processing with safety verification and rollback support.

Components

1. Agent (agents/mermaid-diagram-fixer.md)

Specialized agent for Mermaid diagram GitHub compatibility fixes.

2. Command (commands/fix-mermaid-diagrams.md)

/fix-mermaid-diagrams slash command for manual invocation.

3. Script (scripts/fix-mermaid-diagrams.py)

Python script with CLI interface for diagram fixing.

4. Tests (tests/unit/test_mermaid_fixer.py)

Comprehensive test suite for validation.

Capabilities

Syntax Issue Detection (9 Patterns)

  • Line break detection (<br/>, <br>, <br />) - CRITICAL
  • Forward slash in labels ([/text]) - CRITICAL (causes lexical errors)
  • Raw ampersands (&) in node labels - CRITICAL
  • Over-encoded ampersands (&amp;amp;...)
  • Excessive quotes from repeated fixes
  • Cylinder node quote counting errors
  • Double braces ({{, }})
  • Gantt dateFormat X (Unix timestamp format)
  • Pie chart title parentheses

Idempotent Fixing

  • Check-before-apply patterns
  • No re-application of fixes
  • Safe regex that detects existing fixes
  • Atomic independent operations
  • Post-fix validation

Repository Operations

  • Recursive .mmd file scanning
  • Git submodule support
  • Exclude patterns (.git/, node_modules/)
  • Progress tracking and reporting
  • Batch processing with statistics

Safety & Recovery

  • Pre-fix backup creation
  • Dry-run preview mode
  • Automatic rollback on failure
  • Git integration for commits
  • Detailed error logging

Known Issues & Fixes

1. Line Breaks (Priority: CRITICAL)

Issue: GitHub Mermaid doesn't support line breaks in node labels.

Pattern:

r'<br\s*/?>'  # Matches <br/>, <br>, <br />

Fix:

content = re.sub(r'<br\s*/?>', ' - ', content)

Idempotent: ✅ No line breaks = no match

1a. Forward Slash in Labels (Priority: CRITICAL)

Issue: GitHub Mermaid lexer fails on [/text] node syntax.

Pattern:

r'\[\/([^\]]+)\]'  # Matches [/anything]

Fix:

content = re.sub(r'\[\/([^\]]+)\]', r'[\1]', content)

Idempotent: ✅ Nodes without leading slash won't match

1b. Raw Ampersands in Labels (Priority: CRITICAL)

Issue: Raw & characters in node labels cause rendering issues.

Pattern:

r'&(?!amp;|lt;|gt;|quot;|#)'  # Raw & not part of entity

Fix:

content = re.sub(r'&(?!amp;|lt;|gt;|quot;|#)', ' and ', content)

Idempotent: ✅ Already-escaped entities won't match

2. Over-Encoded Ampersands (Priority: HIGH)

Issue: Multiple encoding: &&amp;&amp;amp; → ...

Pattern:

r'&(?:amp;){2,}'  # Matches 2+ repetitions

Fix:

content = re.sub(r'&(?:amp;){2,}', '&amp;', content)

Idempotent: ✅ Single &amp; won't match

3. Excessive Quotes (Priority: HIGH)

Issue: Repeated parentheses wrapping adds quotes.

Pattern:

r'\["{2,}([^"]+?)"{2,}\]'  # Matches 2+ quotes

Fix:

content = re.sub(r'\["{2,}([^"]+?)"{2,}\]', r'["\1"]', content)

Idempotent: ✅ Single quote won't match

4. Cylinder Nodes (Priority: MEDIUM)

Issue: Needs exactly 3 quotes: ["""(Label)"""]

Pattern:

r'\["{4,}(\([^)]+?\))"{4,}\]'  # Matches 4+ quotes

Fix:

content = re.sub(r'\["{4,}(\([^)]+?\))"{4,}\]', r'["""\1"""]', content)

Idempotent: ✅ 3 quotes won't match

5. Double Braces (Priority: MEDIUM)

Issue: {{ and }} unsupported in Mermaid.

Pattern:

r'\{\{|\}\}'

Fix:

content = re.sub(r'\{\{', '{', content)
content = re.sub(r'\}\}', '}', content)

Idempotent: ✅ Single braces won't match

6. Graph vs. Flowchart (Priority: LOW)

Issue: graph TB deprecated, use flowchart TB

Pattern:

r'^(\s*)graph\s+(TB|TD|BT|RL|LR)'

Fix:

content = re.sub(r'^(\s*)graph\s+', r'\1flowchart ', content, flags=re.MULTILINE)

Idempotent:flowchart won't match

7. Gantt dateFormat X (Priority: MEDIUM)

Issue: GitHub Mermaid has issues with dateFormat X (Unix timestamp).

Pattern:

r'dateFormat\s+X'  # Matches Unix timestamp format

Fix:

content = re.sub(r'dateFormat\s+X', 'dateFormat YYYY-MM-DD', content)

Idempotent:dateFormat YYYY-MM-DD won't match

8. Pie Chart Title Parentheses (Priority: MEDIUM)

Issue: Pie chart titles with parentheses can cause parsing issues.

Pattern:

r'pie\s+title\s+.*\('  # Title containing parentheses

Fix:

content = re.sub(r'(pie\s+title\s+[^(\n]*)\([^)]*\)', r'\1', content)

Idempotent: ✅ No parentheses = no match

Usage Patterns

Via Agent Invocation

Task(subagent_type="general-purpose",
prompt="Use mermaid-diagram-fixer subagent to fix all Mermaid diagrams in the repository")

Via Slash Command

/fix-mermaid-diagrams --scope repo
/fix-mermaid-diagrams --scope repo --dry-run
/fix-mermaid-diagrams --scope file --path diagrams/diagram-01.mmd

Via Python Script

python3 scripts/fix-mermaid-diagrams.py --all
python3 scripts/fix-mermaid-diagrams.py --all --dry-run
python3 scripts/fix-mermaid-diagrams.py --directory diagrams/

Integration with Git Workflow

# Fix diagrams, then commit changes

## How to Use This Skill

1. Review the patterns and examples below
2. Apply the relevant patterns to your implementation
3. Follow the best practices outlined in this skill

Task(subagent_type="mermaid-diagram-fixer",
prompt="Fix all Mermaid diagrams")

Task(subagent_type="git-workflow-orchestrator",
prompt="Commit diagram fixes with conventional commits")

Testing Strategy

Unit Tests

  • Test each idempotent pattern independently
  • Verify no re-application of fixes
  • Test edge cases (empty files, malformed syntax)
  • Validate error handling

Integration Tests

  • End-to-end repository processing
  • Git operations verification
  • Backup and rollback testing
  • Multi-file batch processing

Test Coverage

  • Target: 90%+ overall
  • Critical: 100% for idempotent patterns

Performance Metrics

Benchmarks

Repository SizeFilesTimeMemory
Small<50<10s<100MB
Medium50-200<30s<200MB
Large200+<2min<500MB

Optimizations

  • Parallel file processing
  • Skip unchanged files
  • Incremental mode for large repos
  • Memory-efficient streaming for huge files

Error Handling

Safe Failure Modes

  • Read-only on validation failure
  • Partial success reporting
  • Automatic rollback on critical errors
  • Detailed error tracing

Common Errors

File Not Found:

if not Path(file_path).exists():
raise FileNotFoundError(f"File not found: {file_path}")

Invalid Mermaid:

if not is_valid_mermaid(content):
raise ValueError(f"Invalid Mermaid syntax: {file_path}")

Git Conflicts:

if has_git_conflicts():
raise RuntimeError("Git conflicts detected")

Integration Points

Upstream Dependencies

  • codebase-locator - File discovery
  • orchestrator - Multi-phase coordination

Downstream Consumers

  • git-workflow-orchestrator - Commit fixes
  • codi-documentation-writer - Document changes
  • documentation-librarian - Update indexes

Complementary Skills

  • search-strategies - Efficient file finding
  • production-patterns - Error handling patterns
  • git-workflow-automation - Repository operations

CODITECT Integration

With Project Planning

# Add to tasklist.md
- [ ] Fix all Mermaid diagrams for GitHub compatibility
- [ ] Verify diagrams render correctly on GitHub
- [ ] Update diagram documentation

With CI/CD

# .github/workflows/mermaid-check.yml
name: Mermaid Diagram Validation
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Fix Mermaid Diagrams
run: python3 scripts/fix-mermaid-diagrams.py --all --dry-run
- name: Verify No Changes Needed
run: git diff --exit-code

With Documentation

# Update after fixing diagrams
Task(subagent_type="mermaid-diagram-fixer",
prompt="Fix all diagrams in docs/")

Task(subagent_type="codi-documentation-writer",
prompt="Update diagram documentation and create usage guide")

Best Practices

Before Fixing

  1. Create backup: cp -r diagrams diagrams.backup
  2. Run dry-run: --dry-run to preview changes
  3. Check git status: Ensure clean working directory
  4. Review patterns: Understand what will be fixed

During Fixing

  1. Monitor progress: Watch for errors or warnings
  2. Validate incrementally: Check samples as they're fixed
  3. Track statistics: Note files processed and fixes applied

After Fixing

  1. Verify on GitHub: Check actual rendering
  2. Update documentation: Document changes made
  3. Commit properly: Use conventional commits
  4. Test thoroughly: Ensure no regressions

Troubleshooting

Issue: Fixes Not Applied

Cause: Patterns already fixed or syntax doesn't match

Solution:

  1. Check with --verbose flag
  2. Verify file contains actual issues
  3. Review regex patterns for accuracy

Issue: Regressions After Fix

Cause: Overly aggressive patterns

Solution:

  1. Restore from backup
  2. Review pattern specificity
  3. Add validation checks
  4. Re-run with updated patterns

Issue: Git Conflicts

Cause: Files modified externally

Solution:

  1. Stash or commit local changes
  2. Pull latest changes
  3. Re-run fixer
  4. Resolve any merge conflicts

Version History

  • v1.1.0 (2025-12-16): Enhanced GitHub compatibility

    • Added 3 CRITICAL patterns: forward slash, raw ampersands, line breaks (priority upgrade)
    • Added Gantt dateFormat X detection
    • Added pie chart parentheses detection
    • Total: 9 idempotent fixing patterns (was 6)
  • v1.0.0 (2025-12-02): Initial release

    • 6 idempotent fixing patterns
    • Repository-wide processing
    • Backup and rollback support
    • Comprehensive testing
  • Agent: agents/mermaid-diagram-fixer.md
  • Command: commands/fix-mermaid-diagrams.md
  • Script: scripts/fix-mermaid-diagrams.py
  • Tests: tests/unit/test_mermaid_fixer.py
  • Guide: docs/MERMAID-FIXING-GUIDE.md

Success Output

When this skill completes successfully, output:

✅ SKILL COMPLETE: mermaid-diagram-fixing

Diagram Fixes Applied:
- [x] Files scanned: [count] .mmd files
- [x] Files fixed: [count]
- [x] Syntax issues resolved: [count]
- Line breaks: [count]
- Forward slashes: [count]
- Raw ampersands: [count]
- Over-encoded ampersands: [count]
- Excessive quotes: [count]
- Cylinder nodes: [count]
- Double braces: [count]
- Gantt dateFormat: [count]
- Pie chart titles: [count]

Outputs:
- Fixed diagrams: [paths]
- Backup directory: [path]
- Fix report: [path]
- GitHub compatibility: VERIFIED

Idempotency: All fixes are idempotent (safe to re-run)

Completion Checklist

Before marking this skill as complete, verify:

  • All .mmd files in scope processed
  • Backups created before modifications
  • All 9 syntax patterns checked
  • Fixed files render correctly on GitHub
  • No new syntax errors introduced
  • Dry-run validated before actual fixes (if used)
  • Git status clean or changes intentional
  • Fix report generated with statistics

Failure Indicators

This skill has FAILED if:

  • ❌ Python script throws exceptions
  • ❌ File I/O errors (permission denied, file not found)
  • ❌ Regex patterns fail to match known issues
  • ❌ Fixed diagrams still fail to render on GitHub
  • ❌ Backup creation failed
  • ❌ JSON parsing errors in task state
  • ❌ Git conflicts introduced by fixes
  • ❌ Idempotency violated (re-running produces different results)

When NOT to Use

Do NOT use this skill when:

  • Diagrams already render correctly on GitHub
    • Solution: No fixes needed, skip
  • Creating new diagrams from scratch
    • Solution: Use diagram creation tools (Mermaid Live Editor)
  • Only viewing/previewing diagrams locally
    • Solution: Use local Mermaid preview tools
  • Syntax errors outside Mermaid specification
    • Solution: Manual diagram correction needed
  • Manual editing preferred over automation
    • Solution: Edit .mmd files directly
  • Non-Mermaid diagram formats (PlantUML, Graphviz)
    • Solution: Use format-specific fixing tools
  • Diagrams in version control with conflicts
    • Solution: Resolve git conflicts first

Anti-Patterns (Avoid)

Anti-PatternProblemSolution
Running without backupsData loss riskAlways create backups before fixes
Skipping dry-run on bulk fixesUnexpected mass changesUse --dry-run first for large batches
Ignoring GitHub validationFixes may not renderVerify on GitHub after fixing
Not tracking fixed filesCannot identify what changedUse fix report and git diff
Re-applying fixes repeatedlyIdempotency violationPatterns should detect existing fixes
Fixing without understandingWrong fixes appliedReview patterns and syntax rules first
No version controlCannot rollback bad fixesCommit before and after fixes
Batch fixing without reviewPropagate errorsReview sample fixes before full batch
Overwriting original filesNo recovery pathUse backup and rollback mechanisms
Ignoring pattern confidenceFalse positivesReview low-confidence matches manually

Principles

This skill embodies the following CODITECT principles:

#1 Recycle → Extend → Re-Use → Create

  • Reuses standard Mermaid syntax rules
  • Extends with GitHub-specific compatibility fixes
  • Creates idempotent fixing patterns

#2 Automation with Minimal Human Intervention

  • Automated repository-wide scanning
  • Automatic syntax issue detection
  • Self-correcting with idempotent patterns
  • Automatic backup and rollback

#3 Separation of Concerns

  • Pattern detection separate from fixing
  • Backup mechanism independent of fixing logic
  • Git integration isolated from core functionality

#4 Keep It Simple

  • Simple regex patterns for each issue
  • One pattern per syntax problem
  • Clear success/failure indicators

#5 Eliminate Ambiguity

  • Explicit idempotency (check before apply)
  • Clear pattern matching (no guessing)
  • Documented syntax rules for each pattern

#6 Clear, Understandable, Explainable

  • Each pattern documented with example
  • Fix report shows what was changed
  • Dry-run preview shows impact before applying

#7 First Principles Thinking

  • Based on Mermaid specification
  • GitHub renderer requirements understood
  • Patterns address root causes, not symptoms

#8 No Assumptions

  • Validates file exists before processing
  • Checks pattern match before applying fix
  • Verifies GitHub compatibility after fixes
  • Confirms backup exists before modifying files

Last Updated: 2025-12-16 Status: Production Ready Version: 1.1.0 Maintained By: CODITECT Production Operations Team