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: live-infra importers — draw what's actually running (v1.20.0) (#67)
Agents365.ai1658756bf75e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b8e17b9..ef04118 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,26 @@ 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.20.0] — 2026-07-03+### Added+- **Live-infrastructure importers** — draw what's *actually running / deployed*,+ not just the declared config:+ - `scripts/tfstate.py` — `terraform show -json | tfstate.py -` renders the+ **deployed** state (provider-agnostic; `count`/`for_each` instances expanded,+ module nesting preserved, `depends_on` edges). Reuses tfimports' icon+ resolver, so the same official AWS/Azure/GCP icons and `--no-icons` fallback+ apply. The actually-deployed counterpart to tfimports' `.tf` view.+ - `scripts/dockerimports.py` — `docker inspect $(docker ps -q) | dockerimports.py -`+ renders the **running** containers, the user networks they attach to (green+ ellipses) and the named volumes they mount (cylinders); edges from `links`+ and the compose `depends_on` label. Built-in `bridge`/`host`/`none`/`ingress`+ networks and bind mounts are dropped as noise. The running counterpart to+ composeimports.+- **`k8simports.py` now reads a live cluster from stdin** (`-`):+ `kubectl get all,ing,cm,secret,pvc -o json | k8simports.py -`.+- New `references/live-infra.md` recipe (the three `terraform`/`docker`/`kubectl`+ one-liners + caveats); router + autolayout reference updated. Suite now 50.+## [1.19.0] — 2026-07-03### Added- **Accessibility built-in presets**: `colorblind-safe` (Okabe-Ito palette —diff --git a/README.md b/README.mdindex 33c2be4..1700fd6 100644--- a/README.md+++ b/README.md@@ -160,6 +160,11 @@ python3 scripts/tfimports.py ./infra -o graph.json # Terraform → AWS/python3 scripts/k8simports.py ./manifests -o graph.json # K8s YAML/JSON → kind iconspython3 scripts/composeimports.py compose.yml -o graph.json # services + named volumes+# Live infrastructure — draw what's ACTUALLY running / deployed+terraform show -json | python3 scripts/tfstate.py - -o graph.json # deployed cloud+docker inspect $(docker ps -q)| python3 scripts/dockerimports.py - -o graph.json # running containers+kubectl get all,ing,cm,secret,pvc -o json | python3 scripts/k8simports.py - -o graph.json # live cluster+# Data & interactionspython3 scripts/sqlerd.py schema.sql -o graph.json # SQL DDL → ER diagrampython3 scripts/seqlayout.py seq.json -o sequence.drawio # sequence diagram, direct to .drawio@@ -171,7 +176,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio| Piece | What it does ||---|---|-| **9 extractors** | import graphs for **Python · JS/TS · Go · Rust**, **Python class inheritance**, **Terraform / Kubernetes / docker-compose** resource graphs (official cloud icons), and **SQL DDL → ERD** |+| **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) || **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.mdindex a8b808a..a48bc21 100644--- a/README_CN.md+++ b/README_CN.md@@ -158,6 +158,11 @@ python3 scripts/tfimports.py ./infra -o graph.json # Terraform → AWS/python3 scripts/k8simports.py ./manifests -o graph.json # K8s YAML/JSON → kind 图标python3 scripts/composeimports.py compose.yml -o graph.json # 服务 + 命名卷+# 实时基础设施 —— 画「真正在运行 / 已部署」的东西+terraform show -json | python3 scripts/tfstate.py - -o graph.json # 已部署的云资源+docker inspect $(docker ps -q)| python3 scripts/dockerimports.py - -o graph.json # 正在运行的容器+kubectl get all,ing,cm,secret,pvc -o json | python3 scripts/k8simports.py - -o graph.json # 实时集群+# 数据与交互python3 scripts/sqlerd.py schema.sql -o graph.json # SQL DDL → ER 图python3 scripts/seqlayout.py seq.json -o sequence.drawio # 时序图,直接生成 .drawio@@ -169,7 +174,7 @@ python3 scripts/autolayout.py graph.json -o diagram.drawio| 组件 | 作用 ||---|---|-| **9 个提取器** | **Python · JS/TS · Go · Rust** 的导入关系图、**Python 类继承**、**Terraform / Kubernetes / docker-compose** 资源图(自动配官方云图标),以及 **SQL DDL → ER 图** |+| **11 个提取器** | **Python · JS/TS · Go · Rust** 的导入关系图、**Python 类继承**、**Terraform / Kubernetes / docker-compose** 资源图(自动配官方云图标)、**SQL DDL → ER 图**,以及从 `terraform show -json` / `docker inspect` / `kubectl get -o json` 提取的**实时**基础设施(画出真正已部署的样子) || **时序图引擎** | `seqlayout.py` 从消息列表直接算出 lifeline / 激活条 / 箭头几何 —— 不需要 Graphviz,不需要手摆 || **自动布局** | Graphviz 自动布点,正交连线**绕开**节点 —— 大图不再需要手动摆坐标。`--tune` 双向各排一次取更可读的 || **传递约简** | 删掉被更长路径蕴含的边,把密集的"毛线团"变成可读图(asyncio:149 → 46 条边) |diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex 9b27f02..15f2dfe 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -1,6 +1,6 @@---name: drawio-skill-version: 1.19.0+version: 1.20.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@@ -47,7 +47,8 @@ When the workflow references one of these, read it on demand — none of them ne| `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` · `rustimports.py` | The user wants to visualize a **Python, JS/TS, Go, or Rust project** structure — extracts the import graph (transitive-reduced, optional `--group` containers, nested by sub-package) for autolayout || `scripts/pyclasses.py` | The user wants a **Python class hierarchy / class diagram** — extracts classes + inheritance edges (boxed by module with `--group`) for autolayout |-| `scripts/tfimports.py` · `k8simports.py` · `composeimports.py` | The user wants to visualize **Terraform, Kubernetes, or docker-compose infrastructure** — extracts the resource/service reference graph (official AWS/Azure/GCP/K8s icons for tf/k8s; service boxes + volume cylinders for compose) 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/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 |@@ -101,7 +102,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; 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 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/autolayout.md b/skills/drawio-skill/references/autolayout.mdindex 52fdbfb..b7f2c36 100644--- a/skills/drawio-skill/references/autolayout.md+++ b/skills/drawio-skill/references/autolayout.md@@ -100,6 +100,8 @@ Bundled importers turn a codebase or an IaC configuration into a graph JSON read| Terraform | `scripts/tfimports.py <dir>` | `resource` / `module` block, rendered as its **official AWS/Azure/GCP icon** | cross-resource reference (`aws_iam_role.x.arn`, `${...}`, `depends_on`) || Kubernetes | `scripts/k8simports.py <dir>` | manifest object (kind/name), rendered as its **official K8s kind icon** | Ingress→Service, Service→workload (selector), workload→ConfigMap/Secret/PVC, HPA→target || docker-compose | `scripts/composeimports.py <file-or-dir>` | service (name + image box) / named volume (cylinder) | `depends_on` / `links` / `volumes_from` / named-volume mounts |+| Terraform state (**live**) | `terraform show -json \| scripts/tfstate.py -` | **deployed** resource instance, rendered as its **official cloud icon** | recorded dependency (`depends_on` in state) |+| Docker (**live**) | `docker inspect $(docker ps -q) \| scripts/dockerimports.py -` | running container (name + image) / user network (ellipse) / named volume (cylinder) | container→network, container→volume, `links` / compose `depends_on` || SQL DDL | `scripts/sqlerd.py <file-or-dir>` | table (column list with PK/FK markers) | foreign key (crow's-foot, labeled with the FK column) |```bash@@ -117,6 +119,8 @@ Each code importer keeps only **intra-project** edges (third-party/stdlib import- **Terraform** (`tfimports.py`): parses `.tf` files directly (regex + brace matching, no HCL library). Each resource type is resolved to its official icon through the bundled shape index — AWS `aws4` set, Azure `azure2` set, GCP icon set — with a curated query table for the ~45 most common types and strict tag-AND matching so a partial match never lands on the wrong vendor's icon; unresolvable types fall back to a plain box labeled `name` + type (`--no-icons` forces boxes for all). `--group` boxes resources by service (`aws_s3_* → s3`). Data sources, variables, locals and providers are ignored; heredocs with unbalanced braces are the known parse limit.- **Kubernetes** (`k8simports.py`): accepts one or more manifest files or a directory. JSON (including `kind: List`, i.e. `kubectl get ... -o json` output) parses with the stdlib alone; `.yaml`/`.yml` needs PyYAML. Kind icons come from the official `mxgraph.kubernetes` set (25 kinds mapped). Edges land only on objects present in the manifest set, matched within the same namespace. `--group` boxes objects by namespace. No `--no-reduce` flag — reference edges are sparse and never reduced.- **docker-compose** (`composeimports.py`): needs PyYAML. Services become rounded boxes labeled `name` + image (or `build:` context); named volumes declared in the top-level `volumes:` section become cylinders. `--group` boxes services by their first network.+- **Terraform state — live** (`tfstate.py`): reads the JSON that `terraform show -json` prints (live state, or a saved plan) from a file or `-` (stdin). Provider-agnostic; `count`/`for_each` instances are expanded (labeled `name[0]`, `name[1]`, …) and module nesting is preserved. Reuses tfimports' icon resolver, so the same official AWS/Azure/GCP icons and `--no-icons` fallback apply. Edges come from the dependencies Terraform recorded in state (`depends_on`); data sources are skipped. `--group` boxes resources by module; shares `--direction` / `--no-reduce`. This is the **actually-deployed** counterpart to tfimports' declared-config view.+- **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.The tf/k8s importers emit `ranksep`/`nodesep` in the graph JSON automatically (icon labels render *below* the shape, so rows need extra separation).diff --git a/skills/drawio-skill/references/live-infra.md b/skills/drawio-skill/references/live-infra.mdnew file mode 100644index 0000000..0bb9a8d--- /dev/null+++ b/skills/drawio-skill/references/live-infra.md@@ -0,0 +1,71 @@+# Live infrastructure — draw what's actually running++The IaC importers (`tfimports.py`, `k8simports.py`, `composeimports.py`) draw the+**declared** config. These three recipes draw the **real** state — the resources+actually deployed, the containers actually running, the cluster as it is now.+Every path ends the same way: an importer emits autolayout graph JSON, then+`autolayout.py` renders an editable `.drawio` with the same official icons.++Read this when the user says things like *"draw my running cluster / stack"*,+*"diagram what's actually deployed"*, *"visualize my live AWS/Azure/GCP infra"*,+or *"map the containers I have up right now"*.++> The commands below read local tool state (`terraform`, `docker`, `kubectl`)+> the user already has authenticated. The skill never reaches out to a cloud+> account itself — it only parses the JSON those tools print. If a tool or its+> auth is missing, say so and fall back to the declared-config importer.++## 1. Deployed cloud resources — Terraform state++Provider-agnostic (AWS / Azure / GCP alike). Run from the Terraform working dir:++```bash+terraform show -json | python3 <this-skill-dir>/scripts/tfstate.py - -o graph.json+python3 <this-skill-dir>/scripts/autolayout.py graph.json -o deployed.drawio+```++- Works on live state (above) or a saved plan: `terraform show -json plan.tfplan | …`.+- `count` / `for_each` resources appear as their real instances (`name[0]`, `name[1]`).+- `--group` boxes resources by module; `--no-icons` for plain boxes; `--direction LR`.+- Edges are the dependencies Terraform recorded in state (`depends_on`). A state+ with no recorded dependencies still produces a useful **inventory** (every+ deployed resource with its official icon) — mention that if edges come out sparse.+- Contrast with `tfimports.py` (the `.tf` files) when the user wants declared-vs-actual.++## 2. Running containers — Docker++```bash+docker inspect $(docker ps -q) | python3 <this-skill-dir>/scripts/dockerimports.py - -o graph.json+python3 <this-skill-dir>/scripts/autolayout.py graph.json -o running.drawio+```++- Containers → rounded boxes (name + image); user networks → green ellipses;+ named volumes → cylinders. Built-in `bridge`/`host`/`none`/`ingress` networks+ and bind mounts are dropped as noise.+- Edges: container→network, container→volume, and container→container from+ `links` and the compose `depends_on` label.+- `--group` boxes containers by their compose project (else first network).+- `docker ps -q` lists only running containers; add `-a` to include stopped ones.++## 3. Live cluster — Kubernetes (via k8simports)++No new script — `k8simports.py` already ingests `kubectl get ... -o json`. Ask for+the resource kinds that make the architecture readable (workloads + what wires them):++```bash+kubectl get deploy,sts,ds,svc,ing,cm,secret,pvc,hpa -n <ns> -o json \+ | python3 <this-skill-dir>/scripts/k8simports.py - -o graph.json+python3 <this-skill-dir>/scripts/autolayout.py graph.json -o cluster.drawio+```++- `kubectl get all` alone omits Ingress / ConfigMap / Secret / PVC — list the+ kinds explicitly (as above) so the reference edges have endpoints to land on.+- `--group` boxes objects by namespace; add `-A` to `kubectl` for all namespaces.+- Edges are derived within a namespace: Ingress→Service, Service→workload+ (selector match), workload→ConfigMap/Secret/PVC, HPA→target.++## After any of them++Continue at the main workflow's **Export draft** step: preview PNG (`--width 2000`),+self-check, review, final export with `-e` + `repair_png.py`. A live snapshot is a+point in time — re-run the pipeline to refresh it.diff --git a/skills/drawio-skill/scripts/dockerimports.py b/skills/drawio-skill/scripts/dockerimports.pynew file mode 100644index 0000000..ef098ec--- /dev/null+++ b/skills/drawio-skill/scripts/dockerimports.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""Draw the containers that are ACTUALLY running from `docker inspect` output.++Where composeimports.py reads the *declared* stack (compose file), this reads+the *live* one: pipe `docker inspect` of the running containers and it maps the+real topology — every container, the user networks they are attached to, the+named volumes they mount, and the container->container edges recorded in+`links` / compose `depends_on` labels. The output feeds autolayout.py:++ docker inspect $(docker ps -q) | python3 dockerimports.py - -o graph.json+ python3 autolayout.py graph.json -o running.drawio++Input is the JSON array `docker inspect` prints (a file path, or `-` for+stdin). Containers become rounded boxes (name + image), user networks become+green ellipses, named volumes become cylinders — visually matching the compose+importer so declared and live diagrams read alike. `--group` boxes containers+by their compose project (falling back to their first user network).++Usage: docker inspect $(docker ps -q) | python3 dockerimports.py - [-o graph.json]+ [--direction TB|LR] [--group]+"""+import argparse+import json+import sys++CONTAINER_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"+NETWORK_STYLE = "ellipse;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;"+VOLUME_STYLE = ("shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;size=15;"+ "fillColor=#f5f5f5;strokeColor=#666666;")+# Docker's built-in networks are topology noise — a compose stack's own+# networks are what tell the architecture story.+BUILTIN_NETS = {"bridge", "host", "none", "ingress"}+++def cname(obj):+ """A container's short name (strip docker's leading slash)."""+ return (obj.get("Name") or obj.get("Id", "")[:12]).lstrip("/")+++def links_of(obj):+ """Container names this one links to (HostConfig.Links + per-network Links)."""+ out = set()+ raw = list((obj.get("HostConfig") or {}).get("Links") or [])+ for net in ((obj.get("NetworkSettings") or {}).get("Networks") or {}).values():+ raw.extend((net or {}).get("Links") or [])+ for link in raw:+ # "/db:/web/db" -> target container is the part before the first colon.+ target = str(link).lstrip("/").split(":", 1)[0]+ if target:+ out.add(target)+ return out+++def depends_on(obj):+ """Compose service names this container depends on (label form)."""+ label = (obj.get("Config") or {}).get("Labels", {}).get("com.docker.compose.depends_on")+ if not label:+ return set()+ # "db:service_healthy:false,cache:service_started:false" -> {db, cache}+ return {part.split(":", 1)[0] for part in label.split(",") if part.strip()}+++def main():+ ap = argparse.ArgumentParser(description="`docker inspect` output -> autolayout graph JSON.")+ ap.add_argument("input", help="`docker inspect` JSON file, or - for stdin")+ 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="group containers by compose project (else first network)")+ args = ap.parse_args()++ text = sys.stdin.read() if args.input == "-" else open(args.input, encoding="utf-8").read()+ try:+ data = json.loads(text)+ except json.JSONDecodeError as exc:+ sys.exit(f"error: input is not valid JSON ({exc}) — feed `docker inspect ...`")+ containers = data if isinstance(data, list) else [data]+ containers = [c for c in containers if isinstance(c, dict) and c.get("Id")]+ if not containers:+ sys.exit("error: no containers found (feed `docker inspect $(docker ps -q)`)")++ names = {cname(c) for c in containers}+ # compose service label -> container name, so depends_on (which names+ # services) can resolve to the real container node.+ svc_to_name = {}+ for c in containers:+ svc = (c.get("Config") or {}).get("Labels", {}).get("com.docker.compose.service")+ if svc:+ svc_to_name[svc] = cname(c)++ nodes, edges, nets, vols = [], set(), set(), set()+ for c in containers:+ name = cname(c)+ image = (c.get("Config") or {}).get("Image") or "?"+ labels = (c.get("Config") or {}).get("Labels", {}) or {}+ node = {"id": name, "label": f"{name}\n{image}", "style": CONTAINER_STYLE,+ "width": 160, "height": 60}++ attached = [n for n in ((c.get("NetworkSettings") or {}).get("Networks") or {})+ if n not in BUILTIN_NETS]+ if args.group:+ project = labels.get("com.docker.compose.project")+ grp = project or (attached[0] if attached else None)+ if grp:+ node["group"] = str(grp)+ nodes.append(node)++ for net in attached:+ nets.add(net)+ edges.add((name, f"net:{net}"))+ for m in c.get("Mounts") or []:+ if m.get("Type") == "volume" and m.get("Name"):+ vols.add(m["Name"])+ edges.add((name, f"vol:{m['Name']}"))+ for target in links_of(c):+ if target in names and target != name:+ edges.add((name, target))+ for dep in depends_on(c):+ target = svc_to_name.get(dep, dep)+ if target in names and target != name:+ edges.add((name, target))++ for net in sorted(nets):+ nodes.append({"id": f"net:{net}", "label": net, "style": NETWORK_STYLE,+ "width": 120, "height": 70})+ for vol in sorted(vols):+ nodes.append({"id": f"vol:{vol}", "label": vol, "style": VOLUME_STYLE,+ "width": 120, "height": 70})++ graph = {"direction": args.direction, "nodes": nodes,+ "edges": [{"source": s, "target": t} for s, t in sorted(edges)]}+ out = json.dumps(graph, indent=2)+ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(out)+ sys.stderr.write(f"wrote {args.output}\n")+ else:+ sys.stdout.write(out)+ sys.stderr.write(f"{len(nodes)} nodes ({len(containers)} containers, "+ f"{len(nets)} networks, {len(vols)} volumes), {len(edges)} edges\n")+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/k8simports.py b/skills/drawio-skill/scripts/k8simports.pyindex 35fd7fb..0d4566b 100644--- a/skills/drawio-skill/scripts/k8simports.py+++ b/skills/drawio-skill/scripts/k8simports.py@@ -21,9 +21,10 @@ feeds autolayout.py:JSON input (single object, or a `kind: List` as produced by`kubectl get ... -o json`) parses with the stdlib alone; .yaml/.yml files-need PyYAML (`pip install pyyaml`).+need PyYAML (`pip install pyyaml`). Pass `-` to read a live cluster snapshot+from stdin: `kubectl get all,ing,cm,secret,pvc -o json | k8simports.py -`.-Usage: python3 k8simports.py <dir-or-manifest...> [-o graph.json]+Usage: python3 k8simports.py <dir-or-manifest...|-> [-o graph.json][--direction TB|LR] [--group] [--no-icons]"""import argparse@@ -76,11 +77,14 @@ def load_manifests(paths):files.append(p)objs = []for path in sorted(set(files)):- with open(path, encoding="utf-8") as f:- text = f.read()- if path.endswith(".json"):- docs = [json.loads(text)]+ if path == "-": # `kubectl get ... -o json | k8simports.py -`+ docs = [json.loads(sys.stdin.read())]+ elif path.endswith(".json"):+ with open(path, encoding="utf-8") as f:+ docs = [json.loads(f.read())]else:+ with open(path, encoding="utf-8") as f:+ text = f.read()try:import yamlexcept ImportError:diff --git a/skills/drawio-skill/scripts/tfstate.py b/skills/drawio-skill/scripts/tfstate.pynew file mode 100644index 0000000..2135e40--- /dev/null+++ b/skills/drawio-skill/scripts/tfstate.py@@ -0,0 +1,128 @@+#!/usr/bin/env python3+"""Draw the cloud resources ACTUALLY deployed, from `terraform show -json`.++Where tfimports.py reads the *declared* config (`.tf` files), this reads the+*real* state: what Terraform recorded as provisioned. It is provider-agnostic+(the JSON is uniform across AWS / Azure / GCP), expands `count`/`for_each` into+their real instances, keeps module nesting, and reuses tfimports' icon resolver+so every resource shows its official cloud icon. The output feeds autolayout.py:++ terraform show -json | python3 tfstate.py - -o graph.json+ python3 autolayout.py graph.json -o deployed.drawio++Input is the JSON `terraform show -json` prints — from live state (no argument)+or a saved plan (`terraform show -json plan.tfplan`) — as a file path or `-` for+stdin. Nodes are the managed resource instances (data sources are ignored);+edges come from the dependencies Terraform recorded in state (`depends_on`).+`--group` boxes resources by their module; `--no-icons` forces plain boxes.++Usage: terraform show -json | python3 tfstate.py - [-o graph.json]+ [--direction TB|LR] [--group] [--no-reduce] [--no-icons]+"""+import argparse+import importlib.util+import json+import os+import sys+++def load_tfimports():+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tfimports.py")+ spec = importlib.util.spec_from_file_location("tfimports", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def walk_module(mod, out):+ """Collect (address, type, name, index, module_path, depends_on) for every+ managed resource, recursing into child modules."""+ addr = mod.get("address", "") # "" for root, else module.x[...]+ for r in mod.get("resources") or []:+ if r.get("mode") == "data":+ continue+ out.append((r.get("address"), r.get("type"), r.get("name"),+ r.get("index"), addr, r.get("depends_on") or []))+ for child in mod.get("child_modules") or []:+ walk_module(child, out)+++def main():+ ap = argparse.ArgumentParser(description="`terraform show -json` -> autolayout graph JSON.")+ ap.add_argument("input", help="`terraform show -json` output file, or - for stdin")+ 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="group resources into containers by module")+ ap.add_argument("--no-reduce", action="store_true",+ help="keep every edge (skip transitive reduction)")+ ap.add_argument("--no-icons", action="store_true",+ help="plain boxes instead of official cloud icons")+ args = ap.parse_args()++ text = sys.stdin.read() if args.input == "-" else open(args.input, encoding="utf-8").read()+ try:+ data = json.loads(text)+ except json.JSONDecodeError as exc:+ sys.exit(f"error: input is not valid JSON ({exc}) — feed `terraform show -json`")+ # State: top-level "values"; saved plan: "planned_values".+ root = ((data.get("values") or data.get("planned_values") or {}).get("root_module")) or {}+ resources = []+ walk_module(root, resources)+ if not resources:+ sys.exit("error: no managed resources found in the Terraform state/plan")++ addresses = {r[0] for r in resources}++ def targets(dep):+ """Instance addresses a depends_on entry names. State records the+ un-indexed address (`aws_subnet.this`) for a resource with several+ instances (`aws_subnet.this[0]`), so expand by prefix too."""+ if dep in addresses:+ return {dep}+ return {a for a in addresses if a.startswith(dep + "[")}++ edges = sorted({(addr, t) for addr, _, _, _, _, deps in resources+ for dep in deps for t in targets(dep) if t != addr})++ tf = load_tfimports()+ raw = len(edges)+ if not args.no_reduce and edges:+ edges = tf.transitive_reduce(list(addresses), edges)++ resolver = None if args.no_icons else tf.IconResolver()+ unmatched, nodes = [], []+ for addr, rtype, name, index, mpath, _ in resources:+ label = name if index is None else f"{name}[{index}]"+ node = {"id": addr, "label": label}+ icon = resolver.resolve(rtype) if resolver and rtype else None+ if icon:+ node.update(style=icon["style"], width=icon["w"], height=icon["h"])+ else:+ node["label"] = f"{label}\n{rtype}" if rtype else label+ if rtype:+ unmatched.append(rtype)+ if args.group and mpath:+ node["group"] = mpath+ nodes.append(node)++ graph = {"direction": args.direction, "nodes": nodes,+ "edges": [{"source": s, "target": t} for s, t in edges]}+ if resolver:+ # Icon labels render below the shape — reserve extra layout spacing.+ graph.update(ranksep=0.7, nodesep=0.6)+ out = json.dumps(graph, indent=2)+ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(out)+ sys.stderr.write(f"wrote {args.output}\n")+ else:+ sys.stdout.write(out)+ note = "" if args.no_reduce else f" (reduced from {raw})"+ sys.stderr.write(f"{len(nodes)} resources, {len(edges)} edges{note}\n")+ if unmatched:+ sys.stderr.write("no icon for: " + ", ".join(sorted(set(unmatched))) + "\n")+++if __name__ == "__main__":+ main()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 0d36e17..12ecec2 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -579,6 +579,78 @@ class TestImportersCli(unittest.TestCase):api = next(n for n in graph["nodes"] if n["id"] == "api")self.assertEqual(api["label"], "api\napi:1")+ DOCKER = [+ {"Id": "a1", "Name": "/shop-web-1",+ "Config": {"Image": "nginx:1.27", "Labels": {+ "com.docker.compose.project": "shop", "com.docker.compose.service": "web",+ "com.docker.compose.depends_on": "db:service_healthy:false"}},+ "NetworkSettings": {"Networks": {"shop_net": {}, "bridge": {}}}, "Mounts": []},+ {"Id": "a2", "Name": "/shop-db-1",+ "Config": {"Image": "postgres:16", "Labels": {+ "com.docker.compose.project": "shop", "com.docker.compose.service": "db"}},+ "NetworkSettings": {"Networks": {"shop_net": {}}},+ "Mounts": [{"Type": "volume", "Name": "pgdata", "Destination": "/data"},+ {"Type": "bind", "Source": "/etc/hosts", "Destination": "/etc/hosts"}]},+ ]++ def test_dockerimports_live(self):+ # `docker inspect` array on stdin (-): depends_on resolves service->container;+ # built-in `bridge` network and the bind mount are dropped as noise.+ graph = json.loads(run("dockerimports.py", "-",+ input=json.dumps(self.DOCKER)).stdout)+ ids = {n["id"] for n in graph["nodes"]}+ self.assertEqual(ids, {"shop-web-1", "shop-db-1", "net:shop_net", "vol:pgdata"})+ edges = {(e["source"], e["target"]) for e in graph["edges"]}+ self.assertEqual(edges, {("shop-web-1", "shop-db-1"),+ ("shop-web-1", "net:shop_net"),+ ("shop-db-1", "net:shop_net"),+ ("shop-db-1", "vol:pgdata")})+ web = next(n for n in graph["nodes"] if n["id"] == "shop-web-1")+ self.assertEqual(web["label"], "shop-web-1\nnginx:1.27")++ def test_dockerimports_group_by_project(self):+ graph = json.loads(run("dockerimports.py", "-", "--group",+ input=json.dumps(self.DOCKER)).stdout)+ containers = [n for n in graph["nodes"] if not n["id"].startswith(("net:", "vol:"))]+ self.assertTrue(all(n["group"] == "shop" for n in containers))++ TFSTATE = {"format_version": "1.0", "values": {"root_module": {+ "resources": [+ {"address": "aws_instance.web", "mode": "managed", "type": "aws_instance",+ "name": "web", "depends_on": ["aws_security_group.web"], "values": {}},+ {"address": "aws_security_group.web", "mode": "managed",+ "type": "aws_security_group", "name": "web", "values": {}},+ {"address": "data.aws_ami.x", "mode": "data", "type": "aws_ami",+ "name": "x", "values": {}}],+ "child_modules": [{"address": "module.vpc", "resources": [+ {"address": "module.vpc.aws_subnet.p[0]", "mode": "managed",+ "type": "aws_subnet", "name": "p", "index": 0, "values": {}},+ {"address": "module.vpc.aws_subnet.p[1]", "mode": "managed",+ "type": "aws_subnet", "name": "p", "index": 1, "values": {}}]}]}}}++ def test_tfstate_live(self):+ # `terraform show -json` on stdin: data sources excluded, depends_on edge,+ # count instances expanded, aws_instance -> official icon, module grouping.+ graph = json.loads(run("tfstate.py", "-", "--group", "--no-reduce",+ input=json.dumps(self.TFSTATE)).stdout)+ ids = {n["id"] for n in graph["nodes"]}+ self.assertEqual(ids, {"aws_instance.web", "aws_security_group.web",+ "module.vpc.aws_subnet.p[0]", "module.vpc.aws_subnet.p[1]"})+ self.assertEqual(graph["edges"],+ [{"source": "aws_instance.web", "target": "aws_security_group.web"}])+ ec2 = next(n for n in graph["nodes"] if n["id"] == "aws_instance.web")+ self.assertIn("mxgraph.aws4", ec2["style"])+ sub = next(n for n in graph["nodes"] if n["id"].endswith("p[0]"))+ self.assertEqual(sub["label"], "p[0]\naws_subnet") # no icon -> type on box+ self.assertEqual(sub["group"], "module.vpc")++ def test_k8simports_stdin(self):+ # `kubectl get ... -o json | k8simports.py -` reads the live snapshot.+ graph = json.loads(run("k8simports.py", "-",+ input=json.dumps(self.K8S_LIST)).stdout)+ self.assertEqual({n["id"] for n in graph["nodes"]},+ {"shop/Service/web", "shop/Deployment/web", "shop/ConfigMap/cfg"})+SQL = ("CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255));\n""CREATE TABLE orders (\n"" id INT,\n"