diagramming-code
Generates Mermaid diagrams from Trailmark code graphs. Produces call graphs, class hierarchies, module dependency maps, containment diagrams, complexity heatmaps, and attack surface data flow visualizations. Use when visualizing code architecture, drawing call graphs, generating
Install
npx skills add https://github.com/trailofbits/skills/tree/main/plugins/trailmark/skills/diagramming-code
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install trailofbits-skills@llmmart
git clone https://github.com/trailofbits/skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole trailofbits/skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Diagramming Code
Generates Mermaid diagrams from Trailmark's code graph. A pre-made script
handles Mermaid syntax generation; Claude selects the diagram type and
parameters. Trailmark 0.4.0 includes a native trailmark diagram command; use
it only after a version/command check, otherwise use this skill's bundled
script.
When to Use
- Visualizing call paths between functions
- Drawing class inheritance hierarchies
- Mapping module import dependencies
- Showing class structure with members
- Highlighting complexity hotspots with color coding
- Tracing data flow from entrypoints to sensitive functions
When NOT to Use
- Querying the graph without visualization (use the
trailmarkskill) - Mutation testing triage (use the
genotoxicskill) - Architecture diagrams not derived from code (draw by hand)
Prerequisites
trailmark must be installed. If uv run trailmark fails, run:
uv tool install trailmark
# Python snippets: uv run --with trailmark python - (a tool env is not importable)
DO NOT fall back to hand-writing Mermaid from source code reading. The script uses Trailmark's parsed graph for accuracy. If installation fails, report the error to the user.
Version Gate
Check whether native v0.4 diagram support exists:
trailmark diagram --help 2>/dev/null || uv run trailmark diagram --help 2>/dev/null
If this succeeds, you may use trailmark diagram. If it fails, use
uv run {baseDir}/scripts/diagram.py, which keeps the older skill workflow
intact. Do not assume the native CLI exists on Trailmark 0.2.x.
Quick Start
uv run {baseDir}/scripts/diagram.py \
--target {targetDir} --language auto --type call-graph \
--focus main --depth 2
# Trailmark 0.4.0+ equivalent after the Version Gate succeeds
uv run trailmark diagram \
--target {targetDir} --language auto --type call-graph \
--focus main --depth 2
Output is raw Mermaid text. Wrap in a fenced code block:
```mermaid
flowchart TB
...
```
Diagram Types
├─ "Who calls what?" → --type call-graph
├─ "Class inheritance?" → --type class-hierarchy
├─ "Module dependencies?" → --type module-deps
├─ "Class members and structure?" → --type containment
├─ "Where is complexity highest?" → --type complexity
└─ "Path from input to function?" → --type data-flow
For detailed examples of each type, see references/diagram-types.md.
Workflow
Diagram Progress:
- [ ] Step 1: Verify trailmark is installed
- [ ] Step 2: Identify diagram type from user request
- [ ] Step 3: Determine focus node and parameters
- [ ] Step 4: Run diagram.py script (or native trailmark diagram on v0.4+)
- [ ] Step 5: Verify output is non-empty and well-formed
- [ ] Step 6: Embed diagram in response
Step 1: Run uv run trailmark analyze --language auto --summary {targetDir}. Install
if it fails. Then run pre-analysis via the programmatic API:
from trailmark.query.api import QueryEngine
engine = QueryEngine.from_directory("{targetDir}", language="auto")
engine.preanalysis()
Pre-analysis enriches the graph with blast radius, taint propagation,
and privilege boundary data used by data-flow diagrams.
If auto-detection is wrong for the target, rerun with an explicit language or
comma-separated list such as python,rust.
Step 2: Match the user's request to a --type using the decision tree
above.
Step 3: For call-graph and data-flow, identify the focus function.
Default --depth 2. Use --direction LR for dependency flows.
Step 4: Run the script and capture stdout. If the native v0.4 CLI is available, either command is acceptable; prefer the bundled script when you need behavior consistent with this skill's references.
Step 5: Check: output starts with flowchart or classDiagram,
contains at least one node. If empty or malformed, consult
references/mermaid-syntax.md.
Step 6: Wrap output in ```mermaid ``` code fence.
Script Reference
uv run {baseDir}/scripts/diagram.py [OPTIONS]
# or, on Trailmark 0.4.0+:
uv run trailmark diagram [OPTIONS]
| Argument | Short | Default | Description |
|---|---|---|---|
--target |
-t |
required | Directory to analyze |
--language |
-l |
python |
Source language |
--type |
-T |
required | Diagram type (see above) |
--focus |
-f |
none | Center diagram on this node |
--depth |
-d |
2 |
BFS traversal depth |
--direction |
TB |
Layout: TB (top-bottom) or LR (left-right) |
|
--threshold |
10 |
Min complexity for complexity type |
Examples
# Call graph centered on a function
uv run {baseDir}/scripts/diagram.py -t src/ -T call-graph -f parse_file
# Class hierarchy for a Rust project
uv run {baseDir}/scripts/diagram.py -t src/ -l rust -T class-hierarchy
# Module dependency map, left-to-right
uv run {baseDir}/scripts/diagram.py -t src/ -T module-deps --direction LR
# Class members
uv run {baseDir}/scripts/diagram.py -t src/ -T containment
# Complexity heatmap (threshold 5)
uv run {baseDir}/scripts/diagram.py -t src/ -T complexity --threshold 5
# Data flow from entrypoints to a specific function
uv run {baseDir}/scripts/diagram.py -t src/ -T data-flow -f execute_query
Customization
Direction: Use TB (default) for hierarchical views, LR for
left-to-right flows like dependency chains.
Depth: Increase --depth to see more of the call graph. Decrease to
reduce clutter. The script warns if the diagram exceeds 100 nodes.
Focus: Always use --focus for call-graph on non-trivial codebases.
For data-flow, omitting focus auto-targets the top 10 complexity hotspots.
Language: Prefer --language auto for polyglot or unfamiliar repos.
Use an explicit language only when you know the target is single-language or
you need to exclude unrelated components.
Supporting Documentation
- references/diagram-types.md - Detailed docs and Mermaid examples for each diagram type
- references/mermaid-syntax.md - ID sanitization, escaping, style definitions, and common pitfalls
Files (skills)
-
agents
-
openai.yaml 241 B
interface: display_name: "Code Diagrams" short_description: "Generate architecture diagrams from Trailmark code graphs" icon_small: "assets/trail-of-bits-mark.svg" icon_large: "assets/trail-of-bits-mark.svg" brand_color: "#D83A34"
-
-
assets
-
trail-of-bits-mark.svg 3 KB · in bundle
-
-
references
-
diagram-types.md 5.1 KB
# Diagram Types ## Contents - [Call graph](#call-graph) - [Class hierarchy](#class-hierarchy) - [Module dependencies](#module-dependencies) - [Containment](#containment) - [Complexity heatmap](#complexity-heatmap) - [Attack surface / data flow](#attack-surface--data-flow) --- ## Call Graph Shows which functions call which. Built from `callers_of` / `callees_of` queries and `calls` edges. **Mermaid type:** `flowchart` **When to use `--focus`:** Almost always. Without focus, large codebases produce unreadable diagrams. Start with `--depth 2` and increase if needed. **Arrow styles reflect edge confidence:** - Solid (`-->`) = certain (direct call) - Dashed (`-.->`) = inferred (attribute access on non-self) - Dotted (`..->`) = uncertain (dynamic dispatch) **Example output:** ```mermaid flowchart TB query_api_QueryEngine_callers_of["callers_of, method"] query_api_QueryEngine_callees_of["callees_of, method"] query_api_QueryEngine_paths_between["paths_between, method"] storage_graph_store_GraphStore_find_node_id["find_node_id, method"] query_api_QueryEngine_callers_of --> storage_graph_store_GraphStore_find_node_id query_api_QueryEngine_callees_of --> storage_graph_store_GraphStore_find_node_id query_api_QueryEngine_paths_between --> storage_graph_store_GraphStore_find_node_id ``` **Script invocation:** ```bash uv run {baseDir}/scripts/diagram.py \ --target {targetDir} --type call-graph \ --focus QueryEngine --depth 2 ``` --- ## Class Hierarchy Shows inheritance (`<|--`) and interface implementation (`<|..`) relationships between classes, structs, interfaces, and traits. **Mermaid type:** `classDiagram` **Limitations:** Languages without class inheritance (e.g., Go, C) produce empty diagrams. The script emits a note node in that case. **Example output:** ```mermaid classDiagram class models_nodes_CodeUnit { class } class models_edges_CodeEdge { class } models_nodes_CodeUnit <|-- models_nodes_Parameter ``` **Script invocation:** ```bash uv run {baseDir}/scripts/diagram.py \ --target {targetDir} --type class-hierarchy ``` --- ## Module Dependencies Shows import relationships between modules. Built from `imports` edges. **Mermaid type:** `flowchart` **Best with `--direction LR`** for left-to-right dependency flow. **Example output:** ```mermaid flowchart LR query_api["api, module"] storage_graph_store["graph_store, module"] models_nodes["nodes, module"] query_api --> storage_graph_store storage_graph_store --> models_nodes ``` **Script invocation:** ```bash uv run {baseDir}/scripts/diagram.py \ --target {targetDir} --type module-deps --direction LR ``` --- ## Containment Shows classes and their member functions/methods using `contains` edges. **Mermaid type:** `classDiagram` (with member lists) **Example output:** ```mermaid classDiagram class storage_graph_store_GraphStore { +callers_of() +callees_of() +paths_between() list +find_node() CodeUnit } ``` **Script invocation:** ```bash uv run {baseDir}/scripts/diagram.py \ --target {targetDir} --type containment ``` --- ## Complexity Heatmap Shows functions color-coded by cyclomatic complexity with call edges between them. Only nodes meeting `--threshold` are included. **Mermaid type:** `flowchart` with `classDef` styles **Color scale:** - Green (`low`): CC < 5 - Yellow (`medium`): CC 5-10 - Red (`high`): CC > 10 **Example output:** ```mermaid flowchart TB parsers_python_parser_parse_file["parse_file, method, CC=15"]:::high parsers_python_parser_visit_class["visit_class, method, CC=8"]:::medium parsers_python_parser_parse_file --> parsers_python_parser_visit_class classDef low fill:rgba(40,167,69,0.2),stroke:#28a745,color:#28a745 classDef medium fill:rgba(255,193,7,0.2),stroke:#e6a817,color:#e6a817 classDef high fill:rgba(220,53,69,0.2),stroke:#dc3545,color:#dc3545 ``` **Script invocation:** ```bash uv run {baseDir}/scripts/diagram.py \ --target {targetDir} --type complexity --threshold 5 ``` --- ## Attack Surface / Data Flow Shows paths from entrypoints (user input, API endpoints) to sensitive functions. Entrypoints are styled distinctly (rounded rectangles, blue). **Mermaid type:** `flowchart` Without `--focus`, the script targets the top 10 complexity hotspots reachable from entrypoints. With `--focus`, it shows all paths from entrypoints to the specified function. **Example output:** ```mermaid flowchart TB handle_request(["handle_request, function"]):::entrypoint validate_input["validate_input, function"] execute_query["execute_query, function"] handle_request --> validate_input validate_input --> execute_query classDef entrypoint fill:rgba(0,123,255,0.2),stroke:#007bff,color:#007bff ``` **Script invocation:** ```bash # Focus on a specific sensitive function uv run {baseDir}/scripts/diagram.py \ --target {targetDir} --type data-flow \ --focus execute_query # Auto-detect: entrypoints to top complexity hotspots uv run {baseDir}/scripts/diagram.py \ --target {targetDir} --type data-flow ``` -
mermaid-syntax.md 2.9 KB
# Mermaid Syntax Reference Pitfalls and edge cases when generating Mermaid from code graph data. ## Contents - [Node ID sanitization](#node-id-sanitization) - [Label escaping](#label-escaping) - [Style definitions](#style-definitions) - [Edge confidence styling](#edge-confidence-styling) - [Common pitfalls](#common-pitfalls) --- ## Node ID Sanitization Trailmark node IDs use `module:Class.method` format. Mermaid node IDs only allow `[a-zA-Z0-9_]`. **Rules applied by `diagram.py`:** - Replace any non-alphanumeric character (except `_`) with `_` - Prefix with `n_` if the result starts with a digit **Examples:** | Trailmark ID | Mermaid ID | |---|---| | `query.api:QueryEngine.callers_of` | `query_api_QueryEngine_callers_of` | | `3rdparty:init` | `n_3rdparty_init` | --- ## Label Escaping Node labels are wrapped in double quotes to safely include special characters: ``` node_id["label with (parens) and: colons"] ``` If the label itself contains double quotes, replace `"` with `#quot;` (Mermaid's HTML entity escape). --- ## Style Definitions Use `classDef` to define reusable styles and `:::` to apply them: ```mermaid flowchart TB A["Low complexity"]:::low B["High complexity"]:::high classDef low fill:rgba(40,167,69,0.2),stroke:#28a745,color:#28a745 classDef high fill:rgba(220,53,69,0.2),stroke:#dc3545,color:#dc3545 ``` The script defines three classes for complexity heatmaps: - `low` (green): CC < 5 - `medium` (yellow): CC 5-10 - `high` (red): CC > 10 And one for data flow: - `entrypoint` (blue): marks untrusted input sources --- ## Edge Confidence Styling Arrow syntax varies by edge confidence: | Confidence | Arrow | Meaning | |---|---|---| | `certain` | `-->` | Direct call or `self.method()` | | `inferred` | `-.->` | Attribute access on non-self object | | `uncertain` | `..->` | Dynamic dispatch, reflection | For class diagrams, arrows are different: - `<\|--` = inherits - `<\|..` = implements --- ## Common Pitfalls **Reserved words as node IDs:** `end`, `graph`, `subgraph`, `style`, `classDef`, `click` are reserved. The sanitization function avoids most conflicts since it replaces special characters, but single-word function names matching reserved words can still collide. Workaround: use the full qualified ID which includes the module prefix. **Leading digits:** Mermaid node IDs cannot start with a digit. The script prefixes `n_` in this case. **Diagram size:** Mermaid renderers struggle with >100 nodes. The script warns when this limit is exceeded and suggests using `--focus` to scope the diagram. **Empty diagrams:** When no edges of the required type exist (e.g., no `inherits` edges in a Go codebase), the script emits a single-node diagram with an explanatory message rather than failing. **Parentheses in labels:** Mermaid interprets `()` as rounded-rectangle node shape. Always use quoted labels (`["label"]`) to avoid accidental shape changes.
-
-
scripts
-
diagram.py 389 B
# /// script # requires-python = ">=3.12" # dependencies = ["trailmark"] # /// """Generate Mermaid diagrams from Trailmark code graphs. Thin wrapper — all logic lives in ``trailmark.diagram``. Run via ``uv run {this_file} --target ... --type ...``. """ from __future__ import annotations import sys from trailmark.diagram import main if __name__ == "__main__": sys.exit(main())
-
-
SKILL.md 6.7 KB
--- name: diagramming-code description: > Generates Mermaid diagrams from Trailmark code graphs. Produces call graphs, class hierarchies, module dependency maps, containment diagrams, complexity heatmaps, and attack surface data flow visualizations. Use when visualizing code architecture, drawing call graphs, generating class diagrams, creating dependency maps, producing complexity heatmaps, or visualizing data flow and attack surface paths as Mermaid diagrams. --- # Diagramming Code Generates Mermaid diagrams from Trailmark's code graph. A pre-made script handles Mermaid syntax generation; Claude selects the diagram type and parameters. Trailmark 0.4.0 includes a native `trailmark diagram` command; use it only after a version/command check, otherwise use this skill's bundled script. ## When to Use - Visualizing call paths between functions - Drawing class inheritance hierarchies - Mapping module import dependencies - Showing class structure with members - Highlighting complexity hotspots with color coding - Tracing data flow from entrypoints to sensitive functions ## When NOT to Use - Querying the graph without visualization (use the `trailmark` skill) - Mutation testing triage (use the `genotoxic` skill) - Architecture diagrams not derived from code (draw by hand) ## Prerequisites **trailmark** must be installed. If `uv run trailmark` fails, run: ```bash uv tool install trailmark # Python snippets: uv run --with trailmark python - (a tool env is not importable) ``` **DO NOT** fall back to hand-writing Mermaid from source code reading. The script uses Trailmark's parsed graph for accuracy. If installation fails, report the error to the user. ## Version Gate Check whether native v0.4 diagram support exists: ```bash trailmark diagram --help 2>/dev/null || uv run trailmark diagram --help 2>/dev/null ``` If this succeeds, you may use `trailmark diagram`. If it fails, use `uv run {baseDir}/scripts/diagram.py`, which keeps the older skill workflow intact. Do not assume the native CLI exists on Trailmark 0.2.x. --- ## Quick Start ```bash uv run {baseDir}/scripts/diagram.py \ --target {targetDir} --language auto --type call-graph \ --focus main --depth 2 # Trailmark 0.4.0+ equivalent after the Version Gate succeeds uv run trailmark diagram \ --target {targetDir} --language auto --type call-graph \ --focus main --depth 2 ``` Output is raw Mermaid text. Wrap in a fenced code block: ````markdown ```mermaid flowchart TB ... ``` ```` --- ## Diagram Types ``` ├─ "Who calls what?" → --type call-graph ├─ "Class inheritance?" → --type class-hierarchy ├─ "Module dependencies?" → --type module-deps ├─ "Class members and structure?" → --type containment ├─ "Where is complexity highest?" → --type complexity └─ "Path from input to function?" → --type data-flow ``` For detailed examples of each type, see [references/diagram-types.md](references/diagram-types.md). --- ## Workflow ``` Diagram Progress: - [ ] Step 1: Verify trailmark is installed - [ ] Step 2: Identify diagram type from user request - [ ] Step 3: Determine focus node and parameters - [ ] Step 4: Run diagram.py script (or native trailmark diagram on v0.4+) - [ ] Step 5: Verify output is non-empty and well-formed - [ ] Step 6: Embed diagram in response ``` **Step 1:** Run `uv run trailmark analyze --language auto --summary {targetDir}`. Install if it fails. Then run pre-analysis via the programmatic API: ```python from trailmark.query.api import QueryEngine engine = QueryEngine.from_directory("{targetDir}", language="auto") engine.preanalysis() ``` Pre-analysis enriches the graph with blast radius, taint propagation, and privilege boundary data used by `data-flow` diagrams. If auto-detection is wrong for the target, rerun with an explicit language or comma-separated list such as `python,rust`. **Step 2:** Match the user's request to a `--type` using the decision tree above. **Step 3:** For `call-graph` and `data-flow`, identify the focus function. Default `--depth 2`. Use `--direction LR` for dependency flows. **Step 4:** Run the script and capture stdout. If the native v0.4 CLI is available, either command is acceptable; prefer the bundled script when you need behavior consistent with this skill's references. **Step 5:** Check: output starts with `flowchart` or `classDiagram`, contains at least one node. If empty or malformed, consult [references/mermaid-syntax.md](references/mermaid-syntax.md). **Step 6:** Wrap output in ` ```mermaid ``` ` code fence. --- ## Script Reference ``` uv run {baseDir}/scripts/diagram.py [OPTIONS] # or, on Trailmark 0.4.0+: uv run trailmark diagram [OPTIONS] ``` | Argument | Short | Default | Description | |---|---|---|---| | `--target` | `-t` | required | Directory to analyze | | `--language` | `-l` | `python` | Source language | | `--type` | `-T` | required | Diagram type (see above) | | `--focus` | `-f` | none | Center diagram on this node | | `--depth` | `-d` | `2` | BFS traversal depth | | `--direction` | | `TB` | Layout: `TB` (top-bottom) or `LR` (left-right) | | `--threshold` | | `10` | Min complexity for `complexity` type | ### Examples ```bash # Call graph centered on a function uv run {baseDir}/scripts/diagram.py -t src/ -T call-graph -f parse_file # Class hierarchy for a Rust project uv run {baseDir}/scripts/diagram.py -t src/ -l rust -T class-hierarchy # Module dependency map, left-to-right uv run {baseDir}/scripts/diagram.py -t src/ -T module-deps --direction LR # Class members uv run {baseDir}/scripts/diagram.py -t src/ -T containment # Complexity heatmap (threshold 5) uv run {baseDir}/scripts/diagram.py -t src/ -T complexity --threshold 5 # Data flow from entrypoints to a specific function uv run {baseDir}/scripts/diagram.py -t src/ -T data-flow -f execute_query ``` --- ## Customization **Direction:** Use `TB` (default) for hierarchical views, `LR` for left-to-right flows like dependency chains. **Depth:** Increase `--depth` to see more of the call graph. Decrease to reduce clutter. The script warns if the diagram exceeds 100 nodes. **Focus:** Always use `--focus` for `call-graph` on non-trivial codebases. For `data-flow`, omitting focus auto-targets the top 10 complexity hotspots. **Language:** Prefer `--language auto` for polyglot or unfamiliar repos. Use an explicit language only when you know the target is single-language or you need to exclude unrelated components. --- ## Supporting Documentation - **[references/diagram-types.md](references/diagram-types.md)** - Detailed docs and Mermaid examples for each diagram type - **[references/mermaid-syntax.md](references/mermaid-syntax.md)** - ID sanitization, escaping, style definitions, and common pitfalls
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.