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: structural validator, JS/Go importers, and container layout (v1.8.0) (#16)

Agents365.ai4b7fb1d2bb18
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index ac9c6b7..fbe93c5 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,12 +1,12 @@
---
name: drawio-skill
-version: 1.7.0
+version: 1.8.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, network topology, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.
license: MIT
homepage: https://github.com/Agents365-ai/drawio-skill
compatibility: Requires draw.io desktop app CLI on PATH (macOS/Linux/Windows). Self-check step requires a vision-enabled model (e.g., Claude Sonnet/Opus); gracefully skipped if unavailable. 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.7.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.8.0"}
---
# Draw.io Diagrams
@@ -32,7 +32,8 @@ When the workflow references one of these, read it on demand — none of them ne
| `scripts/repair_png.py` | After every `-e` PNG export — fixes draw.io's truncated IEND chunk (issue #8) |
| `scripts/encode_drawio_url.py` | The CLI is unavailable and you need a browser-fallback diagrams.net URL |
| `references/autolayout.md` | The diagram is large or layout-heavy (dependency/call graph, code structure, >~15 nodes) and you want Graphviz to place nodes + route edges instead of hand-placing coordinates |
-| `scripts/pyimports.py` | The user wants to visualize a **Python project/package** structure — extracts the import graph (transitive-reduced) for autolayout |
+| `scripts/pyimports.py` · `jsimports.py` · `goimports.py` | The user wants to visualize a **Python, JS/TS, or Go project** structure — extracts the import graph (transitive-reduced, optional `--group` containers) 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 |
## Prerequisites
@@ -82,7 +83,7 @@ When a preset loads successfully, mention it in the first line of the reply: *"U
1. **Check deps** — **resolve which name the binary has on this system** and use that name verbatim in every subsequent command in this workflow. Try in order: (a) `drawio --version` (the canonical name for Homebrew cask, jgraph `.deb`/`.rpm`, Arch AUR), (b) `draw.io --version` (older builds, some custom symlinks, some distro packages), (c) macOS `.app` direct: `/Applications/draw.io.app/Contents/MacOS/draw.io --version`, (d) Windows: `"C:\Program Files\draw.io\draw.io.exe" --version`. The first one that prints a version is your binary; remember the exact path/name and substitute it for `drawio` in every export command below. **Do not copy the example commands verbatim if your binary is named differently** — the examples use `drawio` only because it's the most common. On macOS-Homebrew, `drawio` is just a thin wrapper script that execs `/Applications/draw.io.app/Contents/MacOS/draw.io` — they run the same engine, so candidate (c) is only needed when the `drawio` wrapper is absent (e.g. the app was installed by drag-and-drop without the cask).
2. **Plan** — identify shapes, relationships, layout (LR or TB), group by tier/layer
-3. **Generate** — write `.drawio` XML file to disk. 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 project/package**, `python3 <this-skill-dir>/scripts/pyimports.py <dir> -o graph.json` extracts the import graph (transitive-reduced) ready for autolayout. Default output dir is the user's working dir; if the user specified an output path or directory (e.g. `./artifacts/`, `docs/images/`), use that instead — `mkdir -p` the target dir first. Apply the same dir choice to PNG/SVG/PDF exports in steps 4 and 7.
+3. **Generate** — write `.drawio` XML file to disk. Hand-place coordinates for small/styled diagrams. **For large or layout-heavy diagrams (dependency/call graphs, code structure, >~15 nodes), don't hand-place** — describe the graph as JSON and run `python3 <this-skill-dir>/scripts/autolayout.py graph.json -o <name>.drawio` to compute node positions + orthogonal edge routing via Graphviz (see `references/autolayout.md`). For a **Python / JS-TS / Go project**, the matching importer (`scripts/pyimports.py`, `jsimports.py`, or `goimports.py`) extracts the import graph (transitive-reduced; add `--group` to box modules by sub-package) ready for autolayout. 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
diff --git a/skills/drawio-skill/references/autolayout.md b/skills/drawio-skill/references/autolayout.md
index 533d685..f3afe4e 100644
--- a/skills/drawio-skill/references/autolayout.md
+++ b/skills/drawio-skill/references/autolayout.md
@@ -34,8 +34,8 @@ It prints `wrote diagram.drawio (N nodes, M edges)` to stderr and writes a norma
"direction": "TB",
"nodes": [
{"id": "client", "label": "Web Client", "style": "rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;"},
- {"id": "gw", "label": "API Gateway"},
- {"id": "db", "label": "User DB", "style": "shape=cylinder3;whiteSpace=wrap;html=1;", "width": 120, "height": 80}
+ {"id": "gw", "label": "API Gateway", "group": "edge", "groupLabel": "Edge tier"},
+ {"id": "db", "label": "User DB", "style": "shape=cylinder3;whiteSpace=wrap;html=1;", "width": 120, "height": 80, "group": "data"}
],
"edges": [
{"source": "client", "target": "gw", "label": "HTTPS"},
@@ -53,6 +53,8 @@ It prints `wrote diagram.drawio (N nodes, M edges)` to stderr and writes a norma
| `nodes[].label` | no | the `id` | Display text; auto XML-escaped |
| `nodes[].style` | no | blue rounded box | Any draw.io style string — reuse the role/shape styles from `diagram-types.md` and the active preset |
| `nodes[].width` / `height` | no | `120` / `60` | Pixels; dot lays out at this real size |
+| `nodes[].group` | no | none | Group key — nodes sharing a key are kept together and wrapped in a labeled container (see **Containers / grouping**) |
+| `nodes[].groupLabel` | no | the group key | Title shown on the container for this group (first node with the key wins) |
| `edges[].source` / `target` | **yes** | — | Must match node ids |
| `edges[].label` | no | empty | Edge text |
@@ -62,26 +64,55 @@ It prints `wrote diagram.drawio (N nodes, M edges)` to stderr and writes a norma
- Edges use `splines=ortho`: dot's orthogonal route is replayed as draw.io waypoints, so edges go **around** nodes instead of through them.
- Apply the active style preset by setting each node's `style` to the preset's role/shape values before calling the script — the script does not know about presets.
+## Containers / grouping
+
+Give nodes a `group` key and the script wraps each group in a labeled container (a dashed box with the group title on top), and tells dot to keep that group's nodes together via a Graphviz cluster. Grouped nodes become children of their container (`parent="<container>"`, relative coordinates); ungrouped nodes stay at the top level. This turns a flat hairball into a "boxes of related modules" architecture view.
+
+- The container box is the bounding box of its members plus padding and a title strip; the dot cluster margin matches the padding so adjacent containers don't overlap.
+- Containers are visual only (no edges of their own). Edges still connect node→node and route across containers normally.
+- Set `groupLabel` on any member to title the box; otherwise the `group` key is the title.
+- If the topmost container would sit above the page origin, the whole diagram is shifted down so nothing lands at a negative coordinate.
+
+## Validate before previewing
+
+`scripts/validate.py` is a deterministic structural linter — run it on the produced `.drawio` before the (slower, vision-based) self-check:
+
+```bash
+python3 <this-skill-dir>/scripts/validate.py diagram.drawio
+```
+
+It catches dangling edge endpoints, duplicate/reserved ids, broken parent references (errors), plus off-grid/negative geometry and overlapping sibling nodes (warnings) — without launching draw.io. Exit status is non-zero on any error (or any warning with `--strict`), so it can gate the workflow. Auto-layout output should always pass clean; a failure means a malformed input graph (e.g. an edge referencing a missing node id).
+
## Importers — visualize code structure
-`scripts/pyimports.py` turns a **Python project/package** into a graph JSON ready for autolayout, so "visualize this codebase" is a two-step pipeline:
+Three bundled importers turn a codebase into a graph JSON ready for autolayout, so "visualize this project" is a two-step pipeline:
+
+| Language | Script | Node = | Edge = |
+|---|---|---|---|
+| Python | `scripts/pyimports.py <dir>` | module / package (`ast`) | intra-project `import` / `from` |
+| JS / TS | `scripts/jsimports.py <dir>` | source file (`.ts/.tsx/.js/.jsx/.mjs/.cjs`) | resolved relative `import`/`export from`/`require()`/`import()` |
+| Go | `scripts/goimports.py <dir>` | package (directory, via `go.mod`) | intra-module package import |
```bash
python3 <this-skill-dir>/scripts/pyimports.py myproject -o graph.json
python3 <this-skill-dir>/scripts/autolayout.py graph.json -o diagram.drawio
```
-It walks the directory, parses each module with `ast`, and builds the **intra-project** module-import edges (third-party/stdlib imports are ignored). If the directory is itself a package (`__init__.py` present), module names are package-qualified so the project's own absolute imports resolve; nested subpackages (`pkg.sub.mod`) are handled.
+Each keeps only **intra-project** edges (third-party/stdlib imports are ignored), shortens node labels (drops the shared package/module/directory prefix; ids stay fully qualified), and shares the same flags: `--direction TB|LR` (default `TB`), `--group`, `--no-reduce`.
+
+- **Python** (`pyimports.py`): if the directory is itself a package (`__init__.py` present), module names are package-qualified so the project's own absolute imports resolve; nested subpackages (`pkg.sub.mod`) are handled.
+- **JS/TS** (`jsimports.py`): resolution is path-based (tries the source extensions and directory `index` files); `node_modules` and bare specifiers are skipped. Scanning is regex-based, not a full parser.
+- **Go** (`goimports.py`): reads the `module` path from `go.mod`; each directory of `.go` files is one package; `*_test.go` and `vendor/` are skipped.
-**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. `pyimports.py` 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.
+**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.
-Flags: `--direction TB|LR` (default `TB`), `--no-reduce`. Node labels are shortened (the shared package prefix is dropped); ids stay fully qualified.
+**`--group`** assigns each node a container by its top-level sub-package / directory, so autolayout boxes related modules together (see **Containers / grouping**) — the fastest way to turn a large code graph into a tiered architecture view.
-For other languages, produce the same graph JSON from any analyzer (e.g. `dependency-cruiser` for JS/TS, `go-callvis` for Go) and feed it to autolayout the same way.
+For any other language, produce the same graph JSON from any analyzer (e.g. `dependency-cruiser` for richer JS/TS resolution, `go-callvis` for Go call graphs) and feed it to autolayout the same way.
## Limitations
- **Placement is topological, not semantic** — dot minimises edge crossings, which may put a node in a different column than you'd choose by hand. Re-export with the other `direction`, or hand-tune the produced XML afterwards (it's a normal `.drawio`).
-- **`pyimports.py` is module-level** — it maps module→module imports, not function/class call graphs, and resolves static `import`/`from` statements (not dynamic `importlib` calls).
+- **Importers are module/package-level** — they map module→module (or package→package) imports, not function/class call graphs, and read static import statements (not dynamic `importlib`, runtime `require`, or reflection).
- **Parallel edges** between the same `(source, target)` pair share one route.
-- **No containers/swimlanes** — this MVP lays out a flat node/edge graph. For nested architecture diagrams, hand-place containers (see SKILL.md "Containers and groups").
+- **Containers are single-level** — `group` produces one flat layer of boxes (no nested containers within containers). For hand-built nested architecture diagrams, see SKILL.md "Containers and groups".
diff --git a/skills/drawio-skill/scripts/autolayout.py b/skills/drawio-skill/scripts/autolayout.py
index ea50ecc..ae6ce3c 100644
--- a/skills/drawio-skill/scripts/autolayout.py
+++ b/skills/drawio-skill/scripts/autolayout.py
@@ -33,6 +33,9 @@ from xml.sax.saxutils import escape
DEFAULT_W, DEFAULT_H = 120, 60
NODE_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"
EDGE_STYLE = "html=1;rounded=0;"
+GROUP_STYLE = ("rounded=0;whiteSpace=wrap;html=1;fillColor=none;strokeColor=#999999;"
+ "verticalAlign=top;fontStyle=2;dashed=1;")
+GROUP_PAD, GROUP_TOP = 16, 24 # padding, and title strip on top
def attr(value):
@@ -49,6 +52,19 @@ def build_dot(graph):
# splines=ortho makes dot route edges as orthogonal polylines; we replay
# those bends as draw.io waypoints so edges go around nodes, not through them.
lines = [f"digraph G {{ rankdir={rankdir}; splines=ortho; node [shape=box fixedsize=true];"]
+ # Group nodes into clusters so dot keeps each group together; a node's first
+ # appearance fixes its cluster, so list members before the size attributes.
+ members = {}
+ for node in graph["nodes"]:
+ g = node.get("group")
+ if g is not None:
+ members.setdefault(str(g), []).append(node["id"])
+ for i, ms in enumerate(members.values()):
+ # margin matches GROUP_PAD so dot separates clusters enough that the
+ # padded container boxes we draw below do not overlap each other.
+ lines.append(f"subgraph cluster_{i} {{ margin={GROUP_PAD};")
+ lines += [f'"{m}";' for m in ms]
+ lines.append("}")
for node in graph["nodes"]:
# Pass our pixel sizes to dot as inches so it lays out at the real size.
w = node.get("width", DEFAULT_W) / 72.0
@@ -93,8 +109,10 @@ def layout(dot_src):
def to_drawio(graph, height, pos, edge_pts):
- cells = []
- for node in graph["nodes"]:
+ nodes = graph["nodes"]
+ # Absolute snapped rect for every placed node.
+ rects = {}
+ for node in nodes:
nid = node["id"]
if nid not in pos:
continue
@@ -102,10 +120,63 @@ def to_drawio(graph, height, pos, edge_pts):
xc, yc = pos[nid]
x = snap(xc * 72 - w / 2)
y = snap((height - yc) * 72 - h / 2) # flip: dot origin is bottom-left
+ rects[nid] = (x, y, w, h)
+ # Group membership -> container id + bounding box (members + padding + title strip).
+ members, glabel = {}, {}
+ for node in nodes:
+ g = node.get("group")
+ if g is None or node["id"] not in rects:
+ continue
+ members.setdefault(str(g), []).append(node["id"])
+ glabel.setdefault(str(g), str(node.get("groupLabel", g)))
+ used = {n["id"] for n in nodes}
+ gid, gbox = {}, {}
+ for i, (g, ms) in enumerate(members.items()):
+ cid = f"group_{i}"
+ while cid in used: # never collide with a node id
+ cid += "_"
+ used.add(cid)
+ gid[g] = cid
+ x0 = min(rects[m][0] for m in ms) - GROUP_PAD
+ y0 = min(rects[m][1] for m in ms) - GROUP_PAD - GROUP_TOP
+ x1 = max(rects[m][0] + rects[m][2] for m in ms) + GROUP_PAD
+ y1 = max(rects[m][1] + rects[m][3] for m in ms) + GROUP_PAD
+ gbox[g] = (x0, y0, x1 - x0, y1 - y0)
+
+ # Shift everything positive: a container's title strip can push its top edge
+ # above the page origin. Only translates when something would be negative.
+ absx = [r[0] for r in rects.values()] + [b[0] for b in gbox.values()]
+ absy = [r[1] for r in rects.values()] + [b[1] for b in gbox.values()]
+ dx = GROUP_PAD - min(absx) if absx and min(absx) < 0 else 0
+ dy = GROUP_PAD - min(absy) if absy and min(absy) < 0 else 0
+
+ cells = []
+ # Containers first so they render behind their children.
+ for g, (gx, gy, gw, gh) in gbox.items():
+ cells.append(
+ f' <mxCell id="{attr(gid[g])}" value="{attr(glabel[g])}" '
+ f'style="{GROUP_STYLE}" vertex="1" parent="1">\n'
+ f' <mxGeometry x="{gx + dx}" y="{gy + dy}" width="{gw}" height="{gh}" as="geometry"/>\n'
+ f" </mxCell>"
+ )
+ node_group = {n["id"]: str(n["group"]) for n in nodes
+ if n.get("group") is not None and n["id"] in rects}
+ for node in nodes:
+ nid = node["id"]
+ if nid not in rects:
+ continue
+ x, y, w, h = rects[nid]
+ parent = "1"
+ if nid in node_group: # rebase into its container
+ g = node_group[nid]
+ gx, gy = gbox[g][0], gbox[g][1]
+ parent, x, y = gid[g], x - gx, y - gy # relative; shift cancels
+ else:
+ x, y = x + dx, y + dy
style = node.get("style", NODE_STYLE)
cells.append(
f' <mxCell id="{attr(nid)}" value="{attr(node.get("label", nid))}" '
- f'style="{style}" vertex="1" parent="1">\n'
+ f'style="{style}" vertex="1" parent="{attr(parent)}">\n'
f' <mxGeometry x="{x}" y="{y}" width="{w}" height="{h}" as="geometry"/>\n'
f" </mxCell>"
)
@@ -115,7 +186,7 @@ def to_drawio(graph, height, pos, edge_pts):
interior = edge_pts.get((edge["source"], edge["target"]), [])[1:-1]
if interior:
points = "".join(
- f'<mxPoint x="{snap(x * 72)}" y="{snap((height - y) * 72)}"/>'
+ f'<mxPoint x="{snap(x * 72) + dx}" y="{snap((height - y) * 72) + dy}"/>'
for x, y in interior
)
geom = (f'<mxGeometry relative="1" as="geometry">'
diff --git a/skills/drawio-skill/scripts/goimports.py b/skills/drawio-skill/scripts/goimports.py
new file mode 100644
index 0000000..ae71387
--- /dev/null
+++ b/skills/drawio-skill/scripts/goimports.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+"""Extract a Go module's package-import graph as autolayout graph JSON.
+
+The Go counterpart to pyimports.py / jsimports.py. Reads the module path from
+go.mod, walks the module, treats each directory of .go files as one package
+(node = its import path), and records the intra-module package imports. Stdlib
+and third-party imports are ignored. Transitive reduction is on by default so
+the diagram stays readable.
+
+ python3 goimports.py ./mymodule -o graph.json
+ python3 autolayout.py graph.json -o diagram.drawio
+
+Parsing is regex-based over `import` statements (single and block form),
+which is enough for a structural package graph. *_test.go files and vendor/
+are skipped.
+
+Usage: python3 goimports.py <module_dir> [-o graph.json] [--direction TB|LR]
+ [--group] [--no-reduce]
+"""
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+
+MODULE = re.compile(r"^module\s+(\S+)", re.MULTILINE)
+BLOCK = re.compile(r"import\s*\((.*?)\)", re.DOTALL)
+SINGLE = re.compile(r'import\s+(?:[\w.]+\s+|_\s+)?"([^"]+)"')
+QUOTED = re.compile(r'"([^"]+)"')
+
+
+def module_path(root):
+ """Read the `module` path from go.mod at the module root, or None."""
+ gomod = os.path.join(root, "go.mod")
+ if not os.path.exists(gomod):
+ return None
+ m = MODULE.search(open(gomod, encoding="utf-8", errors="ignore").read())
+ return m.group(1) if m else None
+
+
+def discover(root, modpath):
+ """Map package import path -> list of .go files (one entry per directory)."""
+ root = os.path.abspath(root)
+ pkgs = {}
+ for dirpath, dirs, files in os.walk(root):
+ dirs[:] = [d for d in dirs
+ if d not in ("vendor", "testdata") and not d.startswith(".")]
+ gofiles = [os.path.join(dirpath, f) for f in files
+ if f.endswith(".go") and not f.endswith("_test.go")]
+ if not gofiles:
+ continue
+ rel = os.path.relpath(dirpath, root).replace(os.sep, "/")
+ ip = modpath if rel == "." else f"{modpath}/{rel}"
+ pkgs[ip] = gofiles
+ return pkgs
+
+
+def imports_of(files, modpath, pkgs):
+ """Intra-module package import paths referenced by a package's files."""
+ found = set()
+ for path in files:
+ try:
+ src = open(path, encoding="utf-8", errors="ignore").read()
+ except OSError:
+ continue
+ specs = []
+ for block in BLOCK.findall(src):
+ specs += QUOTED.findall(block)
+ specs += SINGLE.findall(src)
+ for spec in specs:
+ if (spec == modpath or spec.startswith(modpath + "/")) and spec in pkgs:
+ found.add(spec)
+ return found
+
+
+def transitive_reduce(nodes, edges):
+ """Drop edges implied by a longer path, via Graphviz `tred`."""
+ idx = {n: i for i, n in enumerate(nodes)}
+ dot = "digraph{" + "".join(f"{idx[s]}->{idx[t]};" for s, t in edges) + "}"
+ try:
+ out = subprocess.run(["tred"], input=dot, capture_output=True,
+ text=True, check=True).stdout
+ except (FileNotFoundError, subprocess.CalledProcessError) as exc:
+ sys.stderr.write(f"warning: tred unavailable, keeping all edges ({exc})\n")
+ return edges
+ rev = {i: n for n, i in idx.items()}
+ return [(rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)]
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Go import graph -> autolayout graph JSON.")
+ ap.add_argument("module", help="module directory (contains go.mod)")
+ 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 nodes into containers by top-level package dir")
+ ap.add_argument("--no-reduce", action="store_true",
+ help="keep every edge (skip transitive reduction)")
+ args = ap.parse_args()
+
+ modpath = module_path(args.module)
+ if not modpath:
+ sys.exit(f"error: no go.mod with a module path found in {args.module}")
+ pkgs = discover(args.module, modpath)
+ if not pkgs:
+ sys.exit(f"error: no Go packages found under {args.module}")
+ edges = sorted({(ip, t) for ip, files in pkgs.items()
+ for t in imports_of(files, modpath, pkgs) if t != ip})
+ raw = len(edges)
+ if not args.no_reduce:
+ edges = transitive_reduce(list(pkgs), edges)
+ # Drop the module prefix from labels for readability; ids stay full.
+ strip = modpath + "/"
+ label = lambda ip: ip[len(strip):] if ip.startswith(strip) else os.path.basename(ip)
+
+ def node(ip):
+ d = {"id": ip, "label": label(ip)}
+ if args.group:
+ rest = label(ip).split("/")
+ if len(rest) > 1: # nested under a sub-package
+ d["group"] = rest[0]
+ return d
+
+ graph = {
+ "direction": args.direction,
+ "nodes": [node(ip) for ip in pkgs],
+ "edges": [{"source": s, "target": t} for s, t in edges],
+ }
+ text = json.dumps(graph, indent=2)
+ if args.output:
+ open(args.output, "w", encoding="utf-8").write(text)
+ sys.stderr.write(f"wrote {args.output}\n")
+ else:
+ sys.stdout.write(text)
+ note = "" if args.no_reduce else f" (reduced from {raw})"
+ sys.stderr.write(f"{len(pkgs)} packages, {len(edges)} edges{note}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/drawio-skill/scripts/jsimports.py b/skills/drawio-skill/scripts/jsimports.py
new file mode 100644
index 0000000..e63e571
--- /dev/null
+++ b/skills/drawio-skill/scripts/jsimports.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""Extract a JS/TS project's module-import graph as autolayout graph JSON.
+
+The JavaScript/TypeScript counterpart to pyimports.py: walks a source
+directory, scans each module for static and dynamic import specifiers
+(`import`/`export ... from`, `require()`, `import()`), keeps only the
+intra-project edges (relative specifiers that resolve to a file under the
+root), and applies transitive reduction so the diagram stays readable.
+
+ python3 jsimports.py src -o graph.json
+ python3 autolayout.py graph.json -o diagram.drawio
+
+Resolution is path-based: relative specifiers are resolved against the
+importing file's directory, trying the .ts/.tsx/.js/.jsx/.mjs/.cjs extensions
+and directory index files. Bare specifiers (node_modules packages such as
+"react") are ignored. Scanning is regex-based rather than a full parser, so a
+specifier inside a comment or string literal is counted in rare cases.
+
+Usage: python3 jsimports.py <src_dir> [-o graph.json] [--direction TB|LR]
+ [--group] [--no-reduce]
+"""
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+
+EXTS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs")
+SPEC = re.compile(
+ r"(?:import|export)\b[^'\";]*?\bfrom\s*['\"]([^'\"]+)['\"]" # import/export ... from "x"
+ r"|import\s*['\"]([^'\"]+)['\"]" # import "x" (side effect)
+ r"|require\s*\(\s*['\"]([^'\"]+)['\"]\s*\)" # require("x")
+ r"|import\s*\(\s*['\"]([^'\"]+)['\"]\s*\)" # import("x") dynamic
+)
+
+
+def modid(path, root):
+ """Module id = path relative to root, extension stripped, posix separators."""
+ rel = os.path.relpath(path, root)
+ for ext in EXTS:
+ if rel.endswith(ext):
+ rel = rel[: -len(ext)]
+ break
+ return rel.replace(os.sep, "/")
+
+
+def discover(root):
+ """Map module id -> absolute file path for every source file under root."""
+ root = os.path.abspath(root)
+ modules = {}
+ for dirpath, dirs, files in os.walk(root):
+ dirs[:] = [d for d in dirs if d != "node_modules" and not d.startswith(".")]
+ for fn in files:
+ if fn.endswith(EXTS) and not fn.endswith(".d.ts"):
+ full = os.path.join(dirpath, fn)
+ modules[modid(full, root)] = full
+ return modules, root
+
+
+def resolve(spec, importer, root, modules):
+ """Resolve a relative specifier to a known module id, or None (external)."""
+ if not spec.startswith("."):
+ return None
+ base = os.path.normpath(os.path.join(os.path.dirname(importer), spec))
+ candidates = ([base + e for e in EXTS]
+ + [os.path.join(base, "index" + e) for e in EXTS]
+ + [base])
+ for cand in candidates:
+ mid = modid(cand, root)
+ if mid in modules and modules[mid] != importer:
+ return mid
+ return None
+
+
+def edges_of(mid, path, root, modules):
+ """Intra-project modules imported by module `mid`."""
+ found = set()
+ try:
+ src = open(path, encoding="utf-8", errors="ignore").read()
+ except OSError:
+ return found
+ for m in SPEC.finditer(src):
+ spec = m.group(1) or m.group(2) or m.group(3) or m.group(4)
+ target = resolve(spec, path, root, modules)
+ if target and target != mid:
+ found.add(target)
+ return found
+
+
+def transitive_reduce(nodes, edges):
+ """Drop edges implied by a longer path, via Graphviz `tred`."""
+ idx = {n: i for i, n in enumerate(nodes)}
+ dot = "digraph{" + "".join(f"{idx[s]}->{idx[t]};" for s, t in edges) + "}"
+ try:
+ out = subprocess.run(["tred"], input=dot, capture_output=True,
+ text=True, check=True).stdout
+ except (FileNotFoundError, subprocess.CalledProcessError) as exc:
+ sys.stderr.write(f"warning: tred unavailable, keeping all edges ({exc})\n")
+ return edges
+ rev = {i: n for n, i in idx.items()}
+ return [(rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)]
+
+
+def common_dir(ids):
+ """Longest shared leading path segment across module ids (e.g. 'src/')."""
+ common = []
+ for parts in zip(*[m.split("/") for m in ids]):
+ if len(set(parts)) == 1:
+ common.append(parts[0])
+ else:
+ break
+ return "/".join(common) + "/" if common else ""
+
+
+def main():
+ ap = argparse.ArgumentParser(description="JS/TS import graph -> autolayout graph JSON.")
+ ap.add_argument("src", help="source directory")
+ 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 nodes into containers by top-level directory")
+ ap.add_argument("--no-reduce", action="store_true",
+ help="keep every edge (skip transitive reduction)")
+ args = ap.parse_args()
+
+ modules, root = discover(args.src)
+ if not modules:
+ sys.exit(f"error: no JS/TS modules found under {args.src}")
+ edges = sorted({(m, t) for m, p in modules.items()
+ for t in edges_of(m, p, root, modules)})
+ raw = len(edges)
+ if not args.no_reduce:
+ edges = transitive_reduce(list(modules), edges)
+ strip = common_dir(list(modules))
+ label = lambda m: (m[len(strip):] if strip and m.startswith(strip) else m) or m
+
+ def node(m):
+ d = {"id": m, "label": label(m)}
+ if args.group:
+ rest = label(m).split("/")
+ if len(rest) > 1: # has a sub-directory
+ d["group"] = rest[0]
+ return d
+
+ graph = {
+ "direction": args.direction,
+ "nodes": [node(m) for m in modules],
+ "edges": [{"source": s, "target": t} for s, t in edges],
+ }
+ text = json.dumps(graph, indent=2)
+ if args.output:
+ open(args.output, "w", encoding="utf-8").write(text)
+ sys.stderr.write(f"wrote {args.output}\n")
+ else:
+ sys.stdout.write(text)
+ note = "" if args.no_reduce else f" (reduced from {raw})"
+ sys.stderr.write(f"{len(modules)} modules, {len(edges)} edges{note}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/drawio-skill/scripts/pyimports.py b/skills/drawio-skill/scripts/pyimports.py
index 74f2782..4868b0c 100644
--- a/skills/drawio-skill/scripts/pyimports.py
+++ b/skills/drawio-skill/scripts/pyimports.py
@@ -108,6 +108,8 @@ def main():
ap.add_argument("project", help="package or project directory")
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 nodes into containers by sub-package")
ap.add_argument("--no-reduce", action="store_true",
help="keep every edge (skip transitive reduction)")
args = ap.parse_args()
@@ -123,9 +125,18 @@ def main():
# Drop the shared package prefix from labels for readability; ids stay full.
strip = base + "." if base else ""
label = lambda m: m[len(strip):] if strip and m.startswith(strip) else m
+
+ def node(m):
+ d = {"id": m, "label": label(m)}
+ if args.group:
+ rest = label(m).split(".")
+ if len(rest) > 1: # nested under a sub-package
+ d["group"] = rest[0]
+ return d
+
graph = {
"direction": args.direction,
- "nodes": [{"id": m, "label": label(m)} for m in modules],
+ "nodes": [node(m) for m in modules],
"edges": [{"source": s, "target": t} for s, t in edges],
}
text = json.dumps(graph, indent=2)
diff --git a/skills/drawio-skill/scripts/validate.py b/skills/drawio-skill/scripts/validate.py
new file mode 100644
index 0000000..f2a38e4
--- /dev/null
+++ b/skills/drawio-skill/scripts/validate.py
@@ -0,0 +1,117 @@
+#!/usr/bin/env python3
+"""Deterministic structural linter for .drawio files.
+
+Catches the class of mistakes a vision self-check is slow and unreliable at:
+dangling edge endpoints, duplicate or reserved ids, broken parent references,
+and (as warnings) off-grid geometry and overlapping sibling nodes. Runs without
+launching draw.io, so it is a fast pre-check before the visual review step.
+
+ python3 validate.py diagram.drawio
+
+Exit status is non-zero when any error (or, with --strict, any warning) is
+found, so it can gate a workflow. Compressed (non-XML) diagram pages are
+skipped with a warning — this skill always writes uncompressed XML.
+
+Usage: python3 validate.py <file.drawio> [--strict]
+"""
+import argparse
+import sys
+import xml.etree.ElementTree as ET
+
+RESERVED = {"0", "1"}
+
+
+def rect(cell):
+ """Return (x, y, w, h) floats for a cell's geometry, or None if absent/bad."""
+ g = cell.find("mxGeometry")
+ if g is None:
+ return None
+ try:
+ return tuple(float(g.get(k, "nan")) for k in ("x", "y", "width", "height"))
+ except ValueError:
+ return None
+
+
+def overlap(a, b):
+ ax, ay, aw, ah = a
+ bx, by, bw, bh = b
+ return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
+
+
+def check_page(diagram):
+ """Return (errors, warnings) for one <diagram> page."""
+ name = diagram.get("name", "?")
+ model = diagram.find("mxGraphModel")
+ if model is None:
+ if (diagram.text or "").strip():
+ return [], [f"page {name!r}: compressed, skipped (cannot lint)"]
+ return [f"page {name!r}: no <mxGraphModel>"], []
+ root = model.find("root")
+ cells = root.findall("mxCell") if root is not None else []
+ errors, warns = [], []
+ ids = {}
+ for c in cells:
+ cid = c.get("id")
+ if cid in ids:
+ errors.append(f"duplicate id {cid!r}")
+ ids[cid] = c
+ parents = {c.get("parent") for c in cells} # ids that have children
+ for c in cells:
+ cid, parent = c.get("id"), c.get("parent")
+ is_v, is_e = c.get("vertex") == "1", c.get("edge") == "1"
+ if parent is not None and parent not in ids:
+ errors.append(f"cell {cid!r} parent {parent!r} does not exist")
+ for end in ("source", "target"):
+ ref = c.get(end)
+ if ref and ref not in ids:
+ errors.append(f"edge {cid!r} {end} {ref!r} does not exist")
+ if (is_v or is_e) and cid in RESERVED:
+ errors.append(f"cell {cid!r} reuses reserved id 0/1")
+ if is_v:
+ r = rect(c)
+ if r is None or any(v != v for v in r): # None or NaN
+ errors.append(f"vertex {cid!r} has missing/invalid geometry")
+ else:
+ x, y, w, h = r
+ if w <= 0 or h <= 0:
+ warns.append(f"vertex {cid!r} non-positive size {w:g}x{h:g}")
+ if x < 0 or y < 0:
+ warns.append(f"vertex {cid!r} negative position ({x:g},{y:g})")
+ # Sibling overlap: only leaf vertices (containers legitimately wrap children).
+ boxes = [(c.get("id"), c.get("parent"), rect(c)) for c in cells
+ if c.get("vertex") == "1" and c.get("id") not in parents and rect(c)
+ and not any(v != v for v in rect(c))]
+ for i in range(len(boxes)):
+ for j in range(i + 1, len(boxes)):
+ (ia, pa, ra), (ib, pb, rb) = boxes[i], boxes[j]
+ if pa == pb and overlap(ra, rb):
+ warns.append(f"vertices {ia!r} and {ib!r} overlap")
+ return errors, warns
+
+
+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")
+ args = ap.parse_args()
+ try:
+ tree = ET.parse(args.file)
+ except (ET.ParseError, OSError) as exc:
+ sys.exit(f"error: cannot parse {args.file}: {exc}")
+ pages = tree.getroot().findall("diagram") or [tree.getroot()]
+ errors, warns = [], []
+ for page in pages:
+ e, w = check_page(page)
+ errors += e
+ warns += w
+ for w in warns:
+ print(f"warning: {w}")
+ for e in errors:
+ print(f"error: {e}")
+ print(f"{len(errors)} error(s), {len(warns)} warning(s)")
+ if errors or (args.strict and warns):
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()