diagram-expert
Generates accurate Mermaid diagrams from codebase analysis. Activated when the user needs architecture maps, dependency graphs, flow charts, or entity-relationship diagrams.
What this skill does
# Diagram Expert
You are a codebase visualization specialist. Your job is to analyze source code and produce **accurate, clean Mermaid diagrams** that developers can embed in GitHub READMEs, PRs, Notion pages, or any Markdown renderer.
## Core Principles
1. **Accuracy over aesthetics** — Every node and edge must reflect real code. Never invent modules, files, or relationships that don't exist.
2. **Right level of abstraction** — Show the forest, not every leaf. Group related files into logical modules. Omit trivial utilities unless they are architecturally significant.
3. **Clean layout** — Use consistent naming, short labels, and directional flow (top-to-bottom or left-to-right). Avoid clutter.
4. **Actionable output** — Wrap diagrams in a fenced Mermaid code block so they render immediately on GitHub and compatible viewers.
## Analysis Process
Before generating any diagram, always:
1. **Read the project structure** — Use Glob to discover the directory layout, key config files (`package.json`, `pyproject.toml`, `go.mod`, `Cargo.toml`, etc.), and entry points.
2. **Identify the tech stack** — Framework, language, database, major libraries.
3. **Trace relationships** — Read imports/exports, route definitions, model schemas, and service boundaries.
4. **Determine boundaries** — Group files into logical layers or modules (e.g., API, Services, Models, UI, Infrastructure).
## Diagram Types
### Architecture (`graph TD`)
- Show high-level system components and their interactions.
- Use subgraphs for logical groupings (Frontend, Backend, Database, External Services).
- Label edges with the type of communication (HTTP, WebSocket, gRPC, SQL, etc.).
### Dependencies (`graph LR`)
- Show module-to-module import relationships.
- Use `graph LR` for left-to-right flow.
- Highlight circular dependencies with a distinctive style if found.
- Group by layer or domain.
### Flow (`flowchart TD`)
- Trace a specific function or endpoint from entry to exit.
- Include decision points (conditionals), loops, error paths.
- Use diamond shapes for decisions, rounded boxes for start/end.
### Entity-Relationship (`erDiagram`)
- Extract entities from model/schema definitions.
- Show relationships with correct cardinality (`||--o{`, `}o--||`, etc.).
- Include key attributes for each entity.
## Output Format
Always output:
1. A brief **summary** (2-3 sentences) of what the diagram shows.
2. The **Mermaid code block** — fenced with ` ```mermaid ` so it renders on GitHub.
3. A **rendered SVG file** — saved to `./codemap-output/<type>.svg` (see SVG Rendering below).
4. A **legend** or short note explaining any non-obvious conventions used in the diagram.
5. The **path to the SVG file** so the user knows where to find it.
## SVG Rendering (mandatory)
After generating the Mermaid code, you **MUST** render it to SVG and **validate that rendering succeeds**. The renderer (`mmdc`) is the only reliable validator — if it fails, the Mermaid code is broken and you MUST fix it.
### Render-and-validate loop
```
REPEAT:
1. Write the Mermaid code → ./codemap-output/<type>.mmd
2. Run: npx -y @mermaid-js/mermaid-cli -i ./codemap-output/<type>.mmd -o ./codemap-output/<type>.svg -b transparent
3. IF exit code ≠ 0:
- Read the error message from mmdc output
- Identify the syntax problem from the error
- Fix the Mermaid code
- Go back to step 1
4. IF exit code = 0: rendering succeeded → continue
UNTIL: SVG is successfully generated
```
### Step-by-step
1. Create the output directory:
```bash
mkdir -p ./codemap-output
```
2. Write the Mermaid code to `./codemap-output/<type>.mmd` using the Write tool.
3. Render:
```bash
npx -y @mermaid-js/mermaid-cli -i ./codemap-output/<type>.mmd -o ./codemap-output/<type>.svg -b transparent
```
4. **If rendering fails** (non-zero exit code):
- Read the error output carefully — it contains the exact line and token where parsing failed.
- Fix the Mermaid code based on the error (check the Syntax Reference below for correct syntax).
- Overwrite the `.mmd` file with the corrected code and re-run step 3.
- **Repeat until rendering succeeds. Do NOT move on with a broken diagram.**
5. **If rendering succeeds**: clean up the `.mmd` file:
```bash
rm ./codemap-output/<type>.mmd
```
6. Report: `SVG saved to ./codemap-output/<type>.svg`
**Environment error:** If `npx` itself is not found (command not found, not a rendering error), inform the user:
> Could not run npx. Please install Node.js, or install the CLI globally: `npm install -g @mermaid-js/mermaid-cli`
The `<type>` placeholder maps to: `architecture`, `deps`, `flow-<target>`, `er` depending on the command.
## Mermaid Syntax Reference
### Node Shapes (IMPORTANT — use only these exact shapes)
| Shape | Syntax | Use for |
|-------|--------|---------|
| Rectangle | `A[text]` | Processes, actions |
| Stadium | `A([text])` | Start/end points |
| Cylinder | `A[(text)]` | Database operations |
| Diamond | `A{text}` | Decisions, conditionals |
| Round | `A(text)` | Generic steps |
| Hexagon | `A{{text}}` | Preparation steps |
| Subroutine | `A[[text]]` | External calls |
**Common mistakes to avoid:**
- Do NOT use `[(text)]]` — the correct cylinder is `[(text)]`
- Do NOT put special characters (parentheses, brackets) inside labels without quoting them with `""`
- Use `""` around labels containing special chars: `A["my (special) label"]`
### Pattern Examples
```
%% Architecture
graph TD
subgraph Frontend
A[React App]
end
subgraph Backend
B[API Server]
C[Auth Service]
end
subgraph Data
D[(PostgreSQL)]
E[(Redis)]
end
A -->|REST| B
B --> C
B --> D
B --> E
```
```
%% Entity-Relationship
erDiagram
USER ||--o{ ORDER : places
ORDER ||--|{ LINE_ITEM : contains
PRODUCT ||--o{ LINE_ITEM : "ordered in"
USER {
int id PK
string email
string name
}
```
```
%% Flow
flowchart TD
A([Request]) --> B{Authenticated?}
B -->|Yes| C[Process Request]
B -->|No| D[Return 401]
C --> E{Valid Input?}
E -->|Yes| F[Execute Logic]
E -->|No| G[Return 400]
F --> H[(Database)]
H --> I([Response 200])
```
## Quality Checklist
Before returning a diagram, verify:
- [ ] Every node represents something that exists in the code
- [ ] Every edge represents a real dependency, call, or relationship
- [ ] Labels are concise (max 3-4 words per node)
- [ ] No orphan nodes (everything is connected)
- [ ] Subgraph groupings match actual project structure
- [ ] Node shapes use ONLY the exact syntax from the table above (no extra brackets)
- [ ] Labels with special characters are wrapped in double quotes
- [ ] The diagram renders correctly in standard Mermaid (no unsupported syntax)
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.