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: Rust module-use importer (v1.10.0) (#18)

Agents365.ai5fa16f093697
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 0c0080b..481c6a2 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,12 +1,12 @@
---
name: drawio-skill
-version: 1.9.0
+version: 1.10.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.9.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.10.0"}
---
# Draw.io Diagrams
@@ -32,7 +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` · `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, nested by sub-package) for autolayout |
+| `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/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 |
@@ -84,7 +84,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 / 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, nested for deep trees) ready for autolayout; for a **Python class hierarchy**, `scripts/pyclasses.py` extracts classes + inheritance instead. 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. **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. 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 9ce4f1f..1a170e3 100644
--- a/skills/drawio-skill/references/autolayout.md
+++ b/skills/drawio-skill/references/autolayout.md
@@ -94,6 +94,7 @@ Bundled importers turn a codebase into a graph JSON ready for autolayout, so "vi
| 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 |
+| Rust | `scripts/rustimports.py <dir>` | module (`.rs` file / `mod`) | intra-crate `use crate::` / `super::` / `self::` |
| Python (classes) | `scripts/pyclasses.py <dir>` | class (`ast`) | subclass → base (inheritance) |
```bash
@@ -106,6 +107,7 @@ Each keeps only **intra-project** edges (third-party/stdlib imports are ignored)
- **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.
+- **Rust** (`rustimports.py`): each `.rs` file is a module (`mod.rs`/`main.rs`/`lib.rs` name the enclosing module); edges come from `use` paths rooted at `crate::`/`super::`/`self::` (brace groups expanded). `std`/external crates and `target/` are skipped. Regex-based — inline `mod { … }` blocks aren't split out, and 2015-edition bare intra-crate paths aren't resolved.
- **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).
**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.
diff --git a/skills/drawio-skill/scripts/rustimports.py b/skills/drawio-skill/scripts/rustimports.py
new file mode 100644
index 0000000..6f13ba5
--- /dev/null
+++ b/skills/drawio-skill/scripts/rustimports.py
@@ -0,0 +1,203 @@
+#!/usr/bin/env python3
+"""Extract a Rust crate's module-use graph as autolayout graph JSON.
+
+The Rust counterpart to pyimports.py / jsimports.py / goimports.py. Treats each
+.rs file as a module (path-derived: src/foo/bar.rs -> module foo::bar; main.rs /
+lib.rs / mod.rs name the enclosing module), and records intra-crate `use` edges
+resolved through Rust's path roots:
+
+ use crate::a::b::C; -> edge to module a::b
+ use super::sibling; -> resolved against the current module's parent
+ use self::child::Item;-> resolved against the current module
+ use other_crate::...; / use std::...; -> external, ignored
+
+Brace groups (`use crate::a::{B, C};`, `use crate::{a, b};`) are expanded.
+Transitive reduction is on by default so the diagram stays readable.
+
+ python3 rustimports.py ./mycrate --group -o graph.json
+ python3 autolayout.py graph.json -o diagram.drawio
+
+Parsing is regex-based, not a full parser: inline `mod { ... }` blocks are not
+split out, `#[cfg]`-gated modules are always included, and 2015-edition bare
+intra-crate paths (without `crate::`) are not resolved.
+
+Usage: python3 rustimports.py <crate_dir> [-o graph.json] [--direction TB|LR]
+ [--group] [--no-reduce]
+"""
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+
+USE = re.compile(r"\buse\s+([^;]+);")
+
+
+def crate_name(root):
+ cargo = os.path.join(root, "Cargo.toml")
+ if os.path.exists(cargo):
+ m = re.search(r'(?m)^\s*name\s*=\s*"([^"]+)"',
+ open(cargo, encoding="utf-8", errors="ignore").read())
+ if m:
+ return m.group(1)
+ return "crate"
+
+
+def discover(root):
+ """Map module path (tuple of segments; () is the crate root) -> file path."""
+ root = os.path.abspath(root)
+ src = os.path.join(root, "src") if os.path.isdir(os.path.join(root, "src")) else root
+ modules = {}
+ for dirpath, dirs, files in os.walk(src):
+ dirs[:] = [d for d in dirs if d != "target" and not d.startswith(".")]
+ for fn in files:
+ if not fn.endswith(".rs"):
+ continue
+ parts = os.path.relpath(os.path.join(dirpath, fn), src)[:-3].split(os.sep)
+ if parts[-1] == "mod":
+ parts = parts[:-1]
+ if len(parts) == 1 and parts[0] in ("main", "lib"):
+ parts = [] # crate root
+ modules[tuple(parts)] = os.path.join(dirpath, fn)
+ return modules, src
+
+
+def split_top(inner):
+ """Split a brace group on top-level commas, ignoring nested braces."""
+ out, depth, cur = [], 0, ""
+ for ch in inner:
+ if ch == "{":
+ depth += 1
+ elif ch == "}":
+ depth -= 1
+ if ch == "," and depth == 0:
+ out.append(cur)
+ cur = ""
+ else:
+ cur += ch
+ if cur.strip():
+ out.append(cur)
+ return out
+
+
+def base_segments(prefix, current):
+ """Classify a `use` path prefix into intra-crate base segments, or None."""
+ segs = [s for s in (p.strip() for p in prefix.split("::")) if s]
+ if not segs:
+ return None
+ if segs[0] == "crate":
+ return segs[1:]
+ if segs[0] == "self":
+ return list(current) + segs[1:]
+ if segs[0] == "super":
+ n = 0
+ while segs and segs[0] == "super":
+ n += 1
+ segs = segs[1:]
+ if n > len(current):
+ return None # climbs above the crate root
+ return list(current)[: len(current) - n] + segs
+ return None # std / external crate
+
+
+def resolve(parts, modules, current):
+ """Longest known module prefix of `parts` (a tuple), or None."""
+ if not parts:
+ return () if () in modules and () != tuple(current) else None
+ p = list(parts)
+ while p:
+ if tuple(p) in modules and tuple(p) != tuple(current):
+ return tuple(p)
+ p = p[:-1]
+ return None
+
+
+def edges_of(current, path, modules):
+ """Intra-crate module paths used by the module at `current`."""
+ found = set()
+ try:
+ src = open(path, encoding="utf-8", errors="ignore").read()
+ except OSError:
+ return found
+ for stmt in USE.findall(src):
+ if "{" in stmt:
+ prefix = stmt[: stmt.index("{")]
+ inner = stmt[stmt.index("{") + 1: stmt.rindex("}")] if "}" in stmt else ""
+ leaves = split_top(inner)
+ else:
+ prefix, leaves = stmt, [None]
+ base = base_segments(prefix, current)
+ if base is None:
+ continue
+ for leaf in leaves:
+ segs = list(base)
+ if leaf:
+ first = leaf.strip().split("::")[0].split()[0]
+ if first and first not in ("self", "*"):
+ segs.append(first)
+ target = resolve(tuple(segs), modules, current)
+ if target is not None and target != current:
+ 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="Rust module-use graph -> autolayout graph JSON.")
+ ap.add_argument("crate", help="crate directory (contains Cargo.toml and/or src/)")
+ 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="box modules by their parent module path (nested)")
+ ap.add_argument("--no-reduce", action="store_true",
+ help="keep every edge (skip transitive reduction)")
+ args = ap.parse_args()
+
+ modules, _ = discover(args.crate)
+ if not modules:
+ sys.exit(f"error: no .rs modules found under {args.crate}")
+ name = crate_name(args.crate)
+ mid = lambda parts: name if not parts else "::".join(parts)
+ edges = sorted({(mid(m), mid(t)) for m, path in modules.items()
+ for t in edges_of(m, path, modules)})
+ raw = len(edges)
+ if not args.no_reduce:
+ edges = transitive_reduce([mid(m) for m in modules], edges)
+
+ def node(parts):
+ d = {"id": mid(parts), "label": name if not parts else parts[-1]}
+ if args.group and len(parts) > 1:
+ d["group"] = "/".join(parts[:-1]) # parent module path -> nested boxes
+ 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()