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: diagram diff — colour-coded "what changed" between two .drawio (v1.21.0) (#69)

Agents365.aie5786c8cdb1d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef04118..a948bcc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,20 @@ 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.21.0] — 2026-07-03
+### Added
+- **Diagram diff** (`scripts/drawiodiff.py`) — compare two `.drawio` files into a
+ single colour-coded "what changed" graph for autolayout: nodes/edges **added**
+ (green), **removed** (red, dashed), **changed** (orange — a matched node whose
+ label moved), **unchanged** (grey).
+ - Matches by cell **id** by default (stable for importer/live-snapshot output,
+ so *snapshot → change → snapshot → diff* shows **drift** directly — pairs with
+ the v1.20 live importers); `--by-label` matches on visible text for
+ hand-drawn diagrams. Leaf vertices + their edges only; multi-page flattened.
+ - `drawiodiff.py old.drawio new.drawio -o diff.json` → `autolayout.py diff.json`.
+ - Documented in `references/autolayout.md`; SKILL.md router + READMEs updated.
+ Suite now 52.
+
## [1.20.0] — 2026-07-03
### Added
- **Live-infrastructure importers** — draw what's *actually running / deployed*,
diff --git a/README.md b/README.md
index 1700fd6..96e520f 100644
--- a/README.md
+++ b/README.md
@@ -170,6 +170,9 @@ python3 scripts/sqlerd.py schema.sql -o graph.json # SQL DDL → ER dia
python3 scripts/seqlayout.py seq.json -o sequence.drawio # sequence diagram, direct to .drawio
python3 scripts/c4.py c4.json -o c4.drawio # C4 model, multi-page + drill-down
+# Diff two diagrams / snapshots → colour-coded "what changed"
+python3 scripts/drawiodiff.py old.drawio new.drawio -o graph.json # +added -removed ~changed
+
# any extractor → auto-layout → editable .drawio
python3 scripts/autolayout.py graph.json -o diagram.drawio
```
@@ -177,6 +180,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio
| Piece | What it does |
|---|---|
| **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 |
| **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 a48bc21..fc5a770 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -168,6 +168,9 @@ python3 scripts/sqlerd.py schema.sql -o graph.json # SQL DDL → ER 图
python3 scripts/seqlayout.py seq.json -o sequence.drawio # 时序图,直接生成 .drawio
python3 scripts/c4.py c4.json -o c4.drawio # C4 模型,多页 + 下钻
+# 对比两张图 / 两个快照 → 高亮「改了什么」
+python3 scripts/drawiodiff.py old.drawio new.drawio -o graph.json # +新增 -删除 ~变更
+
# 任一提取器 → 自动布局 → 可编辑的 .drawio
python3 scripts/autolayout.py graph.json -o diagram.drawio
```
@@ -175,6 +178,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`(或两个实时快照)对比成一张彩色图 —— 新增=绿、删除=红、变更=橙 —— 一眼看出架构 / 基础设施**漂移** |
| **时序图引擎** | `seqlayout.py` 从消息列表直接算出 lifeline / 激活条 / 箭头几何 —— 不需要 Graphviz,不需要手摆 |
| **自动布局** | Graphviz 自动布点,正交连线**绕开**节点 —— 大图不再需要手动摆坐标。`--tune` 双向各排一次取更可读的 |
| **传递约简** | 删掉被更长路径蕴含的边,把密集的"毛线团"变成可读图(asyncio:149 → 46 条边) |
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 15f2dfe..e5f2b32 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: drawio-skill
-version: 1.20.0
+version: 1.21.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
@@ -49,6 +49,7 @@ When the workflow references one of these, read it on demand — none of them ne
| `scripts/pyclasses.py` | The user wants a **Python class hierarchy / class diagram** — extracts classes + inheritance edges (boxed by module with `--group`) for autolayout |
| `scripts/tfimports.py` · `k8simports.py` · `composeimports.py` | The user wants to visualize **declared** infrastructure (**Terraform** `.tf`, **Kubernetes** manifests, or **docker-compose**) — extracts the resource/service reference graph (official AWS/Azure/GCP/K8s icons for tf/k8s; service boxes + volume cylinders for compose) for autolayout |
| `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/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/references/autolayout.md b/skills/drawio-skill/references/autolayout.md
index b7f2c36..5c9c771 100644
--- a/skills/drawio-skill/references/autolayout.md
+++ b/skills/drawio-skill/references/autolayout.md
@@ -123,6 +123,17 @@ Each code importer keeps only **intra-project** edges (third-party/stdlib import
- **Docker — live** (`dockerimports.py`): reads the JSON array `docker inspect` prints (file or `-`). Containers become rounded boxes (name + image) matching the compose look; the user networks they attach to become green ellipses and the named volumes they mount become cylinders (Docker's built-in `bridge`/`host`/`none`/`ingress` networks and bind mounts are ignored as noise). Edges: container→network, container→volume, plus container→container from `links` and the compose `depends_on` label. `--group` boxes containers by compose project (falling back to first network). The **actually-running** counterpart to composeimports' declared view.
- **SQL DDL** (`sqlerd.py`): regex + paren matching, no SQL library. Handles inline and table-level `PRIMARY KEY`/`FOREIGN KEY ... REFERENCES`, quoted identifiers, `schema.table` prefixes (`--group` boxes by schema). Column lines carry `PK`/`FK` markers and types (`--no-types` to hide). Unknown dialect clauses are skipped, never mis-parsed into edges.
+## Diffing two diagrams (`drawiodiff.py`)
+
+`drawiodiff.py old.drawio new.drawio -o diff.json` compares two `.drawio` files and emits a colour-coded graph JSON for autolayout — one diagram showing **what changed**: nodes/edges added (green), removed (red, dashed), changed (orange, a matched node whose label moved) or unchanged (grey).
+
+```bash
+python3 <this-skill-dir>/scripts/drawiodiff.py old.drawio new.drawio -o diff.json
+python3 <this-skill-dir>/scripts/autolayout.py diff.json -o diff.drawio
+```
+
+Nodes match by cell **id** by default — ideal for anything the importers or live-infra snapshots produce (their ids are stable semantic keys), so *snapshot → change → snapshot → diff* shows drift directly (e.g. two `tfstate.py` or `k8simports.py` snapshots). Pass `--by-label` to match on the visible label instead, for hand-drawn diagrams whose ids are random. Only leaf vertices and their edges are compared (containers/group cells and edge labels are skipped); the diff is a flat colour-coded view, so original icons are replaced by status colours (labels are kept). Multi-page files are flattened; compressed pages are skipped with a warning (this skill always writes uncompressed XML).
+
The tf/k8s importers emit `ranksep`/`nodesep` in the graph JSON automatically (icon labels render *below* the shape, so rows need extra separation).
**`--tune` (autolayout flag)**: lays the graph out in both directions (TB and LR), scores each (through-vertex routes ×20 + edge crossings ×10 + total edge length as tiebreak), and keeps the better one — report on stderr. `validate.py --score` prints the same style of readability score for a finished `.drawio`, for comparing variants.
diff --git a/skills/drawio-skill/scripts/drawiodiff.py b/skills/drawio-skill/scripts/drawiodiff.py
new file mode 100644
index 0000000..68f1e26
--- /dev/null
+++ b/skills/drawio-skill/scripts/drawiodiff.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python3
+"""Diff two .drawio diagrams into a colour-coded autolayout graph JSON.
+
+Compares an OLD and a NEW .drawio and emits a single graph where every node and
+edge is tinted by what happened to it:
+
+ added (in new only) -> green
+ removed (in old only) -> red, dashed
+ changed (matched, label moved) -> orange
+ same (matched, unchanged) -> grey
+
+The output is a normal graph JSON — feed it to autolayout.py for one clean,
+freshly laid-out "what changed" diagram:
+
+ python3 drawiodiff.py old.drawio new.drawio -o diff.json
+ python3 autolayout.py diff.json -o diff.drawio
+
+Nodes are matched by cell **id** (the default) — perfect for diagrams the
+bundled importers generate, whose ids are stable semantic keys
+(`aws_instance.web`, `shop-db-1`), so two snapshots line up exactly. This makes
+it the natural companion to the live-infra importers: snapshot `terraform show
+-json` / `docker inspect` / `kubectl get -o json` twice and diff the two to see
+drift. For hand-drawn diagrams whose ids are random, pass `--by-label` to match
+on the visible label text instead.
+
+Only leaf vertices and the edges between them are compared; container/group
+cells and edge labels are skipped. The diff is a flat colour-coded view, so the
+original icons/shapes are replaced by status colours (the label is kept).
+
+Usage: python3 drawiodiff.py <old.drawio> <new.drawio> [-o diff.json]
+ [--direction TB|LR] [--by-label]
+"""
+import argparse
+import json
+import sys
+import xml.etree.ElementTree as ET
+
+STYLE = {
+ "added": "rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;",
+ "removed": "rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;dashed=1;",
+ "changed": "rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;",
+ "same": "rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#999999;",
+}
+EDGE_STYLE = {
+ "added": "endArrow=classic;html=1;strokeColor=#82b366;strokeWidth=2;",
+ "removed": "endArrow=classic;html=1;strokeColor=#b85450;strokeWidth=2;dashed=1;",
+ "same": "endArrow=classic;html=1;strokeColor=#999999;",
+}
+
+
+def parse(path):
+ """Return (nodes, edges) for a .drawio: nodes {id: (label, style)} for leaf
+ vertices, edges {(source_id, target_id)}. Cells are flattened across pages;
+ UserObject/object wrappers are unwrapped (id on the wrapper, cell inside)."""
+ try:
+ tree = ET.parse(path)
+ except (ET.ParseError, OSError) as exc:
+ sys.exit(f"error: cannot parse {path}: {exc}")
+ pages = tree.getroot().findall("diagram") or [tree.getroot()]
+ cells, labels = [], {}
+ for page in pages:
+ model = page.find("mxGraphModel")
+ root = model.find("root") if model is not None else None
+ if root is None:
+ if (page.text or "").strip():
+ sys.stderr.write(f"warning: {path}: a page is compressed, skipped\n")
+ continue
+ for child in root:
+ if child.tag == "mxCell":
+ cells.append(child)
+ labels[child.get("id")] = child.get("value") or ""
+ elif child.tag in ("UserObject", "object"):
+ inner = child.find("mxCell")
+ if inner is not None:
+ inner.set("id", child.get("id", ""))
+ cells.append(inner)
+ labels[child.get("id")] = child.get("label") or child.get("value") or ""
+ parents = {c.get("parent") for c in cells} # ids that have children
+ nodes, edges = {}, set()
+ for c in cells:
+ cid = c.get("id")
+ if c.get("edge") == "1":
+ s, t = c.get("source"), c.get("target")
+ if s and t:
+ edges.add((s, t))
+ elif c.get("vertex") == "1" and cid not in parents: # leaf vertices only
+ if "edgeLabel" in (c.get("style") or ""):
+ continue
+ g = c.find("mxGeometry")
+ if g is not None and g.get("relative") == "1": # edge-label child
+ continue
+ nodes[cid] = (labels.get(cid, ""), c.get("style") or "")
+ return nodes, edges
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Diff two .drawio files -> autolayout graph JSON.")
+ ap.add_argument("old", help="baseline .drawio")
+ ap.add_argument("new", help="updated .drawio")
+ ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")
+ ap.add_argument("--direction", default="TB", choices=["TB", "LR"])
+ ap.add_argument("--by-label", action="store_true",
+ help="match nodes by visible label instead of cell id "
+ "(for hand-drawn diagrams with non-stable ids)")
+ args = ap.parse_args()
+
+ old_n, old_e = parse(args.old)
+ new_n, new_e = parse(args.new)
+
+ def keyed(nodes):
+ """Map match-key -> label. By id (default) the key is the cell id and the
+ value is its label; by label the key *is* the label."""
+ if args.by_label:
+ return {lbl: lbl for lbl, _ in nodes.values()}, {i: lbl for i, (lbl, _) in nodes.items()}
+ return {i: lbl for i, (lbl, _) in nodes.items()}, {i: i for i in nodes}
+
+ old_keys, old_id2key = keyed(old_n)
+ new_keys, new_id2key = keyed(new_n)
+
+ nodes, counts = [], {"added": 0, "removed": 0, "changed": 0, "same": 0}
+ for key in sorted(set(old_keys) | set(new_keys)):
+ if key in old_keys and key not in new_keys:
+ status, label = "removed", old_keys[key]
+ elif key in new_keys and key not in old_keys:
+ status, label = "added", new_keys[key]
+ elif old_keys[key] != new_keys[key]: # matched, label moved
+ status, label = "changed", new_keys[key]
+ else:
+ status, label = "same", new_keys[key]
+ counts[status] += 1
+ nodes.append({"id": key, "label": label or key, "style": STYLE[status],
+ "width": 160, "height": 60})
+
+ def edge_keys(edges, id2key):
+ out = set()
+ for s, t in edges:
+ if s in id2key and t in id2key:
+ out.add((id2key[s], id2key[t]))
+ return out
+
+ old_ek, new_ek = edge_keys(old_e, old_id2key), edge_keys(new_e, new_id2key)
+ node_keys = {n["id"] for n in nodes}
+ edges = []
+ for s, t in sorted(old_ek | new_ek):
+ if s not in node_keys or t not in node_keys:
+ continue
+ status = "same" if (s, t) in old_ek and (s, t) in new_ek else \
+ ("added" if (s, t) in new_ek else "removed")
+ edges.append({"source": s, "target": t, "style": EDGE_STYLE[status]})
+
+ graph = {"direction": args.direction, "nodes": nodes, "edges": edges}
+ text = json.dumps(graph, indent=2)
+ 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)
+ sys.stderr.write(f"+{counts['added']} added, -{counts['removed']} removed, "
+ f"~{counts['changed']} changed, ={counts['same']} unchanged\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 12ecec2..685177d 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -651,6 +651,65 @@ class TestImportersCli(unittest.TestCase):
self.assertEqual({n["id"] for n in graph["nodes"]},
{"shop/Service/web", "shop/Deployment/web", "shop/ConfigMap/cfg"})
+ @staticmethod
+ def _drawio(nodes, edges):
+ """Minimal .drawio XML from (id, label) nodes and (src, tgt) edges."""
+ cells = ['<mxCell id="0"/>', '<mxCell id="1" parent="0"/>']
+ for i, (cid, label) in enumerate(nodes):
+ cells.append(f'<mxCell id="{cid}" value="{label}" vertex="1" parent="1" '
+ f'style="rounded=1;"><mxGeometry x="{i*200}" y="0" '
+ 'width="120" height="60" as="geometry"/></mxCell>')
+ for i, (s, t) in enumerate(edges):
+ cells.append(f'<mxCell id="e{i}" edge="1" parent="1" source="{s}" '
+ 'target="{}"><mxGeometry relative="1" as="geometry"/></mxCell>'.format(t))
+ return ('<mxfile><diagram name="P"><mxGraphModel><root>'
+ + "".join(cells) + "</root></mxGraphModel></diagram></mxfile>")
+
+ @staticmethod
+ def _status(style):
+ for tag, hue in (("added", "82b366"), ("removed", "b85450"),
+ ("changed", "d79b00"), ("same", "999999")):
+ if hue in style:
+ return tag
+ return "?"
+
+ def test_drawiodiff_by_id(self):
+ # api label moves (changed), cache removed, worker added, db unchanged.
+ old = self._drawio([("api", "api v1"), ("db", "db"), ("cache", "cache")],
+ [("api", "db"), ("api", "cache")])
+ new = self._drawio([("api", "api v2"), ("db", "db"), ("worker", "worker")],
+ [("api", "db"), ("api", "worker")])
+ with tempfile.TemporaryDirectory() as d:
+ self._write(os.path.join(d, "old.drawio"), old)
+ self._write(os.path.join(d, "new.drawio"), new)
+ graph = json.loads(run("drawiodiff.py", os.path.join(d, "old.drawio"),
+ os.path.join(d, "new.drawio")).stdout)
+ status = {n["id"]: self._status(n["style"]) for n in graph["nodes"]}
+ self.assertEqual(status, {"api": "changed", "db": "same",
+ "cache": "removed", "worker": "added"})
+ estatus = {(e["source"], e["target"]): self._status(e["style"])
+ for e in graph["edges"]}
+ self.assertEqual(estatus, {("api", "db"): "same",
+ ("api", "cache"): "removed",
+ ("api", "worker"): "added"})
+
+ def test_drawiodiff_by_label(self):
+ # ids differ across versions; --by-label matches on the visible text.
+ old = self._drawio([("x1", "API"), ("x2", "DB")], [])
+ new = self._drawio([("y9", "API"), ("y8", "Cache")], [])
+ with tempfile.TemporaryDirectory() as d:
+ self._write(os.path.join(d, "old.drawio"), old)
+ self._write(os.path.join(d, "new.drawio"), new)
+ base = run("drawiodiff.py", os.path.join(d, "old.drawio"),
+ os.path.join(d, "new.drawio"))
+ # Without --by-label the random ids make everything add/remove.
+ self.assertNotIn("same", {self._status(n["style"])
+ for n in json.loads(base.stdout)["nodes"]})
+ graph = json.loads(run("drawiodiff.py", os.path.join(d, "old.drawio"),
+ os.path.join(d, "new.drawio"), "--by-label").stdout)
+ status = {n["id"]: self._status(n["style"]) for n in graph["nodes"]}
+ self.assertEqual(status, {"API": "same", "DB": "removed", "Cache": "added"})
+
SQL = ("CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255));\n"
"CREATE TABLE orders (\n"
" id INT,\n"