Tech Graph
Generate production-quality SVG technical diagrams, optionally exported as PNG via rsvg-convert.
Vendored from upstream fireworks-tech-graph (yizhiyanhua-ai, MIT). System dep librsvg (provides rsvg-convert) must be installed via your package manager. Do NOT use upstream's npx skills add instructions — this skill is vendored directly into this kit.
SVG-only is a supported success path. If rsvg-convert is not installed, generate-diagram.sh warns and still exits 0, leaving the validated SVG in place — PNG export is a nice-to-have, not a requirement. Install librsvg (brew install librsvg / apt-get install librsvg2-bin) only if you specifically need the PNG.
Vendoring Notes
This skill is vendored — no manual npx skills add step is needed. The required system dependency librsvg (rsvg-convert binary) is a plain package-manager install (brew install librsvg on macOS, apt-get install librsvg2-bin on Debian/Ubuntu). Drift from the upstream fireworks-tech-graph repository is tracked manually; re-check the upstream source when updating this skill.
Helper Scripts (Recommended)
Four helper scripts in scripts/ directory provide stable SVG generation and validation:
1. generate-diagram.sh - Validate SVG + export PNG
./scripts/generate-diagram.sh -t architecture -s 1 -o ./output/arch.svg
- Validates an existing SVG file
- Exports PNG after validation
- Example:
./scripts/generate-diagram.sh -t architecture -s 1 -o ./output/arch.svg
2. generate-from-template.py - Create starter SVG from template
python3 ./scripts/generate-from-template.py architecture ./output/arch.svg '{"title":"My Diagram","nodes":[],"arrows":[]}'
- Loads a built-in SVG template
- Renders nodes, arrows, and legend entries from JSON input
- Escapes text content to keep output XML-valid
3. validate-svg.sh - Validate SVG syntax
./scripts/validate-svg.sh <svg-file>
- Checks XML syntax
- Verifies tag balance
- Validates marker references
- Checks attribute completeness
- Validates path data
4. test-all-styles.sh - Batch test all styles
./scripts/test-all-styles.sh
- Tests multiple diagram sizes
- Validates all generated SVGs
- Generates test report
When to use scripts:
- Use scripts when generating complex SVGs to avoid syntax errors
- Scripts provide automatic validation and error reporting
- Recommended for production diagrams
When to generate SVG directly:
- Simple diagrams with few elements
- Quick prototypes
- When you need full control over SVG structure
Workflow (Always Follow This Order)
- Classify the diagram type (see Diagram Types below)
- Extract structure — identify layers, nodes, edges, flows, and semantic groups from user description
- Plan layout — apply the layout rules for the diagram type
- Load style reference — always load
references/style-1-flat-icon.md unless user specifies another; load the matching numbered style reference for exact color tokens and SVG patterns
- Map nodes to shapes — use Shape Vocabulary below
- Check icon needs — load
references/icons.md for known products
- Write SVG with adaptive strategy (see SVG Generation Strategy below)
- Validate: Run
rsvg-convert file.svg -o /dev/null 2>&1 to check syntax
- Export PNG:
rsvg-convert -w 1920 file.svg -o file.png
- Report the generated file paths
- (Optional) Visual self-review — if your runtime can read images, load the exported PNG back and inspect it. Syntactic validity does not guarantee visual correctness: arrows may cross through component interiors, labels may collide with lifelines or other labels, boxes may overlap, alt-frame text may sit on top of a message, or a legend may cover content. If you see any of these, revise the SVG and re-export; repeat until the rendered image is clean. Common fixes:
- Route arrows through gaps between boxes, not through box interiors
- Add background rects behind arrow labels (opacity 0.95, matching canvas color)
- Widen inter-row/inter-column gutters so same-layer arrows have clear corridors
- Collapse repeated cross-layer arrows into a single "delegates down" rail outside the content area
- Move legend/notes out of any region where arrows or labels land
- Increase viewBox height/width rather than packing elements tighter
Skip this step silently if image reading is unavailable — do not guess.
Diagram Types & Layout Rules
Architecture Diagram
Nodes = services/components. Group into horizontal layers (top→bottom or left→right).
- Typical layers: Client → Gateway/LB → Services → Data/Storage
- Use
<rect> dashed containers to group related services in the same layer
- Arrow direction follows data/request flow
- ViewBox:
0 0 960 600 standard, 0 0 960 800 for tall stacks
Data Flow Diagram
Emphasizes what data moves where. Focus on data transformation.
- Label every arrow with the data type (e.g., "embeddings", "query", "context")
- Use wider arrows (
stroke-width: 2.5) for primary data paths
- Dashed arrows for control/trigger flows
- Color arrows by data category (not just Agent/RAG — use semantics)
Flowchart / Process Flow
Sequential decision/process steps.
- Top-to-bottom preferred; left-to-right for wide flows
- Diamond shapes for decisions, rounded rects for processes, parallelograms for I/O
- Keep node labels short (≤3 words); put detail in sub-labels
- Align nodes on a grid: x positions snap to 120px intervals, y to 80px
Agent Architecture Diagram
Shows how an AI agent reasons, uses tools, and manages memory.
Key conceptual layers to always consider:
- Input layer: User, query, trigger
- Agent core: LLM, reasoning loop, planner
- Memory layer: Short-term (context window), Long-term (vector/graph DB), Episodic
- Tool layer: Tool calls, APIs, search, code execution
- Output layer: Response, action, side-effects
Use cyclic arrows (loop arcs) to show iterative reasoning. Separate memory types visually.
Memory Architecture Diagram (Mem0, MemGPT-style)
Specialized agent diagram focused on memory operations.
- Show memory write path and read path separately (different arrow colors)
- Memory tiers: Working Memory → Short-term → Long-term → External Store
- Label memory operations:
store(), retrieve(), forget(), consolidate()
- Use stacked rects or layered cylinders for storage tiers
Sequence Diagram
Time-ordered message exchanges between participants.
- Participants as vertical lifelines (top labels + vertical dashed lines)
- Messages as horizontal arrows between lifelines, top-to-bottom time order
- Activation boxes (thin filled rects on lifeline) show active processing
- Group with
<rect> loop/alt frames with label in top-left corner
- ViewBox height = 80 + (num_messages × 50)
Comparison / Feature Matrix
Side-by-side comparison of approaches, systems, or components.
- Column headers = systems, row headers = attributes
- Row height: 40px; column width: min 120px; header row height: 50px
- Checked cell: tinted background (e.g.
#dcfce7) + ✓ checkmark; unsupported: #f9fafb fill
- Alternating row fills (
#f9fafb / #ffffff) for readability
- Max readable columns: 5; beyond that, split into two diagrams
Timeline / Gantt
Horizontal time axis showing durations, phases, and milestones.
- X-axis = time (weeks/months/quarters); Y-axis = items/tasks/phases
- Bars: rounded rects, colored by category, labeled inside or beside
- Milestone markers: diamond or filled circle at specific x position with label above
- ViewBox:
0 0 960 400 typical; wider for many time periods: 0 0 1200 400
Mind Map / Concept Map
Radial layout from central concept.
- Central node at
cx=480, cy=280
- First-level branches: evenly distributed around center (360/N degrees)
- Second-level branches: branch off first-level at 30-45° offset
- Use curved
<path> with cubic bezier for branches, not straight lines
Class Diagram (UML)
Static structure showing classes, attributes, methods, and relationships.
- Class box: 3-compartment rect (name / attributes / methods), min width 160px
- Top compartment: class name, bold, centered (abstract = italic)
- Middle: attributes with visibility (
+ public, - private, # protected)
- Bottom: method signatures, same visibility notation
- Relationships:
- Inheritance (extends): solid line + hollow triangle arrowhead, child → parent
- Implementation (interface): dashed line + hollow triangle, class → interface
- Association: solid line + open arrowhead, label with multiplicity (1, 0.., 1..)
- Aggregation: solid line + hollow diamond on container side
- Composition: solid line + filled diamond on container side
- Dependency: dashed line + open arrowhead
- Interface:
<<interface>> stereotype above name, or circle/lollipop notation
- Enum: compartment rect with
<<enumeration>> stereotype, values in bottom
- Layout: parent classes top, children below; interfaces to the left/right of implementors
- ViewBox:
0 0 960 600 standard; 0 0 960 800 for deep hierarchies
Use Case Diagram (UML)
System functionality from user perspective.
- Actor: stick figure (circle head + body line) placed outside system boundary
- Label below figure, 13-14px
- Primary actors on left, secondary/supporting on right
- Use case: ellipse with label centered inside, min 140×60px
- Keep names verb phrases: "Create Order", "Process Payment"
- System boundary: large rect with dashed border + system name in top-left
- Relationships:
- Include: dashed arrow
<<include>> from base to included use case
- Extend: dashed arrow
<<extend>> from extension to base use case
- Generalization: solid line + hollow triangle (specialized → general)
- Layout: system boundary centered, actors outside, use cases inside
- ViewBox:
0 0 960 600 standard
State Machine Diagram (UML)
Lifecycle states and transitions of an entity.
- State: rounded rect with state name, min 120×50px
- Internal activities: small text
entry/ action, exit/ action, do/ activity
- Initial state: filled black circle (r=8), one outgoing arrow
- Final state: filled circle (r=8) inside hollow circle (r=12)
- Choice: small hollow diamond, guard labels on outgoing arrows
[condition]
- Transition: arrow with optional label
event [guard] / action
- Guard conditions in square brackets
- Actions after
/
- Composite/nested state: larger rect containing sub-states, with name tab
- Fork/join: thick horizontal or vertical black bar (synchronization)
- Layout: initial state top-left, final state bottom-right, flow top-to-bottom
- ViewBox:
0 0 960 600 standard
ER Diagram (Entity-Relationship)
Database schema and data relationships.
- Entity: rect with entity name in header (bold), attributes below
- Primary key attribute: underlined
- Foreign key: italic or marked with (FK)
- Min width: 160px; attribute font-size: 12px
- Relationship: diamond shape on connecting line
- Label inside diamond: "has", "belongs to", "enrolls in"
- Cardinality labels near entity:
1, N, 0..1, 0..*, 1..*
- Weak entity: double-bordered rect with double diamond relationship
- Associative entity: diamond + rect hybrid (rect with diamond inside)
- Line style: solid for identifying relationships, dashed for non-identifying
- Layout: entities in 2-3 rows, relationships between related entities
- ViewBox:
0 0 960 600 standard; wider 0 0 1200 600 for many entities
Network Topology
Physical or logical network infrastructure.
- Devices: icon-like rects or rounded rects
- Router: circle with cross arrows
- Switch: rect with arrow grid
- Server: stacked rect (rack icon)
- Firewall: brick-pattern rect or shield shape
- Load Balancer: horizontal split rect with arrows
- Cloud: cloud path (overlapping arcs)
- Connections: lines between device centers
- Ethernet/wired: solid line, label bandwidth
- Wireless: dashed line with WiFi symbol
- VPN: dashed line with lock icon
- Subnets/Zones: dashed rect containers with zone label (DMZ, Internal, External)
- Labels: device hostname + IP below, 12-13px
- Layout: tiered top-to-bottom (Internet → Edge → Core → Access → Endpoints)
- ViewBox:
0 0 960 600 standard
UML Coverage Map
Full mapping of UML 14 diagram types to supported diagram types:
| UML Diagram |
Supported As |
Notes |
| Class |
Class Diagram |
Full UML notation |
| Component |
Architecture Diagram |
Use colored fills per component type |
| Deployment |
Architecture Diagram |
Add node/instance labels |
| Package |
Architecture Diagram |
Use dashed grouping containers |
| Composite Structure |
Architecture Diagram |
Nested rects within components |
| Object |
Class Diagram |
Instance boxes with underlined name |
| Use Case |
Use Case Diagram |
Full actor/ellipse/relationship |
| Activity |
Flowchart / Process Flow |
Add fork/join bars |
| State Machine |
State Machine Diagram |
Full UML notation |
| Sequence |
Sequence Diagram |
Add alt/opt/loop frames |
| Communication |
— |
Approximate with Sequence (swap axes) |
| Timing |
Timeline |
Adapt time axis |
| Interaction Overview |
Flowchart |
Combine activity + sequence fragments |
| ER Diagram |
ER Diagram |
Chen/Crow's foot notation |
Shape Vocabulary
Map semantic concepts to consistent shapes across all diagram types:
| Concept |
Shape |
Notes |
| User / Human |
Circle + body path |
Stick figure or avatar |
| LLM / Model |
Rounded rect with brain/spark icon or gradient fill |
Use accent color |
| Agent / Orchestrator |
Hexagon or rounded rect with double border |
Signals "active controller" |
| Memory (short-term) |
Rounded rect, dashed border |
Ephemeral = dashed |
| Memory (long-term) |
Cylinder (database shape) |
Persistent = solid cylinder |
| Vector Store |
Cylinder with grid lines inside |
Add 3 horizontal lines |
| Graph DB |
Circle cluster (3 overlapping circles) |
|
| Tool / Function |
Gear-like rect or rect with wrench icon |
|
| API / Gateway |
Hexagon (single border) |
|
| Queue / Stream |
Horizontal tube (pipe shape) |
|
| File / Document |
Folded-corner rect |
|
| Browser / UI |
Rect with 3-dot titlebar |
|
| Decision |
Diamond |
Flowcharts only |
| Process / Step |
Rounded rect |
Standard box |
| External Service |
Rect with cloud icon or dashed border |
|
| Data / Artifact |
Parallelogram |
I/O in flowcharts |
Arrow Semantics
Always assign arrow meaning, not just color:
| Flow Type |
Color |
Stroke |
Dash |
Meaning |
| Primary data flow |
blue #2563eb |
2px solid |
none |
Main request/response path |
| Control / trigger |
orange #ea580c |
1.5px solid |
none |
One system triggering another |
| Memory read |
green #059669 |
1.5px solid |
none |
Retrieval from store |
| Memory write |
green #059669 |
1.5px |
5,3 |
Write/store operation |
| Async / event |
gray #6b7280 |
1.5px |
4,2 |
Non-blocking, event-driven |
| Embedding / transform |
purple #7c3aed |
1px solid |
none |
Data transformation |
| Feedback / loop |
purple #7c3aed |
1.5px curved |
none |
Iterative reasoning loop |
Always include a legend when 2+ arrow types are used.
Layout Rules & Validation
Spacing:
- Same-layer nodes: 80px horizontal, 120px vertical between layers
- Canvas margins: 40px minimum, 60px between node edges
- Snap to 8px grid: horizontal 120px intervals, vertical 120px intervals
Arrow Labels (CRITICAL):
- MUST have background rect:
<rect fill="canvas_bg" opacity="0.95"/> with 4px horizontal, 2px vertical padding
- Place mid-arrow, ≤3 words, stagger by 15-20px when multiple arrows converge
- Maintain 10px safety distance from nodes
Arrow Routing:
- Prefer orthogonal (L-shaped) paths to minimize crossings
- Anchor arrows on component edges, not geometric centers
- Route around dense node clusters, use different y-offsets for parallel arrows
- Jump-over arcs (5px radius) for unavoidable crossings
Line Overlap Prevention (CRITICAL - most common bug on Codex):
When two arrows must cross each other, ALWAYS use jump-over arcs to prevent visual overlap:
- Crossing horizontal arrows: add a small semicircle arc (radius 5px, stroke same color as arrow, fill none) that "jumps over" the other line
- SVG pattern for jump-over: use a white/matching-background arc on the lower layer, then draw the upper arc on top
- Multiple crossings: stagger arc radii (5px, 7px, 9px) so arcs don't overlap each other
- Never let two arrows' straight-line segments cross without a jump-over arc
Validation Checklist (run before finalizing):
- Arrow-Component Collision: Arrows MUST NOT pass through component interiors (route around with orthogonal paths)
- Text Overflow: All text MUST fit with 8px padding (estimate:
text.length × 7px ≤ shape_width - 16px)
- Arrow-Text Alignment: Arrow endpoints MUST connect to shape edges (not floating); all arrow labels MUST have background rects
- Container Discipline: Prefer arrows entering and leaving section containers through open gaps between components, not through inner component bodies
SVG Technical Rules
- ViewBox:
0 0 960 600 default; 0 0 960 800 tall; 0 0 1200 600 wide
- Fonts: embed via
<style>font-family: ...</style> — no external @import (breaks rsvg-convert)
<defs>: arrow markers, gradients, filters, clip paths
- Text: minimum 12px, prefer 13-14px labels, 11px sub-labels, 16-18px titles
- All arrows:
<marker> with markerEnd, sized markerWidth="10" markerHeight="7"
- Drop shadows:
<feDropShadow> in <filter>, apply sparingly (key nodes only)
- Curved paths: use
M x1,y1 C cx1,cy1 cx2,cy2 x2,y2 cubic bezier for loops/feedback arrows
- Clip content: use
<clipPath> if text might overflow a node box
SVG Generation & Error Prevention
MANDATORY: Python List Method (ALWAYS use this):
python3 << 'EOF'
lines = []
lines.append('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 700">')
lines.append(' <defs>')
# ... each line separately
lines.append('</svg>')
with open('/path/to/output.svg', 'w') as f:
f.write('\n'.join(lines))
print("SVG generated successfully")
EOF
Why mandatory: Prevents character truncation, typos, and syntax errors. Each line is independent and easy to verify.
Pre-Tool-Call Checklist (CRITICAL - use EVERY time):
- ✅ Can I write out the COMPLETE command/content right now?
- ✅ Do I have ALL required parameters ready?
- ✅ Have I checked for syntax errors in my prepared content?
If ANY answer is NO: STOP. Do NOT call the tool. Prepare the content first.
Error Recovery Protocol:
- First error: Analyze root cause, apply targeted fix
- Second error: Switch method entirely (Python list → chunked generation)
- Third error: STOP and report to user - do NOT loop endlessly
- Never: Retry the same failing command or call tools with empty parameters
Validation (run after generation):
rsvg-convert file.svg -o /tmp/test.png 2>&1 && echo "✓ Valid" && rm /tmp/test.png
If using generate-from-template.py:
- Prefer
source / target node ids in arrow JSON so the generator can snap to node edges
- Keep
x1,y1,x2,y2 as hints or fallback coordinates, not the main routing primitive
- Let the generator choose orthogonal routes; avoid hardcoding center-to-center straight lines unless the path is guaranteed clear
Common Syntax Errors to Avoid:
- ❌
yt-anchor → ✅ y="60" text-anchor="middle"
- ❌
x="390 (missing y) → ✅ x="390" y="250"
- ❌
fill=#fff → ✅ fill="#ffffff"
- ❌
marker-end= → ✅ marker-end="url(#arrow)"
- ❌
L 29450 → ✅ L 290,220
- ❌ Missing
</svg> at end
Output
- Default:
./[derived-name].svg and ./[derived-name].png in current directory
- Custom: user specifies path with
--output /path/ or 输出到 /path/
- PNG export:
rsvg-convert -w 1920 file.svg -o file.png (1920px = 2x retina)
Styles
| # |
Name |
Background |
Best For |
| 1 |
Flat Icon (default) |
White |
Blogs, docs, presentations |
| 2 |
Dark Terminal |
#0f0f1a |
GitHub, dev articles |
| 3 |
Blueprint |
#0a1628 |
Architecture docs |
| 4 |
Notion Clean |
White, minimal |
Notionnce |
| 5 |
Glassmorphism |
Dark gradient |
Product sites, keynotes |
| 6 |
Claude Official |
Warm cream #f8f6f3 |
Anthropic-style diagrams |
| 7 |
OpenAI Official |
Pure white #ffffff |
OpenAI-style diagrams |
Load the matching numbered style reference for exact color tokens and SVG patterns.
Style Selection
Default: Style 1 (Flat Icon) for most diagrams. Load references/style-diagram-matrix.md for detailed style-to-diagram-type recommendations.
These patterns appear frequently — internalize them:
RAG Pipeline: Query → Embed → VectorSearch → Retrieve → Augment → LLM → Response
Agentic RAG: adds Agent loop with Tool use between Query and LLM
Agentic Search: Query → Planner → [Search Tool / Calculator / Code] → Synthesizer → Response
Mem0 / Memory Layer: Input → Memory Manager → [Write: VectorDB + GraphDB] / [Read: Retrieve+Rank] → Context
Agent Memory Types: Sensory (raw input) → Working (context window) → Episodic (past interactions) → Semantic (facts) → Procedural (skills)
Multi-Agent: Orchestrator → [SubAgent A / SubAgent B / SubAgent C] → Aggregator → Output
Tool Call Flow: LLM → Tool Selector → Tool Execution → Result Parser → LLM (loop)
1---2name: hs-tech-graph3description: Generate production-quality SVG+PNG technical diagrams — architecture, data flow, flowchart, sequence, agent/memory, or concept maps — across 7 visual styles. Use when user wants "generate diagram", "draw diagram", "visualize", "architecture diagram", "flowchart", or any system/flow they want illustrated. Pairs with /hs:preview --diagram for visual self-review and /hs:mermaidjs-v11 for inline-doc diagrams; this skill is the publish-grade output mode.4---56# Tech Graph78Generate production-quality SVG technical diagrams, optionally exported as PNG via `rsvg-convert`.910> Vendored from upstream `fireworks-tech-graph` (yizhiyanhua-ai, MIT). System dep `librsvg` (provides `rsvg-convert`) must be installed via your package manager. Do NOT use upstream's `npx skills add` instructions — this skill is vendored directly into this kit.1112**SVG-only is a supported success path.** If `rsvg-convert` is not installed, `generate-diagram.sh` warns and still exits `0`, leaving the validated SVG in place — PNG export is a nice-to-have, not a requirement. Install `librsvg` (`brew install librsvg` / `apt-get install librsvg2-bin`) only if you specifically need the PNG.1314## Vendoring Notes1516This skill is vendored — no manual `npx skills add` step is needed. The required system dependency `librsvg` (`rsvg-convert` binary) is a plain package-manager install (`brew install librsvg` on macOS, `apt-get install librsvg2-bin` on Debian/Ubuntu). Drift from the upstream `fireworks-tech-graph` repository is tracked manually; re-check the upstream source when updating this skill.1718## Helper Scripts (Recommended)1920Four helper scripts in `scripts/` directory provide stable SVG generation and validation:2122### 1. `generate-diagram.sh` - Validate SVG + export PNG2324```bash25./scripts/generate-diagram.sh -t architecture -s 1 -o ./output/arch.svg26```2728- Validates an existing SVG file29- Exports PNG after validation30- Example: `./scripts/generate-diagram.sh -t architecture -s 1 -o ./output/arch.svg`3132### 2. `generate-from-template.py` - Create starter SVG from template3334```bash35python3 ./scripts/generate-from-template.py architecture ./output/arch.svg '{"title":"My Diagram","nodes":[],"arrows":[]}'36```3738- Loads a built-in SVG template39- Renders nodes, arrows, and legend entries from JSON input40- Escapes text content to keep output XML-valid4142### 3. `validate-svg.sh` - Validate SVG syntax4344```bash45./scripts/validate-svg.sh <svg-file>46```4748- Checks XML syntax49- Verifies tag balance50- Validates marker references51- Checks attribute completeness52- Validates path data5354### 4. `test-all-styles.sh` - Batch test all styles5556```bash57./scripts/test-all-styles.sh58```5960- Tests multiple diagram sizes61- Validates all generated SVGs62- Generates test report6364**When to use scripts:**6566- Use scripts when generating complex SVGs to avoid syntax errors67- Scripts provide automatic validation and error reporting68- Recommended for production diagrams6970**When to generate SVG directly:**7172- Simple diagrams with few elements73- Quick prototypes74- When you need full control over SVG structure7576## Workflow (Always Follow This Order)77781. **Classify** the diagram type (see Diagram Types below)792. **Extract structure** — identify layers, nodes, edges, flows, and semantic groups from user description803. **Plan layout** — apply the layout rules for the diagram type814. **Load style reference** — always load `references/style-1-flat-icon.md` unless user specifies another; load the matching numbered style reference for exact color tokens and SVG patterns825. **Map nodes to shapes** — use Shape Vocabulary below836. **Check icon needs** — load `references/icons.md` for known products847. **Write SVG** with adaptive strategy (see SVG Generation Strategy below)858. **Validate**: Run `rsvg-convert file.svg -o /dev/null 2>&1` to check syntax869. **Export PNG**: `rsvg-convert -w 1920 file.svg -o file.png`8710. **Report** the generated file paths8811. **(Optional) Visual self-review** — if your runtime can read images, load the exported PNG back and inspect it. Syntactic validity does not guarantee visual correctness: arrows may cross through component interiors, labels may collide with lifelines or other labels, boxes may overlap, alt-frame text may sit on top of a message, or a legend may cover content. If you see any of these, revise the SVG and re-export; repeat until the rendered image is clean. Common fixes:89 - Route arrows through gaps between boxes, not through box interiors90 - Add background rects behind arrow labels (opacity 0.95, matching canvas color)91 - Widen inter-row/inter-column gutters so same-layer arrows have clear corridors92 - Collapse repeated cross-layer arrows into a single "delegates down" rail outside the content area93 - Move legend/notes out of any region where arrows or labels land94 - Increase viewBox height/width rather than packing elements tighter95 Skip this step silently if image reading is unavailable — do not guess.9697## Diagram Types & Layout Rules9899### Architecture Diagram100101Nodes = services/components. Group into **horizontal layers** (top→bottom or left→right).102103- Typical layers: Client → Gateway/LB → Services → Data/Storage104- Use `<rect>` dashed containers to group related services in the same layer105- Arrow direction follows data/request flow106- ViewBox: `0 0 960 600` standard, `0 0 960 800` for tall stacks107108### Data Flow Diagram109110Emphasizes **what data moves where**. Focus on data transformation.111112- Label every arrow with the data type (e.g., "embeddings", "query", "context")113- Use wider arrows (`stroke-width: 2.5`) for primary data paths114- Dashed arrows for control/trigger flows115- Color arrows by data category (not just Agent/RAG — use semantics)116117### Flowchart / Process Flow118119Sequential decision/process steps.120121- Top-to-bottom preferred; left-to-right for wide flows122- Diamond shapes for decisions, rounded rects for processes, parallelograms for I/O123- Keep node labels short (≤3 words); put detail in sub-labels124- Align nodes on a grid: x positions snap to 120px intervals, y to 80px125126### Agent Architecture Diagram127128Shows how an AI agent reasons, uses tools, and manages memory.129Key conceptual layers to always consider:130131- **Input layer**: User, query, trigger132- **Agent core**: LLM, reasoning loop, planner133- **Memory layer**: Short-term (context window), Long-term (vector/graph DB), Episodic134- **Tool layer**: Tool calls, APIs, search, code execution135- **Output layer**: Response, action, side-effects136 Use cyclic arrows (loop arcs) to show iterative reasoning. Separate memory types visually.137138### Memory Architecture Diagram (Mem0, MemGPT-style)139140Specialized agent diagram focused on memory operations.141142- Show memory **write path** and **read path** separately (different arrow colors)143- Memory tiers: Working Memory → Short-term → Long-term → External Store144- Label memory operations: `store()`, `retrieve()`, `forget()`, `consolidate()`145- Use stacked rects or layered cylinders for storage tiers146147### Sequence Diagram148149Time-ordered message exchanges between participants.150151- Participants as vertical **lifelines** (top labels + vertical dashed lines)152- Messages as horizontal arrows between lifelines, top-to-bottom time order153- Activation boxes (thin filled rects on lifeline) show active processing154- Group with `<rect>` loop/alt frames with label in top-left corner155- ViewBox height = 80 + (num_messages × 50)156157### Comparison / Feature Matrix158159Side-by-side comparison of approaches, systems, or components.160161- Column headers = systems, row headers = attributes162- Row height: 40px; column width: min 120px; header row height: 50px163- Checked cell: tinted background (e.g. `#dcfce7`) + `✓` checkmark; unsupported: `#f9fafb` fill164- Alternating row fills (`#f9fafb` / `#ffffff`) for readability165- Max readable columns: 5; beyond that, split into two diagrams166167### Timeline / Gantt168169Horizontal time axis showing durations, phases, and milestones.170171- X-axis = time (weeks/months/quarters); Y-axis = items/tasks/phases172- Bars: rounded rects, colored by category, labeled inside or beside173- Milestone markers: diamond or filled circle at specific x position with label above174- ViewBox: `0 0 960 400` typical; wider for many time periods: `0 0 1200 400`175176### Mind Map / Concept Map177178Radial layout from central concept.179180- Central node at `cx=480, cy=280`181- First-level branches: evenly distributed around center (360/N degrees)182- Second-level branches: branch off first-level at 30-45° offset183- Use curved `<path>` with cubic bezier for branches, not straight lines184185### Class Diagram (UML)186187Static structure showing classes, attributes, methods, and relationships.188189- **Class box**: 3-compartment rect (name / attributes / methods), min width 160px190 - Top compartment: class name, bold, centered (abstract = _italic_)191 - Middle: attributes with visibility (`+` public, `-` private, `#` protected)192 - Bottom: method signatures, same visibility notation193- **Relationships**:194 - Inheritance (extends): solid line + hollow triangle arrowhead, child → parent195 - Implementation (interface): dashed line + hollow triangle, class → interface196 - Association: solid line + open arrowhead, label with multiplicity (1, 0.._, 1.._)197 - Aggregation: solid line + hollow diamond on container side198 - Composition: solid line + filled diamond on container side199 - Dependency: dashed line + open arrowhead200- **Interface**: `<<interface>>` stereotype above name, or circle/lollipop notation201- **Enum**: compartment rect with `<<enumeration>>` stereotype, values in bottom202- Layout: parent classes top, children below; interfaces to the left/right of implementors203- ViewBox: `0 0 960 600` standard; `0 0 960 800` for deep hierarchies204205### Use Case Diagram (UML)206207System functionality from user perspective.208209- **Actor**: stick figure (circle head + body line) placed outside system boundary210 - Label below figure, 13-14px211 - Primary actors on left, secondary/supporting on right212- **Use case**: ellipse with label centered inside, min 140×60px213 - Keep names verb phrases: "Create Order", "Process Payment"214- **System boundary**: large rect with dashed border + system name in top-left215- **Relationships**:216 - Include: dashed arrow `<<include>>` from base to included use case217 - Extend: dashed arrow `<<extend>>` from extension to base use case218 - Generalization: solid line + hollow triangle (specialized → general)219- Layout: system boundary centered, actors outside, use cases inside220- ViewBox: `0 0 960 600` standard221222### State Machine Diagram (UML)223224Lifecycle states and transitions of an entity.225226- **State**: rounded rect with state name, min 120×50px227 - Internal activities: small text `entry/ action`, `exit/ action`, `do/ activity`228 - **Initial state**: filled black circle (r=8), one outgoing arrow229 - **Final state**: filled circle (r=8) inside hollow circle (r=12)230 - **Choice**: small hollow diamond, guard labels on outgoing arrows `[condition]`231- **Transition**: arrow with optional label `event [guard] / action`232 - Guard conditions in square brackets233 - Actions after `/`234- **Composite/nested state**: larger rect containing sub-states, with name tab235- **Fork/join**: thick horizontal or vertical black bar (synchronization)236- Layout: initial state top-left, final state bottom-right, flow top-to-bottom237- ViewBox: `0 0 960 600` standard238239### ER Diagram (Entity-Relationship)240241Database schema and data relationships.242243- **Entity**: rect with entity name in header (bold), attributes below244 - Primary key attribute: underlined245 - Foreign key: italic or marked with (FK)246 - Min width: 160px; attribute font-size: 12px247- **Relationship**: diamond shape on connecting line248 - Label inside diamond: "has", "belongs to", "enrolls in"249 - Cardinality labels near entity: `1`, `N`, `0..1`, `0..*`, `1..*`250- **Weak entity**: double-bordered rect with double diamond relationship251- **Associative entity**: diamond + rect hybrid (rect with diamond inside)252- Line style: solid for identifying relationships, dashed for non-identifying253- Layout: entities in 2-3 rows, relationships between related entities254- ViewBox: `0 0 960 600` standard; wider `0 0 1200 600` for many entities255256### Network Topology257258Physical or logical network infrastructure.259260- **Devices**: icon-like rects or rounded rects261 - Router: circle with cross arrows262 - Switch: rect with arrow grid263 - Server: stacked rect (rack icon)264 - Firewall: brick-pattern rect or shield shape265 - Load Balancer: horizontal split rect with arrows266 - Cloud: cloud path (overlapping arcs)267- **Connections**: lines between device centers268 - Ethernet/wired: solid line, label bandwidth269 - Wireless: dashed line with WiFi symbol270 - VPN: dashed line with lock icon271- **Subnets/Zones**: dashed rect containers with zone label (DMZ, Internal, External)272- **Labels**: device hostname + IP below, 12-13px273- Layout: tiered top-to-bottom (Internet → Edge → Core → Access → Endpoints)274- ViewBox: `0 0 960 600` standard275276## UML Coverage Map277278Full mapping of UML 14 diagram types to supported diagram types:279280| UML Diagram | Supported As | Notes |281| -------------------- | ------------------------ | ------------------------------------- |282| Class | Class Diagram | Full UML notation |283| Component | Architecture Diagram | Use colored fills per component type |284| Deployment | Architecture Diagram | Add node/instance labels |285| Package | Architecture Diagram | Use dashed grouping containers |286| Composite Structure | Architecture Diagram | Nested rects within components |287| Object | Class Diagram | Instance boxes with underlined name |288| Use Case | Use Case Diagram | Full actor/ellipse/relationship |289| Activity | Flowchart / Process Flow | Add fork/join bars |290| State Machine | State Machine Diagram | Full UML notation |291| Sequence | Sequence Diagram | Add alt/opt/loop frames |292| Communication | — | Approximate with Sequence (swap axes) |293| Timing | Timeline | Adapt time axis |294| Interaction Overview | Flowchart | Combine activity + sequence fragments |295| ER Diagram | ER Diagram | Chen/Crow's foot notation |296297## Shape Vocabulary298299Map semantic concepts to consistent shapes across all diagram types:300301| Concept | Shape | Notes |302| -------------------- | --------------------------------------------------- | --------------------------- |303| User / Human | Circle + body path | Stick figure or avatar |304| LLM / Model | Rounded rect with brain/spark icon or gradient fill | Use accent color |305| Agent / Orchestrator | Hexagon or rounded rect with double border | Signals "active controller" |306| Memory (short-term) | Rounded rect, dashed border | Ephemeral = dashed |307| Memory (long-term) | Cylinder (database shape) | Persistent = solid cylinder |308| Vector Store | Cylinder with grid lines inside | Add 3 horizontal lines |309| Graph DB | Circle cluster (3 overlapping circles) | |310| Tool / Function | Gear-like rect or rect with wrench icon | |311| API / Gateway | Hexagon (single border) | |312| Queue / Stream | Horizontal tube (pipe shape) | |313| File / Document | Folded-corner rect | |314| Browser / UI | Rect with 3-dot titlebar | |315| Decision | Diamond | Flowcharts only |316| Process / Step | Rounded rect | Standard box |317| External Service | Rect with cloud icon or dashed border | |318| Data / Artifact | Parallelogram | I/O in flowcharts |319320## Arrow Semantics321322Always assign arrow meaning, not just color:323324| Flow Type | Color | Stroke | Dash | Meaning |325| --------------------- | ---------------- | ------------ | ----- | ----------------------------- |326| Primary data flow | blue `#2563eb` | 2px solid | none | Main request/response path |327| Control / trigger | orange `#ea580c` | 1.5px solid | none | One system triggering another |328| Memory read | green `#059669` | 1.5px solid | none | Retrieval from store |329| Memory write | green `#059669` | 1.5px | `5,3` | Write/store operation |330| Async / event | gray `#6b7280` | 1.5px | `4,2` | Non-blocking, event-driven |331| Embedding / transform | purple `#7c3aed` | 1px solid | none | Data transformation |332| Feedback / loop | purple `#7c3aed` | 1.5px curved | none | Iterative reasoning loop |333334Always include a **legend** when 2+ arrow types are used.335336## Layout Rules & Validation337338**Spacing**:339340- Same-layer nodes: 80px horizontal, 120px vertical between layers341- Canvas margins: 40px minimum, 60px between node edges342- Snap to 8px grid: horizontal 120px intervals, vertical 120px intervals343344**Arrow Labels** (CRITICAL):345346- MUST have background rect: `<rect fill="canvas_bg" opacity="0.95"/>` with 4px horizontal, 2px vertical padding347- Place mid-arrow, ≤3 words, stagger by 15-20px when multiple arrows converge348- Maintain 10px safety distance from nodes349350**Arrow Routing**:351352- Prefer orthogonal (L-shaped) paths to minimize crossings353- Anchor arrows on component edges, not geometric centers354- Route around dense node clusters, use different y-offsets for parallel arrows355- Jump-over arcs (5px radius) for unavoidable crossings356357**Line Overlap Prevention** (CRITICAL - most common bug on Codex):358When two arrows must cross each other, ALWAYS use jump-over arcs to prevent visual overlap:359360- Crossing horizontal arrows: add a small semicircle arc (radius 5px, stroke same color as arrow, fill none) that "jumps over" the other line361- SVG pattern for jump-over: use a white/matching-background arc on the lower layer, then draw the upper arc on top362- Multiple crossings: stagger arc radii (5px, 7px, 9px) so arcs don't overlap each other363- Never let two arrows' straight-line segments cross without a jump-over arc364365**Validation Checklist** (run before finalizing):3663671. **Arrow-Component Collision**: Arrows MUST NOT pass through component interiors (route around with orthogonal paths)3682. **Text Overflow**: All text MUST fit with 8px padding (estimate: `text.length × 7px ≤ shape_width - 16px`)3693. **Arrow-Text Alignment**: Arrow endpoints MUST connect to shape edges (not floating); all arrow labels MUST have background rects3704. **Container Discipline**: Prefer arrows entering and leaving section containers through open gaps between components, not through inner component bodies371372## SVG Technical Rules373374- ViewBox: `0 0 960 600` default; `0 0 960 800` tall; `0 0 1200 600` wide375- Fonts: embed via `<style>font-family: ...</style>` — no external `@import` (breaks rsvg-convert)376- `<defs>`: arrow markers, gradients, filters, clip paths377- Text: minimum 12px, prefer 13-14px labels, 11px sub-labels, 16-18px titles378- All arrows: `<marker>` with `markerEnd`, sized `markerWidth="10" markerHeight="7"`379- Drop shadows: `<feDropShadow>` in `<filter>`, apply sparingly (key nodes only)380- Curved paths: use `M x1,y1 C cx1,cy1 cx2,cy2 x2,y2` cubic bezier for loops/feedback arrows381- Clip content: use `<clipPath>` if text might overflow a node box382383## SVG Generation & Error Prevention384385**MANDATORY: Python List Method** (ALWAYS use this):386387```python388python3 << 'EOF'389lines = []390lines.append('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 700">')391lines.append(' <defs>')392# ... each line separately393lines.append('</svg>')394395with open('/path/to/output.svg', 'w') as f:396 f.write('\n'.join(lines))397print("SVG generated successfully")398EOF399```400401**Why mandatory**: Prevents character truncation, typos, and syntax errors. Each line is independent and easy to verify.402403**Pre-Tool-Call Checklist** (CRITICAL - use EVERY time):4044051. ✅ Can I write out the COMPLETE command/content right now?4062. ✅ Do I have ALL required parameters ready?4073. ✅ Have I checked for syntax errors in my prepared content?408409**If ANY answer is NO**: STOP. Do NOT call the tool. Prepare the content first.410411**Error Recovery Protocol**:412413- **First error**: Analyze root cause, apply targeted fix414- **Second error**: Switch method entirely (Python list → chunked generation)415- **Third error**: STOP and report to user - do NOT loop endlessly416- **Never**: Retry the same failing command or call tools with empty parameters417418**Validation** (run after generation):419420```bash421rsvg-convert file.svg -o /tmp/test.png 2>&1 && echo "✓ Valid" && rm /tmp/test.png422```423424**If using `generate-from-template.py`**:425426- Prefer `source` / `target` node ids in arrow JSON so the generator can snap to node edges427- Keep `x1,y1,x2,y2` as hints or fallback coordinates, not the main routing primitive428- Let the generator choose orthogonal routes; avoid hardcoding center-to-center straight lines unless the path is guaranteed clear429430**Common Syntax Errors to Avoid**:431432- ❌ `yt-anchor` → ✅ `y="60" text-anchor="middle"`433- ❌ `x="390` (missing y) → ✅ `x="390" y="250"`434- ❌ `fill=#fff` → ✅ `fill="#ffffff"`435- ❌ `marker-end=` → ✅ `marker-end="url(#arrow)"`436- ❌ `L 29450` → ✅ `L 290,220`437- ❌ Missing `</svg>` at end438439## Output440441- **Default**: `./[derived-name].svg` and `./[derived-name].png` in current directory442- **Custom**: user specifies path with `--output /path/` or `输出到 /path/`443- **PNG export**: `rsvg-convert -w 1920 file.svg -o file.png` (1920px = 2x retina)444445## Styles446447| # | Name | Background | Best For |448| --- | ----------------------- | -------------------- | -------------------------- |449| 1 | **Flat Icon** (default) | White | Blogs, docs, presentations |450| 2 | **Dark Terminal** | `#0f0f1a` | GitHub, dev articles |451| 3 | **Blueprint** | `#0a1628` | Architecture docs |452| 4 | **Notion Clean** | White, minimal | Notionnce |453| 5 | **Glassmorphism** | Dark gradient | Product sites, keynotes |454| 6 | **Claude Official** | Warm cream `#f8f6f3` | Anthropic-style diagrams |455| 7 | **OpenAI Official** | Pure white `#ffffff` | OpenAI-style diagrams |456457Load the matching numbered style reference for exact color tokens and SVG patterns.458459## Style Selection460461**Default**: Style 1 (Flat Icon) for most diagrams. Load `references/style-diagram-matrix.md` for detailed style-to-diagram-type recommendations.462463These patterns appear frequently — internalize them:464465**RAG Pipeline**: Query → Embed → VectorSearch → Retrieve → Augment → LLM → Response466**Agentic RAG**: adds Agent loop with Tool use between Query and LLM467**Agentic Search**: Query → Planner → [Search Tool / Calculator / Code] → Synthesizer → Response468**Mem0 / Memory Layer**: Input → Memory Manager → [Write: VectorDB + GraphDB] / [Read: Retrieve+Rank] → Context469**Agent Memory Types**: Sensory (raw input) → Working (context window) → Episodic (past interactions) → Semantic (facts) → Procedural (skills)470**Multi-Agent**: Orchestrator → [SubAgent A / SubAgent B / SubAgent C] → Aggregator → Output471**Tool Call Flow**: LLM → Tool Selector → Tool Execution → Result Parser → LLM (loop)