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: nested containers + Python class-inheritance graph (v1.9.0) (#17)

Agents365.ai1b4df46adad3
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index fbe93c5..0c0080b 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,12 +1,12 @@
---
name: drawio-skill
-version: 1.8.0
+version: 1.9.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.8.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.9.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` · `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/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/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 |
## Prerequisites
@@ -83,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) 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.
+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.
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 f3afe4e..9ce4f1f 100644
--- a/skills/drawio-skill/references/autolayout.md
+++ b/skills/drawio-skill/references/autolayout.md
@@ -53,8 +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) |
+| `nodes[].group` | no | none | Group key, or a `/`-delimited path (`"core/db"`) for **nested** containers — nodes sharing a path are boxed together (see **Containers / grouping**) |
+| `nodes[].groupLabel` | no | last path segment | Title shown on the node's deepest container (first node with the path wins) |
| `edges[].source` / `target` | **yes** | — | Must match node ids |
| `edges[].label` | no | empty | Edge text |
@@ -66,12 +66,14 @@ It prints `wrote diagram.drawio (N nodes, M edges)` to stderr and writes a norma
## 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.
+Give nodes a `group` key and the script wraps each group in a labeled container (a dashed box with the group title at 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.
+**Nesting.** A `group` value with `/` separators builds nested containers: `"core/db"` puts the node inside a `db` box that itself sits inside a `core` box. Every path prefix becomes a container, so an arbitrarily deep package tree maps to nested boxes. A node can also sit *directly* in a parent box (`group: "core"`) alongside a sibling sub-box (`group: "core/db"`).
+
+- Each container box is the bounding box of its members and child boxes plus a uniform padding. The dot cluster margin is set to that same padding, so each box equals dot's cluster box — which dot keeps non-overlapping at **any nesting depth**.
+- The title sits in the top padding (`verticalAlign=top`); the box title is the path's last segment, or a member's `groupLabel`.
- 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.
+- If a container's top padding would cross the page origin, the whole diagram is shifted so nothing lands at a negative coordinate.
## Validate before previewing
@@ -85,13 +87,14 @@ It catches dangling edge endpoints, duplicate/reserved ids, broken parent refere
## Importers — visualize code structure
-Three bundled importers turn a codebase into a graph JSON ready for autolayout, so "visualize this project" is a two-step pipeline:
+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 |
+| Python (classes) | `scripts/pyclasses.py <dir>` | class (`ast`) | subclass → base (inheritance) |
```bash
python3 <this-skill-dir>/scripts/pyimports.py myproject -o graph.json
@@ -103,16 +106,17 @@ 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.
+- **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.
-**`--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.
+**`--group`** assigns each node a container by its sub-package / directory path, so autolayout boxes related modules together — nested when the path has depth (see **Containers / grouping**). The fastest way to turn a large code graph into a tiered architecture view.
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`).
-- **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).
+- **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 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".
+- **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".
diff --git a/skills/drawio-skill/scripts/autolayout.py b/skills/drawio-skill/scripts/autolayout.py
index ae6ce3c..8220f68 100644
--- a/skills/drawio-skill/scripts/autolayout.py
+++ b/skills/drawio-skill/scripts/autolayout.py
@@ -35,7 +35,10 @@ NODE_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c
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
+# Uniform container padding; the title sits in the top pad (verticalAlign=top).
+# dot's cluster margin is set to this same value so each container box equals
+# dot's cluster box — which dot guarantees never overlaps, at any nesting depth.
+GROUP_PAD = 24
def attr(value):
@@ -47,24 +50,55 @@ def snap(value, grid=10):
return int(round(value / grid) * grid)
+def group_tree(nodes):
+ """Parse hierarchical `group` paths ("a/b") into a container tree.
+
+ Returns (gpath, direct, children, ordered):
+ gpath[node_id] = tuple of path segments (the node's deepest container)
+ direct[path] = node ids whose group is exactly this path
+ children[path] = child container paths
+ ordered = all container paths, shallow-to-deep (stable)
+ """
+ gpath, direct, paths = {}, {}, set()
+ for node in nodes:
+ g = node.get("group")
+ if g is None or str(g).strip("/") == "":
+ continue
+ t = tuple(str(g).strip("/").split("/"))
+ gpath[node["id"]] = t
+ direct.setdefault(t, []).append(node["id"])
+ for k in range(1, len(t) + 1):
+ paths.add(t[:k])
+ children = {}
+ for p in sorted(paths):
+ if len(p) > 1:
+ children.setdefault(p[:-1], []).append(p)
+ ordered = sorted(paths, key=lambda p: (len(p), p))
+ return gpath, direct, children, ordered
+
+
def build_dot(graph):
rankdir = "LR" if str(graph.get("direction", "TB")).upper() == "LR" else "TB"
# 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("}")
+ # Group nodes into (possibly nested) clusters so dot keeps each group
+ # together; a node's first appearance fixes its cluster, so list members
+ # before the size attributes. The cluster margin reserves room for the
+ # padded container boxes we draw below (extra on Y for the title strip) so
+ # neighbouring boxes do not overlap.
+ _, direct, children, ordered = group_tree(graph["nodes"])
+ cidx = {p: i for i, p in enumerate(ordered)}
+
+ def emit_cluster(p, pad):
+ lines.append(f'{pad}subgraph cluster_{cidx[p]} {{ margin={GROUP_PAD};')
+ for c in children.get(p, []):
+ emit_cluster(c, pad + " ")
+ lines.extend(f'{pad} "{m}";' for m in direct.get(p, []))
+ lines.append(pad + "}")
+
+ for root in [p for p in ordered if len(p) == 1]:
+ emit_cluster(root, "")
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
@@ -121,58 +155,71 @@ def to_drawio(graph, height, pos, edge_pts):
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)))
+ # Parse the (possibly nested) group tree and assign each container a
+ # collision-free id and a title (the path's last segment, or a member's groupLabel).
+ gpath, direct, children, ordered = group_tree(nodes)
used = {n["id"] for n in nodes}
- gid, gbox = {}, {}
- for i, (g, ms) in enumerate(members.items()):
+ label_override = {}
+ for node in nodes:
+ if node["id"] in gpath and "groupLabel" in node:
+ label_override.setdefault(gpath[node["id"]], str(node["groupLabel"]))
+ gid, glabel = {}, {}
+ for i, p in enumerate(ordered):
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
+ gid[p] = cid
+ glabel[p] = label_override.get(p, p[-1])
+ # Container bounding box (members + nested children + uniform padding),
+ # computed deepest-first so a parent can wrap its already-sized children.
+ gbox = {}
+ for p in sorted(ordered, key=len, reverse=True):
+ xs = [(rects[m][0], rects[m][1], rects[m][0] + rects[m][2], rects[m][1] + rects[m][3])
+ for m in direct.get(p, []) if m in rects]
+ xs += [(gbox[c][0], gbox[c][1], gbox[c][0] + gbox[c][2], gbox[c][1] + gbox[c][3])
+ for c in children.get(p, []) if c in gbox]
+ if not xs:
+ continue
+ x0 = min(b[0] for b in xs) - GROUP_PAD
+ y0 = min(b[1] for b in xs) - GROUP_PAD
+ x1 = max(b[2] for b in xs) + GROUP_PAD
+ y1 = max(b[3] for b in xs) + GROUP_PAD
+ gbox[p] = (x0, y0, x1 - x0, y1 - y0)
+
+ # Shift everything positive: a container's top padding 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
+ def rebase(x, y, parent_path):
+ """Absolute -> coordinates relative to parent_path's box (or shifted if top-level)."""
+ if parent_path is None:
+ return x + dx, y + dy, "1"
+ px, py, _, _ = gbox[parent_path]
+ return x - px, y - py, gid[parent_path]
+
cells = []
- # Containers first so they render behind their children.
- for g, (gx, gy, gw, gh) in gbox.items():
+ # Containers shallow-first so each parent precedes its children.
+ for p in ordered:
+ if p not in gbox:
+ continue
+ gx, gy, gw, gh = gbox[p]
+ x, y, parent = rebase(gx, gy, p[:-1] if len(p) > 1 else None)
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 id="{attr(gid[p])}" value="{attr(glabel[p])}" '
+ f'style="{GROUP_STYLE}" vertex="1" parent="{attr(parent)}">\n'
+ f' <mxGeometry x="{x}" y="{y}" 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
+ rx, ry, w, h = rects[nid]
+ x, y, parent = rebase(rx, ry, gpath.get(nid) if gpath.get(nid) in gbox else None)
style = node.get("style", NODE_STYLE)
cells.append(
f' <mxCell id="{attr(nid)}" value="{attr(node.get("label", nid))}" '
diff --git a/skills/drawio-skill/scripts/goimports.py b/skills/drawio-skill/scripts/goimports.py
index ae71387..8b70a2d 100644
--- a/skills/drawio-skill/scripts/goimports.py
+++ b/skills/drawio-skill/scripts/goimports.py
@@ -119,7 +119,7 @@ def main():
if args.group:
rest = label(ip).split("/")
if len(rest) > 1: # nested under a sub-package
- d["group"] = rest[0]
+ d["group"] = "/".join(rest[:-1]) # full sub-package path -> nested boxes
return d
graph = {
diff --git a/skills/drawio-skill/scripts/jsimports.py b/skills/drawio-skill/scripts/jsimports.py
index e63e571..afa6d6a 100644
--- a/skills/drawio-skill/scripts/jsimports.py
+++ b/skills/drawio-skill/scripts/jsimports.py
@@ -140,7 +140,7 @@ def main():
if args.group:
rest = label(m).split("/")
if len(rest) > 1: # has a sub-directory
- d["group"] = rest[0]
+ d["group"] = "/".join(rest[:-1]) # full directory path -> nested boxes
return d
graph = {
diff --git a/skills/drawio-skill/scripts/pyclasses.py b/skills/drawio-skill/scripts/pyclasses.py
new file mode 100644
index 0000000..e4ced44
--- /dev/null
+++ b/skills/drawio-skill/scripts/pyclasses.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""Extract a Python project's class-inheritance graph as autolayout graph JSON.
+
+A finer-grained companion to pyimports.py: instead of module->module imports,
+it emits one node per class and an edge from each subclass to the project base
+classes it extends. With --group, classes are boxed by their module (nested by
+sub-package), so the result reads as an auto-generated class hierarchy.
+
+ python3 pyclasses.py myproject --group -o graph.json
+ python3 autolayout.py graph.json -o diagram.drawio
+
+Only inheritance is resolved (statically reliable); base classes are matched
+by name, preferring a class in the same module. External bases (object,
+Exception, third-party) are ignored. This is a *class structure* view, not a
+function-level call graph — static call resolution in Python is unreliable, so
+that is deliberately out of scope.
+
+Usage: python3 pyclasses.py <project_dir> [-o graph.json] [--direction TB|LR]
+ [--group] [--no-reduce]
+"""
+import argparse
+import ast
+import json
+import os
+import re
+import subprocess
+import sys
+
+CLASS_STYLE = "rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;"
+
+
+def discover(root):
+ """Map dotted module name -> file path; qualify with the package name when
+ root is itself a package (mirrors pyimports.py)."""
+ 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]
+ parts = rel.split(os.sep)
+ if parts[-1] == "__init__":
+ parts = parts[:-1]
+ parts = ([base] + parts) if base else parts
+ if parts:
+ modules[".".join(parts)] = os.path.join(dirpath, fn)
+ return modules, base
+
+
+def base_name(node):
+ """Simple name of a base-class expression (`Foo` or `pkg.Foo` -> 'Foo')."""
+ if isinstance(node, ast.Name):
+ return node.id
+ if isinstance(node, ast.Attribute):
+ return node.attr
+ return None
+
+
+def classes_in(module, path):
+ """Top-level classes of a module: list of (qualified_id, simple_name, [base names])."""
+ try:
+ tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
+ except SyntaxError:
+ return []
+ out = []
+ for node in tree.body:
+ if isinstance(node, ast.ClassDef):
+ bases = [b for b in (base_name(b) for b in node.bases) if b]
+ out.append((f"{module}.{node.name}", node.name, bases))
+ return out
+
+
+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 class-inheritance 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("--group", action="store_true",
+ help="box classes by their module (nested by sub-package)")
+ ap.add_argument("--no-reduce", action="store_true",
+ help="keep every edge (skip transitive reduction)")
+ args = ap.parse_args()
+
+ modules, base = discover(args.project)
+ classes = {} # qualified id -> (module, bases)
+ by_name = {} # simple name -> [qualified ids]
+ for mod, path in modules.items():
+ for cid, name, bases in classes_in(mod, path):
+ classes[cid] = (mod, bases)
+ by_name.setdefault(name, []).append(cid)
+ if not classes:
+ sys.exit(f"error: no classes found under {args.project}")
+
+ def resolve(name, module):
+ cands = by_name.get(name, [])
+ same = [c for c in cands if classes[c][0] == module]
+ if same:
+ return same[0] # prefer a class in the same module
+ return cands[0] if len(cands) == 1 else None # else only if unambiguous
+
+ edges = set()
+ for cid, (mod, bases) in classes.items():
+ for b in bases:
+ target = resolve(b, mod)
+ if target and target != cid:
+ edges.add((cid, target))
+ edges = sorted(edges)
+ raw = len(edges)
+ if not args.no_reduce:
+ edges = transitive_reduce(list(classes), edges)
+
+ strip = base + "." if base else ""
+ short = lambda m: m[len(strip):] if strip and m.startswith(strip) else m
+
+ def node(cid):
+ d = {"id": cid, "label": cid.rsplit(".", 1)[1], "style": CLASS_STYLE}
+ if args.group:
+ mod = classes[cid][0]
+ path = short(mod).replace(".", "/") # module path -> nested boxes
+ if path:
+ d["group"] = path
+ return d
+
+ graph = {
+ "direction": args.direction,
+ "nodes": [node(cid) for cid in classes],
+ "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(classes)} classes, {len(edges)} inheritance edges{note}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/drawio-skill/scripts/pyimports.py b/skills/drawio-skill/scripts/pyimports.py
index 4868b0c..4dd96e5 100644
--- a/skills/drawio-skill/scripts/pyimports.py
+++ b/skills/drawio-skill/scripts/pyimports.py
@@ -131,7 +131,7 @@ def main():
if args.group:
rest = label(m).split(".")
if len(rest) > 1: # nested under a sub-package
- d["group"] = rest[0]
+ d["group"] = "/".join(rest[:-1]) # full sub-package path -> nested boxes
return d
graph = {