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(scripts): add pyimports.py — Python import-graph importer (v1.7.0) (#15)

Agents365.ai2d388e729223
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 86eba23..ac9c6b7 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,12 +1,12 @@
---
name: drawio-skill
-version: 1.6.0
+version: 1.7.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.6.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.7.0"}
---
# Draw.io Diagrams
@@ -32,6 +32,7 @@ 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 |
## Prerequisites
@@ -81,7 +82,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`). 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 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.
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 ef237aa..533d685 100644
--- a/skills/drawio-skill/references/autolayout.md
+++ b/skills/drawio-skill/references/autolayout.md
@@ -62,8 +62,26 @@ 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.
+## 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:
+
+```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.
+
+**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.
+
+Flags: `--direction TB|LR` (default `TB`), `--no-reduce`. Node labels are shortened (the shared package prefix is dropped); ids stay fully qualified.
+
+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.
+
## 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).
- **Parallel edges** between the same `(source, target)` pair share one route.
- **No containers/swimlanes** — this MVP lays out a flat node/edge graph. For nested architecture diagrams, hand-place containers (see SKILL.md "Containers and groups").
diff --git a/skills/drawio-skill/scripts/pyimports.py b/skills/drawio-skill/scripts/pyimports.py
new file mode 100644
index 0000000..74f2782
--- /dev/null
+++ b/skills/drawio-skill/scripts/pyimports.py
@@ -0,0 +1,142 @@
+#!/usr/bin/env python3
+"""Extract a Python project's module-import graph as autolayout graph JSON.
+
+Walks a package/project directory, parses each module with `ast`, builds the
+intra-project import edges, and (by default) applies transitive reduction so
+the diagram stays readable instead of becoming a hairball. The output feeds
+autolayout.py:
+
+ python3 pyimports.py myproject -o graph.json
+ python3 autolayout.py graph.json -o diagram.drawio
+
+Transitive reduction uses Graphviz `tred` (drops edges implied by a longer
+path); pass --no-reduce to keep every import edge. Only intra-project imports
+are kept — third-party and stdlib imports are ignored.
+
+Usage: python3 pyimports.py <project_dir> [-o graph.json] [--direction TB|LR] [--no-reduce]
+"""
+import argparse
+import ast
+import json
+import os
+import re
+import subprocess
+import sys
+
+
+def discover(root):
+ """Map dotted module name -> file path for every .py under root, plus the
+ package prefix. If root is itself a package (has __init__.py), module names
+ are qualified with its name so the project's own absolute imports resolve."""
+ root = os.path.abspath(root)
+ base = os.path.basename(root) if os.path.exists(os.path.join(root, "__init__.py")) else ""
+ modules = {}
+ for dirpath, _, files in os.walk(root):
+ for fn in files:
+ if not fn.endswith(".py"):
+ continue
+ rel = os.path.relpath(os.path.join(dirpath, fn), root)[:-3] # strip .py
+ parts = rel.split(os.sep)
+ if parts[-1] == "__init__":
+ parts = parts[:-1] # package = its dir
+ parts = ([base] + parts) if base else parts
+ if parts:
+ modules[".".join(parts)] = os.path.join(dirpath, fn)
+ return modules, base
+
+
+def resolve(name, current, modules):
+ """Resolve a dotted name to the longest known module prefix (or None)."""
+ parts = name.split(".") if name else []
+ while parts:
+ cand = ".".join(parts)
+ if cand in modules and cand != current:
+ return cand
+ parts = parts[:-1]
+ return None
+
+
+def edges_of(name, path, modules):
+ """Intra-project modules imported by `name`."""
+ pkg = name if path.endswith("__init__.py") else name.rsplit(".", 1)[0] if "." in name else ""
+ found = set()
+ try:
+ tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
+ except SyntaxError:
+ return found
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import): # import a.b.c
+ for alias in node.names:
+ target = resolve(alias.name, name, modules)
+ if target:
+ found.add(target)
+ elif isinstance(node, ast.ImportFrom): # from a.b import c
+ if node.level: # relative: climb level-1 packages
+ base = pkg.split(".") if pkg else []
+ base = base[: len(base) - (node.level - 1)]
+ prefix = ".".join(base)
+ mod = f"{prefix}.{node.module}" if prefix and node.module else (node.module or prefix)
+ else:
+ mod = node.module or ""
+ target = resolve(mod, name, modules)
+ if target:
+ found.add(target)
+ for alias in node.names: # `from pkg import submodule`
+ sub = f"{mod}.{alias.name}" if mod else alias.name
+ target = resolve(sub, name, modules)
+ if target:
+ 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 main():
+ ap = argparse.ArgumentParser(description="Python import graph -> autolayout graph JSON.")
+ 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("--no-reduce", action="store_true",
+ help="keep every edge (skip transitive reduction)")
+ args = ap.parse_args()
+
+ modules, base = discover(args.project)
+ if not modules:
+ sys.exit(f"error: no .py modules found under {args.project}")
+ edges = sorted({(name, t) for name, path in modules.items()
+ for t in edges_of(name, path, modules)})
+ raw = len(edges)
+ if not args.no_reduce:
+ edges = transitive_reduce(list(modules), edges)
+ # 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
+ graph = {
+ "direction": args.direction,
+ "nodes": [{"id": m, "label": label(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()