mermaid-gen

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

mermaid-gen

mermaid-gen

Purpose

用途

The
mermaid-gen
skill provides AI assistants with expert guidance for creating syntactically correct Mermaid diagrams while avoiding common parsing errors that cause rendering failures. This skill focuses on diagram syntax correctness and best practices.
Key Benefits:
  • Error Prevention: Avoid nested quotes, special character issues, and malformed syntax
  • Syntax Mastery: Apply correct patterns for flowcharts, sequence diagrams, state machines, etc.
  • Quality Assurance: Validate diagrams before rendering using proven templates
  • Troubleshooting: Diagnose and fix parse errors systematically
  • Best Practices: Follow standardized naming, styling, and structure conventions
mermaid-gen
技能为AI助手提供专业指导,帮助创建语法正确的Mermaid图表,同时避免导致渲染失败的常见解析错误。本技能专注于图表语法的正确性与最佳实践。
核心优势:
  • 错误预防: 避免嵌套引号、特殊字符问题和格式错误的语法
  • 语法精通: 为流程图、序列图、状态机等应用正确的语法模式
  • 质量保证: 使用经过验证的模板在渲染前验证图表
  • 故障排查: 系统地诊断并修复解析错误
  • 最佳实践: 遵循标准化的命名、样式和结构规范

When to Use This Skill

适用场景

Use mermaid-gen when:
  • Creating new Mermaid diagrams (flowcharts, sequence diagrams, state machines, etc.)
  • Fixing parse errors or rendering issues in existing diagrams
  • Converting written descriptions into Mermaid syntax
  • Validating diagram syntax before committing to documentation
  • Debugging "Expecting X, got Y" parse errors
  • Migrating diagrams from other formats to Mermaid
  • Need best practice guidance for node naming, styling, subgraphs
Do NOT use mermaid-gen when:
  • Creating simple tables or text-based lists (use markdown tables)
  • Need diagram file management or SVG generation (use
    charts-flow
    skill instead)
  • Creating data visualization charts (bar, pie, line - use charting libraries)
  • Need Gantt charts or Git graphs (outside core focus)
  • Diagram is already working perfectly (no changes needed)
Relationship to charts-flow skill:
  • charts-flow
    : Manages diagram files, generates SVG, embeds in documents
  • mermaid-gen
    : Ensures diagram syntax is correct before file creation
  • Use together:
    charts-flow
    skill calls
    mermaid-gen
    for diagram generation
使用mermaid-gen的场景:
  • 创建新的Mermaid图表(流程图、序列图、状态机等)
  • 修复现有图表中的解析错误或渲染问题
  • 将文字描述转换为Mermaid语法
  • 在提交到文档前验证图表语法
  • 调试「期望X,得到Y」的解析错误
  • 将其他格式的图表迁移为Mermaid格式
  • 需要节点命名、样式、子图等方面的最佳实践指导
不适用mermaid-gen的场景:
  • 创建简单表格或文本列表(使用Markdown表格)
  • 需要图表文件管理或SVG生成(改用
    charts-flow
    技能)
  • 创建数据可视化图表(柱状图、饼图、折线图 - 使用图表库)
  • 需要甘特图或Git图(超出核心聚焦范围)
  • 图表已能完美运行(无需修改)
与charts-flow技能的关系:
  • charts-flow
    : 管理图表文件、生成SVG、嵌入文档
  • mermaid-gen
    : 在创建文件前确保图表语法正确
  • 组合使用:
    charts-flow
    技能调用
    mermaid-gen
    生成图表

Skill Inputs

技能输入项

Required Inputs

必填输入项

InputDescriptionExample
Diagram TypeType of Mermaid diagram
flowchart
,
sequence
,
state
,
class
Diagram PurposeWhat the diagram represents"Agent communication flow", "State machine transitions"
Content DescriptionKey elements and relationships"3 agents, 1 database, request/response flow"
输入项描述示例
图表类型Mermaid图表的类型
flowchart
,
sequence
,
state
,
class
图表用途图表所代表的内容"Agent通信流程", "状态机转换逻辑"
内容描述核心元素及关系"3个Agent、1个数据库、请求/响应流程"

Optional Inputs

可选输入项

InputDescriptionDefault
Existing CodeCurrent Mermaid code (if fixing)None (creating new)
Error MessageParse error from rendererNone
Styling PreferencesColor scheme, layout directionProject defaults
Naming ConventionNode ID format
camelCase
输入项描述默认值
现有代码当前的Mermaid代码(用于修复场景)无(创建新图表时)
错误信息渲染器返回的解析错误
样式偏好配色方案、布局方向项目默认值
命名规范节点ID格式
camelCase

Skill Workflow

技能工作流程

Follow this 5-step process to create or fix Mermaid diagrams:
遵循以下5步流程创建或修复Mermaid图表:

Step 1: Understand Requirements

步骤1: 理解需求

  • Identify diagram type (flowchart, sequence, state, class, etc.)
  • List all nodes/entities that need to be represented
  • Identify relationships and connections
  • Determine flow direction (TD, LR, etc.)
  • Note any grouping needs (subgraphs)
  • 确定图表类型(流程图、序列图、状态图、类图等)
  • 列出需要表示的所有节点/实体
  • 明确节点间的关系与连接
  • 确定流方向(TD、LR等)
  • 记录分组需求(子图)

Step 2: Plan Node Structure

步骤2: 规划节点结构

  • Create meaningful node IDs (camelCase, no spaces)
  • Keep display labels concise but descriptive
  • Identify decision points (diamond shapes)
  • Plan database/storage nodes (cylinder shapes)
  • Determine which nodes need special shapes
  • 创建有意义的节点ID(采用camelCase,无空格)
  • 保持显示标签简洁且具有描述性
  • 确定决策点(菱形形状)
  • 规划数据库/存储节点(圆柱形形状)
  • 确定需要特殊形状的节点

Step 3: Apply Syntax Rules (Critical)

步骤3: 应用语法规则(关键)

  • Remove nested quotes from all node labels
  • Wrap multi-line labels (with
    <br/>
    ) in double quotes
  • Keep edge labels simple - no quotes unless necessary
  • Use ID/label syntax for subgraphs with special characters
  • Separate node IDs from labels:
    NodeID[Display Label]
  • One statement per line: never append or wrap extra tokens after a node/edge definition
  • 移除所有节点标签中的嵌套引号
  • 将多行标签(使用
    <br/>
    )用双引号包裹
  • 简化边标签 - 除非必要,否则不要加引号
  • 对包含特殊字符的子图使用ID/标签语法
  • 分离节点ID与标签:
    NodeID[显示标签]
  • 每行一个语句: 节点/边定义后绝不追加或换行添加额外标记

Step 4: Build Diagram with Template

步骤4: 使用模板构建图表

  • Start with appropriate template (flowchart, sequence, state)
  • Add nodes with correct syntax
  • Define relationships/edges with proper arrow types
  • Group related nodes in subgraphs (if needed)
  • Add styling directives AFTER all nodes defined
  • Include comments (
    %%
    ) for complex sections
  • 从合适的模板开始(流程图、序列图、状态图)
  • 添加语法正确的节点
  • 使用正确的箭头类型定义关系/边
  • 将相关节点分组到子图中(如有需要)
  • 在所有节点定义完成后添加样式指令
  • 为复杂部分添加注释(
    %%

Step 5: Validate and Test

步骤5: 验证与测试

  • Check for nested quotes in any labels
  • Verify subgraph IDs match style references
  • Confirm all node IDs are unique
  • Test in Mermaid Live Editor (https://mermaid.live)
  • Validate all relationships resolve correctly
  • Ensure rendering succeeds without errors
  • Scan for stray tokens after closing brackets
    ]
    or
    }
    on each line
  • Generate Mermaid Live Editor link using
    mermaid-gen/encode-link.ts
  • Return the link only unless raw code is explicitly requested
Error Recovery: If parse error occurs, see "Troubleshooting Guide" section below.
  • 检查所有标签中是否存在嵌套引号
  • 验证子图ID与样式引用是否匹配
  • 确认所有节点ID唯一
  • 在Mermaid在线编辑器(https://mermaid.live)中测试
  • 验证所有关系均可正确解析
  • 确保渲染成功无错误
  • 扫描每行闭合括号
    ]
    }
    后的多余标记
  • 使用
    mermaid-gen/encode-link.ts
    生成Mermaid在线编辑器链接
  • 除非明确要求原始代码,否则仅返回链接
错误恢复: 如果出现解析错误,请查看下方的「故障排查指南」部分。

Common Mermaid Syntax Errors & Solutions

常见Mermaid语法错误与解决方案

1. Quotes in Node Labels

1. 节点标签中的引号

❌ WRONG - Nested quotes cause parse errors:
mermaid
User[User: "What is the status?"] --> System
Response["Message: "Success""] --> User
✅ CORRECT - Remove inner quotes or escape properly:
mermaid
User[User: What is the status?] --> System
Response["Message: Success"] --> User
Rule: Never use nested quotes within node labels enclosed in
[]
or
()
. Either:
  • Remove the inner quotes entirely
  • Wrap the entire label in double quotes if using
    <br/>
    tags
❌ 错误示例 - 嵌套引号会导致解析错误:
mermaid
User[User: "What is the status?"] --> System
Response["Message: "Success""] --> User
✅ 正确示例 - 移除内部引号或正确转义:
mermaid
User[User: What is the status?] --> System
Response["Message: Success"] --> User
规则: 不要在
[]
()
包裹的节点标签中使用嵌套引号。可以选择:
  • 完全移除内部引号
  • 如果使用
    <br/>
    标签,将整个标签用双引号包裹

2. Multi-line Nodes with Special Characters

2. 包含特殊字符的多行节点

❌ WRONG - Decimals and special chars without quotes:
mermaid
Results[Top Results:<br/>1. system_arch.md (0.89)<br/>2. safety.yaml (0.84)]
✅ CORRECT - Wrap in double quotes when using <br/> with numbers/decimals:
mermaid
Results["Top Results:<br/>1. system_arch.md (0.89)<br/>2. safety.yaml (0.84)"]
Rule: When node labels contain:
  • <br/>
    tags AND decimal numbers
  • <br/>
    tags AND special characters
  • Multiple lines with complex content
Wrap the ENTIRE label in double quotes:
NodeID["label content"]
❌ 错误示例 - 包含小数和特殊字符却未加引号:
mermaid
Results[Top Results:<br/>1. system_arch.md (0.89)<br/>2. safety.yaml (0.84)]
✅ 正确示例 - 当使用<br/>和数字/小数时,用双引号包裹:
mermaid
Results["Top Results:<br/>1. system_arch.md (0.89)<br/>2. safety.yaml (0.84)"]
规则: 当节点标签包含以下内容时:
  • <br/>
    标签和小数
  • <br/>
    标签和特殊字符
  • 包含复杂内容的多行文本
请将整个标签用双引号包裹:
NodeID["标签内容"]

3. Edge Labels with Quotes

3. 边标签中的引号

❌ WRONG - Quotes in edge labels:
mermaid
A -->|"Execute"| B
A -->|"Cancel" or Timeout| C
✅ CORRECT - Remove quotes from edge labels:
mermaid
A -->|Execute| B
A -->|Cancel or Timeout| C
Rule: Edge labels (text between
|...|
) should never contain quotes unless absolutely necessary. Use plain text.
❌ 错误示例 - 边标签中使用引号:
mermaid
A -->|"Execute"| B
A -->|"Cancel" or Timeout| C
✅ 正确示例 - 移除边标签中的引号:
mermaid
A -->|Execute| B
A -->|Cancel or Timeout| C
规则: 边标签(
|...|
之间的文本)绝不应该包含引号,除非绝对必要。请使用纯文本。

4. Subgraph Names with Special Characters in Style Directives

4. 样式指令中包含特殊字符的子图名称

❌ WRONG - Ampersands and special chars in style references:
mermaid
subgraph "Audit & Compliance"
    Node1
end
style Audit & Compliance fill:#fff
✅ CORRECT - Use ID/label syntax for subgraphs:
mermaid
subgraph AuditCompliance["Audit & Compliance"]
    Node1
end
style AuditCompliance fill:#fff
Rule: When applying styles to subgraphs with special characters:
  1. Give subgraph an ID without special chars:
    subgraph ID["Display Name"]
  2. Reference the ID in style directive:
    style ID fill:#color
❌ 错误示例 - 样式引用中包含&等特殊字符:
mermaid
subgraph "Audit & Compliance"
    Node1
end
style Audit & Compliance fill:#fff
✅ 正确示例 - 对子图使用ID/标签语法:
mermaid
subgraph AuditCompliance["Audit & Compliance"]
    Node1
end
style AuditCompliance fill:#fff
规则: 当为包含特殊字符的子图应用样式时:
  1. 为子图指定不含特殊字符的ID:
    subgraph ID["显示名称"]
  2. 在样式指令中引用该ID:
    style ID fill:#color

5. Node IDs vs Display Labels

5. 节点ID与显示标签

✅ CORRECT - Separate IDs from labels:
mermaid
UserNode[User: Query the system] --> ProcessNode[Processing Service]
ProcessNode --> DBNode[(Database)]
Rule:
  • First part (before
    [
    ) is the node ID (no spaces, use camelCase)
  • Content in
    []
    is the display label (can have spaces, special chars when quoted)
✅ 正确示例 - 分离ID与标签:
mermaid
UserNode[User: Query the system] --> ProcessNode[Processing Service]
ProcessNode --> DBNode[(Database)]
规则:
  • [
    之前的部分是节点ID(无空格,使用camelCase)
  • []
    内的内容是显示标签(可以包含空格,加引号后可包含特殊字符)

Mermaid Chart Templates

Mermaid图表模板

Flowchart Template (Architecture Diagrams)

流程图模板(架构图)

mermaid
flowchart TD
    %% Define nodes with clear IDs and labels
    User[User Input] -->|Action| Service[Processing Service<br/>FastAPI]

    Service -->|Validate| Validator{Validation Check}
    Validator -->|Invalid| ErrorNode["Error Response<br/>Status: 400"]
    Validator -->|Valid| Database[(Database<br/>PostgreSQL)]

    Database -->|Query Result| Transform[Transform Data]
    Transform -->|Response| User

    %% Group related components
    subgraph Backend["Backend Services"]
        Service
        Validator
        Transform
    end

    subgraph Storage["Data Storage"]
        Database
    end

    %% Apply styles AFTER all nodes defined
    style User fill:#e1f5ff
    style Backend fill:#f0f0f0
    style Storage fill:#fff4e1
mermaid
flowchart TD
    %% 定义具有清晰ID和标签的节点
    User[用户输入] -->|操作| Service[处理服务<br/>FastAPI]

    Service -->|验证| Validator{验证检查}
    Validator -->|无效| ErrorNode["错误响应<br/>状态码: 400"]
    Validator -->|有效| Database[(数据库<br/>PostgreSQL)]

    Database -->|查询结果| Transform[数据转换]
    Transform -->|响应| User

    %% 对相关组件进行分组
    subgraph Backend["后端服务"]
        Service
        Validator
        Transform
    end

    subgraph Storage["数据存储"]
        Database
    end

    %% 在所有节点定义完成后应用样式
    style User fill:#e1f5ff
    style Backend fill:#f0f0f0
    style Storage fill:#fff4e1

Sequence Diagram Template

序列图模板

mermaid
sequenceDiagram
    participant User
    participant API as API Gateway
    participant Auth as Auth Service
    participant DB as Database

    User->>API: Request with credentials
    API->>Auth: Validate token
    Auth-->>API: Token valid
    API->>DB: Query data
    DB-->>API: Return results
    API-->>User: Success response

    Note over User,DB: All communication encrypted via TLS
mermaid
sequenceDiagram
    participant User
    participant API as API网关
    participant Auth as 认证服务
    participant DB as 数据库

    User->>API: 携带凭证的请求
    API->>Auth: 验证令牌
    Auth-->>API: 令牌有效
    API->>DB: 查询数据
    DB-->>API: 返回结果
    API-->>User: 成功响应

    Note over User,DB: 所有通信通过TLS加密

State Diagram Template

状态图模板

mermaid
stateDiagram-v2
    [*] --> Idle
    Idle --> Processing: Start request
    Processing --> Success: Complete
    Processing --> Failed: Error occurs
    Success --> [*]
    Failed --> Retry: Auto retry
    Retry --> Processing: Attempt again
    Failed --> [*]: Max retries exceeded
mermaid
stateDiagram-v2
    [*] --> Idle
    Idle --> Processing: 启动请求
    Processing --> Success: 完成
    Processing --> Failed: 发生错误
    Success --> [*]
    Failed --> Retry: 自动重试
    Retry --> Processing: 再次尝试
    Failed --> [*]: 超出最大重试次数

Quality Gates (Definition of Done)

质量验收标准(完成定义)

Syntax Validation Gates

语法验证标准

  • No nested quotes: All node labels checked for nested quote issues
  • Multi-line syntax: Labels with
    <br/>
    wrapped in double quotes
  • Edge labels clean: No unnecessary quotes in edge labels (between
    |...|
    )
  • Subgraph IDs valid: Subgraphs with special chars use ID/label syntax
  • Node IDs unique: No duplicate node IDs in diagram
  • Node ID format: All IDs use camelCase with no spaces
  • 无嵌套引号: 所有节点标签均检查过嵌套引号问题
  • 多行语法正确: 包含
    <br/>
    的标签用双引号包裹
  • 边标签简洁: 边标签(
    |...|
    之间)无多余引号
  • 子图ID有效: 包含特殊字符的子图使用ID/标签语法
  • 节点ID唯一: 图表中无重复节点ID
  • 节点ID格式正确: 所有ID均使用camelCase且无空格

Structure Validation Gates

结构验证标准

  • Diagram renders: Successfully renders in Mermaid Live Editor
  • All relationships resolve: No broken node references
  • Flow direction correct: TD, LR, RL, BT specified appropriately
  • Subgraphs organized: Related nodes grouped logically
  • Styling applied: Style directives added AFTER all nodes defined
  • 图表可渲染: 能在Mermaid在线编辑器中成功渲染
  • 所有关系可解析: 无节点引用断裂问题
  • 流方向正确: 正确指定TD、LR、RL、BT等方向
  • 子图组织合理: 相关节点逻辑分组
  • 样式应用正确: 样式指令在所有节点定义完成后添加

Quality Assurance Gates

质量保证标准

  • Labels concise: Display labels descriptive but not verbose
  • Comments added: Complex sections documented with
    %%
    comments
  • Appropriate diagram type: Using correct type (flowchart vs sequence vs state)
  • Visual clarity: Diagram is readable and understandable
  • Documentation integration: Title/caption added if embedding in docs
  • 标签简洁: 显示标签具有描述性但不冗长
  • 添加注释: 复杂部分用
    %%
    注释说明
  • 图表类型合适: 使用正确的图表类型(流程图vs序列图vs状态图)
  • 视觉清晰: 图表可读性强、易于理解
  • 文档集成友好: 若嵌入文档则添加标题/说明

Pre-Commit Validation

提交前验证

  • Parse errors: Zero parse errors in renderer
  • Cross-browser: Renders correctly in GitHub, VS Code, docs site
  • File size: Diagram complexity reasonable (not overly complex)
  • Standards compliance: Follows project diagram naming conventions
  • 解析错误: 渲染器中无解析错误
  • 跨浏览器兼容: 在GitHub、VS Code、文档站点中均可正确渲染
  • 文件大小合理: 图表复杂度适中(节点数不超过50个 - 否则拆分)
  • 符合标准: 遵循项目图表命名规范

Skill Constraints

技能约束

What NOT to Do

禁止操作

  • Do NOT use nested quotes in any node labels (causes parse errors)
  • Do NOT put quotes in edge labels unless absolutely necessary
  • Do NOT use special characters in subgraph IDs without ID/label syntax
  • Do NOT reference subgraph display names in style directives (use IDs)
  • Do NOT add styling directives before all nodes are defined
  • Do NOT use literal newlines in labels (use
    <br/>
    tags instead)
  • Do NOT create overly complex diagrams (>50 nodes - split into multiple)
  • Do NOT use generic node IDs like
    node1
    ,
    node2
    (use descriptive IDs)
  • Do NOT skip validation in Mermaid Live Editor before committing
  • Do NOT use deprecated Mermaid syntax (check version compatibility)
  • Do NOT output raw Mermaid code blocks unless explicitly requested
  • Do NOT place extra text after a node/edge on the same line (stray tokens cause parse errors)
  • 禁止在任何节点标签中使用嵌套引号(会导致解析错误)
  • 禁止在边标签中添加引号,除非绝对必要
  • 禁止在子图ID中使用特殊字符,除非采用ID/标签语法
  • 禁止在样式指令中引用子图显示名称(请使用ID)
  • 禁止在所有节点定义完成前添加样式指令
  • 禁止在标签中使用实际换行(请改用
    <br/>
    标签)
  • 禁止创建过于复杂的图表(节点数>50个 - 拆分为多个图表)
  • 禁止使用
    node1
    node2
    等通用节点ID(请使用描述性ID)
  • 禁止在提交前跳过Mermaid在线编辑器的验证步骤
  • 禁止使用已弃用的Mermaid语法(请检查版本兼容性)
  • 禁止输出原始Mermaid代码块,除非明确要求
  • 禁止在节点/边定义的同一行添加额外文本(多余标记会导致解析错误)

Diagram Type Restrictions

图表类型限制

  • Do NOT use Mermaid for:
    • Data visualization charts (bar, pie, line charts - use charting library)
    • Gantt charts for project management (use dedicated PM tools)
    • Git graphs (use git visualization tools)
    • Organizational charts with photos (use org chart tools)
    • Complex data tables (use markdown tables)
  • 禁止使用Mermaid创建以下内容:
    • 数据可视化图表(柱状图、饼图、折线图 - 使用图表库)
    • 项目管理甘特图(使用专用项目管理工具)
    • Git图(使用Git可视化工具)
    • 包含图片的组织结构图(使用组织结构图工具)
    • 复杂数据表格(使用Markdown表格)

File Organization Rules

文件组织规则

  • Always validate syntax before creating diagram files
  • Always use templates as starting point for diagram type
  • Always test in Mermaid Live Editor before embedding
  • Always include diagram type in filename or documentation
  • Always follow project naming conventions for node IDs
  • 必须在创建图表文件前验证语法
  • 必须以对应类型的模板为起点创建图表
  • 必须在嵌入前在Mermaid在线编辑器中测试
  • 必须在文件名或文档中注明图表类型
  • 必须遵循项目的节点ID命名规范

Example Usage

使用示例

Example 1: Create New Flowchart

示例1: 创建新流程图

User Request:
"Create a flowchart showing the authentication flow: user submits credentials, system validates, checks database, returns token or error"
Skill Actions:
  1. Identify type: Flowchart (process flow with decisions)
  2. Plan nodes: User, Validator, Database, TokenService, Error, Success
  3. Plan flow: User → Validate → Decision → Database OR Error → Success OR Error
  4. Apply syntax rules:
    • Node IDs:
      userInput
      ,
      validator
      ,
      dbCheck
      ,
      tokenService
      ,
      errorResponse
      ,
      successResponse
    • Remove nested quotes from all labels
    • Use decision diamond for validation check
  5. Build from template: Use Flowchart Template
  6. Validate: Test in Mermaid Live Editor
Result:
https://mermaid.live/edit#pako:ENCODED_DIAGRAM_HERE
用户请求:
"创建一个展示认证流程的流程图:用户提交凭证,系统验证,检查数据库,返回令牌或错误"
技能操作:
  1. 确定类型: 流程图(包含决策的流程)
  2. 规划节点: 用户、验证器、数据库、令牌服务、错误、成功
  3. 规划流程: 用户 → 验证 → 决策 → 数据库或错误 → 成功或错误
  4. 应用语法规则:
    • 节点ID:
      userInput
      ,
      validator
      ,
      dbCheck
      ,
      tokenService
      ,
      errorResponse
      ,
      successResponse
    • 移除所有标签中的嵌套引号
    • 对验证检查使用决策菱形
  5. 基于模板构建: 使用流程图模板
  6. 验证: 在Mermaid在线编辑器中测试
结果:
https://mermaid.live/edit#pako:ENCODED_DIAGRAM_HERE

Example 2: Fix Parse Error

示例2: 修复解析错误

User Request:
"My sequence diagram won't render. Error: 'Expecting SQE, got STR'. Here's the code:
User->>API: Request "data"
"
Skill Actions:
  1. Diagnose error: "Expecting SQE, got STR" = nested quotes issue
  2. Locate problem: Edge label has nested quotes:
    Request "data"
  3. Apply fix: Remove inner quotes:
    Request data
  4. Validate: Test corrected syntax in Mermaid Live Editor
  5. Return fixed code
Result:
https://mermaid.live/edit#pako:ENCODED_DIAGRAM_HERE
Explanation: Edge labels between
|...|
or after
:
should not contain quotes.
用户请求:
"我的序列图无法渲染。错误信息:'Expecting SQE, got STR'。代码如下:
User->>API: Request "data"
"
技能操作:
  1. 诊断错误: "Expecting SQE, got STR" = 嵌套引号问题
  2. 定位问题: 边标签中存在嵌套引号:
    Request "data"
  3. 应用修复: 移除内部引号:
    Request data
  4. 验证: 在Mermaid在线编辑器中测试修正后的语法
  5. 返回修复后的代码
结果:
https://mermaid.live/edit#pako:ENCODED_DIAGRAM_HERE
说明:
|...|
之间或
:
之后的边标签不应包含引号。

Example 3: Create State Machine with Complex Labels

示例3: 创建包含复杂标签的状态机

User Request:
"Create a state diagram for order processing: Draft → Submitted → Processing → Completed or Failed. Include transition conditions."
Skill Actions:
  1. Identify type: State diagram (state transitions)
  2. Plan states: Draft, Submitted, Processing, Completed, Failed
  3. Plan transitions: With labeled conditions
  4. Apply syntax rules:
    • Use
      stateDiagram-v2
      syntax
    • State IDs:
      Draft
      ,
      Submitted
      ,
      Processing
      ,
      Completed
      ,
      Failed
    • Transition labels with conditions (no quotes)
  5. Build from template: Use State Diagram Template
  6. Validate: Test in Mermaid Live Editor
Result:
https://mermaid.live/edit#pako:ENCODED_DIAGRAM_HERE
用户请求:
"创建一个订单处理的状态图:草稿 → 已提交 → 处理中 → 已完成或失败。包含转换条件。"
技能操作:
  1. 确定类型: 状态图(状态转换)
  2. 规划状态: 草稿、已提交、处理中、已完成、失败
  3. 规划转换: 包含带标签的条件
  4. 应用语法规则:
    • 使用
      stateDiagram-v2
      语法
    • 状态ID:
      Draft
      ,
      Submitted
      ,
      Processing
      ,
      Completed
      ,
      Failed
    • 转换标签包含条件(无引号)
  5. 基于模板构建: 使用状态图模板
  6. 验证: 在Mermaid在线编辑器中测试
结果:
https://mermaid.live/edit#pako:ENCODED_DIAGRAM_HERE

Common Patterns

常见模式

Decision Flow Pattern

决策流模式

mermaid
flowchart TD
    Input[Receive Input] --> Validate{Validate Input}
    Validate -->|Invalid| Reject["Reject with Error<br/>Return 400"]
    Validate -->|Valid| Process[Process Request]
    Process --> Output[Return Success]
mermaid
flowchart TD
    Input[接收输入] --> Validate{验证输入}
    Validate -->|无效| Reject["拒绝并返回错误<br/>状态码: 400"]
    Validate -->|有效| Process[处理请求]
    Process --> Output[返回成功]

Multi-Source Integration Pattern

多源集成模式

mermaid
flowchart TD
    User[User Query] --> Router{Query Router}

    Router -->|Database| SQL[SQL Connector]
    Router -->|Cache| Redis[Redis Connector]
    Router -->|API| External[External API]

    SQL --> Merge[Merge Results]
    Redis --> Merge
    External --> Merge

    Merge --> Response[Formatted Response]
    Response --> User
mermaid
flowchart TD
    User[用户查询] --> Router{查询路由}

    Router -->|数据库| SQL[SQL连接器]
    Router -->|缓存| Redis[Redis连接器]
    Router -->|API| External[外部API]

    SQL --> Merge[合并结果]
    Redis --> Merge
    External --> Merge

    Merge --> Response[格式化响应]
    Response --> User

Error Handling Pattern

错误处理模式

mermaid
flowchart TD
    Start[Start Process] --> Try{Execute}
    Try -->|Success| Complete[Complete Successfully]
    Try -->|Error| Retry{Retry Count < 3?}
    Retry -->|Yes| Wait[Exponential Backoff]
    Wait --> Try
    Retry -->|No| Failed["Failed<br/>Log and Alert"]
mermaid
flowchart TD
    Start[启动流程] --> Try{执行}
    Try -->|成功| Complete[成功完成]
    Try -->|错误| Retry{重试次数 < 3?}
    Retry -->|是| Wait[指数退避]
    Wait --> Try
    Retry -->|否| Failed["失败<br/>记录并告警"]

Troubleshooting Guide

故障排查指南

Error: "Expecting 'SQE', got 'STR'"

错误: "Expecting 'SQE', got 'STR'"

  • Cause: Nested quotes in node labels
  • Fix: Remove inner quotes or wrap entire label in quotes
  • 原因: 节点标签中存在嵌套引号
  • 修复: 移除内部引号或用引号包裹整个标签

Error: "Expecting 'SPACE', got 'AMP'"

错误: "Expecting 'SPACE', got 'AMP'"

  • Cause: Special character (&, /, etc.) in style directive
  • Fix: Use subgraph ID/label syntax:
    subgraph ID["Name"]
  • 原因: 样式指令中包含特殊字符(&、/等)
  • 修复: 使用子图ID/标签语法:
    subgraph ID["名称"]

Error: "Parse error on line X"

错误: "Parse error on line X"

  • Cause: Usually quote-related or malformed syntax
  • Fix: Check for nested quotes, verify node/edge syntax
  • 原因: 通常与引号相关或语法格式错误
  • 修复: 检查嵌套引号,验证节点/边语法

Chart not rendering

图表无法渲染

  • Cause: Invalid node IDs, broken references, or syntax errors
  • Fix: Validate in Mermaid Live Editor, check node ID consistency
  • 原因: 无效节点ID、引用断裂或语法错误
  • 修复: 在Mermaid在线编辑器中验证,检查节点ID一致性

Examples from Real Documentation

真实文档示例

Architecture Flow (ADR Pattern)

架构流程(ADR模式)

mermaid
flowchart TD
    User[User: Submit command] -->|1. Classify| Detector{Command Detector<br/>GPT-4 + Rules}

    Detector -->|Query| QueryPath[Execute Immediately]
    Detector -->|Command| SafetyPath[Safety Validation]

    SafetyPath -->|Check| Circuit{Circuit Breaker Status}
    Circuit -->|Active| Block["Block Command<br/>Display Reason"]
    Circuit -->|Inactive| Execute[Execute Command]

    Execute -->|Log| Audit[WORM Audit Storage]
    Execute -->|Response| User

    subgraph SafetyControls["Safety Controls"]
        Detector
        Circuit
        Audit
    end

    style User fill:#e1f5ff
    style SafetyControls fill:#fff4e1
mermaid
flowchart TD
    User[用户: 提交命令] -->|1. 分类| Detector{命令检测器<br/>GPT-4 + 规则}

    Detector -->|查询| QueryPath[立即执行]
    Detector -->|命令| SafetyPath[安全验证]

    SafetyPath -->|检查| Circuit{断路器状态}
    Circuit -->|激活| Block["拦截命令<br/>显示原因"]
    Circuit -->|未激活| Execute[执行命令]

    Execute -->|记录| Audit[WORM审计存储]
    Execute -->|响应| User

    subgraph SafetyControls["安全控制"]
        Detector
        Circuit
        Audit
    end

    style User fill:#e1f5ff
    style SafetyControls fill:#fff4e1

Data Pipeline Flow

数据流水线流程

mermaid
flowchart LR
    Source[Data Source] -->|Ingest| Process[Processing Pipeline]

    Process -->|Transform| Transform[Transform Layer<br/>Validate & Clean]
    Transform -->|Load| Storage[(Data Warehouse)]

    Storage -->|Query| Analytics[Analytics Service]
    Analytics -->|Visualize| Dashboard[Dashboard UI]

    subgraph Pipeline["Data Pipeline"]
        Process
        Transform
    end

    style Pipeline fill:#f0f0f0
mermaid
flowchart LR
    Source[数据源] -->|摄取| Process[处理流水线]

    Process -->|转换| Transform[转换层<br/>验证与清洗]
    Transform -->|加载| Storage[(数据仓库)]

    Storage -->|查询| Analytics[分析服务]
    Analytics -->|可视化| Dashboard[仪表盘UI]

    subgraph Pipeline["数据流水线"]
        Process
        Transform
    end

    style Pipeline fill:#f0f0f0

Quick Reference Card

快速参考卡

ElementSyntaxExample
Node (rectangle)
ID[Label]
Node1[Process Data]
Node (rounded)
ID(Label)
Start(Begin Process)
Node (database)
ID[(Label)]
DB[(PostgreSQL)]
Node (circle)
ID((Label))
Point((A))
Decision
ID{Label}
Check{Is Valid?}
Arrow
-->
A --> B
Labeled arrow
-- text -->
or `-->
text
Subgraph
subgraph ID["Label"]
subgraph Sys["System"]
Style
style ID fill:#color
style Node1 fill:#e1f5ff
Comment
%% comment
%% This is a note
Line break
<br/>
in label
Node["Line 1<br/>Line 2"]
元素语法示例
节点(矩形)
ID[标签]
Node1[处理数据]
节点(圆角矩形)
ID(标签)
Start(开始流程)
节点(数据库)
ID[(标签)]
DB[(PostgreSQL)]
节点(圆形)
ID((标签))
Point((A))
决策节点
ID{标签}
Check{是否有效?}
箭头
-->
A --> B
带标签的箭头
-- 文本 -->
或 `-->
文本
子图
subgraph ID["标签"]
subgraph Sys["系统"]
样式
style ID fill:#color
style Node1 fill:#e1f5ff
注释
%% 注释
%% 这是一条注释
换行标签中使用
<br/>
Node["第一行<br/>第二行"]

Output Format

输出格式

Generated Artifacts

生成的产物

When using the
mermaid-gen
skill, the primary output is:
Mermaid Live Editor Link:
  • Format: URL to https://mermaid.live/edit with the diagram encoded
  • Content: Syntactically valid Mermaid diagram rendered in the editor
  • Validation: Tested in Mermaid Live Editor before delivery
  • Structure: Includes comments, styling, and proper node/edge syntax
  • Return the link only; do not include the raw Mermaid code unless explicitly requested
Example Output:
https://mermaid.live/edit#pako:ENCODED_DIAGRAM_HERE
使用
mermaid-gen
技能时,主要输出为:
Mermaid在线编辑器链接:
  • 格式: 指向https://mermaid.live/edit的URL,包含编码后的图表
  • 内容: 语法有效的Mermaid图表,可在编辑器中渲染
  • 验证: 交付前已在Mermaid在线编辑器中测试
  • 结构: 包含注释、样式和正确的节点/边语法
  • 仅返回链接;除非明确要求,否则不包含原始Mermaid代码
示例输出:
https://mermaid.live/edit#pako:ENCODED_DIAGRAM_HERE

Link Generation Script

链接生成脚本

Use the sibling Bun script to generate the Mermaid Live Editor link:
bash
bun mermaid-gen/encode-link.ts --file path/to/diagram.mmd
Or pipe Mermaid code via stdin:
bash
printf '%s' "$MERMAID_CODE" | bun mermaid-gen/encode-link.ts
使用配套的Bun脚本生成Mermaid在线编辑器链接:
bash
bun mermaid-gen/encode-link.ts --file path/to/diagram.mmd
或通过标准输入传递Mermaid代码:
bash
printf '%s' "$MERMAID_CODE" | bun mermaid-gen/encode-link.ts

Integration with charts-flow Skill

与charts-flow技能的集成

Skill Relationship:
  • mermaid-gen: Creates syntactically correct diagram code and outputs a Mermaid Live Editor link
  • charts-flow: Takes diagram code and manages file creation, SVG generation, document embedding
Typical Workflow:
  1. User requests diagram for documentation
  2. charts-flow
    skill invoked for file management
  3. charts-flow
    internally calls
    mermaid-gen
    for diagram generation
  4. mermaid-gen
    returns a Mermaid Live Editor link (diagram code is used internally)
  5. charts-flow
    creates diagram file, generates SVG, embeds in parent document
Standalone Usage: When user only needs a shareable diagram link (not file management):
  • Invoke
    mermaid-gen
    directly
  • Returns Mermaid Live Editor link only
  • User opens the link to view or export the diagram
Combined Usage: When user needs complete diagram file workflow:
  • Invoke
    charts-flow
    skill (which uses
    mermaid-gen
    internally)
  • Returns diagram file + SVG + parent document updates
技能关系:
  • mermaid-gen: 创建语法正确的图表代码,输出Mermaid在线编辑器链接
  • charts-flow: 接收图表代码,管理文件创建、SVG生成、文档嵌入
典型工作流程:
  1. 用户请求为文档创建图表
  2. 调用
    charts-flow
    技能进行文件管理
  3. charts-flow
    内部调用
    mermaid-gen
    生成图表内容
  4. mermaid-gen
    返回Mermaid在线编辑器链接(图表代码在内部使用)
  5. charts-flow
    创建图表文件、生成SVG、更新父文档
独立使用: 当用户仅需要可共享的图表链接(无需文件管理)时:
  • 直接调用
    mermaid-gen
  • 仅返回Mermaid在线编辑器链接
  • 用户打开链接即可查看或导出图表
组合使用: 当用户需要完整的图表文件工作流时:
  • 调用
    charts-flow
    技能(内部会使用
    mermaid-gen
  • 返回图表文件 + SVG + 父文档更新

Output Validation Checklist

输出验证清单

Every output from
mermaid-gen
must meet these criteria:
  • ✅ Link opens in Mermaid Live Editor without errors
  • ✅ Output contains only the Mermaid Live Editor link
  • ✅ No nested quotes in any labels
  • ✅ Subgraph IDs match style references
  • ✅ All node IDs are unique
  • ✅ Comments explain complex sections
  • ✅ Follows project naming conventions
mermaid-gen
的每个输出必须满足以下条件:
  • ✅ 链接可在Mermaid在线编辑器中打开且无错误
  • ✅ 输出仅包含Mermaid在线编辑器链接
  • ✅ 所有标签中无嵌套引号
  • ✅ 子图ID与样式引用匹配
  • ✅ 所有节点ID唯一
  • ✅ 复杂部分有注释说明
  • ✅ 遵循项目命名规范

Integration with Project Workflow

与项目工作流的集成

Relationship to Other Skills

与其他技能的关系

charts-flow Skill:
  • Purpose: Diagram file management, SVG generation, document embedding
  • Integration: Calls
    mermaid-gen
    to generate diagram content
  • Use Case: Creating separate diagram files in
    diagrams/
    subdirectories
doc-flow Skill:
  • Purpose: Specification-Driven Development workflow (BRD → PRD → ADR → SYS → SPEC)
  • Integration: Diagrams created with
    mermaid-gen
    support ADRs, SYS docs, and architecture specifications
  • Use Case: Adding architecture diagrams to ADR documents or system specifications
project-mngt Skill:
  • Purpose: MVP/MMP/MMR implementation planning
  • Integration: Diagrams visualize project dependencies and implementation flows
  • Use Case: Creating Gantt-style timelines or dependency graphs (if supported by Mermaid)
charts-flow技能:
  • 用途: 图表文件管理、SVG生成、文档嵌入
  • 集成: 调用
    mermaid-gen
    生成图表内容
  • 使用场景: 在
    diagrams/
    子目录中创建独立的图表文件
doc-flow技能:
  • 用途: 规范驱动的开发工作流(BRD → PRD → ADR → SYS → SPEC)
  • 集成: 使用
    mermaid-gen
    创建的图表支持ADR、SYS文档和架构规范
  • 使用场景: 为ADR文档或系统规范添加架构图
project-mngt技能:
  • 用途: MVP/MMP/MMR实施规划
  • 集成: 图表可视化项目依赖和实施流程
  • 使用场景: 创建甘特式时间线或依赖图(如果Mermaid支持)

Documentation Standards Alignment

与文档标准的对齐

Technical Guidelines (per CLAUDE.md):
  • Focus on technical implementation (not marketing language)
  • Cost optimization considerations (lightweight SVG format)
  • Performance focus (separate diagram files for faster rendering)
  • Security considerations (no executable code in diagrams)
Best Practice Integration:
  • Use
    mermaid-gen
    for syntax correctness
  • Use
    charts-flow
    for file management and performance optimization
  • Follow project naming conventions for node IDs
  • Validate all diagrams before committing to version control
技术指南(遵循CLAUDE.md):
  • 聚焦技术实现(而非营销语言)
  • 考虑成本优化(轻量SVG格式)
  • 聚焦性能(独立图表文件提升渲染速度)
  • 考虑安全性(图表中无可执行代码)
最佳实践集成:
  • 使用
    mermaid-gen
    确保语法正确
  • 使用
    charts-flow
    进行文件管理和性能优化
  • 遵循项目的节点ID命名规范
  • 提交到版本控制前验证所有图表

Version

版本信息

  • Version: 1.0
  • Last Updated: 2025-11-05
  • Lessons Learned From: ADR Architecture Flow diagram fixes
  • 版本: 1.0
  • 最后更新: 2025-11-05
  • 经验来源: ADR架构流程图修复经验

Related Documentation

相关文档