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: explain.py — describe a .drawio as structured Markdown (v1.23.0) (#71)

Agents365.ai74690c4366c1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 128206f..9dbbbd4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,18 @@ All notable changes to **drawio-skill** are documented here. The format is based
on [Keep a Changelog](https://keepachangelog.com/), and the project follows
semantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).
+## [1.23.0] — 2026-07-03
+### Added
+- **Diagram → Markdown** (`scripts/explain.py`) — the inverse of the generators:
+ read a `.drawio` and describe it as structured Markdown. Lists components
+ grouped by their container / swimlane / tier, relations (`A —label→ B`, the
+ edge label becomes the verb), and a section per page for multi-page / C4
+ files. A handful of common shapes are named (data store, actor, decision,
+ queue, cloud, AWS/Azure/GCP/Kubernetes). Handy for dropping an architecture
+ summary into a README or PR, or a text-only read-out of a handed-over diagram.
+ - `explain.py diagram.drawio` (Markdown to stdout) or `-o out.md`.
+ - SKILL.md router + READMEs updated. Suite now 56.
+
## [1.22.0] — 2026-07-03
### Added
- **Architecture time-lapse** (`scripts/timelapse.py`) — animate how a codebase's
diff --git a/README.md b/README.md
index c10bdee..b7889d2 100644
--- a/README.md
+++ b/README.md
@@ -176,6 +176,9 @@ python3 scripts/drawiodiff.py old.drawio new.drawio -o graph.json # +added -remo
# Architecture time-lapse → self-contained HTML player of how a codebase grew
python3 scripts/timelapse.py src --importer pyimports # → architecture-evolution.html
+# Reverse: describe an existing .drawio as structured Markdown (README / PR summary)
+python3 scripts/explain.py architecture.drawio -o architecture.md
+
# any extractor → auto-layout → editable .drawio
python3 scripts/autolayout.py graph.json -o diagram.drawio
```
@@ -185,6 +188,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio
| **11 extractors** | import graphs for **Python · JS/TS · Go · Rust**, **Python class inheritance**, **Terraform / Kubernetes / docker-compose** resource graphs (official cloud icons), **SQL DDL → ERD**, and **live** infra from `terraform show -json` / `docker inspect` / `kubectl get -o json` (draw what's actually deployed) |
| **Diagram diff** | `drawiodiff.py` compares two `.drawio` (or two live snapshots) into one colour-coded graph — added=green, removed=red, changed=orange — so you can see architecture / infra **drift** at a glance |
| **Architecture time-lapse** | `timelapse.py` re-runs an importer across a repo's git history and assembles a self-contained HTML player — watch modules & edges appear over time (▶ play / ‹ › step) |
+| **Diagram → Markdown** | `explain.py` reverses a `.drawio` into a structured description — components by tier, relations, per-page for C4 — for dropping an architecture summary into a README or PR |
| **Sequence engine** | `seqlayout.py` computes lifeline / activation-bar / arrow geometry from a message list — no Graphviz, no hand placement |
| **Auto-layout** | Graphviz places nodes and routes orthogonal edges *around* them — removes the manual-coordinate ceiling for large graphs. `--tune` tries both directions and keeps the more readable one |
| **Transitive reduction** | drops edges implied by a longer path, turning a dense hairball into a traceable graph (asyncio: 149 → 46 edges) |
diff --git a/README_CN.md b/README_CN.md
index 83ba3e8..d7062e8 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -174,6 +174,9 @@ python3 scripts/drawiodiff.py old.drawio new.drawio -o graph.json # +新增 -删
# 架构时间轴 → 从 git 历史生成「代码怎么长出来的」自包含 HTML 播放器
python3 scripts/timelapse.py src --importer pyimports # → architecture-evolution.html
+# 反向:把已有的 .drawio 描述成结构化 Markdown(README / PR 摘要)
+python3 scripts/explain.py architecture.drawio -o architecture.md
+
# 任一提取器 → 自动布局 → 可编辑的 .drawio
python3 scripts/autolayout.py graph.json -o diagram.drawio
```
@@ -183,6 +186,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio
| **11 个提取器** | **Python · JS/TS · Go · Rust** 的导入关系图、**Python 类继承**、**Terraform / Kubernetes / docker-compose** 资源图(自动配官方云图标)、**SQL DDL → ER 图**,以及从 `terraform show -json` / `docker inspect` / `kubectl get -o json` 提取的**实时**基础设施(画出真正已部署的样子) |
| **图对比 (diff)** | `drawiodiff.py` 把两张 `.drawio`(或两个实时快照)对比成一张彩色图 —— 新增=绿、删除=红、变更=橙 —— 一眼看出架构 / 基础设施**漂移** |
| **架构时间轴** | `timelapse.py` 沿 git 历史逐个提交重跑提取器,拼成一个自包含 HTML 播放器 —— 看着模块和依赖边随时间长出来(▶ 播放 / ‹ › 单步) |
+| **图 → Markdown** | `explain.py` 把一张 `.drawio` 反向描述成结构化文档 —— 按层级列出组件、关系、C4 多页分节 —— 方便把架构摘要塞进 README 或 PR |
| **时序图引擎** | `seqlayout.py` 从消息列表直接算出 lifeline / 激活条 / 箭头几何 —— 不需要 Graphviz,不需要手摆 |
| **自动布局** | Graphviz 自动布点,正交连线**绕开**节点 —— 大图不再需要手动摆坐标。`--tune` 双向各排一次取更可读的 |
| **传递约简** | 删掉被更长路径蕴含的边,把密集的"毛线团"变成可读图(asyncio:149 → 46 条边) |
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 7877f3e..429f0c4 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: drawio-skill
-version: 1.22.0
+version: 1.23.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, network topology, cloud architecture from Terraform or Kubernetes manifests, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.
license: MIT
homepage: https://github.com/Agents365-ai/drawio-skill
@@ -51,6 +51,7 @@ When the workflow references one of these, read it on demand — none of them ne
| `scripts/tfstate.py` · `dockerimports.py` (+ `k8simports.py`) | The user wants to draw **what is ACTUALLY running / deployed** — pipe `terraform show -json` (deployed state), `docker inspect $(docker ps -q)` (live containers), or `kubectl get all,ing,cm,secret,pvc -o json` (live cluster, via k8simports) and get the real topology with the same official icons. See `references/live-infra.md` |
| `scripts/drawiodiff.py` | The user wants to **compare / diff two diagrams or two snapshots** ("what changed", infra drift) — `drawiodiff.py old.drawio new.drawio -o diff.json` emits a colour-coded graph (added=green, removed=red, changed=orange, same=grey) for autolayout. Matches by cell id (importer/live-snapshot output) or `--by-label` (hand-drawn) |
| `scripts/timelapse.py` | The user wants an **architecture time-lapse / to see how a codebase's structure evolved over git history** — `timelapse.py <dir> --importer pyimports` re-runs an importer at each sampled commit and assembles a self-contained HTML player (embedded frames, play/step controls). Best on a package with real import edges (point `<dir>` at the module root) |
+| `scripts/explain.py` | The user wants to **describe / document / summarize an existing `.drawio` in words** (reverse of generating one) — `explain.py diagram.drawio` emits structured Markdown: components grouped by container/tier, relations (`A —label→ B`), per-page sections for multi-page/C4. Good for a README/PR summary or a text-only read-out |
| `scripts/sqlerd.py` | The user wants an **ER diagram from SQL DDL** — parses `CREATE TABLE` statements into per-table nodes (columns with PK/FK markers) and crow's-foot FK edges for autolayout |
| `scripts/seqlayout.py` | The user wants a **sequence diagram** — describe participants + messages as JSON and the script computes all lifeline/activation/arrow geometry deterministically (no hand-placed coordinates, no Graphviz needed) |
| `scripts/c4.py` | The user wants a **C4 model** (System Context / Container / Component) — levels JSON in, one multi-page `.drawio` out with official C4 shapes/colors and **click-to-drill-down** links between levels |
diff --git a/skills/drawio-skill/scripts/explain.py b/skills/drawio-skill/scripts/explain.py
new file mode 100644
index 0000000..b2ad7ef
--- /dev/null
+++ b/skills/drawio-skill/scripts/explain.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""Read a .drawio and describe it as structured Markdown.
+
+The inverse of the skill's generators: instead of data -> diagram, this turns a
+diagram -> documentation. It lists the components (grouped by their container /
+swimlane / tier), the relations between them (edge labels become the relation
+verb), and a per-page breakdown for multi-page files (e.g. a C4 model). Handy
+for dropping an architecture summary into a README or PR, or for a text-only
+description of a diagram someone handed you.
+
+ python3 explain.py architecture.drawio # Markdown to stdout
+ python3 explain.py c4.drawio -o architecture.md
+
+Components are the leaf vertices; a vertex that contains others is treated as a
+container and becomes a grouping heading. Relations read `source -> target`,
+annotated with the edge label when present. A handful of common shapes are
+named (data store, actor, decision, queue, cloud, and AWS/Azure/GCP/Kubernetes
+vendor icons). UserObject/object wrappers are unwrapped; compressed pages are
+reported but cannot be described (this skill always writes uncompressed XML).
+
+Usage: python3 explain.py <file.drawio> [-o out.md]
+"""
+import argparse
+import html
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+# style fragment -> human noun. First match wins; order matters (specific first).
+SHAPE_TYPES = [
+ ("mxgraph.aws", "AWS"), ("img/lib/azure", "Azure"), ("mxgraph.gcp", "GCP"),
+ ("mxgraph.kubernetes", "Kubernetes"), ("umlActor", "actor"), ("shape=actor", "actor"),
+ ("shape=cylinder", "data store"), ("shape=datastore", "data store"),
+ ("shape=cloud", "cloud"), ("rhombus", "decision"), ("mscae", "Azure"),
+ ("shape=process", "process"), ("shape=hexagon", "queue"),
+]
+
+
+def clean(text):
+ """Strip HTML tags/entities draw.io stores in labels; collapse whitespace."""
+ if not text:
+ return ""
+ text = re.sub(r"<br\s*/?>", " ", text, flags=re.I)
+ text = re.sub(r"<[^>]+>", "", text)
+ return re.sub(r"\s+", " ", html.unescape(text)).strip()
+
+
+def shape_of(style):
+ for frag, noun in SHAPE_TYPES:
+ if frag in (style or ""):
+ return noun
+ return None
+
+
+def cells_of(page):
+ """[(cell, id, label)] for a page, unwrapping UserObject/object wrappers."""
+ model = page.find("mxGraphModel")
+ root = model.find("root") if model is not None else None
+ if root is None:
+ return None # compressed / empty page
+ out = []
+ for child in root:
+ if child.tag == "mxCell":
+ out.append((child, child.get("id"), clean(child.get("value"))))
+ elif child.tag in ("UserObject", "object"):
+ inner = child.find("mxCell")
+ if inner is not None:
+ inner.set("id", child.get("id", ""))
+ out.append((inner, child.get("id"),
+ clean(child.get("label") or child.get("value"))))
+ return out
+
+
+def describe_page(page):
+ """Markdown body lines for one <diagram> page (no page heading)."""
+ cells = cells_of(page)
+ if cells is None:
+ return ["_(compressed page — cannot describe)_"]
+ label = {cid: lbl for _, cid, lbl in cells}
+ style = {cid: (c.get("style") or "") for c, cid, _ in cells}
+ parents = {c.get("parent") for c, _, _ in cells if c.get("parent")}
+
+ vertices = [(c, cid) for c, cid, _ in cells if c.get("vertex") == "1"]
+ containers = {cid for c, cid in vertices if cid in parents} # holds other cells
+ leaves = [(c, cid) for c, cid in vertices
+ if cid not in containers and "edgeLabel" not in style.get(cid, "")]
+
+ # Group leaves by their container's label (else "Ungrouped").
+ groups, order = {}, []
+ for c, cid in leaves:
+ parent = c.get("parent")
+ gname = label.get(parent) or "" if parent in containers else ""
+ gname = gname or "Ungrouped"
+ if gname not in groups:
+ groups[gname] = []
+ order.append(gname)
+ typ = shape_of(style.get(cid, ""))
+ name = label.get(cid) or f"(unlabeled {cid})"
+ groups[gname].append(f"{name}" + (f" _{typ}_" if typ else ""))
+
+ lines = [f"### Components ({len(leaves)})", ""]
+ single = len(order) == 1 and order[0] == "Ungrouped"
+ for gname in order:
+ if not single:
+ lines.append(f"- **{gname}**")
+ lines += [f" - {item}" for item in groups[gname]]
+ else:
+ lines += [f"- {item}" for item in groups[gname]]
+ lines.append("")
+
+ edges = [c for c, _, _ in cells if c.get("edge") == "1"]
+ rels = []
+ for e in edges:
+ s, t = label.get(e.get("source")), label.get(e.get("target"))
+ if not s or not t: # dangling endpoint — skip
+ continue
+ verb = clean(e.get("value"))
+ rels.append(f"- {s} —{verb}→ {t}" if verb else f"- {s} → {t}")
+ lines.append(f"### Relations ({len(rels)})")
+ lines.append("")
+ lines += rels or ["_(none)_"]
+ lines.append("")
+ return lines
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Describe a .drawio diagram as Markdown.")
+ ap.add_argument("file")
+ ap.add_argument("-o", "--output", help="output Markdown path (default: stdout)")
+ 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()]
+
+ title = args.file.rsplit("/", 1)[-1].rsplit(".", 1)[0]
+ lines = [f"# {title}", ""]
+ for i, page in enumerate(pages, 1):
+ name = page.get("name")
+ if len(pages) > 1:
+ lines.append(f"## Page {i}: {name}" if name else f"## Page {i}")
+ lines.append("")
+ lines += describe_page(page)
+
+ text = "\n".join(lines).rstrip() + "\n"
+ if args.output:
+ with open(args.output, "w", encoding="utf-8") as f:
+ f.write(text)
+ sys.stderr.write(f"wrote {args.output}\n")
+ else:
+ sys.stdout.write(text)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 9cf8a59..a673a15 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -734,6 +734,51 @@ class TestImportersCli(unittest.TestCase):
self.assertIn('"n": 9', html)
self.assertIn('"e": 12', html)
+ # A container ("Tier") holding A + B, an ungrouped cylinder DB, one labeled edge.
+ EXPLAIN_PAGE = (
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<mxCell id="grp" value="Tier" vertex="1" parent="1" style="group">'
+ '<mxGeometry x="0" y="0" width="240" height="120" as="geometry"/></mxCell>'
+ '<mxCell id="a" value="A" vertex="1" parent="grp" style="rounded=1;">'
+ '<mxGeometry x="10" y="30" width="80" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="b" value="B" vertex="1" parent="grp" style="rounded=1;">'
+ '<mxGeometry x="120" y="30" width="80" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="c" value="DB" vertex="1" parent="1" style="shape=cylinder3;">'
+ '<mxGeometry x="400" y="0" width="80" height="80" as="geometry"/></mxCell>'
+ '<mxCell id="e1" value="reads" edge="1" parent="1" source="a" target="c">'
+ '<mxGeometry relative="1" as="geometry"/></mxCell>')
+
+ def test_explain_groups_shapes_relations(self):
+ doc = ('<mxfile><diagram name="P1"><mxGraphModel><root>'
+ + self.EXPLAIN_PAGE + "</root></mxGraphModel></diagram></mxfile>")
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, "arch.drawio")
+ self._write(path, doc)
+ md = run("explain.py", path).stdout
+ self.assertIn("### Components (3)", md) # A, B, DB (grp is a container)
+ self.assertIn("- **Tier**", md) # container -> grouping heading
+ self.assertIn("- A", md)
+ self.assertIn("DB _data store_", md) # cylinder -> data store
+ self.assertIn("A —reads→ DB", md) # labeled relation
+ self.assertNotIn("- Tier _", md) # container itself isn't a component
+
+ def test_explain_multipage(self):
+ doc = ('<mxfile>'
+ '<diagram name="P1"><mxGraphModel><root>' + self.EXPLAIN_PAGE
+ + '</root></mxGraphModel></diagram>'
+ '<diagram name="P2"><mxGraphModel><root>'
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<mxCell id="x" value="Solo" vertex="1" parent="1" style="rounded=1;">'
+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'
+ '</root></mxGraphModel></diagram></mxfile>')
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, "multi.drawio")
+ self._write(path, doc)
+ md = run("explain.py", path).stdout
+ self.assertIn("## Page 1: P1", md)
+ self.assertIn("## Page 2: P2", md)
+ self.assertIn("- Solo", md)
+
SQL = ("CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255));\n"
"CREATE TABLE orders (\n"
" id INT,\n"