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: seqlayout + compose/SQL importers, layout auto-tune, SKILL.md slimming (v1.16.0) (#53)

Agents365.ai2a38afe46417
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b8f739c..6e81b4f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,33 @@ All notable changes to **drawio-skill** are documented here. The format is based
on [Keep a Changelog](https://keepachangelog.com/), and the project follows
semantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).
+## [1.16.0] — 2026-07-02
+### Added
+- **`seqlayout.py` — deterministic sequence diagrams.** Participants +
+ messages JSON in, finished `.drawio` out: lifeline, activation-bar and
+ arrow geometry are computed (not hand-placed), with automatic activation
+ tracking (sync opens a bar on the target, return closes the sender's),
+ self-messages, notes, actor lifelines, and the official umlLifeline styles
+ from `diagram-types.md`. No Graphviz needed.
+- **`composeimports.py`** — docker-compose → autolayout graph: services as
+ name+image boxes, named volumes as cylinders; edges from `depends_on` /
+ `links` / `volumes_from` / volume mounts. `--group` by network.
+- **`sqlerd.py`** — SQL DDL → ER diagram: parses `CREATE TABLE` (inline and
+ table-level PK/FK, quoted identifiers, schema prefixes) into per-table
+ nodes with PK/FK-marked column lists and crow's-foot FK edges.
+- **Layout auto-tuning.** `autolayout.py --tune` lays out in both directions
+ and keeps the more readable one; `validate.py --score` prints the matching
+ readability score (through-vertex ×20, crossings ×10, overlaps ×5).
+- `autolayout.py` honours per-edge `style` in the graph JSON (used by
+ sqlerd's ER edges).
+### Changed
+- **SKILL.md slimmed 488 → 313 lines**: the XML-authoring tutorial (skeleton,
+ shape/edge cells, containers, connection distribution, palette, layout
+ tips) moved to `references/xml-authoring.md`, read on demand before
+ hand-writing XML — generator-driven flows no longer pay for it.
+- Tests: 42 (new coverage for seqlayout, composeimports, sqlerd, edge-style
+ passthrough).
+
## [1.15.0] — 2026-07-02
### Added
- **IaC → architecture diagram.** Two new importers feed autolayout:
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 0b3ca4b..4047dfe 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,12 +1,12 @@
---
name: drawio-skill
-version: 1.15.0
+version: 1.16.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, network topology, cloud architecture from Terraform or Kubernetes manifests, 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. 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"]},{"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.15.0"}
+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.16.0"}
---
# Draw.io Diagrams
@@ -34,6 +34,7 @@ When the workflow references one of these, read it on demand — none of them ne
| File | Read it when |
|---|---|
+| `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/diagram-types.md` | The user names a specific diagram type (ERD, UML class, sequence, architecture, ML/DL, flowchart) |
| `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" |
@@ -45,8 +46,10 @@ When the workflow references one of these, read it on demand — none of them ne
| `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` | The user wants to visualize **Terraform or Kubernetes infrastructure** — extracts the resource/object reference graph with each node resolved to its **official cloud icon** (AWS/Azure/GCP via the shape index, K8s kind icons) for autolayout |
-| `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 |
+| `scripts/tfimports.py` · `k8simports.py` · `composeimports.py` | The user wants to visualize **Terraform, Kubernetes, or docker-compose infrastructure** — extracts the resource/service reference graph (official AWS/Azure/GCP/K8s icons for tf/k8s; service boxes + volume cylinders for compose) for autolayout |
+| `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/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/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 |
## Prerequisites
@@ -92,11 +95,11 @@ Skip clarification if the request already specifies these details or is clearly
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 the **Applying a preset** subsection below for how the preset changes color/shape/edge/font decisions.
+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.
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. 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`). 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** (`scripts/tfimports.py <dir>`) or **Kubernetes manifests** (`scripts/k8simports.py <dir>`), the importer extracts the resource/object reference graph and resolves every node to its official cloud icon (AWS/Azure/GCP/K8s) automatically. 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. 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.
+3. **Generate** — write `.drawio` XML file to disk. Hand-place coordinates for small/styled diagrams — **read `references/xml-authoring.md` first** (skeleton, cell forms, palette, spacing rules). **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; for an **ER diagram from SQL DDL**, `scripts/sqlerd.py` parses `CREATE TABLE` into table nodes + crow's-foot FK edges. 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 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. 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.
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
@@ -175,186 +178,11 @@ Always lowercase the user-provided name before any file operation — the schema
**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.
-## Draw.io XML Structure
-
-### File skeleton
-
-```xml
-<?xml version="1.0" encoding="UTF-8"?>
-<mxfile host="drawio" version="26.0.0">
- <diagram name="Page-1">
- <mxGraphModel>
- <root>
- <mxCell id="0" />
- <mxCell id="1" parent="0" />
- <!-- user shapes start at id="2" -->
- </root>
- </mxGraphModel>
- </diagram>
-</mxfile>
-```
-
-**Rules:**
-- `id="0"` and `id="1"` are required root cells — never omit them
-- User shapes start at `id="2"` and increment sequentially
-- All shapes have `parent="1"` (unless inside a container — then use container's id)
-- All text uses `html=1` in style for proper rendering
-- **Never use `--` inside XML comments** — it's illegal per XML spec and causes parse errors
-- Escape special characters in attribute values: `&amp;`, `&lt;`, `&gt;`, `&quot;`
-- **Multi-line text in labels:** use `&#xa;` for line breaks inside `value` attributes (not literal `\n`). Example: `value="Line 1&#xa;Line 2"`
-
-### Shape types (vertex)
-
-| Style keyword | Use for |
-|--------------|---------|
-| `rounded=0` | plain rectangle (default) |
-| `rounded=1` | rounded rectangle — services, modules |
-| `ellipse;` | circles/ovals — start/end, databases |
-| `rhombus;` | diamond — decision points |
-| `shape=mxgraph.aws4.resourceIcon;` | AWS icons |
-| `shape=cylinder3;` | cylinder — databases |
-| `swimlane;` | group/container with title bar |
-
-For **vendor/branded icons** (AWS/Azure/GCP/Cisco/Kubernetes) and any non-trivial shape, don't guess the `shape=mxgraph.*` name — a wrong name renders as a blank box. Run `python3 <this-skill-dir>/scripts/shapesearch.py "<keywords>"` to get the exact official style + size, or see `references/shapes.md` for the hand-writable cheatsheet. For **AI/LLM brand logos** (OpenAI, Claude, Gemini, …), which draw.io has none of, use `python3 <this-skill-dir>/scripts/aiicons.py "<brand>"`.
-
-### Required properties
-
-```xml
-<!-- Rectangle / rounded box -->
-<mxCell id="2" value="Label" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">
- <mxGeometry x="100" y="100" width="160" height="60" as="geometry" />
-</mxCell>
-
-<!-- Cylinder (database) -->
-<mxCell id="3" value="DB" style="shape=cylinder3;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;" vertex="1" parent="1">
- <mxGeometry x="350" y="100" width="120" height="80" as="geometry" />
-</mxCell>
-
-<!-- Diamond (decision) -->
-<mxCell id="4" value="Check?" style="rhombus;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;" vertex="1" parent="1">
- <mxGeometry x="100" y="220" width="160" height="80" as="geometry" />
-</mxCell>
-```
+## Authoring .drawio XML
-### Containers and groups
-
-For architecture diagrams with nested elements, use draw.io's parent-child containment — do **not** just place shapes on top of larger shapes.
-
-| Type | Style | When to use |
-|------|-------|-------------|
-| **Group** (invisible) | `group;pointerEvents=0;` | No visual border needed, container has no connections |
-| **Swimlane** (titled) | `swimlane;startSize=30;` | Container needs a visible title bar, or container itself has connections |
-| **Custom container** | Add `container=1;pointerEvents=0;` to any shape | Any shape acting as a container without its own connections |
-
-**Key rules:**
-- Add `pointerEvents=0;` to container styles that should not capture connections between children
-- Children set `parent="containerId"` and use coordinates **relative to the container**
-
-```xml
-<!-- Swimlane container -->
-<mxCell id="svc1" value="User Service" style="swimlane;startSize=30;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">
- <mxGeometry x="100" y="100" width="300" height="200" as="geometry"/>
-</mxCell>
-<!-- Child inside container — coordinates relative to parent -->
-<mxCell id="api1" value="REST API" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="svc1">
- <mxGeometry x="20" y="40" width="120" height="60" as="geometry"/>
-</mxCell>
-<mxCell id="db1" value="Database" style="shape=cylinder3;whiteSpace=wrap;html=1;" vertex="1" parent="svc1">
- <mxGeometry x="160" y="40" width="120" height="60" as="geometry"/>
-</mxCell>
-```
-
-### Connector (edge)
-
-**CRITICAL:** Every edge `mxCell` must contain a `<mxGeometry relative="1" as="geometry" />` child element. Self-closing edge cells (`<mxCell ... edge="1" ... />`) are **invalid** and will not render. Always use the expanded form.
-
-```xml
-<!-- Directed arrow — always include rounded, orthogonalLoop, jettySize for clean routing -->
-<mxCell id="10" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="2" target="3">
- <mxGeometry relative="1" as="geometry" />
-</mxCell>
-
-<!-- Arrow with label + explicit entry/exit points to control direction -->
-<mxCell id="11" value="HTTP/REST" style="edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="2" target="4">
- <mxGeometry relative="1" as="geometry" />
-</mxCell>
-
-<!-- Arrow with waypoints — use when edge must route around other shapes -->
-<mxCell id="12" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="3" target="5">
- <mxGeometry relative="1" as="geometry">
- <Array as="points">
- <mxPoint x="500" y="50" />
- </Array>
- </mxGeometry>
-</mxCell>
-```
+**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`).
-**Edge style rules:**
-- **Animated connectors:** add `flowAnimation=1;` to any edge style to show a moving dot animation along the arrow. Works in SVG export and draw.io desktop — ideal for data-flow and pipeline diagrams. Example: `style="edgeStyle=orthogonalEdgeStyle;flowAnimation=1;rounded=1;..."`
-- **Always** include `rounded=1;orthogonalLoop=1;jettySize=auto` — these enable smart routing that avoids overlaps
-- Pin `exitX/exitY/entryX/entryY` on every edge when a node has 2+ connections — distributes lines across the shape perimeter
-- Add `<Array as="points">` waypoints when an edge must detour around an intermediate shape
-- **Leave room for arrowheads:** the final straight segment between the last bend and the target shape must be ≥20px long. If too short, the arrowhead overlaps the bend and looks broken. Fix by increasing node spacing or adding explicit waypoints
-
-### Distributing connections on a shape
-
-When multiple edges connect to the same shape, assign different entry/exit points to prevent stacking:
-
-| Position | exitX/entryX | exitY/entryY | Use when |
-|----------|-------------|-------------|----------|
-| Top center | 0.5 | 0 | connecting to node above |
-| Top-left | 0.25 | 0 | 2nd connection from top |
-| Top-right | 0.75 | 0 | 3rd connection from top |
-| Right center | 1 | 0.5 | connecting to node on right |
-| Bottom center | 0.5 | 1 | connecting to node below |
-| Left center | 0 | 0.5 | connecting to node on left |
-
-**Rule:** if a shape has N connections on one side, space them evenly (e.g., 3 connections on bottom → exitX = 0.25, 0.5, 0.75)
-
-### Color palette (fillColor / strokeColor)
-
-*Used only when no preset is active (see "Applying a preset" above).*
-
-| Color name | fillColor | strokeColor | Use for |
-|-----------|-----------|-------------|---------|
-| Blue | `#dae8fc` | `#6c8ebf` | services, clients |
-| Green | `#d5e8d4` | `#82b366` | success, databases |
-| Yellow | `#fff2cc` | `#d6b656` | queues, decisions |
-| Orange | `#ffe6cc` | `#d79b00` | gateways, APIs |
-| Red/Pink | `#f8cecc` | `#b85450` | errors, alerts |
-| Grey | `#f5f5f5` | `#666666` | external/neutral |
-| Purple | `#e1d5e7` | `#9673a6` | security, auth |
-
-### Layout tips
-
-**Spacing — scale with complexity:**
-
-| Diagram complexity | Nodes | Horizontal gap | Vertical gap |
-|-------------------|-------|----------------|--------------|
-| Simple | ≤5 | 200px | 150px |
-| Medium | 6–10 | 280px | 200px |
-| Complex | >10 | 350px | 250px |
-
-**Routing corridors:** between shape rows/columns, leave an extra ~80px empty corridor where edges can route without crossing shapes. Never place a shape in a gap that edges need to traverse.
-
-**Grid alignment:** snap all `x`, `y`, `width`, `height` values to **multiples of 10** — this ensures shapes align cleanly on draw.io's default grid and makes manual editing easier.
-
-**General rules:**
-- Plan a grid before assigning x/y coordinates — sketch node positions on paper/mentally first
-- Group related nodes in the same horizontal or vertical band
-- Use `swimlane` cells for logical grouping with visible borders
-- Place heavily-connected "hub" nodes centrally so edges radiate outward instead of crossing
-- To force straight vertical connections, pin entry/exit points explicitly on edges:
- `exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0`
-- Always center-align a child node under its parent (same center x) to avoid diagonal routing
-- **Event bus pattern**: place Kafka/bus nodes in the **center of the service row**, not below — services on either side can reach it with short horizontal arrows (`exitX=1` left side, `exitX=0` right side), eliminating all line crossings
-- Horizontal connections (`exitX=1` or `exitX=0`) never cross vertical nodes in the same row; use them for peer-to-peer and publish connections
-
-**Avoiding edge-shape overlap:**
-- Before finalizing coordinates, trace each edge path mentally — if it must cross an unrelated shape, either move the shape or add waypoints
-- For tree/hierarchical layouts: assign nodes to layers (rows), connect only between adjacent layers to minimize crossings
-- For star/hub layouts: place the hub center, satellites around it — edges stay short and radial
-- When an edge must span multiple rows/columns, route it along the outer corridor, not through the middle of the diagram
+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
diff --git a/skills/drawio-skill/references/autolayout.md b/skills/drawio-skill/references/autolayout.md
index eaad9d6..52fdbfb 100644
--- a/skills/drawio-skill/references/autolayout.md
+++ b/skills/drawio-skill/references/autolayout.md
@@ -99,6 +99,8 @@ Bundled importers turn a codebase or an IaC configuration into a graph JSON read
| Python (classes) | `scripts/pyclasses.py <dir>` | class (`ast`) | subclass → base (inheritance) |
| Terraform | `scripts/tfimports.py <dir>` | `resource` / `module` block, rendered as its **official AWS/Azure/GCP icon** | cross-resource reference (`aws_iam_role.x.arn`, `${...}`, `depends_on`) |
| Kubernetes | `scripts/k8simports.py <dir>` | manifest object (kind/name), rendered as its **official K8s kind icon** | Ingress→Service, Service→workload (selector), workload→ConfigMap/Secret/PVC, HPA→target |
+| docker-compose | `scripts/composeimports.py <file-or-dir>` | service (name + image box) / named volume (cylinder) | `depends_on` / `links` / `volumes_from` / named-volume mounts |
+| SQL DDL | `scripts/sqlerd.py <file-or-dir>` | table (column list with PK/FK markers) | foreign key (crow's-foot, labeled with the FK column) |
```bash
python3 <this-skill-dir>/scripts/pyimports.py myproject -o graph.json
@@ -114,8 +116,12 @@ Each code importer keeps only **intra-project** edges (third-party/stdlib import
- **Python classes** (`pyclasses.py`): a finer granularity — one node per class, edges from each subclass to the project base classes it extends, so the result is an auto-generated class hierarchy. Bases are matched by name (preferring the same module); external bases (`object`, third-party) are ignored. With `--group`, classes are boxed by their module, so a deep package tree nests naturally. Inheritance only — function-level call graphs are out of scope (static call resolution in Python is unreliable).
- **Terraform** (`tfimports.py`): parses `.tf` files directly (regex + brace matching, no HCL library). Each resource type is resolved to its official icon through the bundled shape index — AWS `aws4` set, Azure `azure2` set, GCP icon set — with a curated query table for the ~45 most common types and strict tag-AND matching so a partial match never lands on the wrong vendor's icon; unresolvable types fall back to a plain box labeled `name` + type (`--no-icons` forces boxes for all). `--group` boxes resources by service (`aws_s3_* → s3`). Data sources, variables, locals and providers are ignored; heredocs with unbalanced braces are the known parse limit.
- **Kubernetes** (`k8simports.py`): accepts one or more manifest files or a directory. JSON (including `kind: List`, i.e. `kubectl get ... -o json` output) parses with the stdlib alone; `.yaml`/`.yml` needs PyYAML. Kind icons come from the official `mxgraph.kubernetes` set (25 kinds mapped). Edges land only on objects present in the manifest set, matched within the same namespace. `--group` boxes objects by namespace. No `--no-reduce` flag — reference edges are sparse and never reduced.
+- **docker-compose** (`composeimports.py`): needs PyYAML. Services become rounded boxes labeled `name` + image (or `build:` context); named volumes declared in the top-level `volumes:` section become cylinders. `--group` boxes services by their first network.
+- **SQL DDL** (`sqlerd.py`): regex + paren matching, no SQL library. Handles inline and table-level `PRIMARY KEY`/`FOREIGN KEY ... REFERENCES`, quoted identifiers, `schema.table` prefixes (`--group` boxes by schema). Column lines carry `PK`/`FK` markers and types (`--no-types` to hide). Unknown dialect clauses are skipped, never mis-parsed into edges.
-Both IaC importers emit `ranksep`/`nodesep` in the graph JSON automatically (icon labels render *below* the shape, so rows need extra separation).
+The tf/k8s importers emit `ranksep`/`nodesep` in the graph JSON automatically (icon labels render *below* the shape, so rows need extra separation).
+
+**`--tune` (autolayout flag)**: lays the graph out in both directions (TB and LR), scores each (through-vertex routes ×20 + edge crossings ×10 + total edge length as tiebreak), and keeps the better one — report on stderr. `validate.py --score` prints the same style of readability score for a finished `.drawio`, for comparing variants.
**Density reduction is on by default** — this is the key to a readable result. Real import graphs are dense (asyncio: 33 modules / ~149 edges); without reduction they render as a hairball. Every importer applies **transitive reduction** (Graphviz `tred` — drops edges already implied by a longer path), which on asyncio cuts ~149 edges to ~46 and turns the hairball into a clean, traceable diagram. Pass `--no-reduce` to keep every edge.
@@ -128,4 +134,4 @@ For any other language, produce the same graph JSON from any analyzer (e.g. `dep
- **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`).
- **Import edges are static** — `pyimports`/`jsimports`/`goimports` read static import statements (not dynamic `importlib`, runtime `require`, or reflection); `pyclasses` resolves inheritance only, not method-level calls.
- **Parallel edges** between the same `(source, target)` pair share one route.
-- **Containers don't add edges** — `group`/nesting only boxes nodes for layout; edges remain node→node. For hand-built swimlane/architecture containers with their own connections, see SKILL.md "Containers and groups".
+- **Containers don't add edges** — `group`/nesting only boxes nodes for layout; edges remain node→node. For hand-built swimlane/architecture containers with their own connections, see `references/xml-authoring.md` "Containers and groups".
diff --git a/skills/drawio-skill/references/diagram-types.md b/skills/drawio-skill/references/diagram-types.md
index c053b15..1d11088 100644
--- a/skills/drawio-skill/references/diagram-types.md
+++ b/skills/drawio-skill/references/diagram-types.md
@@ -8,6 +8,8 @@ Read this file when:
## ERD (Entity-Relationship Diagram)
+**From SQL DDL, don't hand-build**: `python3 scripts/sqlerd.py schema.sql -o graph.json` parses `CREATE TABLE` into per-table nodes (PK/FK-marked column lists) + crow's-foot FK edges for autolayout. Hand-build with the styles below when there's no DDL to parse.
+
| Element | Style | Notes |
|---------|-------|-------|
| Table | `shape=table;startSize=30;container=1;collapsible=1;childLayout=tableLayout;fixedRows=1;rowLines=0;fontStyle=1;strokeColor=#6c8ebf;fillColor=#dae8fc;` | Each table is a container |
@@ -30,6 +32,8 @@ Read this file when:
## Sequence Diagram
+**Don't hand-place sequence geometry** — `python3 scripts/seqlayout.py seq.json -o out.drawio` computes all lifeline/activation-bar/arrow coordinates deterministically from a participants + messages JSON (schema in the script docstring), using exactly the styles below. Hand-edit the output only for fragments (alt/loop frames), which are out of its scope.
+
| Element | Style | Notes |
|---------|-------|-------|
| Actor/Object | `shape=umlLifeline;perimeter=lifelinePerimeter;whiteSpace=wrap;html=1;container=1;collapsible=0;recursiveResize=0;outlineConnect=0;portConstraint=eastwest;` | Lifeline with dashed vertical line |
diff --git a/skills/drawio-skill/references/xml-authoring.md b/skills/drawio-skill/references/xml-authoring.md
new file mode 100644
index 0000000..d02f289
--- /dev/null
+++ b/skills/drawio-skill/references/xml-authoring.md
@@ -0,0 +1,184 @@
+# Authoring .drawio XML
+
+Read this **before hand-writing any `.drawio` XML** (workflow step 3). Skip it when a bundled generator writes the XML for you (`autolayout.py` + importers, `seqlayout.py`).
+
+
+### File skeleton
+
+```xml
+<?xml version="1.0" encoding="UTF-8"?>
+<mxfile host="drawio" version="26.0.0">
+ <diagram name="Page-1">
+ <mxGraphModel>
+ <root>
+ <mxCell id="0" />
+ <mxCell id="1" parent="0" />
+ <!-- user shapes start at id="2" -->
+ </root>
+ </mxGraphModel>
+ </diagram>
+</mxfile>
+```
+
+**Rules:**
+- `id="0"` and `id="1"` are required root cells — never omit them
+- User shapes start at `id="2"` and increment sequentially
+- All shapes have `parent="1"` (unless inside a container — then use container's id)
+- All text uses `html=1` in style for proper rendering
+- **Never use `--` inside XML comments** — it's illegal per XML spec and causes parse errors
+- Escape special characters in attribute values: `&amp;`, `&lt;`, `&gt;`, `&quot;`
+- **Multi-line text in labels:** use `&#xa;` for line breaks inside `value` attributes (not literal `\n`). Example: `value="Line 1&#xa;Line 2"`
+
+### Shape types (vertex)
+
+| Style keyword | Use for |
+|--------------|---------|
+| `rounded=0` | plain rectangle (default) |
+| `rounded=1` | rounded rectangle — services, modules |
+| `ellipse;` | circles/ovals — start/end, databases |
+| `rhombus;` | diamond — decision points |
+| `shape=mxgraph.aws4.resourceIcon;` | AWS icons |
+| `shape=cylinder3;` | cylinder — databases |
+| `swimlane;` | group/container with title bar |
+
+For **vendor/branded icons** (AWS/Azure/GCP/Cisco/Kubernetes) and any non-trivial shape, don't guess the `shape=mxgraph.*` name — a wrong name renders as a blank box. Run `python3 <this-skill-dir>/scripts/shapesearch.py "<keywords>"` to get the exact official style + size, or see `references/shapes.md` for the hand-writable cheatsheet. For **AI/LLM brand logos** (OpenAI, Claude, Gemini, …), which draw.io has none of, use `python3 <this-skill-dir>/scripts/aiicons.py "<brand>"`.
+
+### Required properties
+
+```xml
+<!-- Rectangle / rounded box -->
+<mxCell id="2" value="Label" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">
+ <mxGeometry x="100" y="100" width="160" height="60" as="geometry" />
+</mxCell>
+
+<!-- Cylinder (database) -->
+<mxCell id="3" value="DB" style="shape=cylinder3;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;" vertex="1" parent="1">
+ <mxGeometry x="350" y="100" width="120" height="80" as="geometry" />
+</mxCell>
+
+<!-- Diamond (decision) -->
+<mxCell id="4" value="Check?" style="rhombus;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;" vertex="1" parent="1">
+ <mxGeometry x="100" y="220" width="160" height="80" as="geometry" />
+</mxCell>
+```
+
+### Containers and groups
+
+For architecture diagrams with nested elements, use draw.io's parent-child containment — do **not** just place shapes on top of larger shapes.
+
+| Type | Style | When to use |
+|------|-------|-------------|
+| **Group** (invisible) | `group;pointerEvents=0;` | No visual border needed, container has no connections |
+| **Swimlane** (titled) | `swimlane;startSize=30;` | Container needs a visible title bar, or container itself has connections |
+| **Custom container** | Add `container=1;pointerEvents=0;` to any shape | Any shape acting as a container without its own connections |
+
+**Key rules:**
+- Add `pointerEvents=0;` to container styles that should not capture connections between children
+- Children set `parent="containerId"` and use coordinates **relative to the container**
+
+```xml
+<!-- Swimlane container -->
+<mxCell id="svc1" value="User Service" style="swimlane;startSize=30;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">
+ <mxGeometry x="100" y="100" width="300" height="200" as="geometry"/>
+</mxCell>
+<!-- Child inside container — coordinates relative to parent -->
+<mxCell id="api1" value="REST API" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="svc1">
+ <mxGeometry x="20" y="40" width="120" height="60" as="geometry"/>
+</mxCell>
+<mxCell id="db1" value="Database" style="shape=cylinder3;whiteSpace=wrap;html=1;" vertex="1" parent="svc1">
+ <mxGeometry x="160" y="40" width="120" height="60" as="geometry"/>
+</mxCell>
+```
+
+### Connector (edge)
+
+**CRITICAL:** Every edge `mxCell` must contain a `<mxGeometry relative="1" as="geometry" />` child element. Self-closing edge cells (`<mxCell ... edge="1" ... />`) are **invalid** and will not render. Always use the expanded form.
+
+```xml
+<!-- Directed arrow — always include rounded, orthogonalLoop, jettySize for clean routing -->
+<mxCell id="10" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="2" target="3">
+ <mxGeometry relative="1" as="geometry" />
+</mxCell>
+
+<!-- Arrow with label + explicit entry/exit points to control direction -->
+<mxCell id="11" value="HTTP/REST" style="edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="2" target="4">
+ <mxGeometry relative="1" as="geometry" />
+</mxCell>
+
+<!-- Arrow with waypoints — use when edge must route around other shapes -->
+<mxCell id="12" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=1;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="3" target="5">
+ <mxGeometry relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="500" y="50" />
+ </Array>
+ </mxGeometry>
+</mxCell>
+```
+
+**Edge style rules:**
+- **Animated connectors:** add `flowAnimation=1;` to any edge style to show a moving dot animation along the arrow. Works in SVG export and draw.io desktop — ideal for data-flow and pipeline diagrams. Example: `style="edgeStyle=orthogonalEdgeStyle;flowAnimation=1;rounded=1;..."`
+- **Always** include `rounded=1;orthogonalLoop=1;jettySize=auto` — these enable smart routing that avoids overlaps
+- Pin `exitX/exitY/entryX/entryY` on every edge when a node has 2+ connections — distributes lines across the shape perimeter
+- Add `<Array as="points">` waypoints when an edge must detour around an intermediate shape
+- **Leave room for arrowheads:** the final straight segment between the last bend and the target shape must be ≥20px long. If too short, the arrowhead overlaps the bend and looks broken. Fix by increasing node spacing or adding explicit waypoints
+
+### Distributing connections on a shape
+
+When multiple edges connect to the same shape, assign different entry/exit points to prevent stacking:
+
+| Position | exitX/entryX | exitY/entryY | Use when |
+|----------|-------------|-------------|----------|
+| Top center | 0.5 | 0 | connecting to node above |
+| Top-left | 0.25 | 0 | 2nd connection from top |
+| Top-right | 0.75 | 0 | 3rd connection from top |
+| Right center | 1 | 0.5 | connecting to node on right |
+| Bottom center | 0.5 | 1 | connecting to node below |
+| Left center | 0 | 0.5 | connecting to node on left |
+
+**Rule:** if a shape has N connections on one side, space them evenly (e.g., 3 connections on bottom → exitX = 0.25, 0.5, 0.75)
+
+### Color palette (fillColor / strokeColor)
+
+*Used only when no user style preset is active (see `references/style-presets.md` → "Applying a preset").*
+
+| Color name | fillColor | strokeColor | Use for |
+|-----------|-----------|-------------|---------|
+| Blue | `#dae8fc` | `#6c8ebf` | services, clients |
+| Green | `#d5e8d4` | `#82b366` | success, databases |
+| Yellow | `#fff2cc` | `#d6b656` | queues, decisions |
+| Orange | `#ffe6cc` | `#d79b00` | gateways, APIs |
+| Red/Pink | `#f8cecc` | `#b85450` | errors, alerts |
+| Grey | `#f5f5f5` | `#666666` | external/neutral |
+| Purple | `#e1d5e7` | `#9673a6` | security, auth |
+
+### Layout tips
+
+**Spacing — scale with complexity:**
+
+| Diagram complexity | Nodes | Horizontal gap | Vertical gap |
+|-------------------|-------|----------------|--------------|
+| Simple | ≤5 | 200px | 150px |
+| Medium | 6–10 | 280px | 200px |
+| Complex | >10 | 350px | 250px |
+
+**Routing corridors:** between shape rows/columns, leave an extra ~80px empty corridor where edges can route without crossing shapes. Never place a shape in a gap that edges need to traverse.
+
+**Grid alignment:** snap all `x`, `y`, `width`, `height` values to **multiples of 10** — this ensures shapes align cleanly on draw.io's default grid and makes manual editing easier.
+
+**General rules:**
+- Plan a grid before assigning x/y coordinates — sketch node positions on paper/mentally first
+- Group related nodes in the same horizontal or vertical band
+- Use `swimlane` cells for logical grouping with visible borders
+- Place heavily-connected "hub" nodes centrally so edges radiate outward instead of crossing
+- To force straight vertical connections, pin entry/exit points explicitly on edges:
+ `exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0`
+- Always center-align a child node under its parent (same center x) to avoid diagonal routing
+- **Event bus pattern**: place Kafka/bus nodes in the **center of the service row**, not below — services on either side can reach it with short horizontal arrows (`exitX=1` left side, `exitX=0` right side), eliminating all line crossings
+- Horizontal connections (`exitX=1` or `exitX=0`) never cross vertical nodes in the same row; use them for peer-to-peer and publish connections
+
+**Avoiding edge-shape overlap:**
+- Before finalizing coordinates, trace each edge path mentally — if it must cross an unrelated shape, either move the shape or add waypoints
+- For tree/hierarchical layouts: assign nodes to layers (rows), connect only between adjacent layers to minimize crossings
+- For star/hub layouts: place the hub center, satellites around it — edges stay short and radial
+- When an edge must span multiple rows/columns, route it along the outer corridor, not through the middle of the diagram
+
diff --git a/skills/drawio-skill/scripts/autolayout.py b/skills/drawio-skill/scripts/autolayout.py
index 1aa7961..48af046 100644
--- a/skills/drawio-skill/scripts/autolayout.py
+++ b/skills/drawio-skill/scripts/autolayout.py
@@ -304,7 +304,7 @@ def to_drawio(graph, height, pos, edge_pts, color=True):
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'style="{attr(edge.get("style", EDGE_STYLE))}" edge="1" parent="1" '
f'source="{attr(edge["source"])}" target="{attr(edge["target"])}">\n'
f" {geom}\n"
f" </mxCell>"
@@ -322,16 +322,60 @@ def to_drawio(graph, height, pos, edge_pts, color=True):
)
+def route_score(graph, height, pos, edge_pts):
+ """Readability score for one dot layout (lower is better): weighted count
+ of edge-through-vertex hits and edge-edge crossings, with total edge length
+ as a tiebreak. Uses the same geometry predicates as validate.py."""
+ import importlib.util
+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "validate.py")
+ spec = importlib.util.spec_from_file_location("validate", path)
+ v = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(v)
+ rects = {}
+ for node in graph["nodes"]:
+ if node["id"] in pos:
+ w, h = node.get("width", DEFAULT_W), node.get("height", DEFAULT_H)
+ xc, yc = pos[node["id"]]
+ rects[node["id"]] = (xc * 72 - w / 2, (height - yc) * 72 - h / 2, w, h)
+ routes = []
+ for edge in graph.get("edges", []):
+ pts = edge_pts.get((edge["source"], edge["target"]))
+ if pts:
+ routes.append(([(x * 72, (height - y) * 72) for x, y in pts],
+ {edge["source"], edge["target"]}))
+ through = sum(1 for pts, ends in routes for nid, box in rects.items()
+ if nid not in ends and v.route_hits_rect(pts, box))
+ cross = sum(1 for i in range(len(routes)) for j in range(i + 1, len(routes))
+ if v.routes_cross(routes[i][0], routes[j][0]))
+ length = sum(abs(b[0] - a[0]) + abs(b[1] - a[1])
+ for pts, _ in routes for a, b in zip(pts, pts[1:]))
+ return 20 * through + 10 * cross + length / 100000
+
+
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)")
ap.add_argument("--mono", action="store_true",
help="don't colour groups by palette (monochrome boxes)")
+ ap.add_argument("--tune", action="store_true",
+ help="lay out in both directions (TB and LR), keep the more "
+ "readable one (fewer crossings / through-vertex routes)")
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))
+ if args.tune:
+ best = None
+ for d in ("TB", "LR"):
+ cand = dict(graph, direction=d)
+ h, p, ep = layout(build_dot(cand))
+ s = route_score(cand, h, p, ep)
+ if best is None or s < best[0]:
+ best = (s, d, h, p, ep)
+ _, d, height, pos, edge_pts = best
+ print(f"tuned: direction={d} (score {best[0]:.2f})", file=sys.stderr)
+ else:
+ height, pos, edge_pts = layout(build_dot(graph))
xml = to_drawio(graph, height, pos, edge_pts, color=not args.mono)
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
diff --git a/skills/drawio-skill/scripts/composeimports.py b/skills/drawio-skill/scripts/composeimports.py
new file mode 100644
index 0000000..0de3509
--- /dev/null
+++ b/skills/drawio-skill/scripts/composeimports.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+"""Extract a docker-compose file's service graph as autolayout graph JSON.
+
+Services become rounded boxes (labeled name + image), named volumes become
+cylinders, and edges come from real wiring: `depends_on` (list or mapping
+form), `links`, `volumes_from`, and named-volume mounts (short "vol:/path"
+and long {type: volume, source: ...} syntax). The output feeds autolayout.py:
+
+ python3 composeimports.py docker-compose.yml -o graph.json
+ python3 autolayout.py graph.json -o stack.drawio
+
+Given a directory, the usual compose file names are tried
+(compose.yaml/compose.yml/docker-compose.yml/docker-compose.yaml).
+Requires PyYAML (pip install pyyaml). `--group` boxes services by their
+first network.
+
+Usage: python3 composeimports.py <compose-file-or-dir> [-o graph.json]
+ [--direction TB|LR] [--group]
+"""
+import argparse
+import json
+import os
+import sys
+
+SERVICE_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"
+VOLUME_STYLE = ("shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;size=15;"
+ "fillColor=#f5f5f5;strokeColor=#666666;")
+
+
+def find_compose(path):
+ if os.path.isfile(path):
+ return path
+ for name in ("compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml"):
+ cand = os.path.join(path, name)
+ if os.path.isfile(cand):
+ return cand
+ sys.exit(f"error: no compose file found under {path}")
+
+
+def volume_mounts(svc):
+ """Named volumes a service mounts (short and long syntax)."""
+ for v in svc.get("volumes") or []:
+ if isinstance(v, str):
+ src = v.split(":", 1)[0]
+ if src and not src.startswith((".", "/", "~", "$")):
+ yield src
+ elif isinstance(v, dict) and v.get("type", "volume") == "volume" and v.get("source"):
+ yield v["source"]
+
+
+def dependencies(svc):
+ dep = svc.get("depends_on") or []
+ deps = list(dep) if isinstance(dep, (list, dict)) else []
+ for link in svc.get("links") or []:
+ deps.append(str(link).split(":", 1)[0])
+ for vf in svc.get("volumes_from") or []:
+ deps.append(str(vf).split(":", 1)[0])
+ return deps
+
+
+def main():
+ ap = argparse.ArgumentParser(description="docker-compose -> autolayout graph JSON.")
+ ap.add_argument("path", help="compose file, or directory containing one")
+ ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")
+ ap.add_argument("--direction", default="TB", choices=["TB", "LR"])
+ ap.add_argument("--group", action="store_true",
+ help="group services into containers by their first network")
+ args = ap.parse_args()
+
+ try:
+ import yaml
+ except ImportError:
+ sys.exit("error: PyYAML is required (pip install pyyaml)")
+ path = find_compose(args.path)
+ with open(path, encoding="utf-8") as f:
+ spec = yaml.safe_load(f) or {}
+ services = spec.get("services") or {}
+ if not services:
+ sys.exit(f"error: no services in {path}")
+ declared_volumes = set(spec.get("volumes") or {})
+
+ nodes, edges = [], set()
+ for name, svc in services.items():
+ svc = svc or {}
+ image = svc.get("image") or ("build: " + str((svc.get("build") or {}).get("context", ".")
+ if isinstance(svc.get("build"), dict)
+ else svc.get("build", ".")))
+ node = {"id": name, "label": f"{name}\n{image}", "style": SERVICE_STYLE,
+ "width": 160, "height": 60}
+ nets = svc.get("networks")
+ first_net = (sorted(nets)[0] if isinstance(nets, dict) else nets[0]) if nets else None
+ if args.group and first_net:
+ node["group"] = str(first_net)
+ nodes.append(node)
+ for dep in dependencies(svc):
+ if dep in services and dep != name:
+ edges.add((name, dep))
+ for vol in volume_mounts(svc):
+ if vol in declared_volumes:
+ edges.add((name, f"vol:{vol}"))
+ for vol in sorted({t[4:] for _, t in edges if t.startswith("vol:")}):
+ nodes.append({"id": f"vol:{vol}", "label": vol, "style": VOLUME_STYLE,
+ "width": 120, "height": 70})
+
+ graph = {"direction": args.direction, "nodes": nodes,
+ "edges": [{"source": s, "target": t} for s, t in sorted(edges)]}
+ text = json.dumps(graph, indent=2)
+ if args.output:
+ with open(args.output, "w", encoding="utf-8") as f:
+ f.write(text)
+ sys.stderr.write(f"wrote {args.output}\n")
+ else:
+ sys.stdout.write(text)
+ sys.stderr.write(f"{len(nodes)} nodes, {len(edges)} edges\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/drawio-skill/scripts/seqlayout.py b/skills/drawio-skill/scripts/seqlayout.py
new file mode 100644
index 0000000..b5b8c33
--- /dev/null
+++ b/skills/drawio-skill/scripts/seqlayout.py
@@ -0,0 +1,222 @@
+#!/usr/bin/env python3
+"""Deterministic sequence-diagram layout: message list JSON -> .drawio XML.
+
+Sequence diagrams are the easiest type to get wrong by hand-placing
+coordinates (lifelines, activation bars and message arrows all share exact
+x/y math) and the least suited to Graphviz — but their geometry is pure
+arithmetic: participants split the x axis, messages advance the y axis.
+This script computes all of it, using the same official styles as
+references/diagram-types.md (umlLifeline shapes, block/open arrows).
+
+ python3 seqlayout.py seq.json -o diagram.drawio
+
+Input JSON:
+ {
+ "title": "Login flow", # optional page name
+ "participants": [
+ {"id": "u", "label": "User", "actor": true},
+ {"id": "s", "label": "Server"} # order = left-to-right order
+ ],
+ "messages": [
+ {"from": "u", "to": "s", "label": "POST /login"}, # sync (solid, filled arrow)
+ {"from": "s", "to": "s", "label": "validate()"}, # self message
+ {"from": "s", "to": "u", "label": "200 OK", "return": true}, # return (grey dashed)
+ {"from": "u", "to": "s", "label": "notify", "async": true}, # async (dashed, open arrow)
+ {"note": "token cached", "over": "s"} # note beside a lifeline
+ ]
+ }
+
+Activation bars are automatic: a sync/async message opens a bar on the
+target, a return message closes the sender's bar, and bars still open at the
+end run to the bottom. Override per message with "activate": false (don't
+open on target) or "deactivate": true (close the sender's bar after this
+message). Arrows attach to the bar edge when a bar is active, else to the
+lifeline. Fragments (alt/loop/opt frames) are out of scope — add them in
+draw.io afterwards.
+
+Usage: python3 seqlayout.py <seq.json> [-o diagram.drawio]
+"""
+import argparse
+import json
+import sys
+from xml.sax.saxutils import escape
+
+LIFELINE_W, HEADER_H = 100, 40
+BAR_W = 10
+TOP, ROW, SELF_ROW, NOTE_ROW, BOTTOM_PAD = 40, 50, 70, 60, 40
+MIN_SPACING = 200
+
+LIFELINE = ("shape=umlLifeline;perimeter=lifelinePerimeter;whiteSpace=wrap;html=1;"
+ "container=1;dropTarget=0;collapsible=0;recursiveResize=0;outlineConnect=0;"
+ f"portConstraint=eastwest;size={HEADER_H};")
+# Actor lifelines render a stick figure in the header — anchor the name at
+# the header bottom (white-backed) so figure and label don't overlap.
+ACTOR = LIFELINE + ("participant=umlActor;verticalAlign=bottom;"
+ "spacingBottom=-14;labelBackgroundColor=#ffffff;")
+BAR = "html=1;points=[];perimeter=orthogonalPerimeter;outlineConnect=0;fillColor=#ffffff;"
+NOTE = ("shape=note;whiteSpace=wrap;html=1;size=14;fillColor=#fff2cc;"
+ "strokeColor=#d6b656;")
+SYNC = "html=1;verticalAlign=bottom;endArrow=block;curved=0;rounded=0;"
+ASYNC = "html=1;verticalAlign=bottom;endArrow=open;dashed=1;curved=0;rounded=0;"
+RETURN = ("html=1;verticalAlign=bottom;endArrow=open;dashed=1;curved=0;rounded=0;"
+ "strokeColor=#999999;fontColor=#999999;")
+
+
+def attr(value):
+ return escape(str(value), {'"': "&quot;", "\n": "&#xa;"})
+
+
+def frac(y, top, height):
+ return round(max(0.0, min(1.0, (y - top) / height)), 4)
+
+
+def layout(spec):
+ parts = spec["participants"]
+ if not parts:
+ sys.exit("error: no participants")
+ order = {p["id"]: i for i, p in enumerate(parts)}
+ if len(order) != len(parts):
+ sys.exit("error: duplicate participant ids")
+
+ # x axis: uniform spacing, widened if any label needs it (~7px/char).
+ spacing = max([MIN_SPACING] + [7 * len(str(p.get("label", p["id"]))) + 80 for p in parts])
+ spacing = -(-spacing // 10) * 10 # snap up to the grid
+ cx = {p["id"]: TOP + i * spacing + LIFELINE_W // 2 for i, p in enumerate(parts)}
+
+ # y axis: walk the messages once, assigning each row a y position and
+ # tracking one open activation bar per participant ({pid: start_y}).
+ y = TOP + HEADER_H + 50
+ rows, open_bar, bars = [], {}, [] # bars: (pid, y0, y1)
+
+ def close(pid, at):
+ if pid in open_bar:
+ bars.append((pid, open_bar.pop(pid), at))
+
+ for i, m in enumerate(spec.get("messages", [])):
+ if "note" in m:
+ rows.append(("note", m, y))
+ y += NOTE_ROW
+ continue
+ src, dst = m["from"], m["to"]
+ if src not in order or dst not in order:
+ sys.exit(f"error: message {i} references unknown participant")
+ is_return = m.get("return", False)
+ if src == dst:
+ rows.append(("self", m, y))
+ y += SELF_ROW
+ continue
+ rows.append(("msg", m, y))
+ if is_return:
+ close(src, y) # returning ends the caller's work
+ elif m.get("activate", True) and dst not in open_bar:
+ open_bar[dst] = y # call starts work on the target
+ if m.get("deactivate"):
+ close(src, y)
+ y += ROW
+ height = y + BOTTOM_PAD - TOP
+ for pid in list(open_bar):
+ close(pid, TOP + height - BOTTOM_PAD)
+
+ cells = []
+ for p in parts:
+ style = ACTOR if p.get("actor") else LIFELINE
+ cells.append(
+ f' <mxCell id="{attr(p["id"])}" value="{attr(p.get("label", p["id"]))}" '
+ f'style="{style}" vertex="1" parent="1">\n'
+ f' <mxGeometry x="{cx[p["id"]] - LIFELINE_W // 2}" y="{TOP}" '
+ f'width="{LIFELINE_W}" height="{height}" as="geometry"/>\n'
+ " </mxCell>")
+
+ # Activation bars: children of their lifeline (coordinates relative to it).
+ bar_of = {} # pid -> list of (y0, y1, cell_id)
+ for n, (pid, y0, y1) in enumerate(bars):
+ bid = f"act{n}"
+ bar_of.setdefault(pid, []).append((y0, y1, bid))
+ cells.append(
+ f' <mxCell id="{bid}" value="" style="{BAR}" vertex="1" '
+ f'parent="{attr(pid)}">\n'
+ f' <mxGeometry x="{LIFELINE_W // 2 - BAR_W // 2}" y="{y0 - TOP}" '
+ f'width="{BAR_W}" height="{y1 - y0}" as="geometry"/>\n'
+ " </mxCell>")
+
+ def anchor(pid, my, side):
+ """(cell_id, exitX-style fragment values) for a message endpoint: the
+ activation bar's edge when one is active at this y, else the lifeline."""
+ for y0, y1, bid in bar_of.get(pid, []):
+ if y0 <= my <= y1:
+ return bid, (1 if side == "right" else 0), frac(my, y0, y1 - y0)
+ return pid, 0.5, frac(my, TOP, height)
+
+ for i, (kind, m, my) in enumerate(rows):
+ if kind == "note":
+ pid = m.get("over")
+ if pid not in cx:
+ sys.exit(f"error: note {i} is over unknown participant {pid!r}")
+ w = max(120, 7 * len(str(m["note"])) + 30)
+ cells.append(
+ f' <mxCell id="note{i}" value="{attr(m["note"])}" style="{NOTE}" '
+ f'vertex="1" parent="1">\n'
+ f' <mxGeometry x="{cx[pid] + 20}" y="{my - 20}" '
+ f'width="{min(w, spacing - 60)}" height="40" as="geometry"/>\n'
+ " </mxCell>")
+ continue
+ src, dst = m["from"], m["to"]
+ style = RETURN if m.get("return") else ASYNC if m.get("async") else SYNC
+ if kind == "self":
+ sid, sx, sy = anchor(src, my, "right")
+ _, tx, ty = anchor(src, my + 30, "right")
+ loop_x = cx[src] + 60
+ cells.append(
+ f' <mxCell id="m{i}" value="{attr(m.get("label", ""))}" '
+ f'style="{style}exitX={sx};exitY={sy};entryX={tx};entryY={ty};" '
+ f'edge="1" parent="1" source="{attr(sid)}" target="{attr(sid)}">\n'
+ f' <mxGeometry relative="1" as="geometry">\n'
+ f' <Array as="points">'
+ f'<mxPoint x="{loop_x}" y="{my}"/><mxPoint x="{loop_x}" y="{my + 30}"/>'
+ f'</Array>\n'
+ " </mxGeometry>\n"
+ " </mxCell>")
+ continue
+ rightward = order[src] < order[dst]
+ sid, sx, sy = anchor(src, my, "right" if rightward else "left")
+ tid, tx, ty = anchor(dst, my, "left" if rightward else "right")
+ cells.append(
+ f' <mxCell id="m{i}" value="{attr(m.get("label", ""))}" '
+ f'style="{style}exitX={sx};exitY={sy};entryX={tx};entryY={ty};" '
+ f'edge="1" parent="1" source="{attr(sid)}" target="{attr(tid)}">\n'
+ f' <mxGeometry relative="1" as="geometry"/>\n'
+ " </mxCell>")
+
+ name = attr(spec.get("title", "Sequence"))
+ return (
+ f'<mxfile>\n <diagram id="seqlayout" name="{name}">\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="Sequence-diagram JSON -> draw.io XML.")
+ ap.add_argument("input", help="sequence 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:
+ spec = json.load(f)
+ xml = layout(spec)
+ if args.output:
+ with open(args.output, "w", encoding="utf-8") as f:
+ f.write(xml)
+ print(f"wrote {args.output} ({len(spec['participants'])} participants, "
+ f"{len(spec.get('messages', []))} messages)", file=sys.stderr)
+ else:
+ sys.stdout.write(xml)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/drawio-skill/scripts/sqlerd.py b/skills/drawio-skill/scripts/sqlerd.py
new file mode 100644
index 0000000..11e29fd
--- /dev/null
+++ b/skills/drawio-skill/scripts/sqlerd.py
@@ -0,0 +1,167 @@
+#!/usr/bin/env python3
+"""Extract an ER diagram from SQL DDL as autolayout graph JSON.
+
+Parses ``CREATE TABLE`` statements (regex + paren matching — no SQL library),
+one node per table listing its columns with PK/FK markers, and one
+crow's-foot edge per foreign key (many side at the referencing table).
+The output feeds autolayout.py:
+
+ python3 sqlerd.py schema.sql -o graph.json
+ python3 autolayout.py graph.json -o erd.drawio
+
+Understood per table: column name + type, inline ``PRIMARY KEY`` /
+``REFERENCES tab(col)``, table-level ``PRIMARY KEY (...)`` and
+``[CONSTRAINT x] FOREIGN KEY (col) REFERENCES tab(col)``. Quoted identifiers
+("t", `t`, [t]) and ``schema.table`` prefixes are normalized; edges land only
+on tables defined in the scanned files. Dialect-specific clauses beyond that
+(partitioning, generated columns, …) are simply ignored — worst case a column
+line is skipped, never a wrong edge.
+
+Usage: python3 sqlerd.py <file.sql-or-dir> [-o graph.json]
+ [--direction TB|LR] [--group] [--no-types]
+"""
+import argparse
+import glob
+import json
+import os
+import re
+import sys
+
+TABLE_STYLE = ("rounded=0;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"
+ "spacingLeft=6;spacingTop=4;fillColor=#dae8fc;strokeColor=#6c8ebf;")
+# orthogonalEdgeStyle (not entityRelationEdgeStyle) so the edge honours the
+# obstacle-avoiding waypoints dot computed; ER arrows give the crow's foot.
+ER_EDGE = ("edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=11;"
+ "labelBackgroundColor=#ffffff;"
+ "startArrow=ERmany;startFill=0;endArrow=ERone;endFill=0;")
+
+_COMMENT = re.compile(r"/\*.*?\*/|--[^\n]*", re.S)
+_CREATE = re.compile(r"\bCREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w.\"`\[\]]+)\s*\(",
+ re.I)
+_FK = re.compile(r"FOREIGN\s+KEY\s*\(([^)]+)\)\s*REFERENCES\s+([\w.\"`\[\]]+)\s*(?:\(([^)]+)\))?",
+ re.I)
+_PK = re.compile(r"PRIMARY\s+KEY\s*\(([^)]+)\)", re.I)
+_INLINE_REF = re.compile(r"\bREFERENCES\s+([\w.\"`\[\]]+)", re.I)
+_SKIP = re.compile(r"^\s*(CONSTRAINT|UNIQUE|CHECK|KEY|INDEX|FULLTEXT|SPATIAL|EXCLUDE|LIKE)\b",
+ re.I)
+
+
+def ident(raw):
+ """Normalize an identifier: strip quoting, keep the last dotted part."""
+ name = raw.strip().strip('"`[]').split(".")[-1].strip('"`[]')
+ return name.lower()
+
+
+def split_columns(body):
+ """Split a CREATE TABLE body on top-level commas."""
+ items, depth, cur = [], 0, []
+ for ch in body:
+ if ch == "(":
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ if ch == "," and depth == 0:
+ items.append("".join(cur).strip())
+ cur = []
+ else:
+ cur.append(ch)
+ if "".join(cur).strip():
+ items.append("".join(cur).strip())
+ return items
+
+
+def parse_tables(text):
+ """{table: {"schema", "columns": [(name, type)], "pks": set, "fks": [(col, table)]}}"""
+ text = _COMMENT.sub("", text)
+ tables = {}
+ for m in _CREATE.finditer(text):
+ raw_name = m.group(1)
+ depth, i = 1, m.end()
+ while i < len(text) and depth:
+ if text[i] == "(":
+ depth += 1
+ elif text[i] == ")":
+ depth -= 1
+ i += 1
+ body = text[m.end():i - 1]
+ name = ident(raw_name)
+ parts = raw_name.strip().strip('"`[]').split(".")
+ schema = ident(parts[-2]) if len(parts) > 1 else ""
+ cols, pks, fks = [], set(), []
+ for item in split_columns(body):
+ fk = _FK.search(item)
+ if fk:
+ for col in fk.group(1).split(","):
+ fks.append((ident(col), ident(fk.group(2))))
+ continue
+ pk = _PK.search(item)
+ if pk and _SKIP.match(item) is None and item.upper().lstrip().startswith("PRIMARY"):
+ pks.update(ident(c) for c in pk.group(1).split(","))
+ continue
+ if _SKIP.match(item):
+ continue
+ toks = item.split()
+ if len(toks) < 2:
+ continue
+ col, ctype = ident(toks[0]), toks[1].rstrip(",")
+ cols.append((col, ctype))
+ if re.search(r"\bPRIMARY\s+KEY\b", item, re.I):
+ pks.add(col)
+ ref = _INLINE_REF.search(item)
+ if ref:
+ fks.append((col, ident(ref.group(1))))
+ tables[name] = {"schema": schema, "columns": cols, "pks": pks, "fks": fks}
+ return tables
+
+
+def main():
+ ap = argparse.ArgumentParser(description="SQL DDL -> ER diagram graph JSON.")
+ ap.add_argument("path", help=".sql file or directory containing .sql files")
+ ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")
+ ap.add_argument("--direction", default="TB", choices=["TB", "LR"])
+ ap.add_argument("--group", action="store_true", help="group tables by schema")
+ ap.add_argument("--no-types", action="store_true",
+ help="list column names only (hide the SQL types)")
+ args = ap.parse_args()
+
+ files = ([args.path] if os.path.isfile(args.path)
+ else sorted(glob.glob(os.path.join(args.path, "**", "*.sql"), recursive=True)))
+ tables = {}
+ for path in files:
+ with open(path, encoding="utf-8") as f:
+ tables.update(parse_tables(f.read()))
+ if not tables:
+ sys.exit(f"error: no CREATE TABLE statements found under {args.path}")
+
+ nodes, edges = [], []
+ for name, t in tables.items():
+ fk_cols = {c for c, _ in t["fks"]}
+ lines = [name]
+ for col, ctype in t["columns"]:
+ mark = "PK " if col in t["pks"] else "FK " if col in fk_cols else ""
+ lines.append(f"{mark}{col}" + ("" if args.no_types else f": {ctype}"))
+ width = max(160, -(-max(7 * len(l) + 30 for l in lines) // 10) * 10)
+ height = -(-(30 + 20 * len(t["columns"])) // 10) * 10
+ node = {"id": name, "label": "\n".join(lines), "style": TABLE_STYLE,
+ "width": width, "height": height}
+ if args.group and t["schema"]:
+ node["group"] = t["schema"]
+ nodes.append(node)
+ for col, ref in t["fks"]:
+ if ref in tables and ref != name:
+ edges.append({"source": name, "target": ref, "label": col,
+ "style": ER_EDGE})
+
+ graph = {"direction": args.direction, "nodes": nodes, "edges": edges}
+ text = json.dumps(graph, indent=2)
+ if args.output:
+ with open(args.output, "w", encoding="utf-8") as f:
+ f.write(text)
+ sys.stderr.write(f"wrote {args.output}\n")
+ else:
+ sys.stdout.write(text)
+ sys.stderr.write(f"{len(nodes)} tables, {len(edges)} foreign keys\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/drawio-skill/scripts/validate.py b/skills/drawio-skill/scripts/validate.py
index 299d3b2..091d9ac 100644
--- a/skills/drawio-skill/scripts/validate.py
+++ b/skills/drawio-skill/scripts/validate.py
@@ -294,6 +294,9 @@ def main():
ap = argparse.ArgumentParser(description="Lint a .drawio file for structural errors.")
ap.add_argument("file")
ap.add_argument("--strict", action="store_true", help="treat warnings as failure too")
+ ap.add_argument("--score", action="store_true",
+ help="also print a readability score (lower is better) — "
+ "useful for comparing layout variants of the same graph")
args = ap.parse_args()
try:
tree = ET.parse(args.file)
@@ -310,6 +313,14 @@ def main():
for e in errors:
print(f"error: {e}")
print(f"{len(errors)} error(s), {len(warns)} warning(s)")
+ if args.score:
+ # Weighted by how badly each defect hurts readability. Comparable only
+ # across variants of the SAME graph (same nodes/edges).
+ through = sum(1 for w in warns if "routes through" in w)
+ cross = sum(1 for w in warns if " cross" in w)
+ olap = sum(1 for w in warns if " overlap" in w)
+ print(f"score: {20 * through + 10 * cross + 5 * olap} "
+ f"({through} through-vertex, {cross} crossings, {olap} overlaps)")
if errors or (args.strict and warns):
sys.exit(1)
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 6c13f1d..abe1ced 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -180,6 +180,14 @@ class TestAutolayoutColor(unittest.TestCase):
self.assertIn("ranksep=0.70;", dot)
self.assertIn("nodesep=0.60;", dot)
+ def test_edge_style_passthrough(self):
+ out = self.m.to_drawio(
+ {"direction": "TB",
+ "nodes": [{"id": "a"}, {"id": "b"}],
+ "edges": [{"source": "a", "target": "b", "style": "endArrow=ERone;"}]},
+ 5, {"a": (1, 1), "b": (3, 1)}, {}, color=True)
+ self.assertIn("endArrow=ERone;", out)
+
def test_label_newline_becomes_entity(self):
out = self.m.to_drawio(
{"direction": "TB", "nodes": [{"id": "n", "label": "one\ntwo"}],
@@ -496,6 +504,70 @@ class TestImportersCli(unittest.TestCase):
graph = json.loads(run("k8simports.py", d, "--group").stdout)
self.assertTrue(all(n["group"] == "shop" for n in graph["nodes"]))
+ def test_composeimports_edges(self):
+ try:
+ import yaml # noqa: F401
+ except ImportError:
+ self.skipTest("PyYAML not installed")
+ compose = ("services:\n"
+ " api:\n image: api:1\n depends_on: [db]\n"
+ " volumes: ['uploads:/data', './src:/app']\n"
+ " db:\n image: postgres:16\n"
+ "volumes:\n uploads:\n")
+ with tempfile.TemporaryDirectory() as d:
+ self._write(os.path.join(d, "docker-compose.yml"), compose)
+ graph = json.loads(run("composeimports.py", d).stdout)
+ ids = {n["id"] for n in graph["nodes"]}
+ self.assertEqual(ids, {"api", "db", "vol:uploads"})
+ edges = {(e["source"], e["target"]) for e in graph["edges"]}
+ # bind mount ./src is not a named volume -> no node, no edge
+ self.assertEqual(edges, {("api", "db"), ("api", "vol:uploads")})
+ api = next(n for n in graph["nodes"] if n["id"] == "api")
+ self.assertEqual(api["label"], "api\napi:1")
+
+ SQL = ("CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255));\n"
+ "CREATE TABLE orders (\n"
+ " id INT,\n"
+ " user_id INT NOT NULL REFERENCES users(id),\n"
+ " PRIMARY KEY (id),\n"
+ " CONSTRAINT fk FOREIGN KEY (user_id) REFERENCES users (id)\n"
+ ");\n")
+
+ def test_sqlerd_tables_and_fks(self):
+ with tempfile.TemporaryDirectory() as d:
+ self._write(os.path.join(d, "schema.sql"), self.SQL)
+ graph = json.loads(run("sqlerd.py", d).stdout)
+ ids = {n["id"] for n in graph["nodes"]}
+ self.assertEqual(ids, {"users", "orders"})
+ orders = next(n for n in graph["nodes"] if n["id"] == "orders")
+ self.assertIn("PK id: INT", orders["label"])
+ self.assertIn("FK user_id: INT", orders["label"])
+ # inline REFERENCES + the equivalent named constraint -> 2 edges
+ for e in graph["edges"]:
+ self.assertEqual((e["source"], e["target"]), ("orders", "users"))
+ self.assertIn("ERmany", e["style"]) # crow's foot at the FK side
+
+ def test_seqlayout_geometry(self):
+ spec = {"participants": [{"id": "a", "label": "A", "actor": True},
+ {"id": "b", "label": "B"}],
+ "messages": [{"from": "a", "to": "b", "label": "call"},
+ {"from": "b", "to": "b", "label": "work"},
+ {"from": "b", "to": "a", "label": "done", "return": True}]}
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, "seq.json")
+ self._write(path, json.dumps(spec))
+ out = os.path.join(d, "seq.drawio")
+ r = run("seqlayout.py", path, "-o", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ xml = open(out, encoding="utf-8").read()
+ self.assertIn("umlActor", xml) # actor header
+ self.assertIn('parent="b"', xml) # activation bar on b
+ self.assertIn("endArrow=block", xml) # sync arrow
+ self.assertIn("strokeColor=#999999", xml) # return arrow
+ # the generated file passes the structural linter
+ v = run("validate.py", out)
+ self.assertEqual(v.returncode, 0, v.stdout)
+
def test_rustimports_edge(self):
# Node ids are module paths (no crate-root file, so just a, b).
with tempfile.TemporaryDirectory() as d: