Skip to content

Agent skill that turns natural language, code, Terraform/K8s, SQL, OpenAPI, AsyncAPI, Protobuf and GraphQL sources into editable, tested draw.io architecture diagrams: incremental sync, multi-view projection, drift diff, CI architecture tests, whiteboard derasterize, interactive HTML/PPTX/Mermaid exports.

feat: Graphviz auto-layout for draw.io (script + edge routing + workflow wiring, v1.6.0) (#14)

Agents365.aide5976c87b15
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 6c8b37d..86eba23 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,12 +1,12 @@
---
name: drawio-skill
-version: 1.5.3
+version: 1.6.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, network topology, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.
license: MIT
homepage: https://github.com/Agents365-ai/drawio-skill
-compatibility: Requires draw.io desktop app CLI on PATH (macOS/Linux/Windows). Self-check step requires a vision-enabled model (e.g., Claude Sonnet/Opus); gracefully skipped if unavailable.
+compatibility: Requires draw.io desktop app CLI on PATH (macOS/Linux/Windows). Self-check step requires a vision-enabled model (e.g., Claude Sonnet/Opus); gracefully skipped if unavailable. Optional auto-layout (scripts/autolayout.py) needs Graphviz (dot).
platforms: [macos, linux, windows]
-metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.5.3"}
+metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for optional autolayout.py","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.6.0"}
---
# Draw.io Diagrams
@@ -31,6 +31,7 @@ When the workflow references one of these, read it on demand — none of them ne
| `references/troubleshooting.md` | An export fails, vision rejects a PNG, or a rendering looks wrong |
| `scripts/repair_png.py` | After every `-e` PNG export — fixes draw.io's truncated IEND chunk (issue #8) |
| `scripts/encode_drawio_url.py` | The CLI is unavailable and you need a browser-fallback diagrams.net URL |
+| `references/autolayout.md` | The diagram is large or layout-heavy (dependency/call graph, code structure, >~15 nodes) and you want Graphviz to place nodes + route edges instead of hand-placing coordinates |
## Prerequisites
@@ -80,7 +81,7 @@ When a preset loads successfully, mention it in the first line of the reply: *"U
1. **Check deps** — **resolve which name the binary has on this system** and use that name verbatim in every subsequent command in this workflow. Try in order: (a) `drawio --version` (the canonical name for Homebrew cask, jgraph `.deb`/`.rpm`, Arch AUR), (b) `draw.io --version` (older builds, some custom symlinks, some distro packages), (c) macOS `.app` direct: `/Applications/draw.io.app/Contents/MacOS/draw.io --version`, (d) Windows: `"C:\Program Files\draw.io\draw.io.exe" --version`. The first one that prints a version is your binary; remember the exact path/name and substitute it for `drawio` in every export command below. **Do not copy the example commands verbatim if your binary is named differently** — the examples use `drawio` only because it's the most common. On macOS-Homebrew, `drawio` is just a thin wrapper script that execs `/Applications/draw.io.app/Contents/MacOS/draw.io` — they run the same engine, so candidate (c) is only needed when the `drawio` wrapper is absent (e.g. the app was installed by drag-and-drop without the cask).
2. **Plan** — identify shapes, relationships, layout (LR or TB), group by tier/layer
-3. **Generate** — write `.drawio` XML file to disk. Default output dir is the user's working dir; if the user specified an output path or directory (e.g. `./artifacts/`, `docs/images/`), use that instead — `mkdir -p` the target dir first. Apply the same dir choice to PNG/SVG/PDF exports in steps 4 and 7.
+3. **Generate** — write `.drawio` XML file to disk. Hand-place coordinates for small/styled diagrams. **For large or layout-heavy diagrams (dependency/call graphs, code structure, >~15 nodes), don't hand-place** — describe the graph as JSON and run `python3 <this-skill-dir>/scripts/autolayout.py graph.json -o <name>.drawio` to compute node positions + orthogonal edge routing via Graphviz (see `references/autolayout.md`). Default output dir is the user's working dir; if the user specified an output path or directory (e.g. `./artifacts/`, `docs/images/`), use that instead — `mkdir -p` the target dir first. Apply the same dir choice to PNG/SVG/PDF exports in steps 4 and 7.
4. **Export draft** — run CLI to produce a preview PNG. **Do NOT pass `-e`** at this step — the embedded `zTXt mxGraphModel` chunk it adds causes vision APIs (Claude included) to return 400 "Could not process image" in step 5. **Cap the preview width with `--width 2000` (not `-s 2`)** — Claude's vision API rejects images larger than 2576×2576px with "Unable to resize image — dimensions exceed the 2576x2576px limit", and `-s 2` on a medium-or-larger diagram easily overshoots that ceiling. Save the clean preview as `<name>.png` (single extension). Embedding and full-resolution scale are for the final export only (step 7).
5. **Self-check** — use the agent's built-in vision capability to read the exported PNG, catch obvious issues, auto-fix before showing user (requires a vision-enabled model such as Claude Sonnet/Opus). If reading the PNG returns a 400 / "Could not process image" error, you almost certainly exported with `-e` by mistake — re-export without `-e` and retry once. If it still fails, skip self-check and continue to step 6.
6. **Review loop** — show image to user, collect feedback, apply targeted XML edits, re-export, repeat until approved
diff --git a/skills/drawio-skill/references/autolayout.md b/skills/drawio-skill/references/autolayout.md
new file mode 100644
index 0000000..ef237aa
--- /dev/null
+++ b/skills/drawio-skill/references/autolayout.md
@@ -0,0 +1,69 @@
+# Auto-layout (Graphviz)
+
+Read this when a diagram is **large or layout-heavy** — dependency/call graphs, code/module structure, or roughly **more than ~15 nodes** — where hand-placing `x`/`y` coordinates is slow, error-prone, and overlap-prone.
+
+Instead of computing coordinates by hand in the Generate step, describe the graph as JSON and let `scripts/autolayout.py` place the nodes and route the edges with Graphviz, then continue the normal workflow (Export draft → Self-check → …) on the produced `.drawio`.
+
+For small or carefully-styled diagrams, keep hand-placing — auto-layout trades fine control for scale.
+
+## Dependency
+
+Requires Graphviz `dot` on PATH:
+
+```bash
+# macOS
+brew install graphviz
+# Debian/Ubuntu
+sudo apt install graphviz
+```
+
+The script exits with a clear message if `dot` is missing — fall back to hand-placed coordinates in that case.
+
+## Usage
+
+```bash
+python3 <this-skill-dir>/scripts/autolayout.py graph.json -o diagram.drawio
+```
+
+It prints `wrote diagram.drawio (N nodes, M edges)` to stderr and writes a normal `.drawio` file. From there, continue at the **Export draft** step of the main workflow (preview PNG with `--width 2000`, self-check, review loop, final export with `-e` + `repair_png.py`).
+
+## Input format
+
+```json
+{
+ "direction": "TB",
+ "nodes": [
+ {"id": "client", "label": "Web Client", "style": "rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;"},
+ {"id": "gw", "label": "API Gateway"},
+ {"id": "db", "label": "User DB", "style": "shape=cylinder3;whiteSpace=wrap;html=1;", "width": 120, "height": 80}
+ ],
+ "edges": [
+ {"source": "client", "target": "gw", "label": "HTTPS"},
+ {"source": "gw", "target": "db"}
+ ]
+}
+```
+
+**Fields**
+
+| Field | Required | Default | Notes |
+|---|---|---|---|
+| `direction` | no | `TB` | `TB` (top→bottom) or `LR` (left→right) — the layout rank direction |
+| `nodes[].id` | **yes** | — | Unique; must not be `0` or `1` (reserved for draw.io root cells) |
+| `nodes[].label` | no | the `id` | Display text; auto XML-escaped |
+| `nodes[].style` | no | blue rounded box | Any draw.io style string — reuse the role/shape styles from `diagram-types.md` and the active preset |
+| `nodes[].width` / `height` | no | `120` / `60` | Pixels; dot lays out at this real size |
+| `edges[].source` / `target` | **yes** | — | Must match node ids |
+| `edges[].label` | no | empty | Edge text |
+
+## How it places things
+
+- Node positions come from `dot` (hierarchical layered layout), converted to draw.io pixels and snapped to the grid (multiples of 10).
+- Edges use `splines=ortho`: dot's orthogonal route is replayed as draw.io waypoints, so edges go **around** nodes instead of through them.
+- Apply the active style preset by setting each node's `style` to the preset's role/shape values before calling the script — the script does not know about presets.
+
+## Limitations
+
+- **Placement is topological, not semantic** — dot minimises edge crossings, which may put a node in a different column than you'd choose by hand. Re-export with the other `direction`, or hand-tune the produced XML afterwards (it's a normal `.drawio`).
+- **Parallel edges** between the same `(source, target)` pair share one route.
+- **No containers/swimlanes** — this MVP lays out a flat node/edge graph. For nested architecture diagrams, hand-place containers (see SKILL.md "Containers and groups").
diff --git a/skills/drawio-skill/scripts/autolayout.py b/skills/drawio-skill/scripts/autolayout.py
new file mode 100644
index 0000000..ea50ecc
--- /dev/null
+++ b/skills/drawio-skill/scripts/autolayout.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python3
+"""Auto-layout a logical graph into draw.io XML using Graphviz.
+
+Minimal layout pass for the drawio skill: takes a graph (nodes + edges as
+JSON), runs `dot` to position the nodes, and emits a .drawio file with the
+mxGeometry x/y filled in. draw.io routes the edges itself (orthogonal style).
+This removes the manual-coordinate ceiling for medium/large diagrams.
+
+Input JSON:
+ {
+ "direction": "TB", # TB (top-bottom, default) or LR (left-right)
+ "nodes": [
+ {"id": "a", "label": "Service A", "style": "rounded=1;...",
+ "width": 120, "height": 60}
+ ],
+ "edges": [
+ {"source": "a", "target": "b", "label": "calls"}
+ ]
+ }
+Only "id" is required per node; label defaults to id and style/width/height
+have defaults. Node ids must be unique and must not be "0" or "1" (reserved
+for the draw.io root cells). Requires Graphviz `dot` on PATH.
+
+Usage: python3 autolayout.py graph.json [-o diagram.drawio]
+"""
+import argparse
+import json
+import shlex
+import subprocess
+import sys
+from xml.sax.saxutils import escape
+
+DEFAULT_W, DEFAULT_H = 120, 60
+NODE_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"
+EDGE_STYLE = "html=1;rounded=0;"
+
+
+def attr(value):
+ return escape(str(value), {'"': "&quot;"})
+
+
+def snap(value, grid=10):
+ # Align to the grid the skill uses everywhere (multiples of 10).
+ return int(round(value / grid) * grid)
+
+
+def build_dot(graph):
+ rankdir = "LR" if str(graph.get("direction", "TB")).upper() == "LR" else "TB"
+ # splines=ortho makes dot route edges as orthogonal polylines; we replay
+ # those bends as draw.io waypoints so edges go around nodes, not through them.
+ lines = [f"digraph G {{ rankdir={rankdir}; splines=ortho; node [shape=box fixedsize=true];"]
+ for node in graph["nodes"]:
+ # Pass our pixel sizes to dot as inches so it lays out at the real size.
+ w = node.get("width", DEFAULT_W) / 72.0
+ h = node.get("height", DEFAULT_H) / 72.0
+ lines.append(f'"{node["id"]}" [width={w:.4f} height={h:.4f}];')
+ for edge in graph.get("edges", []):
+ lines.append(f'"{edge["source"]}" -> "{edge["target"]}";')
+ lines.append("}")
+ return "\n".join(lines)
+
+
+def layout(dot_src):
+ """Run `dot -Tplain`; return (height_in, {id: (xc, yc)}, {(src, dst): [(x, y), ...]}).
+
+ Node coords are inches (bottom-left origin); each edge's value is the list
+ of orthogonal control points dot computed for routing, endpoints included.
+ """
+ try:
+ proc = subprocess.run(
+ ["dot", "-Tplain"], input=dot_src,
+ capture_output=True, text=True, check=True,
+ )
+ except FileNotFoundError:
+ sys.exit("error: Graphviz `dot` not found on PATH (brew install graphviz)")
+ except subprocess.CalledProcessError as exc:
+ sys.exit(f"error: dot failed: {exc.stderr.strip()}")
+ height, pos, edges = 0.0, {}, {}
+ for line in proc.stdout.splitlines():
+ tok = shlex.split(line)
+ if not tok:
+ continue
+ if tok[0] == "graph":
+ height = float(tok[3]) # graph scale width height
+ elif tok[0] == "node":
+ pos[tok[1]] = (float(tok[2]), float(tok[3])) # node name x y ...
+ elif tok[0] == "edge": # edge tail head n x1 y1 ... xn yn
+ n = int(tok[3])
+ edges[(tok[1], tok[2])] = [
+ (float(tok[4 + 2 * i]), float(tok[5 + 2 * i])) for i in range(n)
+ ]
+ return height, pos, edges
+
+
+def to_drawio(graph, height, pos, edge_pts):
+ cells = []
+ for node in graph["nodes"]:
+ nid = node["id"]
+ if nid not in pos:
+ continue
+ w, h = node.get("width", DEFAULT_W), node.get("height", DEFAULT_H)
+ xc, yc = pos[nid]
+ x = snap(xc * 72 - w / 2)
+ y = snap((height - yc) * 72 - h / 2) # flip: dot origin is bottom-left
+ style = node.get("style", NODE_STYLE)
+ cells.append(
+ f' <mxCell id="{attr(nid)}" value="{attr(node.get("label", nid))}" '
+ f'style="{style}" vertex="1" parent="1">\n'
+ f' <mxGeometry x="{x}" y="{y}" width="{w}" height="{h}" as="geometry"/>\n'
+ f" </mxCell>"
+ )
+ for i, edge in enumerate(graph.get("edges", [])):
+ # Drop the first/last points (they sit on the node borders, where
+ # draw.io attaches anyway) and replay the interior bends as waypoints.
+ interior = edge_pts.get((edge["source"], edge["target"]), [])[1:-1]
+ if interior:
+ points = "".join(
+ f'<mxPoint x="{snap(x * 72)}" y="{snap((height - y) * 72)}"/>'
+ for x, y in interior
+ )
+ geom = (f'<mxGeometry relative="1" as="geometry">'
+ f'<Array as="points">{points}</Array></mxGeometry>')
+ else:
+ geom = '<mxGeometry relative="1" as="geometry"/>'
+ cells.append(
+ f' <mxCell id="e{i}" value="{attr(edge.get("label", ""))}" '
+ f'style="{EDGE_STYLE}" edge="1" parent="1" '
+ f'source="{attr(edge["source"])}" target="{attr(edge["target"])}">\n'
+ f" {geom}\n"
+ f" </mxCell>"
+ )
+ return (
+ '<mxfile>\n <diagram id="autolayout" name="Page-1">\n'
+ ' <mxGraphModel dx="800" dy="600" grid="1" gridSize="10" guides="1" '
+ 'tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" '
+ 'pageWidth="850" pageHeight="1100" math="0" shadow="0">\n'
+ " <root>\n"
+ ' <mxCell id="0"/>\n'
+ ' <mxCell id="1" parent="0"/>\n'
+ + "\n".join(cells)
+ + "\n </root>\n </mxGraphModel>\n </diagram>\n</mxfile>\n"
+ )
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Auto-layout a graph JSON into draw.io XML.")
+ ap.add_argument("input", help="graph JSON file")
+ ap.add_argument("-o", "--output", help="output .drawio path (default: stdout)")
+ args = ap.parse_args()
+ with open(args.input, encoding="utf-8") as f:
+ graph = json.load(f)
+ height, pos, edge_pts = layout(build_dot(graph))
+ xml = to_drawio(graph, height, pos, edge_pts)
+ if args.output:
+ with open(args.output, "w", encoding="utf-8") as f:
+ f.write(xml)
+ print(f"wrote {args.output} ({len(graph['nodes'])} nodes, "
+ f"{len(graph.get('edges', []))} edges)", file=sys.stderr)
+ else:
+ sys.stdout.write(xml)
+
+
+if __name__ == "__main__":
+ main()