Skip to content

Agent skill that turns natural language, code, Terraform/K8s, SQL, OpenAPI, AsyncAPI, Protobuf and GraphQL sources into editable, tested draw.io architecture diagrams: incremental sync, multi-view projection, drift diff, CI architecture tests, whiteboard derasterize, interactive HTML/PPTX/Mermaid exports.

feat: add AsyncAPI architecture importer

akkupratap3232a2effa9e5fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05555da..0b5e37a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ semantic-ish versioning (the `metadata.version` field in
## [3.2.4] - 2026-09-11
+### Added
+
+- **AsyncAPI importer** (`asyncapiimports.py`): AsyncAPI 2 and 3 specs can now
+ produce channel, publish/subscribe operation, and payload-schema graphs with
+ source provenance, direction control, and optional grouping.
+
### Changed
- **README / README_CN reorganized for readability**: the 26 flat Highlights
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index b550bc0..74df6bc 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: drawio-skill
-description: Create, edit, synchronize, inspect, test, and publish editable draw.io diagrams. Use when the user explicitly requests draw.io/diagrams.net, needs a polished architecture, ERD, UML, sequence, C4, SysML, BPMN, network, swimlane, ML, or infrastructure diagram, wants code/IaC/SQL/OpenAPI converted into a diagram, or wants an existing diagram queried, reviewed, diffed, restyled, kept in sync, or made interactive. Prefer Mermaid/PlantUML elsewhere when the requested artifact is diagrams-as-code rather than an editable draw.io file.
+description: Create, edit, synchronize, inspect, test, and publish editable draw.io diagrams. Use when the user explicitly requests draw.io/diagrams.net, needs a polished architecture, ERD, UML, sequence, C4, SysML, BPMN, network, swimlane, ML, or infrastructure diagram, wants code/IaC/SQL/OpenAPI/AsyncAPI converted into a diagram, or wants an existing diagram queried, reviewed, diffed, restyled, kept in sync, or made interactive. Prefer Mermaid/PlantUML elsewhere when the requested artifact is diagrams-as-code rather than an editable draw.io file.
license: MIT
allowed-tools: [Bash, Read, Write, WebFetch]
metadata: {"openclaw":{"requires":{"anyBins":["python3"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io for native exports","os":["darwin"],"optional":true},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for automatic layout","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","architecture","visualization","uml"],"category":"design","requires_tools":["python3"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"3.2.4","homepage":"https://github.com/Agents365-ai/drawio-skill","compatibility":"Core IR, XML, sync, query, test, review, and Story workflows need Python 3 only; native export needs draw.io; Graphviz is optional.","platforms":["macos","linux","windows"]}
@@ -20,7 +20,7 @@ and accessible publishing over a shared Diagram IR.
| Natural-language diagram with precise styling | Read `references/diagram-types.md`, then `references/xml-authoring.md` and author XML |
| Standard flowchart/mindmap/gantt/timeline/etc. with no special styling | If draw.io >=30, read `references/mermaid-authoring.md` and convert Mermaid to native `.drawio` |
| Large graph (~15+ nodes) that needs automatic layout | Use `autolayout.py`; read `references/autolayout.md` before passing any `--layout` value |
-| Code, Terraform, K8s, compose, SQL, OpenAPI, or CI source | Use `diagramctl.py build`; read `references/diagram-ir.md` |
+| Code, Terraform, K8s, compose, SQL, OpenAPI, AsyncAPI, or CI source | Use `diagramctl.py build`; read `references/diagram-ir.md` |
| Running cluster/stack/cloud (actual state, not declared config) | Read `references/live-infra.md`, then use `tfstate.py`, `dockerimports.py`, or `k8simports.py -` |
| Update a generated diagram without losing manual layout | Use `diagramctl.py sync`; read `references/diagram-ir.md` |
| Executive/system/deployment/data-flow/security views | Use `diagramctl.py views`; read `references/diagram-ir.md` |
diff --git a/skills/drawio-skill/references/cookbook.md b/skills/drawio-skill/references/cookbook.md
index b712e2e..e82d0b6 100644
--- a/skills/drawio-skill/references/cookbook.md
+++ b/skills/drawio-skill/references/cookbook.md
@@ -128,6 +128,14 @@ Turn schema.sql into an ER diagram with PK/FK markers and crow's-foot
notation; keep schema prefixes for the billing tables.
```
+## Event-driven architecture from AsyncAPI
+
+```text
+Turn asyncapi.yaml into an event-driven architecture diagram. Show channels,
+publish and subscribe operations, and referenced payload schemas; group related
+flows by tag and lay them out from left to right.
+```
+
## ML / deep-learning model
```text
diff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.md
index 7396f8b..cbcbe52 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 39 focused tools, the unified `diagramctl.py` orchestrator
+A map of the 40 focused tools, the unified `diagramctl.py` orchestrator
(and its MCP server wrapper), and its
internal `diagram_ir.py` model grouped by what you're trying to do. The
per-task routing table in `SKILL.md` says *when* to reach for each; this says
@@ -43,6 +43,7 @@ Use focused scripts directly when you need their narrow interface; use
| 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` |
+| an AsyncAPI 2 / 3 spec | an event-driven architecture diagram | `asyncapiimports` |
| CI workflows (GH Actions / GitLab) | the pipeline as a DAG | `ciimports` |
| a diagram + a metrics file | it coloured by the data | `heatmap` |
| a sequence of interactions | a UML sequence diagram | `seqlayout` |
@@ -88,6 +89,7 @@ All emit graph JSON → `autolayout.py`.
- **`sqlerd.py`** — SQL DDL (`CREATE TABLE`) → ERD with crow's-foot FK edges.
- **`ciimports.py`** — GitHub Actions (`.github/workflows/*.yml`) and/or `.gitlab-ci.yml` -> pipeline DAG: job nodes (runner, `matrix xN`, reusable-workflow calls in purple), `needs:` edges, an `on:` trigger node per workflow, jobs boxed per workflow / per GitLab stage.
- **`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.
+- **`asyncapiimports.py`** — AsyncAPI 2 / 3 spec → event-driven architecture diagram: channel, publish/subscribe operation, and payload-schema nodes with provenance. `--group` by operation tag, channel tag, or channel prefix.
## 4. Live infrastructure → diagram (actually running)
diff --git a/skills/drawio-skill/scripts/asyncapiimports.py b/skills/drawio-skill/scripts/asyncapiimports.py
new file mode 100644
index 0000000..514ce48
--- /dev/null
+++ b/skills/drawio-skill/scripts/asyncapiimports.py
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+"""Turn an AsyncAPI 2/3 spec into an event-driven architecture graph.
+
+Emits autolayout graph JSON with channel, publish/subscribe operation, and
+message-payload schema nodes. JSON is supported with the standard library;
+YAML additionally requires PyYAML.
+
+Usage: python3 asyncapiimports.py <spec.json|spec.yaml> [-o graph.json]
+ [--direction TB|LR] [--group]
+"""
+import argparse
+import json
+import os
+import sys
+
+
+CHANNEL_STYLE = (
+ "shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;"
+ "fillColor=#fff2cc;strokeColor=#d6b656;"
+)
+PUBLISH_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;"
+SUBSCRIBE_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"
+SCHEMA_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;"
+EVENT_EDGE = "edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;endArrow=open;"
+SCHEMA_EDGE = (
+ "edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;"
+ "dashed=1;endArrow=open;strokeColor=#9673a6;"
+)
+
+
+def load_spec(path):
+ """Parse JSON directly and YAML through the optional PyYAML dependency."""
+ with open(path, encoding="utf-8") as handle:
+ text = handle.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)")
+ 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 resolve_ref(spec, ref):
+ """Resolve an internal JSON Pointer, returning None for external refs."""
+ if not isinstance(ref, str) or not ref.startswith("#/"):
+ return None
+ value = spec
+ try:
+ for part in ref[2:].split("/"):
+ key = part.replace("~1", "/").replace("~0", "~")
+ value = value[key]
+ except (KeyError, TypeError):
+ return None
+ return value
+
+
+def pointer_token(value):
+ """Escape a mapping key for use as a JSON Pointer token."""
+ return str(value).replace("~", "~0").replace("/", "~1")
+
+
+def decode_pointer_token(value):
+ return str(value).replace("~1", "/").replace("~0", "~")
+
+
+def schema_refs(obj, spec, seen=None):
+ """Yield component-schema names reachable through messages and payloads."""
+ seen = set() if seen is None else seen
+ if isinstance(obj, dict):
+ ref = obj.get("$ref")
+ if isinstance(ref, str) and ref.startswith("#/components/schemas/"):
+ name = ref.split("/")[-1].replace("~1", "/").replace("~0", "~")
+ yield name
+ if isinstance(ref, str) and ref not in seen:
+ resolved = resolve_ref(spec, ref)
+ if resolved is not None:
+ seen.add(ref)
+ yield from schema_refs(resolved, spec, seen)
+ for key, value in obj.items():
+ if key != "$ref":
+ yield from schema_refs(value, spec, seen)
+ elif isinstance(obj, list):
+ for value in obj:
+ yield from schema_refs(value, spec, seen)
+
+
+def first_tag(obj):
+ tags = obj.get("tags") if isinstance(obj, dict) else None
+ if not isinstance(tags, list) or not tags:
+ return None
+ tag = tags[0]
+ return tag.get("name") if isinstance(tag, dict) else str(tag)
+
+
+def channel_group(name, channel):
+ """Prefer a channel tag, falling back to the address/name prefix."""
+ tag = first_tag(channel)
+ if tag:
+ return tag
+ address = str(channel.get("address") or name).strip("/")
+ return address.split("/", 1)[0] or "root"
+
+
+def build(spec, group=False, direction="LR"):
+ """Convert an AsyncAPI 2 or 3 mapping to autolayout graph JSON."""
+ channels = spec.get("channels") or {}
+ schemas = (spec.get("components") or {}).get("schemas") or {}
+ nodes, edges, edge_keys = [], [], set()
+ channel_ids = {name: f"channel:{name}" for name in channels}
+ schema_ids = {name: f"schema:{name}" for name in schemas}
+
+ def add_edge(source, target, label="", style=EVENT_EDGE, pointer=None):
+ key = (source, target, label)
+ if source == target or key in edge_keys:
+ return
+ edge_keys.add(key)
+ edge = {"source": source, "target": target, "label": label, "style": style}
+ if pointer:
+ edge["provenance"] = {"pointer": pointer}
+ edges.append(edge)
+
+ for name, raw_channel in channels.items():
+ channel = raw_channel if isinstance(raw_channel, dict) else {}
+ address = str(channel.get("address") or name)
+ node = {
+ "id": channel_ids[name],
+ "label": address,
+ "style": CHANNEL_STYLE,
+ "width": max(150, 8 * len(address) + 24),
+ "height": 50,
+ "provenance": {"pointer": f"#/channels/{pointer_token(name)}"},
+ }
+ if group:
+ node["group"] = channel_group(name, channel)
+ nodes.append(node)
+
+ operations = []
+ # AsyncAPI 2 keeps publish/subscribe operations under each channel.
+ for channel_name, raw_channel in channels.items():
+ channel = raw_channel if isinstance(raw_channel, dict) else {}
+ for action in ("publish", "subscribe"):
+ operation = channel.get(action)
+ if isinstance(operation, dict):
+ operations.append(
+ (
+ f"{channel_name}:{action}",
+ action,
+ channel_name,
+ operation,
+ f"#/channels/{pointer_token(channel_name)}/{action}",
+ )
+ )
+
+ # AsyncAPI 3 promotes operations to the top level and calls the actions
+ # send/receive. A channel is referenced by JSON Pointer.
+ for operation_name, raw_operation in (spec.get("operations") or {}).items():
+ operation = raw_operation if isinstance(raw_operation, dict) else {}
+ action = {"send": "publish", "receive": "subscribe"}.get(
+ operation.get("action"), operation.get("action")
+ )
+ channel_ref = (operation.get("channel") or {}).get("$ref")
+ channel_name = (
+ decode_pointer_token(channel_ref.split("/")[-1])
+ if isinstance(channel_ref, str)
+ else None
+ )
+ if action in ("publish", "subscribe") and channel_name in channels:
+ operations.append(
+ (
+ operation_name,
+ action,
+ channel_name,
+ operation,
+ f"#/operations/{pointer_token(operation_name)}",
+ )
+ )
+
+ for operation_name, action, channel_name, operation, pointer in operations:
+ operation_id = f"operation:{operation_name}"
+ title = operation.get("summary") or operation.get("operationId") or operation_name
+ node = {
+ "id": operation_id,
+ "label": f"{action.upper()}\n{title}",
+ "style": PUBLISH_STYLE if action == "publish" else SUBSCRIBE_STYLE,
+ "width": max(150, 8 * len(str(title)) + 24),
+ "height": 50,
+ "provenance": {"pointer": pointer},
+ }
+ if group:
+ raw_channel = channels[channel_name]
+ channel = raw_channel if isinstance(raw_channel, dict) else {}
+ node["group"] = first_tag(operation) or channel_group(channel_name, channel)
+ nodes.append(node)
+ add_edge(operation_id, channel_ids[channel_name], action, EVENT_EDGE, pointer)
+ # In AsyncAPI 3, the channel reference identifies the connection but
+ # does not mean that an operation uses every message on that channel.
+ message_source = {
+ key: value for key, value in operation.items() if key != "channel"
+ }
+ for schema_name in sorted(set(schema_refs(message_source, spec))):
+ if schema_name in schema_ids:
+ add_edge(
+ operation_id,
+ schema_ids[schema_name],
+ "payload",
+ SCHEMA_EDGE,
+ pointer,
+ )
+
+ for name, raw_schema in schemas.items():
+ schema = raw_schema if isinstance(raw_schema, dict) else {}
+ properties = schema.get("properties") or {}
+ label = name + (f"\n({len(properties)} fields)" if properties else "")
+ node = {
+ "id": schema_ids[name],
+ "label": label,
+ "style": SCHEMA_STYLE,
+ "width": max(140, 9 * len(name) + 20),
+ "height": 40,
+ "provenance": {"pointer": f"#/components/schemas/{pointer_token(name)}"},
+ }
+ if group:
+ node["group"] = "schemas"
+ nodes.append(node)
+ for ref_name in sorted(set(schema_refs(schema, spec))):
+ if ref_name in schema_ids:
+ add_edge(schema_ids[name], schema_ids[ref_name], "", SCHEMA_EDGE)
+
+ return {"direction": direction, "nodes": nodes, "edges": edges}
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="AsyncAPI 2/3 spec -> event architecture graph JSON."
+ )
+ parser.add_argument("spec", help="AsyncAPI 2/3 spec (.json, .yaml, or .yml)")
+ parser.add_argument("-o", "--output", help="output JSON path (default: stdout)")
+ parser.add_argument("--direction", default="LR", choices=["TB", "LR"])
+ parser.add_argument(
+ "--group",
+ action="store_true",
+ help="group by operation tag or channel prefix",
+ )
+ args = parser.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("asyncapi"):
+ sys.exit("error: missing asyncapi version (is this an AsyncAPI spec?)")
+ if not spec.get("channels"):
+ sys.exit("error: no channels found in AsyncAPI spec")
+
+ graph = build(spec, args.group, args.direction)
+ text = json.dumps(graph, indent=2)
+ if args.output:
+ with open(args.output, "w", encoding="utf-8") as handle:
+ handle.write(text)
+ sys.stderr.write(f"wrote {args.output}\n")
+ else:
+ sys.stdout.write(text)
+ operation_count = sum(node["id"].startswith("operation:") for node in graph["nodes"])
+ sys.stderr.write(
+ f"{operation_count} operations, {len(spec['channels'])} channels, "
+ f"{len((spec.get('components') or {}).get('schemas') or {})} schemas, "
+ f"{len(graph['edges'])} edges\n"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/skills/drawio-skill/scripts/diagramctl.py b/skills/drawio-skill/scripts/diagramctl.py
index b2d3114..baacee8 100644
--- a/skills/drawio-skill/scripts/diagramctl.py
+++ b/skills/drawio-skill/scripts/diagramctl.py
@@ -51,6 +51,7 @@ IMPORTERS = {
"compose": "composeimports.py",
"sql": "sqlerd.py",
"openapi": "openapiimports.py",
+ "asyncapi": "asyncapiimports.py",
"ci": "ciimports.py",
}
CODE_IMPORTERS = {"python", "javascript", "js", "go", "rust", "pyclasses"}
@@ -103,6 +104,8 @@ def detect_source(path):
data = json.loads(p.read_text(encoding="utf-8"))
if data.get("schema") == "drawio-skill/diagram-ir/v1":
return "ir"
+ if "asyncapi" in data:
+ return "asyncapi"
if "openapi" in data or "swagger" in data:
return "openapi"
except (OSError, ValueError):
@@ -110,6 +113,8 @@ def detect_source(path):
return "graph"
if suffix in {".yaml", ".yml"}:
text = p.read_text(encoding="utf-8", errors="ignore")[:10000]
+ if "asyncapi:" in text:
+ return "asyncapi"
if "openapi:" in text or "swagger:" in text:
return "openapi"
if "services:" in text:
@@ -161,6 +166,7 @@ def importer_ir(source, source_type, group=False):
"rust",
"pyclasses",
"openapi",
+ "asyncapi",
}:
cmd.insert(-2, "--group")
proc = subprocess.run(cmd, text=True, capture_output=True)
@@ -500,7 +506,7 @@ def parser():
p.set_defaults(func=cmd_doctor)
p = sub.add_parser(
- "build", help="build a draw.io from IR, graph JSON, code, IaC, SQL or OpenAPI"
+ "build", help="build a draw.io from IR, graph JSON, code, IaC, SQL, OpenAPI or AsyncAPI"
)
p.add_argument("source")
p.add_argument("-o", "--output", required=True)
diff --git a/tests/test_asyncapiimports.py b/tests/test_asyncapiimports.py
new file mode 100644
index 0000000..6eb2808
--- /dev/null
+++ b/tests/test_asyncapiimports.py
@@ -0,0 +1,133 @@
+import importlib.util
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+SCRIPT = os.path.join(ROOT, "skills", "drawio-skill", "scripts", "asyncapiimports.py")
+
+
+def load_importer():
+ spec = importlib.util.spec_from_file_location("asyncapiimports", SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class TestAsyncApiImports(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.importer = load_importer()
+
+ def test_asyncapi_2_operations_channels_and_payload_schemas(self):
+ spec = {
+ "asyncapi": "2.6.0",
+ "channels": {
+ "orders/created": {
+ "publish": {
+ "operationId": "emitOrder",
+ "message": {"$ref": "#/components/messages/OrderCreated"},
+ },
+ "subscribe": {
+ "summary": "Consume order",
+ "message": {"payload": {"$ref": "#/components/schemas/Audit"}},
+ },
+ }
+ },
+ "components": {
+ "messages": {
+ "OrderCreated": {"payload": {"$ref": "#/components/schemas/Order"}}
+ },
+ "schemas": {
+ "Order": {
+ "properties": {"audit": {"$ref": "#/components/schemas/Audit"}}
+ },
+ "Audit": {"properties": {"id": {"type": "string"}}},
+ },
+ },
+ }
+
+ graph = self.importer.build(spec, group=True, direction="TB")
+ by_id = {node["id"]: node for node in graph["nodes"]}
+ pairs = {(edge["source"], edge["target"]) for edge in graph["edges"]}
+
+ self.assertEqual(graph["direction"], "TB")
+ self.assertEqual(by_id["channel:orders/created"]["group"], "orders")
+ self.assertIn("fillColor=#d5e8d4", by_id["operation:orders/created:publish"]["style"])
+ self.assertIn("fillColor=#dae8fc", by_id["operation:orders/created:subscribe"]["style"])
+ self.assertIn(("operation:orders/created:publish", "channel:orders/created"), pairs)
+ self.assertIn(("operation:orders/created:publish", "schema:Order"), pairs)
+ self.assertIn(("operation:orders/created:subscribe", "schema:Audit"), pairs)
+ self.assertIn(("schema:Order", "schema:Audit"), pairs)
+ self.assertEqual(
+ by_id["operation:orders/created:publish"]["provenance"]["pointer"],
+ "#/channels/orders~1created/publish",
+ )
+
+ def test_asyncapi_3_send_operation_and_channel_tag(self):
+ spec = {
+ "asyncapi": "3.0.0",
+ "channels": {
+ "orderEvents": {
+ "address": "orders/{orderId}",
+ "tags": [{"name": "commerce"}],
+ "messages": {
+ "changed": {"$ref": "#/components/messages/OrderChanged"},
+ "ignored": {"payload": {"$ref": "#/components/schemas/Audit"}},
+ },
+ }
+ },
+ "operations": {
+ "sendOrder": {
+ "action": "send",
+ "channel": {"$ref": "#/channels/orderEvents"},
+ "messages": [{"$ref": "#/channels/orderEvents/messages/changed"}],
+ }
+ },
+ "components": {
+ "messages": {
+ "OrderChanged": {"payload": {"$ref": "#/components/schemas/Order"}}
+ },
+ "schemas": {
+ "Order": {"type": "object"},
+ "Audit": {"type": "object"},
+ },
+ },
+ }
+
+ graph = self.importer.build(spec, group=True)
+ by_id = {node["id"]: node for node in graph["nodes"]}
+ pairs = {(edge["source"], edge["target"]) for edge in graph["edges"]}
+
+ self.assertEqual(by_id["channel:orderEvents"]["label"], "orders/{orderId}")
+ self.assertEqual(by_id["operation:sendOrder"]["group"], "commerce")
+ self.assertIn(("operation:sendOrder", "channel:orderEvents"), pairs)
+ self.assertIn(("operation:sendOrder", "schema:Order"), pairs)
+ self.assertNotIn(("operation:sendOrder", "schema:Audit"), pairs)
+
+ def test_cli_emits_graph_json(self):
+ spec = {
+ "asyncapi": "3.0.0",
+ "channels": {"events": {"address": "events"}},
+ }
+ with tempfile.TemporaryDirectory() as directory:
+ path = os.path.join(directory, "asyncapi.json")
+ with open(path, "w", encoding="utf-8") as handle:
+ json.dump(spec, handle)
+ result = subprocess.run(
+ [sys.executable, SCRIPT, path, "--direction", "TB"],
+ capture_output=True,
+ text=True,
+ )
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout)["direction"], "TB")
+ self.assertIn("1 channels", result.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_diagramctl.py b/tests/test_diagramctl.py
index b698368..b471a20 100644
--- a/tests/test_diagramctl.py
+++ b/tests/test_diagramctl.py
@@ -332,6 +332,45 @@ class TestDiagramCtl(unittest.TestCase):
edge = next(e for e in ir["edges"] if e["source"] == "pkg.cli")
self.assertEqual(edge["provenance"]["line"], 1)
+ def test_build_auto_detects_asyncapi_and_preserves_provenance(self):
+ with tempfile.TemporaryDirectory() as td:
+ src = os.path.join(td, "asyncapi.json")
+ out = os.path.join(td, "events.drawio")
+ ir_json = os.path.join(td, "events.ir.json")
+ spec = {
+ "asyncapi": "2.6.0",
+ "channels": {
+ "orders/created": {
+ "publish": {
+ "message": {
+ "payload": {"$ref": "#/components/schemas/Order"}
+ }
+ }
+ }
+ },
+ "components": {"schemas": {"Order": {"type": "object"}}},
+ }
+ with open(src, "w", encoding="utf-8") as fh:
+ json.dump(spec, fh)
+
+ result = self.run_cli(
+ "build", src, "--group", "--ir-output", ir_json, "-o", out
+ )
+
+ self.assertEqual(0, result.returncode, result.stderr)
+ self.assertEqual("asyncapi", json.loads(result.stdout)["source_type"])
+ with open(ir_json, encoding="utf-8") as fh:
+ ir = json.load(fh)
+ operation = next(
+ node for node in ir["nodes"] if node["id"].startswith("operation:")
+ )
+ self.assertEqual("asyncapi", operation["provenance"]["importer"])
+ self.assertEqual(
+ "#/channels/orders~1created/publish",
+ operation["provenance"]["pointer"],
+ )
+ self.assertEqual("orders", operation["group"])
+
def test_view_fallback_reports_metadata_gap(self):
# A model with no deployment/security/data metadata must say so, with a
# hint, instead of silently falling back to the whole graph.