Draw.io Diagrams
Overview
Generate .drawio XML files and export to PNG/SVG/PDF/JPG locally using the native draw.io desktop app CLI.
Mandatory user preference
Every drawing, diagram, flowchart, visual map, or relationship visualization must use this skill, including simple diagrams and diagrams intended for Markdown.
- Always create an editable
.drawio file as the primary deliverable. Export PNG/SVG/PDF/JPG as requested.
- Mermaid is allowed only as an internal authoring format when it is converted to
.drawio before delivery.
- Never replace a requested diagram with Mermaid-only text, an ASCII diagram, or prose because the draw.io CLI is unavailable.
- If the CLI is unavailable, hand-author
.drawio XML and use the browser fallback or deliver the .drawio source. State which preview or export step could not run.
- If the user explicitly requests Mermaid or PlantUML source, provide it only as an additional artifact; keep
.drawio as the primary deliverable unless the user explicitly refuses a .drawio file.
Supported formats: PNG, SVG, PDF, JPG — no browser automation needed.
PNG, SVG, and PDF exports support --embed-diagram (-e) — the exported file contains the full diagram XML, so opening it in draw.io recovers the editable diagram. Use double extensions (name.drawio.png) to signal embedded XML.
Routing rule
Use this skill for every drawing or diagram request. Read references/diagram-routing.md whenever the user has not already confirmed a diagram type.
- If the user has not named a type, identify the viewer question, information structure, audience, and formality. Recommend one primary type with a short reason, offer at most two alternatives only when they reveal materially different aspects, and ask the user to choose. Stop before drawing until the user chooses or explicitly delegates the choice.
- If the user names a suitable type, accept it without reopening the choice.
- If the named type would hide the core information, explain the tradeoff, recommend the better type, and let the user decide. If the user keeps the original choice, respect it.
- Do not dump a catalogue of diagram types or make a recommendation from keywords alone.
After choosing the diagram type, choose the appropriate draw.io authoring path and style:
- Polished or precise diagrams → native draw.io shapes, XML, presets, and exports.
- Casual hand-drawn / whiteboard look → use draw.io's sketch/hand-drawn styling while retaining
.drawio output.
- Diagrams-as-code or Markdown rendering → create
.drawio first; add Mermaid or PlantUML source only when explicitly requested.
- Freeform canvas or exploratory sketches → approximate them in draw.io so the result remains editable.
Bundled resources
When the workflow references one of these, read it on demand — none of them need to be in context up front.
| File |
Read it when |
references/diagram-routing.md |
The user describes logic, data, relationships, or material but does not know which diagram type will communicate it best — route by viewer question and information structure before drawing |
references/flowchart-quality.md |
The output is a flowchart, decision tree, phased process, synchronization workflow, or contains decisions and return loops — semantic grammar, straight-line routing, one-source-of-truth, and full-diagram QA rules |
references/as-is-to-be-cross-functional.md |
The viewer must compare a current and future process and see role/team/system ownership or handoffs — evidence requirements, paired scope, lane/phase alignment, change semantics, and QA; use templates/as-is-to-be-cross-functional.drawio as the editable starting point when appropriate |
references/toolbox.md |
You're not sure which bundled script fits a request, or want to chain several — a map of all 31 scripts grouped by use-case (author / import code / import IaC / import API spec / live infra / compare / annotate / reverse-export / utilities) with an "I have X, I want Y → use Z" guide |
references/xml-authoring.md |
You're about to hand-write .drawio XML (workflow step 3) — file skeleton, shape/edge cells, containers, connection distribution, palette, spacing/grid rules. Not needed when a bundled generator writes the XML |
references/mermaid-authoring.md |
The diagram is a standard type with no custom styling/icon needs (flowchart, state, gantt, mindmap, timeline, journey, pie, …) and the CLI is ≥ v30 — author it as Mermaid text and let the CLI convert to native .drawio (structure only, layout free). Also documents the CLI's ELK --layout pass for XML |
references/diagram-types.md |
The user names a specific diagram type (ERD, UML class, sequence, C4, architecture, ML/DL, flowchart, SysML, BPMN, network topology, swimlane) |
references/shapes.md + scripts/shapesearch.py |
The diagram needs a specific shape — a cloud icon (AWS/Azure/GCP), Cisco/Kubernetes/network symbol, UML/BPMN/ER/electrical/P&ID element — or any time you'd otherwise guess a style= string. shapesearch.py "<keywords>" returns the exact official style for 10k+ shapes |
scripts/aiicons.py |
The diagram involves an AI/LLM brand (OpenAI, Claude, Gemini, Mistral, Llama, HuggingFace, Ollama, LangChain, …) — aiicons.py "<brand>" returns a draw.io image style for the brand logo (lobe-icons via CDN; --embed to inline). draw.io has no built-in AI logos. See references/shapes.md → "AI / LLM brand logos" |
references/style-presets.md |
The user asks to learn / save / list / set-default / delete a style preset, or you've resolved an active preset and need the application rules |
references/style-extraction.md |
You're inside the Learn flow and need the extraction procedure (called from style-presets.md) |
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 (--edit for an editable editor 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 |
scripts/pyimports.py · jsimports.py · goimports.py · rustimports.py |
The user wants to visualize a Python, JS/TS, Go, or Rust project structure — extracts the import graph (transitive-reduced, optional --group containers, nested by sub-package) for autolayout |
scripts/pyclasses.py |
The user wants a Python class hierarchy / class diagram — extracts classes + inheritance edges (boxed by module with --group) for autolayout |
scripts/tfimports.py · k8simports.py · composeimports.py |
The user wants to visualize declared infrastructure (Terraform .tf, Kubernetes manifests, or docker-compose) — extracts the resource/service reference graph (official AWS/Azure/GCP/K8s icons for tf/k8s; service boxes + volume cylinders for compose) for autolayout |
scripts/tfstate.py · dockerimports.py (+ k8simports.py) |
The user wants to draw what is ACTUALLY running / deployed — pipe terraform show -json (deployed state), docker inspect $(docker ps -q) (live containers), or kubectl get all,ing,cm,secret,pvc -o json (live cluster, via k8simports) and get the real topology with the same official icons. See references/live-infra.md |
scripts/drawiodiff.py |
The user wants to compare / diff two diagrams or two snapshots ("what changed", infra drift) — drawiodiff.py old.drawio new.drawio -o diff.json emits a colour-coded graph (added=green, removed=red, changed=orange, same=grey) for autolayout. Matches by cell id (importer/live-snapshot output) or --by-label (hand-drawn) |
scripts/timelapse.py |
The user wants an architecture time-lapse / to see how a codebase's structure evolved over git history — timelapse.py <dir> --importer pyimports re-runs an importer at each sampled commit and assembles a self-contained HTML player (embedded frames, play/step controls). Best on a package with real import edges (point <dir> at the module root) |
scripts/explain.py |
The user wants to describe / document / summarize an existing .drawio in words (reverse of generating one) — explain.py diagram.drawio emits structured Markdown: components grouped by container/tier, relations (A —label→ B), per-page sections for multi-page/C4. Good for a README/PR summary or a text-only read-out |
scripts/drawio2pptx.py |
The user wants a PowerPoint deck / slides from a diagram — drawio2pptx.py diagram.drawio -o deck.pptx puts each page on its own 16:9 slide (page name as title), so a multi-page C4 model becomes a ready-to-present deck. Needs python-pptx (pip install python-pptx) + the draw.io CLI |
scripts/drawiohtml.py |
The user wants a shareable interactive viewer for a diagram (pan / zoom / search, no draw.io needed) — drawiohtml.py diagram.drawio -o viewer.html inlines every page's SVG into ONE self-contained HTML with page tabs, drag-pan, wheel-zoom, node search (Enter cycles + centres matches) and working drill-down links (a C4 model's data:page/id links switch tabs). No server, no external requests — send the file to anyone |
scripts/svgflow.py |
The user wants an animated / "flowing" diagram (data-flow, moving edges) — svgflow.py diagram.drawio -o flow.svg exports to SVG and makes every edge a marching-ants animation (dashes travel along the arrows). Self-contained looping .svg that renders on GitHub / any browser; --speed / --dash / --reverse |
scripts/drawio2mermaid.py |
The user wants to convert a .drawio into Mermaid text (diagrams-as-code for a Markdown file that GitHub renders) — drawio2mermaid.py diagram.drawio emits a flowchart (containers → subgraphs, edge labels kept, cylinder/rhombus shapes mapped); --fenced wraps in ```mermaid, multi-page → one graph per page. Structural only (styling/icons don't survive) |
scripts/sqlerd.py |
The user wants an ER diagram from SQL DDL — parses CREATE TABLE statements into per-table nodes (columns with PK/FK markers) and crow's-foot FK edges for autolayout |
scripts/ciimports.py |
The user wants a CI pipeline diagram (GitHub Actions workflows or GitLab CI) — ciimports.py <repo-root> reads .github/workflows/*.yml + .gitlab-ci.yml and emits jobs (runner, matrix size, reusable-workflow calls), needs: dependency edges, per-workflow trigger nodes, and stage/workflow containers for autolayout. Needs PyYAML |
scripts/openapiimports.py |
The user wants an API diagram from an OpenAPI / Swagger spec — openapiimports.py spec.yaml maps each operation to a node coloured by HTTP method (GET blue, POST green, PUT/PATCH orange, DELETE red) plus one node per component schema, with edges from operations to the schemas they use and between nested schemas. --group boxes by tag, --no-schemas shows just the endpoint surface; feeds autolayout |
scripts/heatmap.py |
The user wants to colour an existing .drawio by data (a cost / latency / traffic / error-rate heat map) — heatmap.py diagram.drawio -m metrics.csv matches each metric (CSV key,value or JSON {key:value}) to a node by id or label and recolours it along a gradient (--palette heat|cool|warm, --reverse), optionally scaling node size (--size) and adding a legend. Post-processes any diagram; export as usual |
scripts/seqlayout.py |
The user wants a sequence diagram — describe participants + messages as JSON and the script computes all lifeline/activation/arrow geometry deterministically (no hand-placed coordinates, no Graphviz needed) |
scripts/c4.py |
The user wants a C4 model (System Context / Container / Component) — levels JSON in, one multi-page .drawio out with official C4 shapes/colors and click-to-drill-down links between levels |
scripts/relabel.py |
The user wants a language variant or bulk text swap of an existing .drawio (e.g. an EN diagram re-labelled in Chinese for a bilingual README) — relabel.py diagram.drawio --extract -o labels.json dumps every label as an identity JSON map; translate the values (keep the keys), then relabel.py diagram.drawio --map labels.json -o diagram_cn.drawio swaps them with layout/styles/ids untouched |
scripts/restyle.py |
The user wants to re-theme an EXISTING .drawio ("make this dark", "apply my corporate style to this diagram") — restyle.py diagram.drawio --preset <name> remaps every vertex fill/stroke to the preset palette by hue, applies font/extras (dark fontColor, edge color, background), and leaves layout, shapes, and edge routing untouched. Presets resolve like Step 0 (user dir, then built-ins) |
scripts/edgeports.py |
Edges stack on top of each other where they meet a shape — the usual swimlane/cross-functional complaint, and anywhere a node has several connections leaving the same side. edgeports.py diagram.drawio pins exitX/exitY+entryX/entryY: it picks the side of each node facing the other endpoint, then spreads that side's edges over evenly-spaced slots ordered by the far endpoint's position, so they keep their relative order instead of crossing. Resolves absolute coordinates through swimlane parents, skips ends you already pinned, and is idempotent. It is a port assigner, not a router — it separates lines at the shape boundary, it will not stop an edge crossing an unrelated shape mid-run (add waypoints for that) |
scripts/validate.py |
You generated a .drawio (especially via autolayout or for a large hand-placed diagram) and want a fast deterministic structural lint (dangling edges, dup/reserved ids, broken parents, overlaps) before the vision self-check. --score prints a readability score for comparing layout variants |
scripts/audit_flowchart.py |
You generated or edited a flowchart — audits decision labels, branch-style consistency, mixed numbering, false return nodes, curves, diagonal segments, avoidable bends, and node-center alignment; run in addition to validate.py |
scripts/raster2drawio.py |
The user has an image of a diagram (whiteboard photo, legacy PNG, Visio screenshot) and wants an editable .drawio — read the image with your own vision, extract nodes/edges as JSON (schema + full workflow in references/derasterize.md), then raster2drawio.py graph.json -o out.drawio honours those coordinates/labels/shapes; nodes missing x/y fall back to autolayout.py placement |
scripts/buildup.py |
The user wants a diagram to build itself node-by-node as a video/GIF (a construction time-lapse of ONE static diagram — distinct from timelapse.py's git-history animation) — buildup.py diagram.drawio reveals cells in topological (dependency) order into a self-contained HTML player (play/pause/step/scrub); --gif also exports an animated GIF (needs Pillow). Needs the draw.io CLI |
scripts/compress.py |
The user wants an executive / boardroom summary of a big diagram — collapses clusters (pure-Python label propagation, no networkx) into one labeled node each with aggregated inter-cluster edges, emitting a 2-page .drawio (exec view + click-to-drill-down into the full original). Claude can rename clusters semantically afterward. Needs Graphviz dot |
scripts/runbook.py |
The user wants a flowchart/decision-tree .drawio turned into a click-through triage app (on-call runbook) — runbook.py flow.drawio reads the XML (no draw.io CLI needed) and emits a self-contained HTML runbook: current-step text, per-edge choice buttons, breadcrumb trail, Back/Restart, end-state on terminal nodes |
scripts/prdiff.py |
You're setting up automated PR diagram review in CI — for every .drawio changed between two git refs it renders base/head/diff PNGs and emits a Markdown report; ships with a composite GitHub Action (.github/actions/drawio-diff/) that posts a sticky PR comment. See references/pr-bot.md |
scripts/tubemap.py |
The user wants a metro / subway / tube map — a system, pipeline, or journey drawn as coloured transit lines with octilinear (H/V/45°) routing, white interchange circles, and station stops. Compose a metro JSON (lines = ordered stations on an integer grid, shared stations = interchanges), then tubemap.py metro.json -o metro.drawio. Stdlib-only; schema + the one grid rule in references/tubemap.md |
Prerequisites
The draw.io desktop app must be installed and the CLI accessible:
macOS sandbox / sandbox isolation note (e.g., codex.app): In some sandboxed macOS environments, invoking the draw.io desktop CLI (even drawio --version) can crash the draw.io process or produce no output. If that happens, treat the CLI as unavailable in this sandbox isolation — do not keep retrying inside the sandbox. Prefer a non-sandboxed host environment (outside sandbox isolation) for any CLI export work, or use the browser fallback / XML-only outputs.
# macOS (Homebrew — recommended; CLI binary is `drawio`, not `draw.io`)
brew install --cask drawio
drawio --version
# macOS (full path if not in PATH)
/Applications/draw.io.app/Contents/MacOS/draw.io --version
# Windows
"C:\Program Files\draw.io\draw.io.exe" --version
# Linux
drawio --version
Install draw.io desktop if missing:
Workflow
Before starting the workflow, assess whether the user's request is specific enough. If the user has not confirmed a diagram type, follow references/diagram-routing.md, present the recommendation and any materially useful alternatives, ask the user to choose, and stop before Step 0. Continue only after the user chooses or explicitly says to decide for them. If other key details are missing, ask 1-3 focused questions:
- Output format — PNG (default), SVG, PDF, or JPG?
- Output location — default is the user's working dir; honor any explicit path the user gives (e.g. "put it in
./artifacts/"). Don't ask if they didn't mention one.
- Scope/fidelity — how many components? Any specific technologies or labels?
Skip diagram-type selection only when the user already specified a suitable type or explicitly delegated the choice. Skip other clarification if the request already specifies the needed details or is clearly simple (e.g., "draw a flowchart of X").
Non-negotiable gates
These gates apply to every authoring path and cannot be skipped because the diagram looks simple or the user reported only one defect.
- Logic gate — before placing shapes, form an internal diagram contract containing the viewer question, chosen diagram type, node vocabulary, complete main sequence, every decision and branch, every return target, reading direction, and grouping. For a flowchart, classify each node as action, decision, or terminal outcome and read
references/flowchart-quality.md. Do not start layout while peer nodes mix semantic roles or a branch/return has no defined destination.
- Source gate — keep the
.drawio file as the only source of truth. Make all content, geometry, style, and routing fixes there, then regenerate previews and final exports.
- Full-diagram QA gate — after the first draft and after every edit, fix the reported instance, search the entire diagram for the same defect class, rerun every applicable deterministic check, export a fresh complete preview, and visually inspect the whole canvas in the fixed scan order from the diagram-specific reference. A local correction never counts as local-only validation.
- Completion gate — do not present an artifact as final while any critical logic, connection, overlap, clipping, consistency, routing, or source/export mismatch remains. If a check cannot run, say which gate is unverified and present the result as a draft.
Step 0 — Resolve active preset. Determine which (if any) user-defined style preset applies to this generation.
- Scan the user's message for a phrase that clearly names a style preset: "use my
<name> style", "with my <name> style", "in <name> mode", "in the style of <name>". A bare with <name> does not count — "draw a diagram with redis" names a component, not a style. If a clear match is found → active preset = <name>.
- Else, check
~/.drawio-skill/styles/ for any file with "default": true. If found → active preset = that one.
- Else → no preset active; fall through to the built-in color/shape/edge conventions for the rest of the workflow.
Load the preset JSON from ~/.drawio-skill/styles/<name>.json, falling back to <this-skill-dir>/styles/built-in/<name>.json. If the named preset exists in neither location, tell the user the name is unknown, list the available presets (user dir + built-in), and stop — do not silently fall back to defaults.
When a preset loads successfully, mention it in the first line of the reply: "Using preset <name> (confidence: <level>)." See references/style-presets.md → "Applying a preset" for how the preset changes color/shape/edge/font decisions.
- 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). Also note the major version the command printed: ≥ 30 unlocks Mermaid→.drawio conversion and the ELK --layout pass (see references/mermaid-authoring.md); on ≤ 29 both are unavailable — .mmd input fails and --layout corrupts argument parsing — so never emit those flags there.
- Plan — complete the logic-gate contract: record the viewer question, selected diagram type, one node vocabulary, full main sequence, every decision/branch/return target, main reading direction, branch convention, return-line corridors, shapes, relationships, and grouping. For a flowchart, read
references/flowchart-quality.md before placing nodes. Resolve contradictions in this contract before generating XML.
- Generate — produce the
.drawio file, choosing the authoring mode: (a) Mermaid → CLI convert when the diagram is a standard type with no custom styling/icon needs and the CLI is ≥ v30 — write a .mmd and run drawio -x -f xml -o <name>.drawio <name>.mmd, see references/mermaid-authoring.md (structure only; layout comes free; never --layout afterwards). (b) Hand-written XML for custom styling, vendor icons, swimlanes, precise geometry — read references/xml-authoring.md first (skeleton, cell forms, palette, spacing rules). (c) A bundled generator for the data-driven cases below. 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; add --tune to auto-pick the more readable direction). For a Python / JS-TS / Go / Rust project, the matching importer (scripts/pyimports.py, jsimports.py, goimports.py, or rustimports.py) extracts the import graph (transitive-reduced; add --group to box modules by sub-package, nested for deep trees) ready for autolayout; for a Python class hierarchy, scripts/pyclasses.py extracts classes + inheritance instead; for Terraform / Kubernetes / docker-compose (scripts/tfimports.py, k8simports.py, composeimports.py), the importer extracts the resource/service reference graph — tf/k8s nodes resolve to their official cloud icons automatically; to draw what is actually running rather than the declared config, pipe terraform show -json into scripts/tfstate.py or docker inspect $(docker ps -q) into scripts/dockerimports.py (k8simports.py already accepts live kubectl get ... -o json) — see references/live-infra.md; for an ER diagram from SQL DDL, scripts/sqlerd.py parses CREATE TABLE into table nodes + crow's-foot FK edges; for an API diagram from an OpenAPI / Swagger spec, scripts/openapiimports.py maps operations (coloured by HTTP method) + component schemas into a graph for autolayout; for a CI pipeline diagram (GitHub Actions / GitLab CI), scripts/ciimports.py extracts jobs, needs: edges, triggers, and stage/workflow containers. To turn any generated .drawio into a metric heat map — recolour nodes by a CSV/JSON of cost/latency/traffic/errors — run python3 <this-skill-dir>/scripts/heatmap.py <name>.drawio -m metrics.csv (matches on cell id or label; --palette, --size, legend). For a sequence diagram, skip autolayout entirely — describe participants + messages as JSON and run python3 <this-skill-dir>/scripts/seqlayout.py seq.json -o <name>.drawio (deterministic lifeline/activation/arrow geometry; see the script docstring for the JSON schema). For a C4 model, python3 <this-skill-dir>/scripts/c4.py c4.json -o <name>.drawio emits the full multi-page Context→Container→Component set with drill-down links (schema in the script docstring). For complex architecture diagrams with many visible edge labels, give labels labelBackgroundColor=#ffffff;fontSize=11 and use edge geometry x/y offsets plus <mxPoint as="offset" /> to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. For hand-placed diagrams where edges cross shapes (architecture, network topology, deployment, UML), fix the routing in the XML — run python3 <this-skill-dir>/scripts/edgeports.py <name>.drawio to distribute stacked edges over each shape's perimeter automatically, then add <Array as="points"> waypoints or widen node spacing for any edge still crossing a shape mid-run (see references/xml-authoring.md). No CLI flag reroutes edges without moving nodes: every --layout preset is an ELK node layout that re-places vertices, and an unrecognised value opens a modal error dialog that hangs headless runs. draw.io's obstacle-avoiding router is editor-side only. After generating any .drawio, run python3 <this-skill-dir>/scripts/validate.py <name>.drawio for a fast structural lint (dangling edges, dup ids, overlaps) before exporting. 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.
Generation gate: Treat .drawio as the single source of truth; never hand-fix SVG or PNG independently. Run python3 <this-skill-dir>/scripts/validate.py <name>.drawio --score; for a flowchart also run python3 <this-skill-dir>/scripts/audit_flowchart.py <name>.drawio. Fix reported issues before exporting.
- 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).
- Self-check — use the agent's built-in vision capability to read the complete exported PNG and audit the whole diagram, not only the last edited area. For flowcharts, use the fixed full-canvas scan order in
references/flowchart-quality.md. If reading the PNG returns a 400 / "Could not process image" error, re-export without -e and retry once. If vision remains unavailable, report that limitation; deterministic checks still do not prove visual correctness.
- Review loop — show the image, collect feedback, edit only the
.drawio source, fix every occurrence of the reported defect class, rerun all structural and diagram-specific audits across the entire diagram, re-export, inspect the complete image, and repeat until approved
- Final export — re-export the approved version to all requested formats. Use
-e here (PNG/SVG/PDF) so the deliverable stays editable in draw.io; save as <name>.drawio.png to signal embedded XML. For PNG with -e, run python3 <this-skill-dir>/scripts/repair_png.py <name>.drawio.png immediately after — draw.io's CLI truncates the IEND chunk in -e PNG output (8 bytes missing), producing a corrupt file that vision APIs and strict PNG decoders reject (issue #8). Report file paths.
If drawio --version crashes or prints nothing (common in restricted macOS sandbox isolation like codex.app):
- Do not keep retrying CLI invocations inside the sandbox.
- Raw Mermaid, ASCII, or prose is not a fallback deliverable. All fallback paths must still create a
.drawio XML file.
- Skip steps 4, 5, 6, and 7 (CLI export + PNG-based review) and use Browser fallback (
scripts/encode_drawio_url.py) or deliver the .drawio XML only.
- If the user needs PNG/SVG/PDF outputs, ask them to run the export commands in a non-sandboxed host environment (outside sandbox isolation) and share the resulting files.
Escalation rule:
- If the binary exists on PATH (or known app path exists) but execution fails with abnormal exit, empty output, Electron startup failure, display/session error, or likely sandbox restriction, prefer one escalated retry before falling back.
- If the binary is missing entirely, do not escalate just to search more aggressively; go to install guidance or fallback.
Step 5: Self-Check
After exporting the draft PNG, use the agent's vision capability (e.g., Claude's image input) to read the image and check for these issues before showing the user. If the agent does not support vision, skip self-check and show the PNG directly.
Important: the draft PNG read here must have been exported without -e. Draw.io's -e flag emits a PNG with a truncated IEND chunk (8 bytes of type+CRC missing) that the Anthropic vision API rejects with 400 "Could not process image" (issue #8). The simplest fix for the preview step is to skip -e entirely; the final export in step 7 keeps -e and runs the repair snippet. If you see the 400 error here, re-export without -e and retry once; if it still fails (any other reason), skip self-check and proceed to step 6.
| Check |
What to look for |
Auto-fix action |
| Overlapping shapes |
Two or more shapes stacked on top of each other |
Shift shapes apart by ≥200px |
| Clipped labels |
Text cut off at shape boundaries |
Increase shape width/height to fit label |
| Missing connections |
Arrows that don't visually connect to shapes |
Verify source/target ids match existing cells |
| Off-canvas shapes |
Shapes at negative coordinates or far from the main group |
Move to positive coordinates near the cluster |
| Edge-shape overlap |
An edge/arrow visually crosses through an unrelated shape |
Add waypoints (<Array as="points">) to route around the shape, or increase spacing between shapes |
| Stacked edges |
Multiple edges overlap each other on the same path |
Distribute entry/exit points across the shape perimeter (use different exitX/entryX values) |
| Edge-label overlap |
Edge text overlaps another label, line, or node in the exported PNG |
Keep the label on the edge, add a white label background, and move it locally with edge geometry x/y offsets into adjacent whitespace |
| Mixed semantics |
Peer nodes mix actions, states, and explanatory notes |
Choose one semantic grammar and change shapes or labels to match it |
| Inconsistent styling |
Number badges, branch labels, fonts, colors, borders, or return lines differ without meaning |
Apply the same style to every item with the same semantic role |
| Avoidable crooked route |
A mostly vertical or horizontal connection bends because nodes are not center-aligned |
Align node centers and use one straight pinned connector |
| False return |
A node says 返回步骤 N but no edge actually reaches step N |
Add the real dashed return edge to the target or remove the claim |
| Source/export mismatch |
PNG or SVG contains changes not present in .drawio |
Fix .drawio, discard the independent export edit, and export again |
- Max 2 automatic repair rounds — if a critical issue remains, show the result explicitly as a draft and list the defect; never call it final
- Re-export after each fix and re-read the new PNG
Step 6: Review Loop
After self-check, show the exported image and ask the user for feedback.
Targeted edit rules — preserve already-approved geometry where possible, but treat the user's marked location as evidence of a defect class, not as the boundary of the review. Apply the minimal source change to the marked item, then find and fix every equivalent defect elsewhere before revalidating the whole diagram:
| User request |
XML edit action |
| Change color of X |
Find mxCell by value matching X, update fillColor/strokeColor in style |
| Add a new node |
Append a new mxCell vertex with next available id, position near related nodes |
| Remove a node |
Delete the mxCell vertex and any edges with matching source/target |
| Move shape X |
Update x/y in the mxGeometry of the matching mxCell |
| Resize shape X |
Update width/height in the mxGeometry of the matching mxCell |
| Add arrow from A to B |
Append a new mxCell edge with source/target matching A and B ids |
| Change label text |
Update the value attribute of the matching mxCell |
| Change layout direction |
Full regeneration — rebuild XML with new orientation |
Rules:
- For single-element changes: edit existing XML in place — preserves layout tuning from prior iterations
- For layout-wide changes (e.g., swap LR↔TB, "start over"): regenerate full XML
- Overwrite the same
{name}.png (no -e) each iteration — do not create v1, v2, v3 files. -e is reserved for the final export in step 7.
- After applying edits, search for the same problem across all pages, rerun the complete structural and diagram-specific audit, then re-export and inspect the whole image rather than only the edited region
- Recheck previously corrected defect classes as well; a later edit must not reintroduce an earlier problem
- Do not show an updated preview until the complete audit has passed, unless it is explicitly labeled as a draft with the remaining defects
- Loop continues until user says approved / done / LGTM
- Safety valve: after 5 iteration rounds, suggest the user open the
.drawio file in draw.io desktop for fine-grained adjustments
Step 7: Final Export
Once the user approves:
- Export every final format from the approved
.drawio source; never deliver an independently edited PNG or SVG as if it matched the editable source
- Export to all requested formats (PNG, SVG, PDF, JPG) — default to PNG if not specified
- Report file paths for both the
.drawio source file and exported image(s)
- Auto-launch: offer to open the
.drawio file in draw.io desktop for fine-tuning — open diagram.drawio (macOS), xdg-open (Linux), start (Windows)
- Confirm files are saved and ready to use
Style Presets
A style preset is a named JSON file capturing a user's visual preferences (palette, shapes, font, edges). When active, it replaces the built-in visual conventions, but it never overrides diagram grammar or the mandatory QA gates. In particular, a flowchart preset may change palette and typography but must still obey flowchart-quality.md, including square-corner routing and full-diagram review.
Lookup order when SKILL.md's Step 0 resolves a preset name:
~/.drawio-skill/styles/<name>.json — user presets (survive git pull)
<this-skill-dir>/styles/built-in/<name>.json — shipped built-ins (default, corporate, handdrawn, colorblind-safe, dark)
Always lowercase the user-provided name before any file operation — the schema enforces lowercase.
For everything else — Learn flow (extracting a preset from a file), management ops (list/default/delete/rename), application rules (color lookup, shape keywords, edges, fonts, extras, interaction with diagram-type presets), and validation — read references/style-presets.md. It's only needed when the user invokes those flows or when an active preset must be applied to the current generation.
Authoring .drawio XML
Before hand-writing any .drawio XML (step 3), read references/xml-authoring.md — file skeleton, shape/edge cell forms, containers, connection-point distribution, color palette, and spacing/grid rules all live there. Skip it only when a bundled generator writes the XML for you (autolayout.py + importers, seqlayout.py).
Two rules worth stating even here: never reuse ids 0/1 (reserved root cells), and every edge mxCell needs a <mxGeometry relative="1" as="geometry" /> child — self-closing edge cells do not render.
Export
Commands
There are two export modes:
- Preview / self-check (step 4 of the workflow) — no
-e. Output diagram.png. Required for vision self-check; using -e here triggers a 400 "Could not process image" error from the vision API (issue #8).
- Final / deliverable (step 7) — pass
-e. Output diagram.drawio.png. The embedded XML keeps the file editable in draw.io.
All commands below write drawio as a placeholder for the binary you resolved in Step 1. If your binary is on PATH as draw.io (with dot — some older or distro-packaged installs), substitute draw.io throughout. If only the macOS .app or Windows .exe is available, use the full path variant shown a few lines down.
# Preview PNG (use this in step 4, before self-check) — NO -e, width-capped to stay under vision's 2576px ceiling
drawio -x -f png --width 2000 -o diagram.png input.drawio
# Final PNG (step 7, after user approval) — WITH -e, double extension
drawio -x -f png -e -s 2 -o diagram.drawio.png input.drawio
# macOS — full path (if not in PATH); preview / final variants
/Applications/draw.io.app/Contents/MacOS/draw.io -x -f png --width 2000 -o diagram.png input.drawio
/Applications/draw.io.app/Contents/MacOS/draw.io -x -f png -e -s 2 -o diagram.drawio.png input.drawio
# Windows
"C:\Program Files\draw.io\draw.io.exe" -x -f png -e -s 2 -o
…(truncated)
1---2name: drawio-skill3description: Use for every request to draw, diagram, map, visualize, or explain relationships visually, including when the user describes logic or information but does not know which diagram type fits. Route the content to the most effective diagram type, then create an editable .drawio artifact and a verified preview. Covers flowcharts, architecture, ERD, UML, SysML, BPMN, swimlanes, network topology, cloud architecture, ML/DL figures, mind maps, data charts, and Markdown-oriented diagrams. Mermaid may be used only as an intermediate converted to .drawio, never as a Mermaid-only fallback.4license: MIT5---67# Draw.io Diagrams89## Overview1011Generate `.drawio` XML files and export to PNG/SVG/PDF/JPG locally using the native draw.io desktop app CLI.1213## Mandatory user preference1415Every drawing, diagram, flowchart, visual map, or relationship visualization must use this skill, including simple diagrams and diagrams intended for Markdown.1617- Always create an editable `.drawio` file as the primary deliverable. Export PNG/SVG/PDF/JPG as requested.18- Mermaid is allowed only as an internal authoring format when it is converted to `.drawio` before delivery.19- Never replace a requested diagram with Mermaid-only text, an ASCII diagram, or prose because the draw.io CLI is unavailable.20- If the CLI is unavailable, hand-author `.drawio` XML and use the browser fallback or deliver the `.drawio` source. State which preview or export step could not run.21- If the user explicitly requests Mermaid or PlantUML source, provide it only as an additional artifact; keep `.drawio` as the primary deliverable unless the user explicitly refuses a `.drawio` file.2223**Supported formats:** PNG, SVG, PDF, JPG — no browser automation needed.2425PNG, SVG, and PDF exports support `--embed-diagram` (`-e`) — the exported file contains the full diagram XML, so opening it in draw.io recovers the editable diagram. Use double extensions (`name.drawio.png`) to signal embedded XML.2627## Routing rule2829Use this skill for every drawing or diagram request. Read `references/diagram-routing.md` whenever the user has not already confirmed a diagram type.3031- If the user has not named a type, identify the viewer question, information structure, audience, and formality. Recommend one primary type with a short reason, offer at most two alternatives only when they reveal materially different aspects, and ask the user to choose. Stop before drawing until the user chooses or explicitly delegates the choice.32- If the user names a suitable type, accept it without reopening the choice.33- If the named type would hide the core information, explain the tradeoff, recommend the better type, and let the user decide. If the user keeps the original choice, respect it.34- Do not dump a catalogue of diagram types or make a recommendation from keywords alone.3536After choosing the diagram type, choose the appropriate draw.io authoring path and style:3738- Polished or precise diagrams → native draw.io shapes, XML, presets, and exports.39- Casual hand-drawn / whiteboard look → use draw.io's sketch/hand-drawn styling while retaining `.drawio` output.40- Diagrams-as-code or Markdown rendering → create `.drawio` first; add Mermaid or PlantUML source only when explicitly requested.41- Freeform canvas or exploratory sketches → approximate them in draw.io so the result remains editable.4243## Bundled resources4445When the workflow references one of these, read it on demand — none of them need to be in context up front.4647| File | Read it when |48| --- | --- |49| `references/diagram-routing.md` | The user describes logic, data, relationships, or material but does not know which diagram type will communicate it best — route by viewer question and information structure before drawing |50| `references/flowchart-quality.md` | The output is a flowchart, decision tree, phased process, synchronization workflow, or contains decisions and return loops — semantic grammar, straight-line routing, one-source-of-truth, and full-diagram QA rules |51| `references/as-is-to-be-cross-functional.md` | The viewer must compare a current and future process **and** see role/team/system ownership or handoffs — evidence requirements, paired scope, lane/phase alignment, change semantics, and QA; use `templates/as-is-to-be-cross-functional.drawio` as the editable starting point when appropriate |52| `references/toolbox.md` | You're **not sure which bundled script fits** a request, or want to chain several — a map of all 31 scripts grouped by use-case (author / import code / import IaC / import API spec / live infra / compare / annotate / reverse-export / utilities) with an "I have X, I want Y → use Z" guide |53| `references/xml-authoring.md` | You're about to **hand-write `.drawio` XML** (workflow step 3) — file skeleton, shape/edge cells, containers, connection distribution, palette, spacing/grid rules. Not needed when a bundled generator writes the XML |54| `references/mermaid-authoring.md` | The diagram is a **standard type with no custom styling/icon needs** (flowchart, state, gantt, mindmap, timeline, journey, pie, …) and the CLI is **≥ v30** — author it as Mermaid text and let the CLI convert to native `.drawio` (structure only, layout free). Also documents the CLI's ELK `--layout` pass for XML |55| `references/diagram-types.md` | The user names a specific diagram type (ERD, UML class, sequence, C4, architecture, ML/DL, flowchart, SysML, BPMN, network topology, swimlane) |56| `references/shapes.md` + `scripts/shapesearch.py` | The diagram needs a **specific shape** — a cloud icon (AWS/Azure/GCP), Cisco/Kubernetes/network symbol, UML/BPMN/ER/electrical/P&ID element — or any time you'd otherwise guess a `style=` string. `shapesearch.py "<keywords>"` returns the exact official style for 10k+ shapes |57| `scripts/aiicons.py` | The diagram involves an **AI/LLM brand** (OpenAI, Claude, Gemini, Mistral, Llama, HuggingFace, Ollama, LangChain, …) — `aiicons.py "<brand>"` returns a draw.io `image` style for the brand logo (lobe-icons via CDN; `--embed` to inline). draw.io has no built-in AI logos. See `references/shapes.md` → "AI / LLM brand logos" |58| `references/style-presets.md` | The user asks to learn / save / list / set-default / delete a style preset, or you've resolved an active preset and need the application rules |59| `references/style-extraction.md` | You're inside the Learn flow and need the extraction procedure (called from `style-presets.md`) |60| `references/troubleshooting.md` | An export fails, vision rejects a PNG, or a rendering looks wrong |61| `scripts/repair_png.py` | After every `-e` PNG export — fixes draw.io's truncated IEND chunk (issue #8) |62| `scripts/encode_drawio_url.py` | The CLI is unavailable and you need a browser-fallback diagrams.net URL (`--edit` for an editable editor URL) |63| `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 |64| `scripts/pyimports.py` · `jsimports.py` · `goimports.py` · `rustimports.py` | The user wants to visualize a **Python, JS/TS, Go, or Rust project** structure — extracts the import graph (transitive-reduced, optional `--group` containers, nested by sub-package) for autolayout |65| `scripts/pyclasses.py` | The user wants a **Python class hierarchy / class diagram** — extracts classes + inheritance edges (boxed by module with `--group`) for autolayout |66| `scripts/tfimports.py` · `k8simports.py` · `composeimports.py` | The user wants to visualize **declared** infrastructure (**Terraform** `.tf`, **Kubernetes** manifests, or **docker-compose**) — extracts the resource/service reference graph (official AWS/Azure/GCP/K8s icons for tf/k8s; service boxes + volume cylinders for compose) for autolayout |67| `scripts/tfstate.py` · `dockerimports.py` (+ `k8simports.py`) | The user wants to draw **what is ACTUALLY running / deployed** — pipe `terraform show -json` (deployed state), `docker inspect $(docker ps -q)` (live containers), or `kubectl get all,ing,cm,secret,pvc -o json` (live cluster, via k8simports) and get the real topology with the same official icons. See `references/live-infra.md` |68| `scripts/drawiodiff.py` | The user wants to **compare / diff two diagrams or two snapshots** ("what changed", infra drift) — `drawiodiff.py old.drawio new.drawio -o diff.json` emits a colour-coded graph (added=green, removed=red, changed=orange, same=grey) for autolayout. Matches by cell id (importer/live-snapshot output) or `--by-label` (hand-drawn) |69| `scripts/timelapse.py` | The user wants an **architecture time-lapse / to see how a codebase's structure evolved over git history** — `timelapse.py <dir> --importer pyimports` re-runs an importer at each sampled commit and assembles a self-contained HTML player (embedded frames, play/step controls). Best on a package with real import edges (point `<dir>` at the module root) |70| `scripts/explain.py` | The user wants to **describe / document / summarize an existing `.drawio` in words** (reverse of generating one) — `explain.py diagram.drawio` emits structured Markdown: components grouped by container/tier, relations (`A —label→ B`), per-page sections for multi-page/C4. Good for a README/PR summary or a text-only read-out |71| `scripts/drawio2pptx.py` | The user wants a **PowerPoint deck / slides from a diagram** — `drawio2pptx.py diagram.drawio -o deck.pptx` puts each page on its own 16:9 slide (page name as title), so a multi-page **C4 model** becomes a ready-to-present deck. Needs `python-pptx` (`pip install python-pptx`) + the draw.io CLI |72| `scripts/drawiohtml.py` | The user wants a **shareable interactive viewer** for a diagram (pan / zoom / search, no draw.io needed) — `drawiohtml.py diagram.drawio -o viewer.html` inlines every page's SVG into ONE self-contained HTML with page tabs, drag-pan, wheel-zoom, node search (Enter cycles + centres matches) and **working drill-down links** (a C4 model's `data:page/id` links switch tabs). No server, no external requests — send the file to anyone |73| `scripts/svgflow.py` | The user wants an **animated / "flowing" diagram** (data-flow, moving edges) — `svgflow.py diagram.drawio -o flow.svg` exports to SVG and makes every edge a marching-ants animation (dashes travel along the arrows). Self-contained looping `.svg` that renders on GitHub / any browser; `--speed` / `--dash` / `--reverse` |74| `scripts/drawio2mermaid.py` | The user wants to **convert a `.drawio` into Mermaid text** (diagrams-as-code for a Markdown file that GitHub renders) — `drawio2mermaid.py diagram.drawio` emits a `flowchart` (containers → `subgraph`s, edge labels kept, cylinder/rhombus shapes mapped); `--fenced` wraps in ```mermaid, multi-page → one graph per page. Structural only (styling/icons don't survive) |75| `scripts/sqlerd.py` | The user wants an **ER diagram from SQL DDL** — parses `CREATE TABLE` statements into per-table nodes (columns with PK/FK markers) and crow's-foot FK edges for autolayout |76| `scripts/ciimports.py` | The user wants a **CI pipeline diagram** (GitHub Actions workflows or GitLab CI) — `ciimports.py <repo-root>` reads `.github/workflows/*.yml` + `.gitlab-ci.yml` and emits jobs (runner, matrix size, reusable-workflow calls), `needs:` dependency edges, per-workflow trigger nodes, and stage/workflow containers for autolayout. Needs PyYAML |77| `scripts/openapiimports.py` | The user wants an **API diagram from an OpenAPI / Swagger spec** — `openapiimports.py spec.yaml` maps each operation to a node **coloured by HTTP method** (GET blue, POST green, PUT/PATCH orange, DELETE red) plus one node per component schema, with edges from operations to the schemas they use and between nested schemas. `--group` boxes by tag, `--no-schemas` shows just the endpoint surface; feeds autolayout |78| `scripts/heatmap.py` | The user wants to **colour an existing `.drawio` by data** (a cost / latency / traffic / error-rate heat map) — `heatmap.py diagram.drawio -m metrics.csv` matches each metric (CSV `key,value` or JSON `{key:value}`) to a node by id or label and recolours it along a gradient (`--palette heat\|cool\|warm`, `--reverse`), optionally scaling node size (`--size`) and adding a legend. Post-processes any diagram; export as usual |79| `scripts/seqlayout.py` | The user wants a **sequence diagram** — describe participants + messages as JSON and the script computes all lifeline/activation/arrow geometry deterministically (no hand-placed coordinates, no Graphviz needed) |80| `scripts/c4.py` | The user wants a **C4 model** (System Context / Container / Component) — levels JSON in, one multi-page `.drawio` out with official C4 shapes/colors and **click-to-drill-down** links between levels |81| `scripts/relabel.py` | The user wants a **language variant or bulk text swap of an existing `.drawio`** (e.g. an EN diagram re-labelled in Chinese for a bilingual README) — `relabel.py diagram.drawio --extract -o labels.json` dumps every label as an identity JSON map; translate the values (keep the keys), then `relabel.py diagram.drawio --map labels.json -o diagram_cn.drawio` swaps them with layout/styles/ids untouched |82| `scripts/restyle.py` | The user wants to **re-theme an EXISTING `.drawio`** ("make this dark", "apply my corporate style to this diagram") — `restyle.py diagram.drawio --preset <name>` remaps every vertex fill/stroke to the preset palette by hue, applies font/extras (dark fontColor, edge color, background), and leaves layout, shapes, and edge routing untouched. Presets resolve like Step 0 (user dir, then built-ins) |83| `scripts/edgeports.py` | Edges **stack on top of each other where they meet a shape** — the usual swimlane/cross-functional complaint, and anywhere a node has several connections leaving the same side. `edgeports.py diagram.drawio` pins `exitX/exitY`+`entryX/entryY`: it picks the side of each node facing the other endpoint, then spreads that side's edges over evenly-spaced slots **ordered by the far endpoint's position**, so they keep their relative order instead of crossing. Resolves absolute coordinates through swimlane parents, skips ends you already pinned, and is idempotent. It is a **port assigner, not a router** — it separates lines at the shape boundary, it will not stop an edge crossing an unrelated shape mid-run (add waypoints for that) |84| `scripts/validate.py` | You generated a `.drawio` (especially via autolayout or for a large hand-placed diagram) and want a fast deterministic structural lint (dangling edges, dup/reserved ids, broken parents, overlaps) before the vision self-check. `--score` prints a readability score for comparing layout variants |85| `scripts/audit_flowchart.py` | You generated or edited a flowchart — audits decision labels, branch-style consistency, mixed numbering, false return nodes, curves, diagonal segments, avoidable bends, and node-center alignment; run in addition to `validate.py` |86| `scripts/raster2drawio.py` | The user has an **image of a diagram** (whiteboard photo, legacy PNG, Visio screenshot) and wants an **editable `.drawio`** — read the image with your own vision, extract nodes/edges as JSON (schema + full workflow in `references/derasterize.md`), then `raster2drawio.py graph.json -o out.drawio` honours those coordinates/labels/shapes; nodes missing `x`/`y` fall back to `autolayout.py` placement |87| `scripts/buildup.py` | The user wants a diagram to **build itself node-by-node** as a video/GIF (a construction time-lapse of ONE static diagram — distinct from `timelapse.py`'s git-history animation) — `buildup.py diagram.drawio` reveals cells in topological (dependency) order into a self-contained HTML player (play/pause/step/scrub); `--gif` also exports an animated GIF (needs Pillow). Needs the draw.io CLI |88| `scripts/compress.py` | The user wants an **executive / boardroom summary of a big diagram** — collapses clusters (pure-Python label propagation, no networkx) into one labeled node each with aggregated inter-cluster edges, emitting a 2-page `.drawio` (exec view + click-to-drill-down into the full original). Claude can rename clusters semantically afterward. Needs Graphviz `dot` |89| `scripts/runbook.py` | The user wants a flowchart/decision-tree `.drawio` turned into a **click-through triage app** (on-call runbook) — `runbook.py flow.drawio` reads the XML (no draw.io CLI needed) and emits a self-contained HTML runbook: current-step text, per-edge choice buttons, breadcrumb trail, Back/Restart, end-state on terminal nodes |90| `scripts/prdiff.py` | You're setting up **automated PR diagram review** in CI — for every `.drawio` changed between two git refs it renders base/head/diff PNGs and emits a Markdown report; ships with a composite GitHub Action (`.github/actions/drawio-diff/`) that posts a sticky PR comment. See `references/pr-bot.md` |91| `scripts/tubemap.py` | The user wants a **metro / subway / tube map** — a system, pipeline, or journey drawn as coloured transit lines with octilinear (H/V/45°) routing, white interchange circles, and station stops. Compose a metro JSON (lines = ordered stations on an integer grid, shared stations = interchanges), then `tubemap.py metro.json -o metro.drawio`. Stdlib-only; schema + the one grid rule in `references/tubemap.md` |9293## Prerequisites9495The draw.io desktop app must be installed and the CLI accessible:9697**macOS sandbox / sandbox isolation note (e.g., codex.app):** In some sandboxed macOS environments, invoking the draw.io desktop CLI (even `drawio --version`) can crash the draw.io process or produce no output. If that happens, treat the CLI as **unavailable in this sandbox isolation** — do not keep retrying inside the sandbox. Prefer a **non-sandboxed host environment** (outside sandbox isolation) for any CLI export work, or use the browser fallback / XML-only outputs.9899```bash100# macOS (Homebrew — recommended; CLI binary is `drawio`, not `draw.io`)101brew install --cask drawio102drawio --version103104# macOS (full path if not in PATH)105/Applications/draw.io.app/Contents/MacOS/draw.io --version106107# Windows108"C:\Program Files\draw.io\draw.io.exe" --version109110# Linux111drawio --version112```113114Install draw.io desktop if missing:115116- macOS: `brew install --cask drawio` or download from <https://github.com/jgraph/drawio-desktop/releases>117- Windows: download installer from <https://github.com/jgraph/drawio-desktop/releases>118- Linux: download `.deb`/`.rpm` from <https://github.com/jgraph/drawio-desktop/releases> — **do not use snap** (AppArmor sandbox denies secrets/keyring on servers, causes crash)119120## Workflow121122Before starting the workflow, assess whether the user's request is specific enough. If the user has not confirmed a diagram type, follow `references/diagram-routing.md`, present the recommendation and any materially useful alternatives, ask the user to choose, and stop before Step 0. Continue only after the user chooses or explicitly says to decide for them. If other key details are missing, ask 1-3 focused questions:123124- **Output format** — PNG (default), SVG, PDF, or JPG?125- **Output location** — default is the user's working dir; honor any explicit path the user gives (e.g. "put it in `./artifacts/`"). Don't ask if they didn't mention one.126- **Scope/fidelity** — how many components? Any specific technologies or labels?127128Skip diagram-type selection only when the user already specified a suitable type or explicitly delegated the choice. Skip other clarification if the request already specifies the needed details or is clearly simple (e.g., "draw a flowchart of X").129130### Non-negotiable gates131132These gates apply to every authoring path and cannot be skipped because the diagram looks simple or the user reported only one defect.1331341. **Logic gate** — before placing shapes, form an internal diagram contract containing the viewer question, chosen diagram type, node vocabulary, complete main sequence, every decision and branch, every return target, reading direction, and grouping. For a flowchart, classify each node as action, decision, or terminal outcome and read `references/flowchart-quality.md`. Do not start layout while peer nodes mix semantic roles or a branch/return has no defined destination.1352. **Source gate** — keep the `.drawio` file as the only source of truth. Make all content, geometry, style, and routing fixes there, then regenerate previews and final exports.1363. **Full-diagram QA gate** — after the first draft and after every edit, fix the reported instance, search the entire diagram for the same defect class, rerun every applicable deterministic check, export a fresh complete preview, and visually inspect the whole canvas in the fixed scan order from the diagram-specific reference. A local correction never counts as local-only validation.1374. **Completion gate** — do not present an artifact as final while any critical logic, connection, overlap, clipping, consistency, routing, or source/export mismatch remains. If a check cannot run, say which gate is unverified and present the result as a draft.138139**Step 0 — Resolve active preset.** Determine which (if any) user-defined style preset applies to this generation.140141- Scan the user's message for a phrase that clearly names a style preset: "use my `<name>` style", "with my `<name>` style", "in `<name>` mode", "in the style of `<name>`". A bare `with <name>` does **not** count — "draw a diagram with redis" names a component, not a style. If a clear match is found → active preset = `<name>`.142- Else, check `~/.drawio-skill/styles/` for any file with `"default": true`. If found → active preset = that one.143- Else → no preset active; fall through to the built-in color/shape/edge conventions for the rest of the workflow.144145Load the preset JSON from `~/.drawio-skill/styles/<name>.json`, falling back to `<this-skill-dir>/styles/built-in/<name>.json`. If the named preset exists in neither location, tell the user the name is unknown, list the available presets (user dir + built-in), and stop — do **not** silently fall back to defaults.146147When a preset loads successfully, mention it in the first line of the reply: *"Using preset `<name>` (confidence: `<level>`)."* See `references/style-presets.md` → "Applying a preset" for how the preset changes color/shape/edge/font decisions.1481491. **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). **Also note the major version** the command printed: **≥ 30** unlocks Mermaid→`.drawio` conversion and the ELK `--layout` pass (see `references/mermaid-authoring.md`); on **≤ 29** both are unavailable — `.mmd` input fails and `--layout` corrupts argument parsing — so never emit those flags there.1502. **Plan** — complete the logic-gate contract: record the viewer question, selected diagram type, one node vocabulary, full main sequence, every decision/branch/return target, main reading direction, branch convention, return-line corridors, shapes, relationships, and grouping. For a flowchart, read `references/flowchart-quality.md` before placing nodes. Resolve contradictions in this contract before generating XML.1513. **Generate** — produce the `.drawio` file, choosing the authoring mode: **(a) Mermaid → CLI convert** when the diagram is a standard type with no custom styling/icon needs **and** the CLI is ≥ v30 — write a `.mmd` and run `drawio -x -f xml -o <name>.drawio <name>.mmd`, see `references/mermaid-authoring.md` (structure only; layout comes free; never `--layout` afterwards). **(b) Hand-written XML** for custom styling, vendor icons, swimlanes, precise geometry — **read `references/xml-authoring.md` first** (skeleton, cell forms, palette, spacing rules). **(c) A bundled generator** for the data-driven cases below. **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`; add `--tune` to auto-pick the more readable direction). For a **Python / JS-TS / Go / Rust project**, the matching importer (`scripts/pyimports.py`, `jsimports.py`, `goimports.py`, or `rustimports.py`) extracts the import graph (transitive-reduced; add `--group` to box modules by sub-package, nested for deep trees) ready for autolayout; for a **Python class hierarchy**, `scripts/pyclasses.py` extracts classes + inheritance instead; for **Terraform / Kubernetes / docker-compose** (`scripts/tfimports.py`, `k8simports.py`, `composeimports.py`), the importer extracts the resource/service reference graph — tf/k8s nodes resolve to their official cloud icons automatically; to draw **what is actually running** rather than the declared config, pipe `terraform show -json` into `scripts/tfstate.py` or `docker inspect $(docker ps -q)` into `scripts/dockerimports.py` (`k8simports.py` already accepts live `kubectl get ... -o json`) — see `references/live-infra.md`; for an **ER diagram from SQL DDL**, `scripts/sqlerd.py` parses `CREATE TABLE` into table nodes + crow's-foot FK edges; for an **API diagram from an OpenAPI / Swagger spec**, `scripts/openapiimports.py` maps operations (coloured by HTTP method) + component schemas into a graph for autolayout; for a **CI pipeline diagram** (GitHub Actions / GitLab CI), `scripts/ciimports.py` extracts jobs, `needs:` edges, triggers, and stage/workflow containers. To turn any generated `.drawio` into a **metric heat map** — recolour nodes by a CSV/JSON of cost/latency/traffic/errors — run `python3 <this-skill-dir>/scripts/heatmap.py <name>.drawio -m metrics.csv` (matches on cell id or label; `--palette`, `--size`, legend). For a **sequence diagram**, skip autolayout entirely — describe participants + messages as JSON and run `python3 <this-skill-dir>/scripts/seqlayout.py seq.json -o <name>.drawio` (deterministic lifeline/activation/arrow geometry; see the script docstring for the JSON schema). For a **C4 model**, `python3 <this-skill-dir>/scripts/c4.py c4.json -o <name>.drawio` emits the full multi-page Context→Container→Component set with drill-down links (schema in the script docstring). For complex architecture diagrams with many visible edge labels, give labels `labelBackgroundColor=#ffffff;fontSize=11` and use edge geometry `x`/`y` offsets plus `<mxPoint as="offset" />` to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. For hand-placed diagrams where edges cross shapes (architecture, network topology, deployment, UML), fix the routing in the XML — run `python3 <this-skill-dir>/scripts/edgeports.py <name>.drawio` to distribute stacked edges over each shape's perimeter automatically, then add `<Array as="points">` waypoints or widen node spacing for any edge still crossing a shape mid-run (see `references/xml-authoring.md`). **No CLI flag reroutes edges without moving nodes**: every `--layout` preset is an ELK *node* layout that re-places vertices, and an unrecognised value opens a modal error dialog that hangs headless runs. draw.io's obstacle-avoiding router is editor-side only. After generating any `.drawio`, run `python3 <this-skill-dir>/scripts/validate.py <name>.drawio` for a fast structural lint (dangling edges, dup ids, overlaps) before exporting. 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.152 **Generation gate:** Treat `.drawio` as the single source of truth; never hand-fix SVG or PNG independently. Run `python3 <this-skill-dir>/scripts/validate.py <name>.drawio --score`; for a flowchart also run `python3 <this-skill-dir>/scripts/audit_flowchart.py <name>.drawio`. Fix reported issues before exporting.1534. **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).1545. **Self-check** — use the agent's built-in vision capability to read the complete exported PNG and audit the whole diagram, not only the last edited area. For flowcharts, use the fixed full-canvas scan order in `references/flowchart-quality.md`. If reading the PNG returns a 400 / "Could not process image" error, re-export without `-e` and retry once. If vision remains unavailable, report that limitation; deterministic checks still do not prove visual correctness.1556. **Review loop** — show the image, collect feedback, edit only the `.drawio` source, fix every occurrence of the reported defect class, rerun all structural and diagram-specific audits across the entire diagram, re-export, inspect the complete image, and repeat until approved1567. **Final export** — re-export the approved version to all requested formats. Use `-e` here (PNG/SVG/PDF) so the deliverable stays editable in draw.io; save as `<name>.drawio.png` to signal embedded XML. **For PNG with `-e`, run `python3 <this-skill-dir>/scripts/repair_png.py <name>.drawio.png` immediately after** — draw.io's CLI truncates the IEND chunk in `-e` PNG output (8 bytes missing), producing a corrupt file that vision APIs and strict PNG decoders reject (issue #8). Report file paths.157158**If `drawio --version` crashes or prints nothing (common in restricted macOS sandbox isolation like codex.app):**159160- Do not keep retrying CLI invocations inside the sandbox.161- Raw Mermaid, ASCII, or prose is not a fallback deliverable. All fallback paths must still create a `.drawio` XML file.162- Skip steps 4, 5, 6, and 7 (CLI export + PNG-based review) and use **Browser fallback** (`scripts/encode_drawio_url.py`) or deliver the `.drawio` XML only.163- If the user needs PNG/SVG/PDF outputs, ask them to run the export commands in a **non-sandboxed host environment** (outside sandbox isolation) and share the resulting files.164165Escalation rule:166167- If the binary exists on PATH (or known app path exists) but execution fails with abnormal exit, empty output, Electron startup failure, display/session error, or likely sandbox restriction, prefer one escalated retry before falling back.168- If the binary is missing entirely, do not escalate just to search more aggressively; go to install guidance or fallback.169170### Step 5: Self-Check171172After exporting the draft PNG, use the agent's vision capability (e.g., Claude's image input) to read the image and check for these issues before showing the user. If the agent does not support vision, skip self-check and show the PNG directly.173174**Important:** the draft PNG read here must have been exported **without** `-e`. Draw.io's `-e` flag emits a PNG with a truncated IEND chunk (8 bytes of type+CRC missing) that the Anthropic vision API rejects with 400 "Could not process image" (issue #8). The simplest fix for the preview step is to skip `-e` entirely; the final export in step 7 keeps `-e` and runs the repair snippet. If you see the 400 error here, re-export without `-e` and retry once; if it still fails (any other reason), skip self-check and proceed to step 6.175176| Check | What to look for | Auto-fix action |177| ------- | ----------------- | ----------------- |178| Overlapping shapes | Two or more shapes stacked on top of each other | Shift shapes apart by ≥200px |179| Clipped labels | Text cut off at shape boundaries | Increase shape width/height to fit label |180| Missing connections | Arrows that don't visually connect to shapes | Verify `source`/`target` ids match existing cells |181| Off-canvas shapes | Shapes at negative coordinates or far from the main group | Move to positive coordinates near the cluster |182| Edge-shape overlap | An edge/arrow visually crosses through an unrelated shape | Add waypoints (`<Array as="points">`) to route around the shape, or increase spacing between shapes |183| Stacked edges | Multiple edges overlap each other on the same path | Distribute entry/exit points across the shape perimeter (use different exitX/entryX values) |184| Edge-label overlap | Edge text overlaps another label, line, or node in the exported PNG | Keep the label on the edge, add a white label background, and move it locally with edge geometry `x`/`y` offsets into adjacent whitespace |185| Mixed semantics | Peer nodes mix actions, states, and explanatory notes | Choose one semantic grammar and change shapes or labels to match it |186| Inconsistent styling | Number badges, branch labels, fonts, colors, borders, or return lines differ without meaning | Apply the same style to every item with the same semantic role |187| Avoidable crooked route | A mostly vertical or horizontal connection bends because nodes are not center-aligned | Align node centers and use one straight pinned connector |188| False return | A node says `返回步骤 N` but no edge actually reaches step N | Add the real dashed return edge to the target or remove the claim |189| Source/export mismatch | PNG or SVG contains changes not present in `.drawio` | Fix `.drawio`, discard the independent export edit, and export again |190191- Max **2 automatic repair rounds** — if a critical issue remains, show the result explicitly as a draft and list the defect; never call it final192- Re-export after each fix and re-read the new PNG193194### Step 6: Review Loop195196After self-check, show the exported image and ask the user for feedback.197198**Targeted edit rules** — preserve already-approved geometry where possible, but treat the user's marked location as evidence of a defect class, not as the boundary of the review. Apply the minimal source change to the marked item, then find and fix every equivalent defect elsewhere before revalidating the whole diagram:199200| User request | XML edit action |201| ------------- | ---------------- |202| Change color of X | Find `mxCell` by `value` matching X, update `fillColor`/`strokeColor` in `style` |203| Add a new node | Append a new `mxCell` vertex with next available `id`, position near related nodes |204| Remove a node | Delete the `mxCell` vertex and any edges with matching `source`/`target` |205| Move shape X | Update `x`/`y` in the `mxGeometry` of the matching `mxCell` |206| Resize shape X | Update `width`/`height` in the `mxGeometry` of the matching `mxCell` |207| Add arrow from A to B | Append a new `mxCell` edge with `source`/`target` matching A and B ids |208| Change label text | Update the `value` attribute of the matching `mxCell` |209| Change layout direction | **Full regeneration** — rebuild XML with new orientation |210211**Rules:**212213- For single-element changes: edit existing XML in place — preserves layout tuning from prior iterations214- For layout-wide changes (e.g., swap LR↔TB, "start over"): regenerate full XML215- Overwrite the same `{name}.png` (no `-e`) each iteration — do not create `v1`, `v2`, `v3` files. `-e` is reserved for the final export in step 7.216- After applying edits, search for the same problem across all pages, rerun the complete structural and diagram-specific audit, then re-export and inspect the whole image rather than only the edited region217- Recheck previously corrected defect classes as well; a later edit must not reintroduce an earlier problem218- Do not show an updated preview until the complete audit has passed, unless it is explicitly labeled as a draft with the remaining defects219- Loop continues until user says approved / done / LGTM220- **Safety valve:** after 5 iteration rounds, suggest the user open the `.drawio` file in draw.io desktop for fine-grained adjustments221222### Step 7: Final Export223224Once the user approves:225226- Export every final format from the approved `.drawio` source; never deliver an independently edited PNG or SVG as if it matched the editable source227- Export to all requested formats (PNG, SVG, PDF, JPG) — default to PNG if not specified228- Report file paths for both the `.drawio` source file and exported image(s)229- **Auto-launch:** offer to open the `.drawio` file in draw.io desktop for fine-tuning — `open diagram.drawio` (macOS), `xdg-open` (Linux), `start` (Windows)230- Confirm files are saved and ready to use231232## Style Presets233234A **style preset** is a named JSON file capturing a user's visual preferences (palette, shapes, font, edges). When active, it replaces the built-in visual conventions, but it never overrides diagram grammar or the mandatory QA gates. In particular, a flowchart preset may change palette and typography but must still obey `flowchart-quality.md`, including square-corner routing and full-diagram review.235236**Lookup order** when SKILL.md's Step 0 resolves a preset name:2372381. `~/.drawio-skill/styles/<name>.json` — user presets (survive `git pull`)2392. `<this-skill-dir>/styles/built-in/<name>.json` — shipped built-ins (`default`, `corporate`, `handdrawn`, `colorblind-safe`, `dark`)240241Always lowercase the user-provided name before any file operation — the schema enforces lowercase.242243**For everything else — Learn flow (extracting a preset from a file), management ops (list/default/delete/rename), application rules (color lookup, shape keywords, edges, fonts, extras, interaction with diagram-type presets), and validation — read `references/style-presets.md`.** It's only needed when the user invokes those flows or when an active preset must be applied to the current generation.244245## Authoring .drawio XML246247**Before hand-writing any `.drawio` XML (step 3), read `references/xml-authoring.md`** — file skeleton, shape/edge cell forms, containers, connection-point distribution, color palette, and spacing/grid rules all live there. Skip it only when a bundled generator writes the XML for you (`autolayout.py` + importers, `seqlayout.py`).248249Two rules worth stating even here: never reuse ids `0`/`1` (reserved root cells), and every edge `mxCell` needs a `<mxGeometry relative="1" as="geometry" />` child — self-closing edge cells do not render.250251## Export252253### Commands254255There are **two** export modes:256257- **Preview / self-check** (step 4 of the workflow) — no `-e`. Output `diagram.png`. Required for vision self-check; using `-e` here triggers a 400 "Could not process image" error from the vision API (issue #8).258- **Final / deliverable** (step 7) — pass `-e`. Output `diagram.drawio.png`. The embedded XML keeps the file editable in draw.io.259260> All commands below write `drawio` as a placeholder for the binary you resolved in Step 1. If your binary is on PATH as `draw.io` (with dot — some older or distro-packaged installs), substitute `draw.io` throughout. If only the macOS `.app` or Windows `.exe` is available, use the full path variant shown a few lines down.261262```bash263# Preview PNG (use this in step 4, before self-check) — NO -e, width-capped to stay under vision's 2576px ceiling264drawio -x -f png --width 2000 -o diagram.png input.drawio265266# Final PNG (step 7, after user approval) — WITH -e, double extension267drawio -x -f png -e -s 2 -o diagram.drawio.png input.drawio268269# macOS — full path (if not in PATH); preview / final variants270/Applications/draw.io.app/Contents/MacOS/draw.io -x -f png --width 2000 -o diagram.png input.drawio271/Applications/draw.io.app/Contents/MacOS/draw.io -x -f png -e -s 2 -o diagram.drawio.png input.drawio272273# Windows274"C:\Program Files\draw.io\draw.io.exe" -x -f png -e -s 2 -o275276…(truncated)