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.
Python agent-skillsarchitecturearchitecture-diagramasyncapibpmnc4-modelclaude-codediagramdiagrams-as-codedrawioflowchartgithub-actionsgraphqlimage-to-diagramkubernetesmcp-serverprotobufsysmlterraformuml
feat: OpenAPI/Swagger API diagrams + metric heat maps (v1.27.0) (#76)
Agents365.aie921d0c53072
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8e6c8ab..57bb897 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,28 @@ All notable changes to **drawio-skill** are documented here. The format is basedon [Keep a Changelog](https://keepachangelog.com/), and the project followssemantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).+## [1.27.0] — 2026-07-04+### Added+- **OpenAPI / Swagger → API diagram** (`scripts/openapiimports.py`) — turn an+ OpenAPI 3 or Swagger 2 spec (JSON, or YAML with PyYAML) into a graph for+ autolayout: one node per operation **coloured by HTTP method** (GET blue, POST+ green, PUT/PATCH orange, DELETE red) plus one node per component schema, with+ edges from each operation to the schemas it references (request/response+ bodies) and between schemas that nest one another. `--group` boxes operations+ by tag; `--no-schemas` shows just the endpoint surface. `$ref`s resolve to+ their final name; only schemas under `components`/`definitions` become nodes.+- **Metric heat map** (`scripts/heatmap.py`) — recolour an existing `.drawio` by+ data: pass a metrics file (CSV `key,value` or JSON `{key: value}`) and each+ node is matched by cell id or label and shaded along a gradient from the+ lowest value to the highest — a cost / latency / traffic / error-rate heat map+ over any architecture diagram. `--palette heat|cool|warm`, `--reverse`,+ `--size` (scale nodes by value), and an auto legend placed clear of the+ content. Unmatched nodes keep their style; post-processes any diagram, export+ as usual.+ - Both verified end-to-end (spec → grouped API PNG; architecture + latency CSV+ → heat map PNG with legend + sizing). SKILL.md router + toolbox.md + READMEs+ updated; script count 25 → 27. Suite now 69.+## [1.26.1] — 2026-07-04### Added- **`references/toolbox.md`** — a use-case map of all 25 bundled scriptsdiff --git a/README.md b/README.mdindex 67926a2..7edc0bb 100644--- a/README.md+++ b/README.md@@ -167,6 +167,7 @@ kubectl get all,ing,cm,secret,pvc -o json | python3 scripts/k8simports.py - -o g# Data & interactionspython3 scripts/sqlerd.py schema.sql -o graph.json # SQL DDL → ER diagram+python3 scripts/openapiimports.py openapi.yaml -o graph.json # OpenAPI/Swagger → API diagram (by method)python3 scripts/seqlayout.py seq.json -o sequence.drawio # sequence diagram, direct to .drawiopython3 scripts/c4.py c4.json -o c4.drawio # C4 model, multi-page + drill-down@@ -188,14 +189,18 @@ python3 scripts/svgflow.py architecture.drawio -o flow.svg# Reverse: .drawio → Mermaid flowchart (diagrams-as-code GitHub renders)python3 scripts/drawio2mermaid.py architecture.drawio --fenced -o arch.md+# Colour an existing .drawio by data → cost / latency / traffic heat map+python3 scripts/heatmap.py architecture.drawio -m latency.csv --size -o hot.drawio+# any extractor → auto-layout → editable .drawiopython3 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) |+| **12 extractors** | import graphs for **Python · JS/TS · Go · Rust**, **Python class inheritance**, **Terraform / Kubernetes / docker-compose** resource graphs (official cloud icons), **SQL DDL → ERD**, **OpenAPI / Swagger → API diagram** (operations coloured by HTTP method + schemas), 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 |+| **Metric heat map** | `heatmap.py` recolours an existing `.drawio` from a CSV/JSON of per-node values — cost / latency / traffic / error-rate shaded low→high on a gradient (optional size-by-value + legend), matched by cell id or label || **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 || **Diagram → PowerPoint** | `drawio2pptx.py` turns a multi-page diagram into a 16:9 deck (one page per slide, page name as title) — a C4 model becomes a ready-to-present slideshow |diff --git a/README_CN.md b/README_CN.mdindex 15121a0..02beaba 100644--- a/README_CN.md+++ b/README_CN.md@@ -165,6 +165,7 @@ kubectl get all,ing,cm,secret,pvc -o json | python3 scripts/k8simports.py - -o g# 数据与交互python3 scripts/sqlerd.py schema.sql -o graph.json # SQL DDL → ER 图+python3 scripts/openapiimports.py openapi.yaml -o graph.json # OpenAPI/Swagger → API 图(按方法着色)python3 scripts/seqlayout.py seq.json -o sequence.drawio # 时序图,直接生成 .drawiopython3 scripts/c4.py c4.json -o c4.drawio # C4 模型,多页 + 下钻@@ -186,14 +187,18 @@ python3 scripts/svgflow.py architecture.drawio -o flow.svg# 反向:.drawio → Mermaid 流程图(GitHub 原生渲染的 diagrams-as-code)python3 scripts/drawio2mermaid.py architecture.drawio --fenced -o arch.md+# 按数据给已有 .drawio 上色 → 成本 / 延迟 / 流量热力图+python3 scripts/heatmap.py architecture.drawio -m latency.csv --size -o hot.drawio+# 任一提取器 → 自动布局 → 可编辑的 .drawiopython3 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` 提取的**实时**基础设施(画出真正已部署的样子) |+| **12 个提取器** | **Python · JS/TS · Go · Rust** 的导入关系图、**Python 类继承**、**Terraform / Kubernetes / docker-compose** 资源图(自动配官方云图标)、**SQL DDL → ER 图**、**OpenAPI / Swagger → API 图**(按 HTTP 方法着色的接口 + schema),以及从 `terraform show -json` / `docker inspect` / `kubectl get -o json` 提取的**实时**基础设施(画出真正已部署的样子) || **图对比 (diff)** | `drawiodiff.py` 把两张 `.drawio`(或两个实时快照)对比成一张彩色图 —— 新增=绿、删除=红、变更=橙 —— 一眼看出架构 / 基础设施**漂移** |+| **指标热力图** | `heatmap.py` 按一份「节点→数值」的 CSV/JSON 给已有 `.drawio` 重新着色 —— 成本 / 延迟 / 流量 / 错误率沿渐变由低到高上色(可选按值缩放节点 + 自动图例),按 cell id 或标签匹配 || **架构时间轴** | `timelapse.py` 沿 git 历史逐个提交重跑提取器,拼成一个自包含 HTML 播放器 —— 看着模块和依赖边随时间长出来(▶ 播放 / ‹ › 单步) || **图 → Markdown** | `explain.py` 把一张 `.drawio` 反向描述成结构化文档 —— 按层级列出组件、关系、C4 多页分节 —— 方便把架构摘要塞进 README 或 PR || **图 → PowerPoint** | `drawio2pptx.py` 把多页图变成 16:9 幻灯片(每页一张、页名当标题)—— C4 模型一键变成可演示的 slideshow |diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex f82084a..c162ad5 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -1,6 +1,6 @@---name: drawio-skill-version: 1.26.1+version: 1.27.0description: 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: MIThomepage: https://github.com/Agents365-ai/drawio-skill@@ -34,7 +34,7 @@ When the workflow references one of these, read it on demand — none of them ne| File | Read it when ||---|---|-| `references/toolbox.md` | You're **not sure which bundled script fits** a request, or want to chain several — a map of all 25 scripts grouped by use-case (author / import code / import IaC / live infra / compare / reverse-export / utilities) with an "I have X, I want Y → use Z" guide |+| `references/toolbox.md` | You're **not sure which bundled script fits** a request, or want to chain several — a map of all 27 scripts grouped by use-case (author / import code / import IaC / import API spec / live infra / compare / annotate / reverse-export / utilities) with an "I have X, I want Y → use Z" guide || `references/xml-authoring.md` | You're about to **hand-write `.drawio` XML** (workflow step 3) — file skeleton, shape/edge cells, containers, connection distribution, palette, spacing/grid rules. Not needed when a bundled generator writes the XML || `references/mermaid-authoring.md` | The diagram is a **standard type with no custom styling/icon needs** (flowchart, state, gantt, mindmap, timeline, journey, pie, …) and the CLI is **≥ v30** — author it as Mermaid text and let the CLI convert to native `.drawio` (structure only, layout free). Also documents the CLI's ELK `--layout` pass for XML || `references/diagram-types.md` | The user names a specific diagram type (ERD, UML class, sequence, C4, architecture, ML/DL, flowchart) |@@ -57,6 +57,8 @@ When the workflow references one of these, read it on demand — none of them ne| `scripts/svgflow.py` | The user wants an **animated / "flowing" diagram** (data-flow, moving edges) — `svgflow.py diagram.drawio -o flow.svg` exports to SVG and makes every edge a marching-ants animation (dashes travel along the arrows). Self-contained looping `.svg` that renders on GitHub / any browser; `--speed` / `--dash` / `--reverse` || `scripts/drawio2mermaid.py` | The user wants to **convert a `.drawio` into Mermaid text** (diagrams-as-code for a Markdown file that GitHub renders) — `drawio2mermaid.py diagram.drawio` emits a `flowchart` (containers → `subgraph`s, edge labels kept, cylinder/rhombus shapes mapped); `--fenced` wraps in ```mermaid, multi-page → one graph per page. Structural only (styling/icons don't survive) || `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/openapiimports.py` | The user wants an **API diagram from an OpenAPI / Swagger spec** — `openapiimports.py spec.yaml` maps each operation to a node **coloured by HTTP method** (GET blue, POST green, PUT/PATCH orange, DELETE red) plus one node per component schema, with edges from operations to the schemas they use and between nested schemas. `--group` boxes by tag, `--no-schemas` shows just the endpoint surface; feeds autolayout |+| `scripts/heatmap.py` | The user wants to **colour an existing `.drawio` by data** (a cost / latency / traffic / error-rate heat map) — `heatmap.py diagram.drawio -m metrics.csv` matches each metric (CSV `key,value` or JSON `{key:value}`) to a node by id or label and recolours it along a gradient (`--palette heat\|cool\|warm`, `--reverse`), optionally scaling node size (`--size`) and adding a legend. Post-processes any diagram; export as usual || `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 || `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. `--score` prints a readability score for comparing layout variants |@@ -109,7 +111,7 @@ When a preset loads successfully, mention it in the first line of the reply: *"U1. **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). **Also note the major version** the command printed: **≥ 30** unlocks Mermaid→`.drawio` conversion and the ELK `--layout` pass (see `references/mermaid-authoring.md`); on **≤ 29** both are unavailable — `.mmd` input fails and `--layout` corrupts argument parsing — so never emit those flags there.2. **Plan** — identify shapes, relationships, layout (LR or TB), group by tier/layer-3. **Generate** — produce the `.drawio` file, choosing the authoring mode: **(a) Mermaid → CLI convert** when the diagram is a standard type with no custom styling/icon needs **and** the CLI is ≥ v30 — write a `.mmd` and run `drawio -x -f xml -o <name>.drawio <name>.mmd`, see `references/mermaid-authoring.md` (structure only; layout comes free; never `--layout` afterwards). **(b) Hand-written XML** for custom styling, vendor icons, swimlanes, precise geometry — **read `references/xml-authoring.md` first** (skeleton, cell forms, palette, spacing rules). **(c) A bundled generator** for the data-driven cases below. **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`; add `--tune` to auto-pick the more readable direction). 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; for **Terraform / Kubernetes / docker-compose** (`scripts/tfimports.py`, `k8simports.py`, `composeimports.py`), the importer extracts the resource/service reference graph — tf/k8s nodes resolve to their official cloud icons automatically; to draw **what is actually running** rather than the declared config, pipe `terraform show -json` into `scripts/tfstate.py` or `docker inspect $(docker ps -q)` into `scripts/dockerimports.py` (`k8simports.py` already accepts live `kubectl get ... -o json`) — see `references/live-infra.md`; for an **ER diagram from SQL DDL**, `scripts/sqlerd.py` parses `CREATE TABLE` into table nodes + crow's-foot FK edges. For a **sequence diagram**, skip autolayout entirely — describe participants + messages as JSON and run `python3 <this-skill-dir>/scripts/seqlayout.py seq.json -o <name>.drawio` (deterministic lifeline/activation/arrow geometry; see the script docstring for the JSON schema). For a **C4 model**, `python3 <this-skill-dir>/scripts/c4.py c4.json -o <name>.drawio` emits the full multi-page Context→Container→Component set with drill-down links (schema in the script docstring). For complex architecture diagrams with many visible edge labels, give labels `labelBackgroundColor=#ffffff;fontSize=11` and use edge geometry `x`/`y` offsets plus `<mxPoint as="offset" />` to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. 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** — produce the `.drawio` file, choosing the authoring mode: **(a) Mermaid → CLI convert** when the diagram is a standard type with no custom styling/icon needs **and** the CLI is ≥ v30 — write a `.mmd` and run `drawio -x -f xml -o <name>.drawio <name>.mmd`, see `references/mermaid-authoring.md` (structure only; layout comes free; never `--layout` afterwards). **(b) Hand-written XML** for custom styling, vendor icons, swimlanes, precise geometry — **read `references/xml-authoring.md` first** (skeleton, cell forms, palette, spacing rules). **(c) A bundled generator** for the data-driven cases below. **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`; add `--tune` to auto-pick the more readable direction). 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; for **Terraform / Kubernetes / docker-compose** (`scripts/tfimports.py`, `k8simports.py`, `composeimports.py`), the importer extracts the resource/service reference graph — tf/k8s nodes resolve to their official cloud icons automatically; to draw **what is actually running** rather than the declared config, pipe `terraform show -json` into `scripts/tfstate.py` or `docker inspect $(docker ps -q)` into `scripts/dockerimports.py` (`k8simports.py` already accepts live `kubectl get ... -o json`) — see `references/live-infra.md`; for an **ER diagram from SQL DDL**, `scripts/sqlerd.py` parses `CREATE TABLE` into table nodes + crow's-foot FK edges; for an **API diagram from an OpenAPI / Swagger spec**, `scripts/openapiimports.py` maps operations (coloured by HTTP method) + component schemas into a graph for autolayout. To turn any generated `.drawio` into a **metric heat map** — recolour nodes by a CSV/JSON of cost/latency/traffic/errors — run `python3 <this-skill-dir>/scripts/heatmap.py <name>.drawio -m metrics.csv` (matches on cell id or label; `--palette`, `--size`, legend). For a **sequence diagram**, skip autolayout entirely — describe participants + messages as JSON and run `python3 <this-skill-dir>/scripts/seqlayout.py seq.json -o <name>.drawio` (deterministic lifeline/activation/arrow geometry; see the script docstring for the JSON schema). For a **C4 model**, `python3 <this-skill-dir>/scripts/c4.py c4.json -o <name>.drawio` emits the full multi-page Context→Container→Component set with drill-down links (schema in the script docstring). For complex architecture diagrams with many visible edge labels, give labels `labelBackgroundColor=#ffffff;fontSize=11` and use edge geometry `x`/`y` offsets plus `<mxPoint as="offset" />` to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. 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 approveddiff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.mdindex 853af35..9726b83 100644--- a/skills/drawio-skill/references/toolbox.md+++ b/skills/drawio-skill/references/toolbox.md@@ -1,6 +1,6 @@# Toolbox — every bundled script, by use-case-A map of the 25 bundled scripts grouped by what you're trying to do. The+A map of the 27 bundled scripts grouped by what you're trying to do. Theper-task routing table in `SKILL.md` says *when* to reach for each; this says*how they fit together*. Read it when you're not sure which script a requestmaps to, or you want to chain several.@@ -23,6 +23,8 @@ exports it:| Terraform/K8s/compose files | the **declared** architecture | `tfimports` · `k8simports` · `composeimports` || a running cluster/stack/cloud | what's **actually deployed** | `tfstate` · `dockerimports` · `k8simports -` || a SQL schema | an ER diagram | `sqlerd` |+| an OpenAPI / Swagger spec | an API diagram (by method) | `openapiimports` |+| a diagram + a metrics file | it coloured by the data | `heatmap` || a sequence of interactions | a UML sequence diagram | `seqlayout` || a system at 3 zoom levels | a C4 model with drill-down | `c4` || two diagrams / two snapshots | what changed (drift) | `drawiodiff` |@@ -53,6 +55,7 @@ All emit graph JSON → `autolayout.py`.- **`k8simports.py`** — K8s manifests → objects as official kind icons (edges: Ingress→Service→workload→ConfigMap/Secret/PVC).- **`composeimports.py`** — docker-compose → service boxes + volume cylinders.- **`sqlerd.py`** — SQL DDL (`CREATE TABLE`) → ERD with crow's-foot FK edges.+- **`openapiimports.py`** — OpenAPI 3 / Swagger 2 spec → API diagram: one node per operation (coloured by HTTP method) + one per component schema, with edges to the schemas each operation uses and between nested schemas. `--group` by tag.## 4. Live infrastructure → diagram (actually running)@@ -66,6 +69,7 @@ The **actual** counterpart to §3 — see `references/live-infra.md`.- **`drawiodiff.py`** — diff two `.drawio` (or two live snapshots) → colour-coded graph (added=green, removed=red, changed=orange). Pairs with §4 for drift.- **`timelapse.py`** — re-run an extractor across git history → a self-contained HTML player of how the architecture grew.+- **`heatmap.py`** — recolour any `.drawio` by a metrics file (CSV/JSON): each node shaded low→high on a gradient by its value (`--palette`, optional `--size`, auto legend). Turns a static architecture into a cost / latency / traffic / error-rate heat map.## 6. Diagram → other formats (reverse / interop)diff --git a/skills/drawio-skill/scripts/heatmap.py b/skills/drawio-skill/scripts/heatmap.pynew file mode 100644index 0000000..d65d463--- /dev/null+++ b/skills/drawio-skill/scripts/heatmap.py@@ -0,0 +1,226 @@+#!/usr/bin/env python3+"""Colour a diagram by data — turn a .drawio into a metric heatmap.++Reads a .drawio and a metrics file (CSV `key,value` or JSON `{key: value}`),+matches each metric key to a node by cell id or by its label text, and recolours+that node along a gradient from the lowest value to the highest. Optionally+scales node size by value (`--size`) and drops in a legend. The result is a new+.drawio you can export like any other — an architecture diagram that now shows+cost / latency / traffic / error-rate as a heat map.++ python3 heatmap.py architecture.drawio --metrics latency.csv -o hot.drawio+ python3 heatmap.py architecture.drawio -m cost.json --palette cool --size++Metrics match on cell id first, then on the (HTML-stripped) label, case-+insensitively. Unmatched nodes keep their original style. `--palette` picks the+colour ramp (heat|cool|warm), `--reverse` flips it (so low = hot).++Usage: python3 heatmap.py <file.drawio> --metrics <file.csv|json> [-o out.drawio]+ [--palette heat|cool|warm] [--reverse] [--size] [--no-legend]+"""+import argparse+import csv+import html+import json+import os+import re+import sys+import xml.etree.ElementTree as ET++# Sequential ramps as (low, mid, high) anchor colours; value is lerped across them.+PALETTES = {+ "heat": ("#57bb8a", "#ffd666", "#e67c73"), # green -> yellow -> red+ "cool": ("#deebf7", "#6baed6", "#08519c"), # light -> deep blue+ "warm": ("#fff7bc", "#fec44f", "#d95f0e"), # pale -> deep amber+}+++def clean(text):+ """Strip the 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 _num(x):+ try:+ return float(x)+ except (TypeError, ValueError):+ return None+++def load_metrics(path):+ """{key: float} from a JSON object/list or a CSV/TSV (first col key, last numeric col value)."""+ with open(path, encoding="utf-8") as f:+ text = f.read()+ if path.lower().endswith(".json"):+ data = json.loads(text)+ if isinstance(data, dict):+ return {str(k): _num(v) for k, v in data.items() if _num(v) is not None}+ out = {}+ for row in data:+ key = row.get("id") or row.get("key") or row.get("name") or row.get("label")+ val = _num(row.get("value", row.get("val", row.get("metric"))))+ if key is not None and val is not None:+ out[str(key)] = val+ return out+ delim = "\t" if text.splitlines() and "\t" in text.splitlines()[0] else ","+ out = {}+ for row in csv.reader(text.splitlines(), delimiter=delim):+ if len(row) < 2:+ continue+ v = _num(row[-1])+ if v is not None: # skip header / non-numeric rows+ out[row[0].strip()] = v+ return out+++def _rgb(c):+ c = c.lstrip("#")+ return tuple(int(c[i:i + 2], 16) for i in (0, 2, 4))+++def ramp(anchors, t):+ """t in [0,1] -> #rrggbb across a 3-stop (low, mid, high) ramp."""+ lo, mid, hi = (_rgb(c) for c in anchors)+ a, b, u = (lo, mid, t * 2) if t < 0.5 else (mid, hi, (t - 0.5) * 2)+ return "#%02x%02x%02x" % tuple(round(a[i] + (b[i] - a[i]) * u) for i in range(3))+++def darker(hexcolor, f=0.6):+ return "#%02x%02x%02x" % tuple(round(c * f) for c in _rgb(hexcolor))+++def set_style(style, fill, stroke):+ """Replace/insert fillColor & strokeColor in a draw.io style string."""+ s = re.sub(r"(fillColor|strokeColor)=[^;]*;?", "", style or "").strip("; ")+ return (s + ";" if s else "") + f"fillColor={fill};strokeColor={stroke};"+++def vertices(root):+ """Yield (cell, id, label) for every vertex, unwrapping UserObject/object wrappers."""+ for child in root:+ if child.tag == "mxCell" and child.get("vertex") == "1":+ yield child, child.get("id"), clean(child.get("value"))+ elif child.tag in ("UserObject", "object"):+ inner = child.find("mxCell")+ if inner is not None and inner.get("vertex") == "1":+ yield inner, child.get("id"), clean(child.get("label") or child.get("value"))+++def scale_geom(cell, factor):+ """Grow/shrink a cell about its centre by `factor`."""+ g = cell.find("mxGeometry")+ if g is None:+ return+ w, h = _num(g.get("width")), _num(g.get("height"))+ if w is None or h is None:+ return+ nw, nh = w * factor, h * factor+ g.set("width", "%g" % nw)+ g.set("height", "%g" % nh)+ for attr, delta in (("x", (nw - w) / 2), ("y", (nh - h) / 2)):+ v = _num(g.get(attr))+ if v is not None:+ g.set(attr, "%g" % (v - delta))+++def color_for(val, lo, hi, anchors, reverse):+ t = (val - lo) / (hi - lo) if hi > lo else 0.5+ fill = ramp(anchors, 1 - t if reverse else t)+ return fill, darker(fill), t+++def content_bounds(root):+ """(min_x, min_y) of the page's top-level cells, so the legend sits clear of them."""+ xs, ys = [], []+ for child in root:+ cell = child if child.tag == "mxCell" else child.find("mxCell")+ if cell is None or cell.get("parent") != "1": # skip nested (relative-coord) cells+ continue+ g = cell.find("mxGeometry")+ x, y = (_num(g.get("x")), _num(g.get("y"))) if g is not None else (None, None)+ if x is not None and y is not None:+ xs.append(x)+ ys.append(y)+ return (min(xs) if xs else 20, min(ys) if ys else 20)+++def add_legend(root, anchors, lo, hi, reverse):+ """Drop a small min/mid/max swatch legend just left of the page's content."""+ w, h = 90, 26+ cx, cy = content_bounds(root)+ x0, y0 = cx - w - 40, cy # to the left of the diagram++ def cell(cid, value, style, gy, gh):+ c = ET.SubElement(root, "mxCell", {"id": cid, "value": value, "style": style,+ "vertex": "1", "parent": "1"})+ ET.SubElement(c, "mxGeometry", {"x": "%g" % x0, "y": "%g" % gy,+ "width": "%g" % w, "height": "%g" % gh, "as": "geometry"})++ cell("hm-title", "Heatmap",+ "text;html=1;fontStyle=1;align=left;verticalAlign=middle;", y0, 20)+ for i, val in enumerate((hi, (lo + hi) / 2, lo)):+ fill, stroke, _ = color_for(val, lo, hi, anchors, reverse)+ cell("hm-%d" % i, "%g" % val,+ set_style("rounded=0;whiteSpace=wrap;html=1;", fill, stroke),+ y0 + 24 + i * (h + 4), h)+++def main():+ ap = argparse.ArgumentParser(description="Recolour a .drawio into a metric heatmap.")+ ap.add_argument("file", help="input .drawio (uncompressed)")+ ap.add_argument("-m", "--metrics", required=True, help="metrics .csv or .json")+ ap.add_argument("-o", "--output", help="output .drawio (default: <name>-heat.drawio)")+ ap.add_argument("--palette", default="heat", choices=list(PALETTES))+ ap.add_argument("--reverse", action="store_true", help="flip the ramp (low = hot)")+ ap.add_argument("--size", action="store_true", help="also scale node size by value")+ ap.add_argument("--no-legend", dest="legend", action="store_false", help="skip the legend")+ args = ap.parse_args()++ if not os.path.isfile(args.file):+ sys.exit(f"error: {args.file} not found")+ if not os.path.isfile(args.metrics):+ sys.exit(f"error: {args.metrics} not found")+ metrics = load_metrics(args.metrics)+ if not metrics:+ sys.exit(f"error: no numeric metrics parsed from {args.metrics}")+ low_map = {k.lower(): v for k, v in metrics.items()}+ anchors = PALETTES[args.palette]+ lo, hi = min(metrics.values()), max(metrics.values())++ tree = ET.parse(args.file)+ matched, first_root = 0, None+ for diagram in tree.getroot().iter("diagram"):+ model = diagram.find("mxGraphModel")+ root = model.find("root") if model is not None else None+ if root is None: # compressed / empty page+ continue+ if first_root is None:+ first_root = root+ for cell, cid, label in list(vertices(root)):+ val = metrics.get(cid)+ if val is None and label:+ val = metrics.get(label, low_map.get(label.lower()))+ if val is None:+ continue+ fill, stroke, t = color_for(val, lo, hi, anchors, args.reverse)+ cell.set("style", set_style(cell.get("style"), fill, stroke))+ if args.size and hi > lo:+ scale_geom(cell, 0.7 + 0.8 * t)+ matched += 1++ if args.legend and first_root is not None and matched:+ add_legend(first_root, anchors, lo, hi, args.reverse)++ out = args.output or os.path.splitext(args.file)[0] + "-heat.drawio"+ tree.write(out, encoding="utf-8", xml_declaration=False)+ if matched == 0:+ sys.stderr.write("warning: no nodes matched any metric key (check ids/labels)\n")+ sys.stderr.write(f"wrote {out} ({matched}/{len(metrics)} metrics matched)\n")+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/openapiimports.py b/skills/drawio-skill/scripts/openapiimports.pynew file mode 100644index 0000000..842c94f--- /dev/null+++ b/skills/drawio-skill/scripts/openapiimports.py@@ -0,0 +1,165 @@+#!/usr/bin/env python3+"""Turn an OpenAPI / Swagger spec into an API diagram as autolayout graph JSON.++Reads an OpenAPI 3 or Swagger 2 spec (JSON, or YAML with PyYAML) and emits one+node per operation — coloured by HTTP method — plus one node per component+schema, with edges from each operation to the schemas it references (request /+response bodies) and between schemas that nest one another. Feeds autolayout.py:++ python3 openapiimports.py openapi.yaml -o graph.json+ python3 autolayout.py graph.json -o api.drawio++Operations are grouped by their first `tag` (falling back to the first path+segment) with `--group`; `--no-schemas` drops the data-model nodes to show just+the endpoint surface. `$ref`s are resolved to their final name; only schemas+defined under components/definitions become nodes, so external refs are ignored.++Usage: python3 openapiimports.py <spec.json|spec.yaml> [-o graph.json]+ [--direction TB|LR] [--group] [--no-schemas]+"""+import argparse+import json+import os+import sys++METHODS = ("get", "post", "put", "patch", "delete", "head", "options", "trace")+# HTTP method -> (fill, stroke). GET reads, POST creates, PUT/PATCH update, DELETE removes.+METHOD_STYLE = {+ "get": ("#dae8fc", "#6c8ebf"), "post": ("#d5e8d4", "#82b366"),+ "put": ("#ffe6cc", "#d79b00"), "patch": ("#ffe6cc", "#d79b00"),+ "delete": ("#f8cecc", "#b85450"),+}+OTHER_STYLE = ("#f5f5f5", "#666666")+SCHEMA_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;"+OP_EDGE = "edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;endArrow=open;"+REF_EDGE = ("edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;"+ "dashed=1;endArrow=open;strokeColor=#9673a6;")+++def load_spec(path):+ """Parse the spec: JSON directly, YAML (or ambiguous) via PyYAML if present."""+ with open(path, encoding="utf-8") as f:+ text = f.read()+ if path.lower().endswith((".yaml", ".yml")):+ try:+ import yaml+ except ImportError:+ sys.exit("error: spec is YAML but PyYAML is not installed "+ "(pip install pyyaml) — or convert the spec to JSON")+ return yaml.safe_load(text)+ try:+ return json.loads(text)+ except json.JSONDecodeError:+ try:+ import yaml+ except ImportError:+ sys.exit("error: could not parse spec as JSON (install PyYAML to read YAML)")+ return yaml.safe_load(text)+++def find_refs(obj):+ """Yield the final name of every $ref anywhere inside a spec fragment."""+ if isinstance(obj, dict):+ for k, v in obj.items():+ if k == "$ref" and isinstance(v, str):+ yield v.split("/")[-1]+ else:+ yield from find_refs(v)+ elif isinstance(obj, list):+ for item in obj:+ yield from find_refs(item)+++def method_style(method):+ fill, stroke = METHOD_STYLE.get(method, OTHER_STYLE)+ return ("rounded=1;whiteSpace=wrap;html=1;align=left;spacingLeft=6;"+ f"fillColor={fill};strokeColor={stroke};")+++def build(spec, group, no_schemas, direction):+ """Spec dict -> autolayout graph JSON dict."""+ paths = spec.get("paths") or {}+ # components.schemas (OpenAPI 3) or definitions (Swagger 2)+ schemas = (spec.get("components") or {}).get("schemas") or spec.get("definitions") or {}+ want_schemas = bool(schemas) and not no_schemas+ sid = {name: f"S:{name}" for name in schemas}++ nodes, edges, seen = [], [], set()++ def add_edge(src, dst, style):+ if src != dst and (src, dst) not in seen:+ seen.add((src, dst))+ edges.append({"source": src, "target": dst, "style": style, "label": ""})++ i = 0+ for path, item in paths.items():+ if not isinstance(item, dict):+ continue+ for method in METHODS:+ op = item.get(method)+ if not isinstance(op, dict):+ continue+ oid = f"op{i}"+ i += 1+ summary = (op.get("summary") or op.get("operationId") or "").strip()+ head = f"{method.upper()} {path}"+ nodes.append({+ "id": oid, "label": head + (f"\n{summary}" if summary else ""),+ "style": method_style(method),+ "width": max(160, 8 * len(head) + 20), "height": 40,+ **({"group": (op.get("tags") or [path.strip('/').split('/')[0] or "root"])[0]}+ if group else {}),+ })+ if want_schemas:+ for ref in set(find_refs(op)):+ if ref in sid:+ add_edge(oid, sid[ref], OP_EDGE)++ if want_schemas:+ for name, schema in schemas.items():+ fields = schema.get("properties") if isinstance(schema, dict) else None+ count = len(fields) if fields else 0+ nodes.append({+ "id": sid[name],+ "label": name + (f"\n({count} field{'s' if count != 1 else ''})" if count else ""),+ "style": SCHEMA_STYLE, "width": max(140, 9 * len(name) + 20), "height": 40,+ **({"group": "schemas"} if group else {}),+ })+ for ref in set(find_refs(schema)):+ if ref in sid:+ add_edge(sid[name], sid[ref], REF_EDGE)++ return {"direction": direction, "nodes": nodes, "edges": edges}+++def main():+ ap = argparse.ArgumentParser(description="OpenAPI/Swagger spec -> API diagram graph JSON.")+ ap.add_argument("spec", help="OpenAPI 3 / Swagger 2 spec (.json or .yaml)")+ ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")+ ap.add_argument("--direction", default="LR", choices=["TB", "LR"])+ ap.add_argument("--group", action="store_true", help="group operations by tag")+ ap.add_argument("--no-schemas", action="store_true",+ help="show only endpoints, omit schema nodes and edges")+ args = ap.parse_args()++ if not os.path.isfile(args.spec):+ sys.exit(f"error: {args.spec} not found")+ spec = load_spec(args.spec) or {}+ if not (spec.get("paths")):+ sys.exit("error: no paths found (is this an OpenAPI/Swagger spec?)")++ graph = build(spec, args.group, args.no_schemas, args.direction)+ 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)+ ops = sum(1 for n in graph["nodes"] if n["id"].startswith("op"))+ sys.stderr.write(f"{ops} operations, {len(graph['nodes']) - ops} schemas, "+ f"{len(graph['edges'])} edges\n")+++if __name__ == "__main__":+ main()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 8eb755e..4bb0199 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -970,6 +970,111 @@ class TestImportersCli(unittest.TestCase):self.assertEqual(len(graph["edges"]), 1)self.assertEqual(graph["edges"][0], {"source": "a", "target": "b"})+ def test_openapiimports_operations_and_schemas(self):+ spec = {+ "openapi": "3.0.0",+ "paths": {"/pets": {+ "get": {"tags": ["pets"], "summary": "List",+ "responses": {"200": {"content": {"application/json":+ {"schema": {"$ref": "#/components/schemas/Pet"}}}}}},+ "post": {"tags": ["pets"],+ "requestBody": {"content": {"application/json":+ {"schema": {"$ref": "#/components/schemas/Pet"}}}},+ "responses": {"201": {"description": "ok"}}},+ }},+ "components": {"schemas": {+ "Pet": {"properties": {"owner": {"$ref": "#/components/schemas/Owner"}}},+ "Owner": {"properties": {"id": {"type": "integer"}}},+ }},+ }+ with tempfile.TemporaryDirectory() as d:+ p = os.path.join(d, "api.json")+ self._write(p, json.dumps(spec))+ graph = json.loads(run("openapiimports.py", p, "--group").stdout)+ ops = [n for n in graph["nodes"] if n["id"].startswith("op")]+ schemas = [n for n in graph["nodes"] if n["id"].startswith("S:")]+ self.assertEqual(len(ops), 2)+ self.assertEqual({n["id"] for n in schemas}, {"S:Pet", "S:Owner"})+ get = next(n for n in ops if n["label"].startswith("GET"))+ post = next(n for n in ops if n["label"].startswith("POST"))+ self.assertIn("fillColor=#dae8fc", get["style"]) # GET blue+ self.assertIn("fillColor=#d5e8d4", post["style"]) # POST green+ pairs = {(e["source"], e["target"]) for e in graph["edges"]}+ self.assertIn((get["id"], "S:Pet"), pairs) # operation -> schema+ self.assertIn(("S:Pet", "S:Owner"), pairs) # schema nesting+ self.assertEqual({n.get("group") for n in ops}, {"pets"})+ self.assertEqual(next(iter(schemas)).get("group"), "schemas")++ def test_openapiimports_no_schemas(self):+ spec = {"openapi": "3.0.0",+ "paths": {"/x": {"get": {"responses": {"200": {"description": "ok"}}}}},+ "components": {"schemas": {"Y": {"properties": {"z": {"type": "string"}}}}}}+ with tempfile.TemporaryDirectory() as d:+ p = os.path.join(d, "api.json")+ self._write(p, json.dumps(spec))+ graph = json.loads(run("openapiimports.py", p, "--no-schemas").stdout)+ self.assertEqual(len(graph["nodes"]), 1)+ self.assertTrue(graph["nodes"][0]["id"].startswith("op"))+ self.assertEqual(graph["edges"], [])+++class TestHeatmap(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("heatmap")++ @staticmethod+ def _write(path, text):+ with open(path, "w", encoding="utf-8") as f:+ f.write(text)++ def test_ramp_hits_anchors(self):+ a = self.m.PALETTES["heat"]+ self.assertEqual(self.m.ramp(a, 0.0), "#57bb8a") # low+ self.assertEqual(self.m.ramp(a, 0.5), "#ffd666") # mid+ self.assertEqual(self.m.ramp(a, 1.0), "#e67c73") # high++ def test_set_style_replaces_colours_once(self):+ s = self.m.set_style("rounded=1;fillColor=#111111;strokeColor=#222222;",+ "#abcdef", "#123456")+ self.assertIn("fillColor=#abcdef", s)+ self.assertIn("strokeColor=#123456", s)+ self.assertNotIn("#111111", s)+ self.assertEqual(s.count("fillColor="), 1)++ def test_load_metrics_csv_and_json(self):+ with tempfile.TemporaryDirectory() as d:+ csvp = os.path.join(d, "m.csv")+ self._write(csvp, "service,ms\nweb,10\ndb,90\n") # header auto-skipped+ self.assertEqual(self.m.load_metrics(csvp), {"web": 10.0, "db": 90.0})+ jp = os.path.join(d, "m.json")+ self._write(jp, '{"web":10,"db":90}')+ self.assertEqual(self.m.load_metrics(jp), {"web": 10.0, "db": 90.0})++ def test_recolors_matched_nodes(self):+ drawio = (+ '<mxfile><diagram id="p" name="P"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="web" value="Web" style="rounded=1;fillColor=#dddddd;'+ 'strokeColor=#999999;" vertex="1" parent="1">'+ '<mxGeometry x="200" y="40" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="db" value="Database" style="rounded=1;fillColor=#dddddd;'+ 'strokeColor=#999999;" vertex="1" parent="1">'+ '<mxGeometry x="360" y="40" width="80" height="40" as="geometry"/></mxCell>'+ '</root></mxGraphModel></diagram></mxfile>')+ with tempfile.TemporaryDirectory() as d:+ dp, mp, out = (os.path.join(d, n) for n in ("a.drawio", "m.csv", "out.drawio"))+ self._write(dp, drawio)+ self._write(mp, "web,10\ndb,90\n")+ r = run("heatmap.py", dp, "-m", mp, "-o", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("2/2 metrics matched", r.stderr)+ import xml.etree.ElementTree as ET+ cells = {c.get("id"): c.get("style") for c in ET.parse(out).getroot().iter("mxCell")}+ self.assertIn("fillColor=#57bb8a", cells["web"]) # min -> green+ self.assertIn("fillColor=#e67c73", cells["db"]) # max -> red+ self.assertIn("hm-title", cells) # legend injected+if __name__ == "__main__":unittest.main()