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: C4 model diagrams with multi-page drill-down (v1.17.0) (#56)
Agents365.ai690d941e4657
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6e81b4f..1e2454e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,27 @@ 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.17.0] — 2026-07-03+### Added+- **`c4.py` — C4 model diagrams with drill-down.** Levels JSON (System+ Context → Containers → Components, any depth) in, one multi-page `.drawio`+ out: official C4 shapes/colors (`mxgraph.c4.person2`, c4model.com+ palette), standard three-line labels (`Name` / `[Type: Tech]` / desc),+ Graphviz placement per page, and **click-to-drill-down** — an element with+ `"children"` links to that level's page (`data:page/id,…`).+- `autolayout.py`: node-level `link` support (wraps the cell in a+ `UserObject`) and a reusable `page_cells`/`wrap_page` split so multi-page+ generators can share its layout pipeline.+- `validate.py`: understands `UserObject`/`object` wrappers — linked cells+ no longer produce false dangling-edge errors (also fixes linting of+ hand-authored diagrams that use links/metadata).+- `references/diagram-types.md`: C4 Model section (styles, label format,+ drill-down recipe); SKILL.md routes "C4", "container diagram", etc. to it.+### Fixed+- SKILL.md export flags: `--page-index` is **1-based** in current+ drawio-desktop (verified on 29.7.8) — previously documented as 0-based.+- Tests: 45.+## [1.16.0] — 2026-07-02### Added- **`seqlayout.py` — deterministic sequence diagrams.** Participants +diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex 4047dfe..01a0e8d 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -1,12 +1,12 @@---name: drawio-skill-version: 1.16.0+version: 1.17.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-skillcompatibility: Requires draw.io desktop app CLI on PATH (macOS/Linux/Windows). Self-check step requires a vision-enabled model (e.g., Claude Sonnet/Opus); gracefully skipped if unavailable. Optional auto-layout (scripts/autolayout.py) needs Graphviz (dot).platforms: [macos, linux, windows]-metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for optional autolayout.py","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.16.0"}+metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for optional autolayout.py","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.17.0"}---# Draw.io Diagrams@@ -35,7 +35,7 @@ When the workflow references one of these, read it on demand — none of them ne| File | Read it when ||---|---|| `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/diagram-types.md` | The user names a specific diagram type (ERD, UML class, sequence, architecture, ML/DL, flowchart) |+| `references/diagram-types.md` | The user names a specific diagram type (ERD, UML class, sequence, C4, architecture, ML/DL, flowchart) || `references/shapes.md` + `scripts/shapesearch.py` | The diagram needs a **specific shape** — a cloud icon (AWS/Azure/GCP), Cisco/Kubernetes/network symbol, UML/BPMN/ER/electrical/P&ID element — or any time you'd otherwise guess a `style=` string. `shapesearch.py "<keywords>"` returns the exact official style for 10k+ shapes || `scripts/aiicons.py` | The diagram involves an **AI/LLM brand** (OpenAI, Claude, Gemini, Mistral, Llama, HuggingFace, Ollama, LangChain, …) — `aiicons.py "<brand>"` returns a draw.io `image` style for the brand logo (lobe-icons via CDN; `--embed` to inline). draw.io has no built-in AI logos. See `references/shapes.md` → "AI / LLM brand logos" || `references/style-presets.md` | The user asks to learn / save / list / set-default / delete a style preset, or you've resolved an active preset and need the application rules |@@ -49,6 +49,7 @@ When the workflow references one of these, read it on demand — none of them ne| `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/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 || `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 |## Prerequisites@@ -99,7 +100,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).2. **Plan** — identify shapes, relationships, layout (LR or TB), group by tier/layer-3. **Generate** — write `.drawio` XML file to disk. Hand-place coordinates for small/styled diagrams — **read `references/xml-authoring.md` first** (skeleton, cell forms, palette, spacing rules). **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 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** — write `.drawio` XML file to disk. Hand-place coordinates for small/styled diagrams — **read `references/xml-authoring.md` first** (skeleton, cell forms, palette, spacing rules). **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.4. **Export draft** — run CLI to produce a preview PNG. **Do NOT pass `-e`** at this step — the embedded `zTXt mxGraphModel` chunk it adds causes vision APIs (Claude included) to return 400 "Could not process image" in step 5. **Cap the preview width with `--width 2000` (not `-s 2`)** — Claude's vision API rejects images larger than 2576×2576px with "Unable to resize image — dimensions exceed the 2576x2576px limit", and `-s 2` on a medium-or-larger diagram easily overshoots that ceiling. Save the clean preview as `<name>.png` (single extension). Embedding and full-resolution scale are for the final export only (step 7).5. **Self-check** — use the agent's built-in vision capability to read the exported PNG, catch obvious issues, auto-fix before showing user (requires a vision-enabled model such as Claude Sonnet/Opus). If reading the PNG returns a 400 / "Could not process image" error, you almost certainly exported with `-e` by mistake — re-export without `-e` and retry once. If it still fails, skip self-check and continue to step 6.6. **Review loop** — show image to user, collect feedback, apply targeted XML edits, re-export, repeat until approved@@ -246,7 +247,7 @@ The script's `endswith(IEND)` guard makes it a no-op once draw.io fixes the bug- `-o` — output file path; accepts any directory (e.g. `./artifacts/diagram.drawio.png`) — `mkdir -p` the target dir first. Use `.drawio.png` double extension when embedding.- `-b` — border width around diagram (default: 0, recommend 10)- `-t` — transparent background (PNG only)-- `--page-index 0` — export specific page (default: all)+- `--page-index <n>` — export one page of a multi-page file. **1-based** in current drawio-desktop (verified on 29.7.8: `--page-index 2` exports the second page; older docs claimed 0-based). Default: first page. `--page-range 2..3` also works### Browser fallback (no CLI needed)@@ -312,5 +313,6 @@ When the user requests a specific diagram type, read `references/diagram-types.m| "architecture", "system diagram", "service diagram" | Architecture || "neural network", "model architecture", "ML diagram", "deep learning" | ML / Deep Learning Model || "flowchart", "decision tree", "process flow" | Flowchart |+| "C4", "system context diagram", "container diagram", "component diagram" | C4 Model |The diagram-type preset sets **structural** style keywords. If a user style preset is also active (see `## Style Presets`), keep the structural keywords and layer color/font/edge/extras on top — read `references/style-presets.md` → "Interaction with diagram-type presets" for the merge rules.diff --git a/skills/drawio-skill/references/diagram-types.md b/skills/drawio-skill/references/diagram-types.mdindex 1d11088..02be470 100644--- a/skills/drawio-skill/references/diagram-types.md+++ b/skills/drawio-skill/references/diagram-types.md@@ -3,7 +3,7 @@When the user requests a specific diagram type, apply the matching preset below for shapes, styles, and layout conventions. These presets set **structural** style keywords (e.g. ERD's `shape=table;childLayout=tableLayout`); a user style preset (see `references/style-presets.md`) layers color/font/edge/extras on top.Read this file when:-- The user names one of these diagram types (ERD, UML class, sequence, architecture, ML/DL model, flowchart)+- The user names one of these diagram types (ERD, UML class, sequence, C4, architecture, ML/DL model, flowchart)- You're choosing shape vocabulary or layout direction for a new diagram## ERD (Entity-Relationship Diagram)@@ -43,6 +43,23 @@ Read this file when:| Activation box | `shape=umlFrame;whiteSpace=wrap;` on the lifeline | Narrow rectangle on lifeline || Layout | LR, lifelines spaced 200px apart | Time flows top to bottom |+## C4 Model (System Context / Container / Component)++**Don't hand-build** — `python3 scripts/c4.py c4.json -o out.drawio` generates the whole multi-page set (one page per level, drill-down links from parent elements to child pages, Graphviz placement; schema in the script docstring). The styles below are what it emits — for hand-tweaks afterwards:++| Element | Style | Notes |+|---------|-------|-------|+| Person | `shape=mxgraph.c4.person2;html=1;whiteSpace=wrap;fontColor=#ffffff;fillColor=#083F75;strokeColor=#06315C;` | Dark-blue person shape, 200×180 |+| Software System | `rounded=1;arcSize=10;html=1;whiteSpace=wrap;fontColor=#ffffff;fillColor=#1061B0;strokeColor=#0D5091;` | 240×120 |+| External System | same, `fillColor=#8C8496;strokeColor=#736782;` | Grey = outside your control |+| Container | same, `fillColor=#23A2D9;strokeColor=#0E7DAD;` | Mid-blue |+| Component | same, `fillColor=#63BEF2;strokeColor=#2086C9;` | Light-blue |+| Database | `shape=cylinder3;size=15;boundedLbl=1;` + Container colors | Cylinder |+| Relationship | `endArrow=blockThin;endFill=1;html=1;fontSize=11;fontColor=#404040;strokeColor=#828282;labelBackgroundColor=#ffffff;` | Grey thin arrow, label = protocol/action |+| Label format | `Name` ⏎ `[Type: Tech]` ⏎ `description` | The standard three-line C4 label |+| Drill-down | wrap the element in `<UserObject link="data:page/id,<pageId>">` | Click jumps to the child page in draw.io / viewer |+| Layout | TB, one `<diagram>` page per level | Export a single page with `--page-index <n>` (1-based) |+## Architecture Diagram| Element | Style | Notes |diff --git a/skills/drawio-skill/scripts/autolayout.py b/skills/drawio-skill/scripts/autolayout.pyindex 48af046..af2a84b 100644--- a/skills/drawio-skill/scripts/autolayout.py+++ b/skills/drawio-skill/scripts/autolayout.py@@ -187,7 +187,9 @@ def group_style(stroke):f"fontColor={stroke};verticalAlign=top;fontStyle=2;dashed=1;")-def to_drawio(graph, height, pos, edge_pts, color=True):+def page_cells(graph, height, pos, edge_pts, color=True):+ """The <root> child cells (everything after the two reserved cells) for one+ laid-out graph — reusable by multi-page generators (c4.py)."""nodes = graph["nodes"]# Absolute snapped rect for every placed node.rects = {}@@ -283,12 +285,19 @@ def to_drawio(graph, height, pos, edge_pts, color=True):style = f"rounded=1;whiteSpace=wrap;html=1;fillColor={fill};strokeColor={stroke};"else:style = NODE_STYLE- cells.append(- f' <mxCell id="{attr(nid)}" value="{attr(node.get("label", nid))}" '- f'style="{attr(style)}" vertex="1" parent="{attr(parent)}">\n'- f' <mxGeometry x="{x}" y="{y}" width="{w}" height="{h}" as="geometry"/>\n'- f" </mxCell>"- )+ body = (f'style="{attr(style)}" vertex="1" parent="{attr(parent)}">\n'+ f' <mxGeometry x="{x}" y="{y}" width="{w}" height="{h}" as="geometry"/>\n'+ f" </mxCell>")+ if node.get("link"):+ # Links ride on a UserObject wrapper (id + label move to it).+ cells.append(+ f' <UserObject label="{attr(node.get("label", nid))}" '+ f'link="{attr(node["link"])}" id="{attr(nid)}">\n'+ f" <mxCell " + body + "\n </UserObject>")+ else:+ cells.append(+ f' <mxCell id="{attr(nid)}" value="{attr(node.get("label", nid))}" '+ + body)for i, edge in enumerate(graph.get("edges", [])):# Drop the first/last points (they sit on the node borders, where# draw.io attaches anyway) and replay the interior bends as waypoints.@@ -309,19 +318,30 @@ def to_drawio(graph, height, pos, edge_pts, color=True):f" {geom}\n"f" </mxCell>")+ return "\n".join(cells)+++def wrap_page(cells, page_id="autolayout", name="Page-1"):+ """One <diagram> page around pre-rendered root cells."""return (- '<mxfile>\n <diagram id="autolayout" name="Page-1">\n'+ f' <diagram id="{attr(page_id)}" name="{attr(name)}">\n'' <mxGraphModel dx="800" dy="600" grid="1" gridSize="10" guides="1" ''tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" ''pageWidth="850" pageHeight="1100" math="0" shadow="0">\n'" <root>\n"' <mxCell id="0"/>\n'' <mxCell id="1" parent="0"/>\n'- + "\n".join(cells)- + "\n </root>\n </mxGraphModel>\n </diagram>\n</mxfile>\n"+ + cells+ + "\n </root>\n </mxGraphModel>\n </diagram>\n")+def to_drawio(graph, height, pos, edge_pts, color=True):+ return ("<mxfile>\n"+ + wrap_page(page_cells(graph, height, pos, edge_pts, color=color))+ + "</mxfile>\n")++def route_score(graph, height, pos, edge_pts):"""Readability score for one dot layout (lower is better): weighted countof edge-through-vertex hits and edge-edge crossings, with total edge lengthdiff --git a/skills/drawio-skill/scripts/c4.py b/skills/drawio-skill/scripts/c4.pynew file mode 100644index 0000000..dab2bf1--- /dev/null+++ b/skills/drawio-skill/scripts/c4.py@@ -0,0 +1,163 @@+#!/usr/bin/env python3+"""C4 model diagrams: levels JSON -> one multi-page .drawio with drill-down.++Generates a C4 architecture diagram set (System Context -> Containers ->+Components, as many levels as you define) in a single `.drawio` file: one+page per level, official draw.io C4 shapes and colors, Graphviz placement+per page (via autolayout), and **drill-down links** — an element with a+`"children"` key becomes clickable and jumps to that level's page in+draw.io / the diagrams.net viewer.++ python3 c4.py c4.json -o architecture.drawio++Input JSON:+ {+ "title": "Internet Banking",+ "levels": [+ {+ "name": "System Context",+ "elements": [+ {"id": "customer", "type": "person", "label": "Personal Customer",+ "desc": "A customer of the bank"},+ {"id": "ibs", "type": "system", "label": "Internet Banking System",+ "desc": "Lets customers manage accounts", "children": "Containers"},+ {"id": "email", "type": "external", "label": "E-mail System",+ "desc": "Microsoft Exchange"}+ ],+ "relations": [+ {"from": "customer", "to": "ibs", "label": "Uses"},+ {"from": "ibs", "to": "email", "label": "Sends e-mail via"}+ ]+ },+ {+ "name": "Containers",+ "elements": [+ {"id": "spa", "type": "container", "label": "Single-Page App",+ "tech": "React", "desc": "Banking UI in the browser"},+ {"id": "api", "type": "container", "label": "API Application",+ "tech": "Java/Spring", "children": "Components"},+ {"id": "db", "type": "database", "label": "Database",+ "tech": "PostgreSQL"}+ ],+ "relations": [+ {"from": "spa", "to": "api", "label": "JSON/HTTPS"},+ {"from": "api", "to": "db", "label": "JDBC"}+ ]+ }+ ]+ }++Element types: person, system, external (greyed external system), container,+component, database. `tech` renders as the [Type: Tech] line, `desc` as the+description line — the standard C4 label. Element ids must be unique across+ALL levels (pages share one link namespace). Requires Graphviz `dot`.++Usage: python3 c4.py <c4.json> [-o out.drawio] [--direction TB|LR]+"""+import argparse+import importlib.util+import json+import os+import re+import sys++# Official draw.io C4 template styles (colors from c4model.com).+_BASE = "html=1;whiteSpace=wrap;fontSize=12;fontColor=#ffffff;align=center;"+STYLES = {+ "person": ("shape=mxgraph.c4.person2;" + _BASE ++ "fillColor=#083F75;strokeColor=#06315C;", 200, 180),+ "system": ("rounded=1;arcSize=10;" + _BASE ++ "fillColor=#1061B0;strokeColor=#0D5091;", 240, 120),+ "external": ("rounded=1;arcSize=10;" + _BASE ++ "fillColor=#8C8496;strokeColor=#736782;", 240, 120),+ "container": ("rounded=1;arcSize=10;" + _BASE ++ "fillColor=#23A2D9;strokeColor=#0E7DAD;", 240, 120),+ "component": ("rounded=1;arcSize=10;" + _BASE ++ "fillColor=#63BEF2;strokeColor=#2086C9;", 240, 120),+ "database": ("shape=cylinder3;size=15;boundedLbl=1;" + _BASE ++ "fillColor=#23A2D9;strokeColor=#0E7DAD;", 240, 120),+}+TYPE_WORD = {"person": "Person", "system": "Software System",+ "external": "Software System", "container": "Container",+ "component": "Component", "database": "Container"}+EDGE = ("endArrow=blockThin;endFill=1;endSize=10;html=1;fontSize=11;"+ "fontColor=#404040;strokeColor=#828282;labelBackgroundColor=#ffffff;"+ "rounded=0;")+++def load_autolayout():+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "autolayout.py")+ spec = importlib.util.spec_from_file_location("autolayout", path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def slug(name):+ return re.sub(r"[^a-z0-9]+", "-", str(name).lower()).strip("-") or "page"+++def c4_label(el):+ """Standard C4 element label: Name / [Type: Tech] / description."""+ kind = TYPE_WORD.get(el.get("type", "system"), "Software System")+ bracket = f"[{kind}: {el['tech']}]" if el.get("tech") else f"[{kind}]"+ lines = [el.get("label", el["id"]), bracket]+ if el.get("desc"):+ lines.append(el["desc"])+ return "\n".join(lines)+++def main():+ ap = argparse.ArgumentParser(description="C4 levels JSON -> multi-page draw.io.")+ ap.add_argument("input", help="C4 JSON file")+ ap.add_argument("-o", "--output", help="output .drawio path (default: stdout)")+ ap.add_argument("--direction", default="TB", choices=["TB", "LR"])+ args = ap.parse_args()+ with open(args.input, encoding="utf-8") as f:+ spec = json.load(f)+ levels = spec.get("levels") or []+ if not levels:+ sys.exit("error: no levels in input")+ al = load_autolayout()++ page_ids = {lv["name"]: slug(lv["name"]) for lv in levels}+ seen = set()+ pages = []+ for lv in levels:+ nodes = []+ for el in lv.get("elements", []):+ if el["id"] in seen:+ sys.exit(f"error: duplicate element id {el['id']!r} "+ "(ids must be unique across all levels)")+ seen.add(el["id"])+ style, w, h = STYLES.get(el.get("type", "system"), STYLES["system"])+ node = {"id": el["id"], "label": c4_label(el), "style": style,+ "width": w, "height": h}+ child = el.get("children")+ if child:+ if child not in page_ids:+ sys.exit(f"error: element {el['id']!r} drills down to "+ f"unknown level {child!r}")+ node["link"] = f"data:page/id,{page_ids[child]}"+ nodes.append(node)+ edges = [{"source": r["from"], "target": r["to"],+ "label": r.get("label", ""), "style": EDGE}+ for r in lv.get("relations", [])]+ graph = {"direction": args.direction, "nodes": nodes, "edges": edges,+ "ranksep": 0.9, "nodesep": 0.5}+ height, pos, edge_pts = al.layout(al.build_dot(graph))+ pages.append(al.wrap_page(al.page_cells(graph, height, pos, edge_pts, color=False),+ page_id=page_ids[lv["name"]], name=lv["name"]))++ xml = "<mxfile>\n" + "".join(pages) + "</mxfile>\n"+ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(xml)+ print(f"wrote {args.output} ({len(pages)} pages, {len(seen)} elements)",+ file=sys.stderr)+ else:+ sys.stdout.write(xml)+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/validate.py b/skills/drawio-skill/scripts/validate.pyindex 091d9ac..be9cf61 100644--- a/skills/drawio-skill/scripts/validate.py+++ b/skills/drawio-skill/scripts/validate.py@@ -247,7 +247,18 @@ def check_page(diagram):return [], [f"page {name!r}: compressed, skipped (cannot lint)"]return [f"page {name!r}: no <mxGraphModel>"], []root = model.find("root")- cells = root.findall("mxCell") if root is not None else []+ # Normalize UserObject/object wrappers (used for links & metadata): the id+ # lives on the wrapper, geometry/style on the inner mxCell — fold the two+ # into one cell so edges referencing the wrapper id resolve.+ cells = []+ for child in (root if root is not None else []):+ if child.tag == "mxCell":+ cells.append(child)+ elif child.tag in ("UserObject", "object"):+ inner = child.find("mxCell")+ if inner is not None:+ inner.set("id", child.get("id", ""))+ cells.append(inner)errors, warns = [], []ids = {}for c in cells:diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex abe1ced..7dea903 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -180,6 +180,14 @@ class TestAutolayoutColor(unittest.TestCase):self.assertIn("ranksep=0.70;", dot)self.assertIn("nodesep=0.60;", dot)+ def test_node_link_wraps_userobject(self):+ out = self.m.to_drawio(+ {"direction": "TB",+ "nodes": [{"id": "n", "label": "L", "link": "data:page/id,p2"}],+ "edges": []}, 5, {"n": (1, 1)}, {}, color=True)+ self.assertIn('<UserObject label="L" link="data:page/id,p2" id="n">', out)+ self.assertNotIn('value="L"', out) # label moved to the wrapper+def test_edge_style_passthrough(self):out = self.m.to_drawio({"direction": "TB",@@ -261,6 +269,25 @@ class TestValidateCli(unittest.TestCase):self.assertEqual(r.returncode, 1)self.assertIn("error", r.stdout)+ # A vertex wrapped in UserObject (link) — the edge references the wrapper id.+ LINKED = ('<mxfile><diagram name="P1"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<UserObject label="A" link="data:page/id,p2" id="2">'+ '<mxCell vertex="1" parent="1">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '</UserObject>'+ '<mxCell id="3" value="B" vertex="1" parent="1">'+ '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="4" edge="1" parent="1" source="2" target="3">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+ '</root></mxGraphModel></diagram></mxfile>')++ def test_userobject_wrapper_resolves(self):+ # The wrapper id must satisfy edge source refs (no dangling-edge error).+ r = self._check(self.LINKED)+ self.assertEqual(r.returncode, 0, r.stdout)+ self.assertIn("0 error(s)", r.stdout)+def test_edge_label_passes(self):# edgeLabel vertices have no width/height; they must not be flagged# as missing/invalid geometry (issue #35).@@ -568,6 +595,35 @@ class TestImportersCli(unittest.TestCase):v = run("validate.py", out)self.assertEqual(v.returncode, 0, v.stdout)+ def test_c4_multipage_drilldown(self):+ import shutil+ if not shutil.which("dot"):+ self.skipTest("Graphviz dot not installed")+ spec = {"levels": [+ {"name": "Context",+ "elements": [{"id": "u", "type": "person", "label": "User"},+ {"id": "sys", "type": "system", "label": "System",+ "children": "Containers"}],+ "relations": [{"from": "u", "to": "sys", "label": "Uses"}]},+ {"name": "Containers",+ "elements": [{"id": "api", "type": "container", "label": "API",+ "tech": "Go"},+ {"id": "db", "type": "database", "label": "DB"}],+ "relations": [{"from": "api", "to": "db"}]}]}+ with tempfile.TemporaryDirectory() as d:+ path = os.path.join(d, "c4.json")+ self._write(path, json.dumps(spec))+ out = os.path.join(d, "c4.drawio")+ r = run("c4.py", path, "-o", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ xml = open(out, encoding="utf-8").read()+ self.assertEqual(xml.count("<diagram"), 2)+ self.assertIn('link="data:page/id,containers"', xml) # drill-down+ self.assertIn("mxgraph.c4.person2", xml)+ self.assertIn("[Container: Go]", xml)+ v = run("validate.py", out)+ self.assertEqual(v.returncode, 0, v.stdout)+def test_rustimports_edge(self):# Node ids are module paths (no crate-root file, so just a, b).with tempfile.TemporaryDirectory() as d: