# drawio-skill

Adopt this skill: https://proskills.md/skills/other/agents365-ai-drawio-skill-skills-drawio-skill

Page: https://proskills.md/skills/other/agents365-ai-drawio-skill-skills-drawio-skill
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/drawio-skill/SKILL.md
size: 10697
sha: a5be57351bcedcc1a90c49baa174c858319062e2
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/SKILL.md

````text
---
disable-model-invocation: true
name: drawio-skill
description: Create and edit draw.io/diagrams.net diagrams as editable `.drawio` files. Covers architecture, UML/ERD/sequence, BPMN, network, and swimlane views authored from a description or converted from code, IaC, SQL, and API schemas, plus sync, query, test, review, export, and publish of existing diagrams. Use when the user asks for draw.io/diagrams.net or an editable diagram; prefer Mermaid/PlantUML when diagrams-as-code is enough.
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.4.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"]}
---

# Draw.io Architecture Studio

Produce editable `.drawio` artifacts, not flattened pictures. The preferred
entrypoint is `scripts/diagramctl.py`, which unifies generation, incremental
sync, multi-view projection, semantic queries/tests/reviews, failure analysis,
and accessible publishing over a shared Diagram IR.

## Choose the workflow

| Request | Route |
| --- | --- |
| 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, AsyncAPI, or CI source | Use `diagramctl.py build`; read `references/diagram-ir.md` |
| Protocol Buffers schema (.proto) | Use `protoimports.py` or `diagramctl.py build`; read `references/toolbox.md` |
| GraphQL SDL schema (.graphql/.gql) or introspection JSON | Use `graphqlerd.py` or `diagramctl.py build`; read `references/toolbox.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` |
| Query, architecture policy, review, what-if, or guided walkthrough | Read `references/semantic-workflows.md` |
| MCP host (Claude Desktop, Cursor, VS Code, Codex) should call these workflows | Register `scripts/diagramctl_mcp.py`; read `references/mcp.md` |
| Prompt phrasing for a diagram type or semantic workflow | Read `references/cookbook.md` |
| Enforce architecture rules or visual diffs in GitHub Actions CI | Read `references/ci-gate.md` |
| Rendered before/after/diff images as a PR review comment | Use `prdiff.py`; read `references/pr-bot.md` |
| Existing `.drawio` to HTML/PPTX/Mermaid/Markdown/animation/runbook | Read `references/toolbox.md`; `diagramctl.py transform` exposes the existing tools |
| Pipeline, journey, or subsystem map drawn as a metro/subway map | Use `tubemap.py`; read `references/tubemap.md` |
| Shape, cloud/vendor, AI, or Databricks icon | Read `references/shapes.md` or `references/databricks.md`; never guess shape names |
| Learn/apply/manage a visual style | Read `references/style-presets.md` |
| Extract a reusable style from an existing diagram or theme | Read `references/style-extraction.md` |
| Existing image to editable diagram (screenshot, whiteboard photo, legacy PNG) | Read `references/derasterize.md` |
| Export/platform problem | Read `references/troubleshooting.md`; for access/network questions read `references/security.md` |

## Unified CLI

Run from this skill directory, or replace `scripts/` with the absolute path to
this skill's scripts directory:

```bash
python3 scripts/diagramctl.py doctor
python3 scripts/diagramctl.py build model.json --from ir -o architecture.drawio
python3 scripts/diagramctl.py build ./infra --from terraform --group \
  --ir-output architecture.ir.json -o architecture.drawio
python3 scripts/diagramctl.py sync architecture.drawio ./infra --from terraform \
  -o architecture.next.drawio
python3 scripts/diagramctl.py views architecture.ir.json \
  --views executive,system,deployment,dataflow,security -o views.drawio
python3 scripts/diagramctl.py test architecture.drawio --rules policy.yml
python3 scripts/diagramctl.py review architecture.drawio -o review.md
python3 scripts/diagramctl.py query architecture.drawio --from internet --to orders-db
python3 scripts/diagramctl.py whatif architecture.ir.json --fail kafka \
  --drawio kafka-failure.drawio -o impact.json
python3 scripts/diagramctl.py story architecture.ir.json -o walkthrough.html
```

`doctor` does not launch GUI tools unless `--probe` is passed. Core semantic
commands are offline and stdlib-only.

## Creation workflow

Before the first native export, resolve the draw.io CLI once (see Export
invariants below). `python3 scripts/diagramctl.py doctor` prints the absolute
path it found. The bundled exporters resolve it themselves, so a name mismatch
(`drawio` vs `draw.io.exe`) no longer blocks them.

1. Infer the diagram type, audience, scope, output format, and location from the
   request. Ask only when a missing choice materially changes the result;
   default to PNG plus `.drawio` in the working directory.
2. Select the authoring route from the table above. For a data-backed diagram,
   prefer Diagram IR and preserve provenance. For a large graph, use an importer
   or `autolayout.py`; do not hand-place more than roughly fifteen nodes.
3. Resolve an explicitly named style preset, or the user's default preset, as
   documented in `references/style-presets.md`. Structural diagram conventions
   and visual presets compose; they do not replace each other.
4. Generate the `.drawio`, then run structural validation:

   ```bash
   python3 scripts/validate.py diagram.drawio --score
   ```

   When semantic metadata or an architecture policy is in scope, also run
   `diagramctl.py test`. Do not present inferred semantic findings as verified
   runtime facts.
5. Export a draft PNG without embedded XML and inspect it visually. Fix obvious
   overlap, clipping, disconnected edges, edge-through-node routing, stacked
   edges, and unreadable labels. Stop automatic vision repair after two rounds.
   When the drawio binary is unavailable or a visual check is inconclusive,
   verify the renderer's own DOM instead (`--dump-dom` on the viewer URL, see
   `references/troubleshooting.md`): read each edge's `<path>` segments and
   label anchor coordinates directly — vision alone both misses geometry
   defects and hallucinates new ones.
6. Show the draft and apply targeted edits. Preserve existing geometry for
   local changes. Use `sync` for source-backed changes and write a reviewable
   output; use `--prune` only when deletion was requested.
7. After approval, create final requested formats and report both editable
   source and export paths.

## Export invariants

Resolve the available binary once, to an **absolute path**, and use that exact
path for the run. `scripts/drawio_cli.py` does this for every bundled exporter
(`buildup.py`, `drawio2pptx.py`, `drawiohtml.py`, `prdiff.py`, `svgflow.py`,
`timelapse.py`), and `diagramctl.py doctor` reports the result. It tries both
PATH names, then the macOS app bundle and the Windows install directories:

- macOS Homebrew and Linux packages: `drawio` (no dot)
- Windows: `draw.io.exe` (with the dot). `drawio` does not exist there, and
  `subprocess` cannot launch a `.cmd`/`.bat` shim, so never pass a bare name.
- macOS app bundle: `/Applications/draw.io.app/Contents/MacOS/draw.io`
- Windows install directories: `%ProgramFiles%\draw.io\draw.io.exe`,
  `%LOCALAPPDATA%\Programs\draw.io\draw.io.exe`

The commands below use `drawio`; substitute your resolved path.

```bash
# Draft for visual inspection: never use -e here
drawio -x -f png --width 2000 -o diagram.png diagram.drawio

# Final editable PNG
drawio -x -f png -e -s 2 -o diagram.drawio.png diagram.drawio
python3 scripts/repair_png.py diagram.drawio.png

# Final editable SVG/PDF
drawio -x -f svg -e --embed-svg-images -o diagram.svg diagram.drawio
drawio -x -f pdf -e -o diagram.pdf diagram.drawio
```

Do not combine `--width` and `-s`. Embedded PNG exports require
`repair_png.py`; draft PNGs used by vision must not use `-e`. On Linux headless,
follow `references/troubleshooting.md` rather than improvising Electron flags.
If the CLI crashes in a macOS sandbox, try one permitted escalated run, then use
`encode_drawio_url.py` or deliver XML; do not repeatedly launch it.

## Editing and identity

- Use stable semantic IDs and never reuse reserved IDs `0` or `1`.
- Every edge requires `<mxGeometry relative="1" as="geometry"/>`.
- For a local edit, change the matching cell only; for a global direction
  change, regenerate/re-layout the page.
- Keep provenance, `data-model-id`, semantic properties, manual geometry, and
  manual styles intact unless the user requests otherwise.
- When reconciling, retain removals as reviewable faded elements by default.
- For edges stacked at a boundary, run `edgeports.py`; add waypoints when an
  edge still crosses an unrelated shape. There is no CLI-only edge rerouter
  that preserves node positions.

## Quality and trust

An attractive diagram can still be wrong. Prefer source-backed relationships,
show provenance where useful, distinguish exact extraction from AI inference,
and keep architecture review findings framed as prompts. Story HTML must remain
self-contained, keyboard usable, and include a text alternative. Never include
secrets in node properties or provenance because they are embedded in outputs.

For all focused scripts and composition patterns, read `references/toolbox.md`;
load only the task-specific reference needed for the current request.
````

## File: skills/drawio-skill/scripts/aiicons.py
size: 8398
sha: b2681fe66a59f680e624d801040ae3df8731849f
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/aiicons.py

```text
#!/usr/bin/env python3
"""Find AI / LLM brand logos (OpenAI, Claude, Gemini, ...) as draw.io styles.

draw.io's bundled shape libraries have no modern AI/LLM brand logos, so an
"LLM app architecture" renders as generic boxes. This resolves a brand name to a
draw.io `image` style that references the matching SVG from the lobe-icons set
(https://github.com/lobehub/lobe-icons, MIT) on the unpkg CDN.

  python3 aiicons.py "openai"
  python3 aiicons.py "claude" --json
  python3 aiicons.py "langchain" --variant mono --size 48

The icon is referenced by URL (data/lobe-icons.json carries only the name list,
not the assets), so draw.io fetches it from the CDN when the diagram is rendered
or opened. That means **network is required at render time**; an offline export
draws a blank box. Use --embed to fetch the SVG once and inline it as a
self-contained data URI instead (portable, no network at render time).

The logos are trademarks of their respective owners and are referenced here for
identification only — the same basis on which draw.io ships AWS/Azure icons.

Usage: python3 aiicons.py <query> [--limit N] [--variant color|mono|text]
                                  [--size PX] [--embed] [--json] [--list]
"""
import argparse
import base64
import json
import os
import re
import sys
import urllib.parse
import urllib.request

MANIFEST = os.path.join(os.path.dirname(__file__), "..", "data", "lobe-icons.json")
STYLE = ("shape=image;html=1;imageAspect=0;aspect=fixed;"
         "verticalLabelPosition=bottom;verticalAlign=top;image=")
_VARIANT = re.compile(r"-(?:color|text(?:-[a-z]{2})?|brand(?:-color)?)$")

# Common RAG/LLM data stores that lobe-icons lacks, mapped to simple-icons
# slugs (https://simpleicons.org, CC0). Served from the simple-icons CDN. Each
# slug below is verified to return HTTP 200 at https://cdn.simpleicons.org/<slug>.
_SIMPLEICONS_CDN = "https://cdn.simpleicons.org/"
_ALLOWED_HOSTS = {"unpkg.com", "cdn.simpleicons.org"}
_SUPPLEMENT = {
    "qdrant": "qdrant",
    "milvus": "milvus",
    "supabase": "supabase",
    "redis": "redis",
    "postgresql": "postgresql",
    "mongodb": "mongodb",
    "elasticsearch": "elasticsearch",
    "neo4j": "neo4j",
    "kafka": "apachekafka",
    "clickhouse": "clickhouse",
    "duckdb": "duckdb",
    "mysql": "mysql",
    "sqlite": "sqlite",
    "cassandra": "apachecassandra",
    "snowflake": "snowflake",
    "databricks": "databricks",
    "mariadb": "mariadb",
    "couchbase": "couchbase",
}

def families(icons):
    """base brand name -> set of its variant filenames (without .svg)."""
    fam = {}
    for name in icons:
        base = _VARIANT.sub("", name)
        fam.setdefault(base, set()).add(name)
    return fam

def squish(s):
    return re.sub(r"[^a-z0-9]", "", s.lower())

def safe_url(url):
    """Reject a tampered manifest before emitting or fetching its URL."""
    parsed = urllib.parse.urlparse(url)
    if parsed.scheme != "https" or parsed.hostname not in _ALLOWED_HOSTS:
        raise ValueError(f"refusing icon URL outside allowlist: {url}")
    return url

def fetch(url):
    return urllib.request.urlopen(safe_url(url), timeout=15).read()

def search(fam, query, limit):
    """Rank brand bases against the query (squished + per-token matching)."""
    q = squish(query)
    tokens = [t for t in re.findall(r"[a-z0-9]+", query.lower()) if t]
    scored = {}
    for base in fam:
        b = squish(base)
        s = 0
        if q and q == b:
            s = 100
        elif q and b.startswith(q):
            s = 60
        elif q and q in b:
            s = 40
        for t in tokens:
            if t == b:
                s = max(s, 90)
            elif len(t) >= 3 and b.startswith(t):
                s = max(s, 50)
            elif len(t) >= 3 and t in b:
                s = max(s, 30)
        if s:
            scored[base] = s
    return sorted(scored, key=lambda base: (-scored[base], base))[:limit]

def search_supplement(query):
    """Fall back to the simple-icons supplement (exact or substring match)."""
    q = squish(query)
    if not q:
        return None
    if q in _SUPPLEMENT:
        return q
    for brand in _SUPPLEMENT:
        if q in brand or brand in q:
            return brand
    return None

def pick_variant(base, variants, prefer):
    order = {"color": ["-color", "-brand-color", "", "-brand", "-text", "-text-cn"],
             "mono":  ["", "-brand", "-color", "-brand-color", "-text", "-text-cn"],
             "text":  ["-text", "-text-cn", "-brand", "-brand-color", "-color", ""]}[prefer]
    for suffix in order:
        cand = base + suffix
        if cand in variants:
            return cand
    return next(iter(sorted(variants)), None)

def main():
    ap = argparse.ArgumentParser(description="Find AI/LLM brand logos as draw.io styles (lobe-icons via CDN).")
    ap.add_argument("query", nargs="?", help='brand name, e.g. "openai" or "claude"')
    ap.add_argument("--limit", type=int, default=8)
    ap.add_argument("--variant", choices=["color", "mono", "text"], default="color")
    ap.add_argument("--size", type=int, default=48, help="cell width/height in px (icons are square)")
    ap.add_argument("--embed", action="store_true",
                    help="inline the SVG as a data URI (fetches it now; portable, no network at render time)")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--list", action="store_true", help="list all brand names and exit")
    args = ap.parse_args()

    if not os.path.exists(MANIFEST):
        sys.exit(f"error: manifest not found at {MANIFEST}")
    with open(MANIFEST, encoding="utf-8") as f:
        manifest = json.load(f)
    fam = families(manifest["icons"])
    cdn = safe_url(manifest["cdn"])

    if args.list:
        for base in sorted(fam):
            print(base)
        return
    if not args.query:
        ap.error("a query is required (or use --list)")

    matches = search(fam, args.query, args.limit)

    results = []
    if matches:
        for base in matches:
            file = pick_variant(base, fam[base], args.variant)
            url = f"{cdn}{file}.svg"
            if args.embed:
                try:
                    svg = fetch(url)
                except Exception as exc:                   # noqa: BLE001 - report and skip
                    sys.stderr.write(f"warning: could not fetch {url} ({exc})\n")
                    continue
                # Rewrite the 1em intrinsic size so draw.io scales the inlined SVG.
                svg = svg.replace(b'width="1em"', b'width="24"').replace(b'height="1em"', b'height="24"')
                # Marker-less base64: draw.io splits style values on ';', so a
                # ';base64,' marker would truncate the image= value (issue #80).
                image = "data:image/svg+xml," + base64.b64encode(svg).decode()
            else:
                image = url
            results.append({"brand": base, "file": file, "w": args.size, "h": args.size,
                            "style": STYLE + image})
    else:
        # lobe has no logo for this brand; fall back to the simple-icons supplement.
        brand = search_supplement(args.query)
        if brand:
            slug = _SUPPLEMENT[brand]
            url = _SIMPLEICONS_CDN + slug
            image = url
            if args.embed:
                try:
                    svg = fetch(url)
                    # Marker-less base64 (see issue #80 note above).
                    image = "data:image/svg+xml," + base64.b64encode(svg).decode()
                except Exception as exc:                   # noqa: BLE001 - keep the CDN URL
                    sys.stderr.write(f"warning: could not fetch {url} ({exc}); using CDN URL\n")
            results.append({"brand": brand, "file": f"simpleicons:{slug}",
                            "w": args.size, "h": args.size, "style": STYLE + image})

    if not results:
        sys.exit(f"no logo for {args.query!r} — for a data store try a cylinder "
                 f"(shape=cylinder3) or shapesearch.py '{args.query} database'")

    if args.json:
        print(json.dumps(results, indent=2, ensure_ascii=False))
    else:
        for r in results:
            shown = r["style"] if len(r["style"]) < 160 else r["style"][:157] + "..."
            print(f"{r['brand']}  ({r['file']}, {r['w']}x{r['h']})\n  {shown}")

if __name__ == "__main__":
    main()
```

## File: skills/drawio-skill/scripts/asyncapiimports.py
size: 11148
sha: 8306e2b016ba8bda2ebea830fee803b573f47eaa
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/asyncapiimports.py

```text
#!/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."""
    # pi-lens-ignore: ast-grep:unchecked-throwing-call-python
    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 = str(operation.get("action") or "")
        action = {"send": "publish", "receive": "subscribe"}.get(action, 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}"
        raw_channel = channels[channel_name]
        channel = raw_channel if isinstance(raw_channel, dict) else {}
        # Without a summary or operationId (common in AsyncAPI 2), the channel
        # address reads better than the synthetic "channel:action" name.
        title = (
            operation.get("summary")
            or operation.get("operationId")
            or str(channel.get("address") or channel_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:
            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 {}
        count = len(properties)
        label = name + (f"\n({count} field{'s' if count != 1 else ''})" if count 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:
        # pi-lens-ignore: ast-grep:unchecked-throwing-call-python
        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()
```

## File: skills/drawio-skill/scripts/autolayout.py
size: 18286
sha: af2a84b4ff8b23f86d3d3bd6e0169791df3d5474
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/autolayout.py

```text
#!/usr/bin/env python3
"""Auto-layout a logical graph into draw.io XML using Graphviz.

Minimal layout pass for the drawio skill: takes a graph (nodes + edges as
JSON), runs `dot` to position the nodes, and emits a .drawio file with the
mxGeometry x/y filled in. draw.io routes the edges itself (orthogonal style).
This removes the manual-coordinate ceiling for medium/large diagrams.

Input JSON:
  {
    "direction": "TB",          # TB (top-bottom, default) or LR (left-right)
    "nodes": [
      {"id": "a", "label": "Service A", "style": "rounded=1;...",
       "width": 120, "height": 60}
    ],
    "edges": [
      {"source": "a", "target": "b", "label": "calls"}
    ]
  }
Only "id" is required per node; label defaults to id and style/width/height
have defaults. Node ids must be unique and must not be "0" or "1" (reserved
for the draw.io root cells). Requires Graphviz `dot` on PATH.

Usage: python3 autolayout.py graph.json [-o diagram.drawio]
"""
import argparse
import json
import os
import shlex
import subprocess
import sys
from xml.sax.saxutils import escape

DEFAULT_W, DEFAULT_H = 120, 60
NODE_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"
EDGE_STYLE = "html=1;rounded=0;"
GROUP_STYLE = ("rounded=0;whiteSpace=wrap;html=1;fillColor=none;strokeColor=#999999;"
               "verticalAlign=top;fontStyle=2;dashed=1;")
# Group colours come from the skill's own palette (styles/built-in/default.json)
# so there is a single source of truth, not a second list baked in here. When a
# grouped graph is laid out, each top-level group takes the next colour (cycled
# in a fixed, harmonious role order) so related modules read as a coloured
# cluster. Nodes that carry their own `style` keep it; only styleless grouped
# nodes are tinted. Disable with --mono.
_PALETTE_ORDER = ["primary", "success", "accent", "secondary", "warning", "danger", "neutral"]
_PALETTE_FILE = os.path.join(os.path.dirname(__file__), "..", "styles", "built-in", "default.json")
_FALLBACK_PALETTE = [("#dae8fc", "#6c8ebf"), ("#d5e8d4", "#82b366"), ("#ffe6cc", "#d79b00"),
                     ("#e1d5e7", "#9673a6"), ("#fff2cc", "#d6b656"), ("#f8cecc", "#b85450")]

def load_palette():
    """Ordered (fill, stroke) list from the default preset's palette; fall back
    to the same colours inline if the preset file can't be read."""
    try:
        with open(_PALETTE_FILE, encoding="utf-8") as fh:
            pal = json.load(fh)["palette"]
        colors = [(pal[r]["fillColor"], pal[r]["strokeColor"]) for r in _PALETTE_ORDER if r in pal]
        if colors:
            return colors
    except (OSError, KeyError, ValueError):
        pass
    return _FALLBACK_PALETTE

PALETTE = load_palette()
# Uniform container padding; the title sits in the top pad (verticalAlign=top).
# dot's cluster margin is set to this same value so each container box equals
# dot's cluster box — which dot guarantees never overlaps, at any nesting depth.
GROUP_PAD = 24

def attr(value):
    # Newlines in labels become &#xa; so draw.io renders a line break (a raw
    # newline inside an XML attribute is normalized to a space by parsers).
    return escape(str(value), {'"': "&quot;", "\n": "&#xa;"})

def dot_quote(value):
    # Wrap as a DOT double-quoted string, escaping backslash and quote so ids
    # with those characters can't corrupt the Graphviz input.
    return '"' + str(value).replace("\\", "\\\\").replace('"', '\\"') + '"'

def snap(value, grid=10):
    # Align to the grid the skill uses everywhere (multiples of 10).
    return int(round(value / grid) * grid)

def group_tree(nodes):
    """Parse hierarchical `group` paths ("a/b") into a container tree.

    Returns (gpath, direct, children, ordered):
      gpath[node_id] = tuple of path segments (the node's deepest container)
      direct[path]   = node ids whose group is exactly this path
      children[path] = child container paths
      ordered        = all container paths, shallow-to-deep (stable)
    """
    gpath, direct, paths = {}, {}, set()
    for node in nodes:
        g = node.get("group")
        if g is None or str(g).strip("/") == "":
            continue
        t = tuple(str(g).strip("/").split("/"))
        gpath[node["id"]] = t
        direct.setdefault(t, []).append(node["id"])
        for k in range(1, len(t) + 1):
            paths.add(t[:k])
    children = {}
    for p in sorted(paths):
        if len(p) > 1:
            children.setdefault(p[:-1], []).append(p)
    ordered = sorted(paths, key=lambda p: (len(p), p))
    return gpath, direct, children, ordered

def build_dot(graph):
    rankdir = "LR" if str(graph.get("direction", "TB")).upper() == "LR" else "TB"
    # Optional graph-level spacing (inches). Icon nodes render their label below
    # the shape, so importers emitting icons ask for extra rank/node separation.
    sep = "".join(f" {k}={float(graph[k]):.2f};" for k in ("ranksep", "nodesep") if k in graph)
    # splines=ortho makes dot route edges as orthogonal polylines; we replay
    # those bends as draw.io waypoints so edges go around nodes, not through them.
    lines = [f"digraph G {{ rankdir={rankdir};{sep} splines=ortho; node [shape=box fixedsize=true];"]
    # Group nodes into (possibly nested) clusters so dot keeps each group
    # together; a node's first appearance fixes its cluster, so list members
    # before the size attributes. The cluster margin reserves room for the
    # padded container boxes we draw below (extra on Y for the title strip) so
    # neighbouring boxes do not overlap.
    _, direct, children, ordered = group_tree(graph["nodes"])
    cidx = {p: i for i, p in enumerate(ordered)}

    def emit_cluster(p, pad):
        lines.append(f'{pad}subgraph cluster_{cidx[p]} {{ margin={GROUP_PAD};')
        for c in children.get(p, []):
            emit_cluster(c, pad + "  ")
        lines.extend(f'{pad}  {dot_quote(m)};' for m in direct.get(p, []))
        lines.append(pad + "}")

    for root in [p for p in ordered if len(p) == 1]:
        emit_cluster(root, "")
    for node in graph["nodes"]:
        # Pass our pixel sizes to dot as inches so it lays out at the real size.
        w = node.get("width", DEFAULT_W) / 72.0
        h = node.get("height", DEFAULT_H) / 72.0
        lines.append(f'{dot_quote(node["id"])} [width={w:.4f} height={h:.4f}];')
    for edge in graph.get("edges", []):
        lines.append(f'{dot_quote(edge["source"])} -> {dot_quote(edge["target"])};')
    lines.append("}")
    return "\n".join(lines)

def layout(dot_src):
    """Run `dot -Tplain`; return (height_in, {id: (xc, yc)}, {(src, dst): [(x, y), ...]}).

    Node coords are inches (bottom-left origin); each edge's value is the list
    of orthogonal control points dot computed for routing, endpoints included.
    """
    try:
        proc = subprocess.run(
            ["dot", "-Tplain"], input=dot_src,
            capture_output=True, text=True, check=True,
        )
    except FileNotFoundError:
        sys.exit("error: Graphviz `dot` not found on PATH (brew install graphviz)")
    except subprocess.CalledProcessError as exc:
        sys.exit(f"error: dot failed: {exc.stderr.strip()}")
    height, pos, edges = 0.0, {}, {}
    for line in proc.stdout.splitlines():
        tok = shlex.split(line)
        if not tok:
            continue
        if tok[0] == "graph":
            height = float(tok[3])                        # graph scale width height
        elif tok[0] == "node":
            pos[tok[1]] = (float(tok[2]), float(tok[3]))  # node name x y ...
        elif tok[0] == "edge":                            # edge tail head n x1 y1 ... xn yn
            n = int(tok[3])
            edges[(tok[1], tok[2])] = [
                (float(tok[4 + 2 * i]), float(tok[5 + 2 * i])) for i in range(n)
            ]
    return height, pos, edges

def group_style(stroke):
    """Container box styled with a group's colour (coloured border + title)."""
    return (f"rounded=0;whiteSpace=wrap;html=1;fillColor=none;strokeColor={stroke};"
            f"fontColor={stroke};verticalAlign=top;fontStyle=2;dashed=1;")

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 = {}
    for node in nodes:
        nid = node["id"]
        if nid not in pos:
            continue
        w, h = node.get("width", DEFAULT_W), node.get("height", DEFAULT_H)
        xc, yc = pos[nid]
        x = snap(xc * 72 - w / 2)
        y = snap((height - yc) * 72 - h / 2)             # flip: dot origin is bottom-left
        rects[nid] = (x, y, w, h)
    # Parse the (possibly nested) group tree and assign each container a
    # collision-free id and a title (the path's last segment, or a member's groupLabel).
    gpath, direct, children, ordered = group_tree(nodes)
    # Assign each top-level group a palette colour, in order of first appearance.
    top_order = []
    for node in nodes:
        t = gpath.get(node["id"])
        if t and t[0] not in top_order:
            top_order.append(t[0])

    def gcolor(seg):
        return PALETTE[top_order.index(seg) % len(PALETTE)]

    used = {n["id"] for n in nodes}
    label_override = {}
    for node in nodes:
        if node["id"] in gpath and "groupLabel" in node:
            label_override.setdefault(gpath[node["id"]], str(node["groupLabel"]))
    gid, glabel = {}, {}
    for i, p in enumerate(ordered):
        cid = f"group_{i}"
        while cid in used:                               # never collide with a node id
            cid += "_"
        used.add(cid)
        gid[p] = cid
        glabel[p] = label_override.get(p, p[-1])
    # Container bounding box (members + nested children + uniform padding),
    # computed deepest-first so a parent can wrap its already-sized children.
    gbox = {}
    for p in sorted(ordered, key=len, reverse=True):
        xs = [(rects[m][0], rects[m][1], rects[m][0] + rects[m][2], rects[m][1] + rects[m][3])
              for m in direct.get(p, []) if m in rects]
        xs += [(gbox[c][0], gbox[c][1], gbox[c][0] + gbox[c][2], gbox[c][1] + gbox[c][3])
               for c in children.get(p, []) if c in gbox]
        if not xs:
            continue
        x0 = min(b[0] for b in xs) - GROUP_PAD
        y0 = min(b[1] for b in xs) - GROUP_PAD
        x1 = max(b[2] for b in xs) + GROUP_PAD
        y1 = max(b[3] for b in xs) + GROUP_PAD
        gbox[p] = (x0, y0, x1 - x0, y1 - y0)

    # Shift everything positive: a container's top padding can push its top edge
    # above the page origin. Only translates when something would be negative.
    absx = [r[0] for r in rects.values()] + [b[0] for b in gbox.values()]
    absy = [r[1] for r in rects.values()] + [b[1] for b in gbox.values()]
    dx = GROUP_PAD - min(absx) if absx and min(absx) < 0 else 0
    dy = GROUP_PAD - min(absy) if absy and min(absy) < 0 else 0

    def rebase(x, y, parent_path):
        """Absolute -> coordinates relative to parent_path's box (or shifted if top-level)."""
        if parent_path is None:
            return x + dx, y + dy, "1"
        px, py, _, _ = gbox[parent_path]
        return x - px, y - py, gid[parent_path]

    cells = []
    # Containers shallow-first so each parent precedes its children.
    for p in ordered:
        if p not in gbox:
            continue
        gx, gy, gw, gh = gbox[p]
        x, y, parent = rebase(gx, gy, p[:-1] if len(p) > 1 else None)
        gstyle = group_style(gcolor(p[0])[1]) if color else GROUP_STYLE
        cells.append(
            f'        <mxCell id="{attr(gid[p])}" value="{attr(glabel[p])}" '
            f'style="{gstyle}" vertex="1" parent="{attr(parent)}">\n'
            f'          <mxGeometry x="{x}" y="{y}" width="{gw}" height="{gh}" as="geometry"/>\n'
            f"        </mxCell>"
        )
    for node in nodes:
        nid = node["id"]
        if nid not in rects:
            continue
        rx, ry, w, h = rects[nid]
        x, y, parent = rebase(rx, ry, gpath.get(nid) if gpath.get(nid) in gbox else None)
        if node.get("style"):
            style = node["style"]                         # explicit style always wins
        elif color and nid in gpath:
            fill, stroke = gcolor(gpath[nid][0])          # tint styleless nodes by group
            style = f"rounded=1;whiteSpace=wrap;html=1;fillColor={fill};strokeColor={stroke};"
        else:
            style = NODE_STYLE
        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.
        interior = edge_pts.get((edge["source"], edge["target"]), [])[1:-1]
        if interior:
            points = "".join(
                f'<mxPoint x="{snap(x * 72) + dx}" y="{snap((height - y) * 72) + dy}"/>'
                for x, y in interior
            )
            geom = (f'<mxGeometry relative="1" as="geometry">'
                    f'<Array as="points">{points}</Array></mxGeometry>')
        else:
            geom = '<mxGeometry relative="1" as="geometry"/>'
        cells.append(
            f'        <mxCell id="e{i}" value="{attr(edge.get("label", ""))}" '
            f'style="{attr(edge.get("style", EDGE_STYLE))}" edge="1" parent="1" '
            f'source="{attr(edge["source"])}" target="{attr(edge["target"])}">\n'
            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 (
        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'
        + 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 count
    of edge-through-vertex hits and edge-edge crossings, with total edge length
    as a tiebreak. Uses the same geometry predicates as validate.py."""
    import importlib.util
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "validate.py")
    spec = importlib.util.spec_from_file_location("validate", path)
    v = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(v)
    rects = {}
    for node in graph["nodes"]:
        if node["id"] in pos:
            w, h = node.get("width", DEFAULT_W), node.get("height", DEFAULT_H)
            xc, yc = pos[node["id"]]
            rects[node["id"]] = (xc * 72 - w / 2, (height - yc) * 72 - h / 2, w, h)
    routes = []
    for edge in graph.get("edges", []):
        pts = edge_pts.get((edge["source"], edge["target"]))
        if pts:
            routes.append(([(x * 72, (height - y) * 72) for x, y in pts],
                           {edge["source"], edge["target"]}))
    through = sum(1 for pts, ends in routes for nid, box in rects.items()
                  if nid not in ends and v.route_hits_rect(pts, box))
    cross = sum(1 for i in range(len(routes)) for j in range(i + 1, len(routes))
                if v.routes_cross(routes[i][0], routes[j][0]))
    length = sum(abs(b[0] - a[0]) + abs(b[1] - a[1])
                 for pts, _ in routes for a, b in zip(pts, pts[1:]))
    return 20 * through + 10 * cross + length / 100000

def main():
    ap = argparse.ArgumentParser(description="Auto-layout a graph JSON into draw.io XML.")
    ap.add_argument("input", help="graph JSON file")
    ap.add_argument("-o", "--output", help="output .drawio path (default: stdout)")
    ap.add_argument("--mono", action="store_true",
                    help="don't colour groups by palette (monochrome boxes)")
    ap.add_argument("--tune", action="store_true",
                    help="lay out in both directions (TB and LR), keep the more "
                         "readable one (fewer crossings / through-vertex routes)")
    args = ap.parse_args()
    with open(args.input, encoding="utf-8") as f:
        graph = json.load(f)
    if args.tune:
        best = None
        for d in ("TB", "LR"):
            cand = dict(graph, direction=d)
            h, p, ep = layout(build_dot(cand))
            s = route_score(cand, h, p, ep)
            if best is None or s < best[0]:
                best = (s, d, h, p, ep)
        _, d, height, pos, edge_pts = best
        print(f"tuned: direction={d} (score {best[0]:.2f})", file=sys.stderr)
    else:
        height, pos, edge_pts = layout(build_dot(graph))
    xml = to_drawio(graph, height, pos, edge_pts, color=not args.mono)
    if args.output:
        with open(args.output, "w", encoding="utf-8") as f:
            f.write(xml)
        print(f"wrote {args.output} ({len(graph['nodes'])} nodes, "
              f"{len(graph.get('edges', []))} edges)", file=sys.stderr)
    else:
        sys.stdout.write(xml)

if __name__ == "__main__":
    main()
```

## File: skills/drawio-skill/scripts/buildup.py
size: 14585
sha: 495cd1a43c2e15f71b031040f5d1666a27ef7336
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/buildup.py

```text
#!/usr/bin/env python3
"""Animate a static .drawio building itself, node by node -> HTML player.

Reveals a diagram's cells incrementally in dependency order — topological over
its edges, so a source always appears before the targets it points to, with
ties (and any leftover cycle members) falling back to document order — and
assembles a self-contained HTML player (base64-embedded PNG frames, play /
pause / step / scrub) of the diagram constructing itself, like a build
time-lapse.

  python3 buildup.py architecture.drawio
  # -> architecture.drawio's directory / buildup.html
  python3 buildup.py architecture.drawio -o build.html --gif build.gif

Each frame is a temp copy of the diagram with not-yet-revealed cells removed
from <root> (not opacity — draw.io ignores that on headless export). An edge
is only shown once BOTH its endpoints are revealed. Container/group cells are
always shown (only leaf vertices and the edges between them build up one step
at a time). The page size is pinned to the FULL diagram's bounding box on
every frame so nothing jumps around as cells appear. Needs the draw.io CLI;
`--gif` additionally needs Pillow (skipped with a warning if absent — the
HTML is written regardless).

Usage: python3 buildup.py <file.drawio> [-o out.html] [--gif out.gif]
       [--fps N] [--hold N] [--keep-frames]
"""
import argparse
import base64
import copy
import io
import json
import os
import subprocess
import sys
import tempfile
import xml.etree.ElementTree as ET

HERE = os.path.dirname(os.path.abspath(__file__))
if HERE not in sys.path:  # loaded by file path (tests): keep the sibling import working
    sys.path.insert(0, HERE)
from drawio_cli import resolve_drawio

def parse_page(path):
    """First page of a .drawio -> (tree, cells).

    cells: list of dicts {id, el, vertex, edge, parent, source, target, style,
    relative, x, y, w, h} in document order. `el` is the TOP-LEVEL <root>
    child (mxCell / UserObject / object) so it can be removed directly;
    vertex/edge/geometry attributes are read off the inner mxCell for wrapped
    cells (UserObject/object), same unwrapping as drawiodiff.parse().
    """
    try:
        tree = ET.parse(path)
    except (ET.ParseError, OSError) as exc:
        sys.exit(f"error: cannot parse {path}: {exc}")
    pages = tree.getroot().findall("diagram")
    if not pages:
        sys.exit(f"error: no <diagram> pages in {path}")
    if len(pages) > 1:
        sys.stderr.write(f"warning: {path} has {len(pages)} pages, animating the first only\n")
    model = pages[0].find("mxGraphModel")
    root = model.find("root") if model is not None else None
    if root is None:
        sys.exit(f"error: {path}: page is compressed, cannot buildup")

    cells = []
    for el in root:
        inner = el if el.tag == "mxCell" else el.find("mxCell")
        if inner is None:
            continue
        g = inner.find("mxGeometry")
        relative = g is not None and g.get("relative") == "1"
        if g is not None and not relative and g.get("x") is not None and g.get("width") is not None:
            x, y = float(g.get("x")), float(g.get("y", 0))
            w, h = float(g.get("width")), float(g.get("height", 0))
        else:
            x = y = w = h = None
        cells.append({
            "id": el.get("id"), "el": el,
            "vertex": inner.get("vertex") == "1", "edge": inner.get("edge") == "1",
            "parent": inner.get("parent"), "source": inner.get("source"),
            "target": inner.get("target"), "style": inner.get("style") or "",
            "relative": relative, "x": x, "y": y, "w": w, "h": h,
        })
    return tree, cells

def classify(cells):
    """cells -> (leaf_vertex_ids in doc order, container_ids, edges[(id,source,target)]).

    Mirrors drawiodiff.parse(): a vertex that is some other cell's `parent` is
    a container/group (always shown, never an individual reveal step); an
    edge-label sub-cell (relative geometry or an `edgeLabel` style) is neither
    a node nor revealed on its own — it rides along once its parent edge is.
    """
    parents = {c["parent"] for c in cells if c["parent"]}
    leaves, containers, edges = [], set(), []
    for c in cells:
        if c["edge"]:
            if c["source"] and c["target"]:
                edges.append((c["id"], c["source"], c["target"]))
        elif c["vertex"]:
            if c["relative"] or "edgeLabel" in c["style"]:
                continue
            if c["id"] in parents:
                containers.add(c["id"])
            else:
                leaves.append(c["id"])
    return leaves, containers, edges

def bounding_box(cells, margin=40):
    """(width, height) of the full diagram from every absolute cell geometry,
    with a margin — used to pin pageWidth/pageHeight so frames don't jump."""
    xs = [c["x"] + c["w"] for c in cells if c["x"] is not None]
    ys = [c["y"] + c["h"] for c in cells if c["y"] is not None]
    if not xs or not ys:
        return 850, 1100
    return int(max(xs)) + margin, int(max(ys)) + margin

def reveal_order(node_ids, edges):
    """Kahn topological order over node_ids given directed (source, target)
    edges. Ties among ready nodes, and any nodes left over from a cycle, fall
    back to document order (node_ids' input order)."""
    doc = list(dict.fromkeys(node_ids))                    # de-dup, keep doc order
    idx = {nid: i for i, nid in enumerate(doc)}
    adj = {nid: [] for nid in doc}
    indeg = {nid: 0 for nid in doc}
    for s, t in edges:
        if s in idx and t in idx and s != t:
            adj[s].append(t)
            indeg[t] += 1

    import heapq
    ready = list({idx[n] for n in doc if indeg[n] == 0})
    heapq.heapify(ready)
    order, seen = [], set()
    while ready:
        nid = doc[heapq.heappop(ready)]
        seen.add(nid)
        order.append(nid)
        for nxt in adj[nid]:
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                heapq.heappush(ready, idx[nxt])
    for nid in doc:                                        # cycle remnants, document order
        if nid not in seen:
            order.append(nid)
    return order

def reveal_steps(node_order, edges):
    """-> (node_step {id: int}, edge_step {edge_id: int}). An edge's step is
    the LATER of its two endpoints' steps, so it only appears once both are
    revealed (endpoints outside node_order, e.g. a container, count as step 0
    — already shown)."""
    node_step = {nid: i for i, nid in enumerate(node_order)}
    edge_step = {eid: max(node_step.get(s, 0), node_step.get(t, 0)) for eid, s, t in edges}
    return node_step, edge_step

def label_of(el):
    """Visible text of a root child (mxCell or UserObject/object wrapper)."""
    if el.tag == "mxCell":
        return el.get("value") or el.get("id") or ""
    return el.get("label") or el.get("value") or el.get("id") or ""

def build_html(frames, title):
    """Self-contained HTML player. frames: [(png_bytes, label, step, total)]."""
    data = [{"img": "data:image/png;base64," + base64.b64encode(png).decode(),
             "label": label, "step": step, "total": total}
            for png, label, step, total in frames]
    payload = json.dumps(data).replace("</", "<\\/")
    return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title}</title><style>
:root{{color-scheme:light dark}}
*{{box-sizing:border-box}}
body{{margin:0;font:14px/1.5 system-ui,-apple-system,Segoe UI,sans-serif;
background:#f6f7f9;color:#1a1a1a}}
@media(prefers-color-scheme:dark){{body{{background:#15171a;color:#e8e8e8}}}}
header{{padding:16px 20px 4px}}h1{{margin:0;font-size:17px;font-weight:600}}
main{{max-width:1100px;margin:0 auto;padding:8px 16px 28px}}
#stage{{background:#fff;border:1px solid #0001;border-radius:10px;
min-height:60vh;display:flex;align-items:center;justify-content:center;padding:12px}}
@media(prefers-color-scheme:dark){{#stage{{background:#1e2226;border-color:#fff2}}}}
#stage img{{max-width:100%;max-height:74vh;object-fit:contain}}
.cap{{display:flex;gap:14px;flex-wrap:wrap;align-items:baseline;
padding:12px 4px 6px;color:#556;font-size:13px}}
@media(prefers-color-scheme:dark){{.cap{{color:#9aa}}}}
.cap .lbl{{color:#1a1a1a;font-weight:600}}
@media(prefers-color-scheme:dark){{.cap .lbl{{color:#e8e8e8}}}}
.bar{{height:6px;border-radius:3px;background:#0d99ff;transition:width .3s}}
.barwrap{{height:6px;background:#0001;border-radius:3px;margin:2px 4px 12px}}
.ctl{{display:flex;gap:10px;align-items:center;padding:4px}}
button{{font:inherit;padding:6px 12px;border:1px solid #0002;border-radius:8px;
background:#fff;cursor:pointer;color:inherit}}
@media(prefers-color-scheme:dark){{button{{background:#262b31;border-color:#fff2}}}}
button:hover{{border-color:#0d99ff}}
input[type=range]{{flex:1;accent-color:#0d99ff}}
</style></head><body>
<header><h1>{title}</h1></header>
<main>
<div id="stage"><img id="img" alt="build-up frame"></div>
<div class="cap">
  <span><b id="idx"></b></span>
  <span>+ <span class="lbl" id="label"></span></span>
</div>
<div class="barwrap"><div class="bar" id="bar"></div></div>
<div class="ctl">
  <button id="prev">‹ Prev</button>
  <button id="play">▶ Play</button>
  <button id="next">Next ›</button>
  <input type="range" id="scrub" min="0" value="0">
</div>
</main>
<script>
const F={payload};
let i=0,timer=null;
const $=id=>document.getElementById(id);
$("scrub").max=F.length-1;
function show(k){{
  i=(k+F.length)%F.length;const f=F[i];
  $("img").src=f.img;$("idx").textContent=`Step ${{f.step}} / ${{f.total}}`;
  $("label").textContent=f.label;
  $("bar").style.width=(6+94*f.step/f.total)+"%";$("scrub").value=i;
}}
function stop(){{clearInterval(timer);timer=null;$("play").textContent="▶ Play";}}
$("prev").onclick=()=>{{stop();show(i-1);}};
$("next").onclick=()=>{{stop();show(i+1);}};
$("scrub").oninput=e=>{{stop();show(+e.target.value);}};
$("play").onclick=()=>{{
  if(timer){{stop();return;}}
  $("play").textContent="⏸ Pause";
  timer=setInterval(()=>{{if(i>=F.length-1){{show(0);}}else{{show(i+1);}}}},700);
}};
show(0);
</script></body></html>"""

def make_gif(pngs, out_path, fps, hold):
    """Assemble PNG frame bytes into an animated GIF via Pillow. Skips with a
    stderr warning (not fatal) if Pillow isn't installed."""
    try:
        from PIL import Image
    except ImportError:
        sys.stderr.write("warning: Pillow not installed, skipping --gif (pip install Pillow)\n")
        return
    frames = [Image.open(io.BytesIO(p)).convert("RGB") for p in pngs]
    duration = [int(1000 / fps)] * (len(frames) - 1) + [int(hold * 1000)]
    frames[0].save(out_path, save_all=True, append_images=frames[1:],
                   duration=duration, loop=0)
    sys.stderr.write(f"wrote {out_path} ({len(frames)} frames)\n")

def main():
    ap = argparse.ArgumentParser(description="Animate a .drawio building itself -> self-contained HTML player.")
    ap.add_argument("file", help="input .drawio (uncompressed)")
    ap.add_argument("-o", "--output", help="output .html (default: buildup.html alongside input)")
    ap.add_argument("--gif", help="also assemble frames into an animated GIF (needs Pillow)")
    ap.add_argument("--fps", type=float, default=2.0, help="GIF frames per second (default 2)")
    ap.add_argument("--hold", type=float, default=1.5, help="seconds to hold the final GIF frame")
    ap.add_argument("--keep-frames", action="store_true", help="also write the PNG frames next to the output")
    args = ap.parse_args()

    if not os.path.isfile(args.file):
        sys.exit(f"error: {args.file} not found")
    drawio = resolve_drawio()
    if not drawio:
        sys.exit("error: draw.io CLI not found on PATH (is the draw.io CLI installed?)")

    tree, cells = parse_page(args.file)
    leaves, containers, edge_list = classify(cells)
    if not leaves:
        sys.exit(f"error: no revealable vertices found in {args.file}")

    order = reveal_order(leaves, [(s, t) for _, s, t in edge_list])
    node_step, edge_step = reveal_steps(order, edge_list)
    width, height = bounding_box(cells)
    labels = {c["id"]: label_of(c["el"]) for c in cells}
    n_total = len(order)

    out = args.output or os.path.join(
        os.path.dirname(os.path.abspath(args.file)) or ".", "buildup.html")

    frames = []
    with tempfile.TemporaryDirectory() as tmp:
        for k in range(n_total):
            revealed_nodes = set(order[:k + 1])
            revealed_edges = {eid for eid, _, _ in edge_list if edge_step[eid] <= k}
            keep = {"0", "1"} | containers | revealed_nodes | revealed_edges
            keep |= {c["id"] for c in cells if c["id"] not in keep and c["parent"] in keep}

            frame_tree = copy.deepcopy(tree)
            model = frame_tree.getroot().find("diagram").find("mxGraphModel")
            model.set("pageWidth", str(width))
            model.set("pageHeight", str(height))
            froot = model.find("root")
            for child in list(froot):
                if child.get("id") not in keep:
                    froot.remove(child)

            src = os.path.join(tmp, f"step{k:03d}.drawio")
            frame_tree.write(src, encoding="utf-8", xml_declaration=False)
            png_path = os.path.join(tmp, f"step{k:03d}.png")
            r = subprocess.run([drawio, "-x", "-f", "png", "--page-index", "1",
                                "--width", "2000", "-o", png_path, src], capture_output=True)
            if r.returncode != 0 or not os.path.exists(png_path):
                sys.stderr.write(f"warning: step {k + 1}/{n_total} export failed — skipped\n")
                continue
            with open(png_path, "rb") as f:
                png = f.read()
            label = labels.get(order[k], order[k])
            frames.append((png, label, k + 1, n_total))
            if args.keep_frames:
                with open(f"{os.path.splitext(out)[0]}-frame{k + 1:03d}.png", "wb") as f:
                    f.write(png)
            sys.stderr.write(f"[{k + 1}/{n_total}] revealed {label!r}\n")

    if not frames:
        sys.exit("error: no frames exported (is the draw.io CLI installed?)")

    title = os.path.splitext(os.path.basename(args.file))[0] + " — build-up"
    with open(out, "w", encoding="utf-8") as f:
        f.write(build_html(frames, title))
    sys.stderr.write(f"wrote {out} ({len(frames)} frames)\n")

    if args.gif:
        make_gif([f[0] for f in frames], args.gif, args.fps, args.hold)

if __name__ == "__main__":
    main()
```

## File: skills/drawio-skill/scripts/c4.py
size: 6670
sha: dab2bf1c912999bf721ccd8910756e3de8ad84c2
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/c4.py

```text
#!/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()
```

## File: skills/drawio-skill/scripts/ciimports.py
size: 7776
sha: 1c865ac1c8cbbc1c739b19460b9246f81f3871a8
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/ciimports.py

```text
#!/usr/bin/env python3
"""Extract a CI pipeline (GitHub Actions / GitLab CI) as autolayout graph JSON.

GitHub Actions: every job becomes a node (label: name, runner, matrix size,
reusable-workflow target), `needs:` become edges, and each workflow gets a
trigger node (its `on:` events) feeding the jobs that have no `needs`. Given a
repo root, all of `.github/workflows/*.yml|yaml` are read and each workflow is
boxed in its own container.

GitLab CI (`.gitlab-ci.yml`, auto-detected): jobs become nodes grouped by
stage; edges come from `needs:`, and jobs without `needs` inherit the stage
DAG (every job of the previous stage), matching GitLab's execution order.

  python3 ciimports.py .                          # repo root -> all workflows
  python3 ciimports.py .github/workflows/ci.yml -o graph.json
  python3 autolayout.py graph.json -o pipeline.drawio

Requires PyYAML (pip install pyyaml).

Usage: python3 ciimports.py <repo-root | workflow.yml ...> [-o graph.json]
       [--direction TB|LR]
"""
import argparse
import json
import os
import sys

JOB_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"
REUSE_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;"
TRIGGER_STYLE = "ellipse;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;"

GITLAB_RESERVED = {"stages", "variables", "workflow", "default", "include", "image",
                   "services", "before_script", "after_script", "cache", "pages"}

def find_workflows(path):
    """Workflow files for a path: file(s) as-is, a repo root via .github/workflows."""
    if os.path.isfile(path):
        return [path]
    wfdir = os.path.join(path, ".github", "workflows")
    files = sorted(os.path.join(wfdir, f) for f in os.listdir(wfdir)
                   if f.endswith((".yml", ".yaml"))) if os.path.isdir(wfdir) else []
    gitlab = os.path.join(path, ".gitlab-ci.yml")
    if os.path.isfile(gitlab):
        files.append(gitlab)
    if not files:
        sys.exit(f"error: no workflow files under {path}")
    return files

def matrix_size(strategy):
    n = 1
    matrix = (strategy or {}).get("matrix") or {}
    if not isinstance(matrix, dict):
        return 0                                # dynamic (fromJSON) — unknown
    for key, vals in matrix.items():
        if key not in ("include", "exclude") and isinstance(vals, list):
            n *= len(vals)
    n += len(matrix.get("include") or []) - len(matrix.get("exclude") or [])
    return max(n, 1)

def parse_actions(spec, wf_id, wf_name, group):
    """One GitHub Actions workflow -> (nodes, edges)."""
    nodes, edges = [], []
    # YAML 1.1 quirk: bare `on:` parses as boolean True
    on = spec.get("on", spec.get(True, {}))
    events = sorted(on) if isinstance(on, dict) else \
        ([on] if isinstance(on, str) else sorted(on or []))
    trig_id = f"{wf_id}//trigger"
    nodes.append({"id": trig_id, "label": "on: " + (", ".join(events) or "?"),
                  "style": TRIGGER_STYLE, "width": 160, "height": 50, "group": group})
    jobs = spec.get("jobs") or {}
    for jid, job in jobs.items():
        job = job or {}
        lines = [job.get("name") or jid]
        if job.get("uses"):
            lines.append("uses: " + os.path.basename(str(job["uses"])))
            style = REUSE_STYLE
        else:
            style = JOB_STYLE
            runner = job.get("runs-on")
            if runner:
                lines.append(str(runner if isinstance(runner, str) else ", ".join(runner)))
        n = matrix_size(job.get("strategy"))
        if n > 1:
            lines.append(f"matrix ×{n}")
        elif n == 0:
            lines.append("matrix (dynamic)")
        nodes.append({"id": f"{wf_id}//{jid}", "label": "\n".join(lines),
                      "style": style, "width": 180, "height": 60, "group": group})
        needs = job.get("needs") or []
        needs = [needs] if isinstance(needs, str) else needs
        for dep in needs:
            if dep in jobs:
                edges.append({"source": f"{wf_id}//{dep}", "target": f"{wf_id}//{jid}"})
        if not needs:
            edges.append({"source": trig_id, "target": f"{wf_id}//{jid}"})
    return nodes, edges

def parse_gitlab(spec, wf_id, group_prefix):
    """A .gitlab-ci.yml -> (nodes, edges); jobs grouped by stage."""
    stages = spec.get("stages") or ["build", "test", "deploy"]
    jobs = {k: v for k, v in spec.items()
            if isinstance(v, dict) and k not in GITLAB_RESERVED and not k.startswith(".")
            and ("script" in v or "trigger" in v or "extends" in v or "stage" in v)}
    nodes, edges = [], []
    by_stage = {}
    for jid, job in jobs.items():
        stage = job.get("stage") or "test"
        by_stage.setdefault(stage, []).append(jid)
        nodes.append({"id": f"{wf_id}//{jid}", "label": jid, "style": JOB_STYLE,
                      "width": 160, "height": 50,
                      "group": f"{group_prefix}{stage}"})
    order = [s for s in stages if s in by_stage]
    for jid, job in jobs.items():
        needs = [(n.get("job") if isinstance(n, dict) else n) for n in job.get("needs") or []]
        needs = [n for n in needs if n in jobs]
        if needs:
            edges.extend({"source": f"{wf_id}//{n}", "target": f"{wf_id}//{jid}"} for n in needs)
        else:                                   # stage DAG: all jobs of the previous stage
            stage = job.get("stage") or "test"
            i = order.index(stage) if stage in order else 0
            if i > 0:
                edges.extend({"source": f"{wf_id}//{p}", "target": f"{wf_id}//{jid}"}
                             for p in by_stage[order[i - 1]])
    return nodes, edges

def main():
    ap = argparse.ArgumentParser(description="CI pipeline -> autolayout graph JSON.")
    ap.add_argument("paths", nargs="+",
                    help="repo root, or workflow file(s) (.github/workflows/*.yml, .gitlab-ci.yml)")
    ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")
    ap.add_argument("--direction", default="LR", choices=["TB", "LR"])
    args = ap.parse_args()

    try:
        import yaml
    except ImportError:
        sys.exit("error: PyYAML is required (pip install pyyaml)")

    files = [f for p in args.paths for f in find_workflows(p)]
    nodes, edges = [], []
    for path in files:
        with open(path, encoding="utf-8") as f:
            try:
                spec = yaml.safe_load(f) or {}
            except yaml.YAMLError as e:
                sys.stderr.write(f"warning: skipping {path}: {e}\n")
                continue
        wf_id = os.path.splitext(os.path.basename(path))[0]
        if os.path.basename(path) == ".gitlab-ci.yml" or (
                "jobs" not in spec and "stages" in spec):
            n, e = parse_gitlab(spec, wf_id, "stage: " if len(files) == 1
                                else f"{wf_id} / stage: ")
        elif spec.get("jobs"):
            wf_name = spec.get("name") or wf_id
            group = wf_name if len(files) > 1 else None
            n, e = parse_actions(spec, wf_id, wf_name, group)
        else:
            sys.stderr.write(f"warning: {path} has no jobs — skipped\n")
            continue
        nodes.extend(n)
        edges.extend(e)
    if not nodes:
        sys.exit("error: no CI jobs found")

    graph = {"direction": args.direction, "nodes": nodes, "edges": edges}
    text = json.dumps(graph, indent=2)
    if args.output:
        with open(args.output, "w", encoding="utf-8") as f:
            f.write(text)
        sys.stderr.write(f"wrote {args.output}\n")
    else:
        sys.stdout.write(text)
    sys.stderr.write(f"{len(nodes)} nodes, {len(edges)} edges from {len(files)} file(s)\n")

if __name__ == "__main__":
    main()
```

## File: skills/drawio-skill/scripts/composeimports.py
size: 4738
sha: 0de350953129da2eb84ec9bbf3af17cffe437e15
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/composeimports.py

```text
#!/usr/bin/env python3
"""Extract a docker-compose file's service graph as autolayout graph JSON.

Services become rounded boxes (labeled name + image), named volumes become
cylinders, and edges come from real wiring: `depends_on` (list or mapping
form), `links`, `volumes_from`, and named-volume mounts (short "vol:/path"
and long {type: volume, source: ...} syntax). The output feeds autolayout.py:

  python3 composeimports.py docker-compose.yml -o graph.json
  python3 autolayout.py graph.json -o stack.drawio

Given a directory, the usual compose file names are tried
(compose.yaml/compose.yml/docker-compose.yml/docker-compose.yaml).
Requires PyYAML (pip install pyyaml). `--group` boxes services by their
first network.

Usage: python3 composeimports.py <compose-file-or-dir> [-o graph.json]
       [--direction TB|LR] [--group]
"""
import argparse
import json
import os
import sys

SERVICE_STYLE = "rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;"
VOLUME_STYLE = ("shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;size=15;"
                "fillColor=#f5f5f5;strokeColor=#666666;")

def find_compose(path):
    if os.path.isfile(path):
        return path
    for name in ("compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml"):
        cand = os.path.join(path, name)
        if os.path.isfile(cand):
            return cand
    sys.exit(f"error: no compose file found under {path}")

def volume_mounts(svc):
    """Named volumes a service mounts (short and long syntax)."""
    for v in svc.get("volumes") or []:
        if isinstance(v, str):
            src = v.split(":", 1)[0]
            if src and not src.startswith((".", "/", "~", "$")):
                yield src
        elif isinstance(v, dict) and v.get("type", "volume") == "volume" and v.get("source"):
            yield v["source"]

def dependencies(svc):
    dep = svc.get("depends_on") or []
    deps = list(dep) if isinstance(dep, (list, dict)) else []
    for link in svc.get("links") or []:
        deps.append(str(link).split(":", 1)[0])
    for vf in svc.get("volumes_from") or []:
        deps.append(str(vf).split(":", 1)[0])
    return deps

def main():
    ap = argparse.ArgumentParser(description="docker-compose -> autolayout graph JSON.")
    ap.add_argument("path", help="compose file, or directory containing one")
    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 services into containers by their first network")
    args = ap.parse_args()

    try:
        import yaml
    except ImportError:
        sys.exit("error: PyYAML is required (pip install pyyaml)")
    path = find_compose(args.path)
    with open(path, encoding="utf-8") as f:
        spec = yaml.safe_load(f) or {}
    services = spec.get("services") or {}
    if not services:
        sys.exit(f"error: no services in {path}")
    declared_volumes = set(spec.get("volumes") or {})

    nodes, edges = [], set()
    for name, svc in services.items():
        svc = svc or {}
        image = svc.get("image") or ("build: " + str((svc.get("build") or {}).get("context", ".")
                                                     if isinstance(svc.get("build"), dict)
                                                     else svc.get("build", ".")))
        node = {"id": name, "label": f"{name}\n{image}", "style": SERVICE_STYLE,
                "width": 160, "height": 60}
        nets = svc.get("networks")
        first_net = (sorted(nets)[0] if isinstance(nets, dict) else nets[0]) if nets else None
        if args.group and first_net:
            node["group"] = str(first_net)
        nodes.append(node)
        for dep in dependencies(svc):
            if dep in services and dep != name:
                edges.add((name, dep))
        for vol in volume_mounts(svc):
            if vol in declared_volumes:
                edges.add((name, f"vol:{vol}"))
    for vol in sorted({t[4:] for _, t in edges if t.startswith("vol:")}):
        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)]}
    text = json.dumps(graph, indent=2)
    if args.output:
        with open(args.output, "w", encoding="utf-8") as f:
            f.write(text)
        sys.stderr.write(f"wrote {args.output}\n")
    else:
        sys.stdout.write(text)
    sys.stderr.write(f"{len(nodes)} nodes, {len(edges)} edges\n")

if __name__ == "__main__":
    main()
```

## File: skills/drawio-skill/scripts/compress.py
size: 10582
sha: ac4ce492661b1e484040cbd6809f409271ae2f24
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/compress.py

```text
#!/usr/bin/env python3
"""Collapse a big .drawio into a boardroom-friendly executive summary.

Detects clusters in a large diagram with a deterministic pure-Python label
propagation pass (no networkx), replaces each cluster with ONE labeled group
node, keeps aggregated inter-cluster edges, and emits a 2-page .drawio: page 1
is the executive view (auto-laid-out via autolayout.py), page 2 is the
original full diagram, copied verbatim. Each executive node is wrapped in a
draw.io UserObject `data:page/id,...` drill-down link to page 2, so clicking
"Auth (5)" jumps straight into the full detail.

Community detection is unsupervised — it finds however many clusters the
graph naturally has; `--clusters` is only a soft hint and may be ignored.
Clusters are named after the longest common leading token shared by their
members' labels (falling back to the highest-degree member's label), with the
member count appended, e.g. "Auth (5)". Rename them by hand afterward for a
more semantic label — label propagation does not know what your system does.

Requires Graphviz `dot` on PATH (shells out to autolayout.py to place the
executive nodes).

  python3 compress.py big-system.drawio -o exec-view.drawio

Usage: python3 compress.py <diagram.drawio> [-o out.drawio] [--clusters N]
"""
import argparse
import copy
import json
import os
import re
import subprocess
import sys
import tempfile
import xml.etree.ElementTree as ET

HERE = os.path.dirname(os.path.abspath(__file__))

def parse(path):
    """Return (nodes, edges) for a .drawio: nodes {id: (label, style)} for leaf
    vertices, edges {(source_id, target_id)}. Cells are flattened across pages;
    UserObject/object wrappers are unwrapped (id on the wrapper, cell inside).
    Copied from drawiodiff.parse() — see SHARED CONVENTIONS."""
    try:
        tree = ET.parse(path)
    except (ET.ParseError, OSError) as exc:
        sys.exit(f"error: cannot parse {path}: {exc}")
    pages = tree.getroot().findall("diagram") or [tree.getroot()]
    cells, labels = [], {}
    for page in pages:
        model = page.find("mxGraphModel")
        root = model.find("root") if model is not None else None
        if root is None:
            if (page.text or "").strip():
                sys.stderr.write(f"warning: {path}: a page is compressed, skipped\n")
            continue
        for child in root:
            if child.tag == "mxCell":
                cells.append(child)
                labels[child.get("id")] = child.get("value") or ""
            elif child.tag in ("UserObject", "object"):
                inner = child.find("mxCell")
                if inner is not None:
                    inner.set("id", child.get("id", ""))
                    cells.append(inner)
                    labels[child.get("id")] = child.get("label") or child.get("value") or ""
    parents = {c.get("parent") for c in cells}                # ids that have children
    nodes, edges = {}, set()
    for c in cells:
        cid = c.get("id")
        if c.get("edge") == "1":
            s, t = c.get("source"), c.get("target")
            if s and t:
                edges.add((s, t))
        elif c.get("vertex") == "1" and cid not in parents:   # leaf vertices only
            if "edgeLabel" in (c.get("style") or ""):
                continue
            g = c.find("mxGeometry")
            if g is not None and g.get("relative") == "1":    # edge-label child
                continue
            nodes[cid] = (labels.get(cid, ""), c.get("style") or "")
    return nodes, edges

def label_propagation(node_ids, edges, max_passes=20):
    """Deterministic pure-Python label propagation for community detection.

    Edges are treated as undirected for clustering. Each pass computes every
    node's new label synchronously from the PREVIOUS pass's labels (most
    frequent label among neighbours, ties -> smallest label), then applies
    them all at once — this keeps a thin bridge between two dense clusters
    from cascading a merge within a single pass. Stops early once no label
    changes, else after `max_passes`. Returns {node_id: community_label}.
    """
    nodes = sorted(set(node_ids))
    neighbours = {n: set() for n in nodes}
    for s, t in edges:
        if s in neighbours and t in neighbours and s != t:
            neighbours[s].add(t)
            neighbours[t].add(s)
    labels = {n: n for n in nodes}
    for _ in range(max_passes):
        new_labels = {}
        for n in nodes:
            if not neighbours[n]:
                new_labels[n] = labels[n]
                continue
            counts = {}
            for nb in neighbours[n]:
                lbl = labels[nb]
                counts[lbl] = counts.get(lbl, 0) + 1
            best = max(counts.values())
            new_labels[n] = min(lbl for lbl, c in counts.items() if c == best)
        if new_labels == labels:
            break
        labels = new_labels
    return labels

def compute_degree(node_ids, edges):
    """Undirected degree per node (used as the naming tiebreak)."""
    degree = {n: 0 for n in node_ids}
    for s, t in edges:
        if s in degree:
            degree[s] += 1
        if t in degree:
            degree[t] += 1
    return degree

def aggregate_edges(edges, community_of):
    """Roll original edges up to inter-community edges: for every edge whose
    endpoints fall in two different communities, count crossings by
    (source_community, target_community) and dedupe into one entry per pair.
    Same-community (internal) edges are dropped. Returns
    {(src_community, tgt_community): crossing_count}."""
    counts = {}
    for s, t in edges:
        cs, ct = community_of.get(s), community_of.get(t)
        if cs is None or ct is None or cs == ct:
            continue
        counts[(cs, ct)] = counts.get((cs, ct), 0) + 1
    return counts

def cluster_name(member_ids, node_labels, degree):
    """Heuristic community name: the longest common leading token shared by
    every member's label (split on whitespace), else the highest-degree
    member's label. The member count is appended, e.g. "Auth (5)"."""
    token_lists = [str(node_labels.get(m, m)).split() for m in member_ids]
    common = []
    if token_lists and all(token_lists):
        for tokens in zip(*token_lists):
            if len(set(tokens)) == 1:
                common.append(tokens[0])
            else:
                break
    if common:
        base = " ".join(common)
    else:
        top = max(member_ids, key=lambda m: (degree.get(m, 0), m))
        base = node_labels.get(top) or top
    return f"{base} ({len(member_ids)})"

def layout_exec_page(graph):
    """Shell out to autolayout.py to place the executive nodes; return the
    rendered <diagram>...</diagram> page, renamed to a friendlier id/title."""
    with tempfile.TemporaryDirectory() as d:
        gpath = os.path.join(d, "exec.json")
        with open(gpath, "w", encoding="utf-8") as f:
            json.dump(graph, f)
        opath = os.path.join(d, "exec.drawio")
        r = subprocess.run(
            [sys.executable, os.path.join(HERE, "autolayout.py"), gpath, "-o", opath],
            capture_output=True, text=True,
        )
        if r.returncode != 0 or not os.path.exists(opath):
            sys.exit(f"error: autolayout failed: {r.stderr.strip()}")
        with open(opath, encoding="utf-8") as f:
            xml = f.read()
    m = re.search(r"(<diagram\b.*?</diagram>)", xml, re.S)
    if not m:
        sys.exit("error: autolayout produced no page")
    page = m.group(1).replace('id="autolayout"', 'id="exec-view"', 1)
    page = page.replace('name="Page-1"', 'name="Executive View"', 1)
    return page + "\n"

def copy_original_page(path, page2_id):
    """Copy the source's first page verbatim (cells untouched) into a new
    <diagram> with id=page2_id, so exec-node drill-down links resolve to it."""
    try:
        tree = ET.parse(path)
    except (ET.ParseError, OSError) as exc:
        sys.exit(f"error: cannot parse {path}: {exc}")
    pages = tree.getroot().findall("diagram") or [tree.getroot()]
    page = copy.deepcopy(pages[0])
    if page.find("mxGraphModel/root") is None:
        sys.exit(f"error: {path}: page is compressed (no <root>), cannot copy verbatim")
    page.set("id", page2_id)
    page.set("name", "Full Diagram")
    return ET.tostring(page, encoding="unicode") + "\n"

def main():
    ap = argparse.ArgumentParser(
        description="Collapse a big .drawio into an executive-summary view with drill-down.")
    ap.add_argument("input", help="source .drawio")
    ap.add_argument("-o", "--output", help="output .drawio path (default: stdout)")
    ap.add_argument("--clusters", type=int,
                    help="soft hint for cluster count; label propagation picks the "
                         "count automatically and may ignore this")
    args = ap.parse_args()

    if args.clusters:
        sys.stderr.write("note: --clusters is a soft hint; label propagation "
                         "determines the actual cluster count automatically\n")

    nodes, edges = parse(args.input)
    if not nodes:
        sys.exit(f"error: no leaf vertices found in {args.input}")

    community_of = label_propagation(nodes.keys(), edges)
    communities = {}
    for nid in sorted(nodes):
        communities.setdefault(community_of[nid], []).append(nid)

    degree = compute_degree(nodes.keys(), edges)
    node_labels = {nid: label for nid, (label, _style) in nodes.items()}
    names = {c: cluster_name(members, node_labels, degree) for c, members in communities.items()}

    crossings = aggregate_edges(edges, community_of)

    page2_id = "full-diagram"
    exec_nodes = [{"id": f"c_{c}", "label": names[c], "link": f"data:page/id,{page2_id}"}
                  for c in communities]
    exec_edges = [{"source": f"c_{s}", "target": f"c_{t}", "label": str(n) if n > 1 else ""}
                  for (s, t), n in sorted(crossings.items())]
    exec_graph = {"direction": "TB", "nodes": exec_nodes, "edges": exec_edges}

    page1 = layout_exec_page(exec_graph)
    page2 = copy_original_page(args.input, page2_id)
    xml = "<mxfile>\n" + page1 + page2 + "</mxfile>\n"

    if args.output:
        with open(args.output, "w", encoding="utf-8") as f:
            f.write(xml)
        sys.stderr.write(f"wrote {args.output} ({len(nodes)} nodes -> "
                         f"{len(communities)} clusters)\n")
    else:
        sys.stdout.write(xml)
        sys.stderr.write(f"{len(nodes)} nodes -> {len(communities)} clusters\n")

if __name__ == "__main__":
    main()
```

## File: skills/drawio-skill/scripts/dbxicons.py
size: 12632
sha: b1fd056fdb3545e1e8ecf65a13128172f48212a3
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/dbxicons.py

```text
#!/usr/bin/env python3
"""Find Databricks product icons (Unity Catalog, Lakeflow, DLT, ...) as draw.io styles.

draw.io's bundled shape libraries have no Databricks shape set, so a lakehouse
architecture renders as generic boxes. This resolves a Databricks product name
to a draw.io `image` style that references the matching SVG from the community
databricks-architecture-icons project
(https://github.com/oieduardorabelo/databricks-architecture-icons), which
packages official Databricks artwork on a 48x48 canvas.

  python3 dbxicons.py "unity catalog"
  python3 dbxicons.py "DLT" --json
  python3 dbxicons.py "vector search" --variant outline --size 48

Renamed products resolve through aliases: "DLT" and "Delta Live Tables" find
`spark-declarative-pipelines`, "Workflows" finds `lakeflow-jobs`. Match order:
exact slug, exact alias, then ranked substring search over slug, name, and
aliases.

The icon is referenced by URL (data/databricks-icons.json carries names and
category facts only, not the assets), so draw.io fetches it from the project's
GitHub Pages site when the diagram is rendered or opened. That means **network
is required at render time**; an offline export draws a blank box. Use --embed
to fetch the SVG once (from the pinned commit, immutable) and inline it as a
self-contained data URI instead (portable, no network at render time).

Variants: `color` (default), `tile`, `outline`. There is no mono variant on
purpose: the upstream mono SVGs use `currentColor`, which draw.io image shapes
render as black.

The icons are official Databricks artwork served by the community project. They
are trademarks of Databricks, Inc., referenced here for identification only —
the same basis on which draw.io ships AWS/Azure icons. No artwork is bundled.

Usage: python3 dbxicons.py <query> [--limit N] [--variant color|tile|outline]
                                   [--size PX] [--embed] [--json] [--list]
       python3 dbxicons.py --refresh-manifest [--ref REF]   (maintainer-facing)
"""
import argparse
import base64
import json
import os
import re
import sys
import urllib.parse
import urllib.request

MANIFEST = os.path.join(os.path.dirname(__file__), "..", "data", "databricks-icons.json")
STYLE = ("shape=image;html=1;imageAspect=0;aspect=fixed;"
         "verticalLabelPosition=bottom;verticalAlign=top;image=")
_VARIANT_DIRS = {"color": "svg", "tile": "svg-tile", "outline": "svg-outline"}

_REPO = "oieduardorabelo/databricks-architecture-icons"
_SOURCE = f"https://github.com/{_REPO}"
_HOSTED = "https://oieduardorabelo.github.io/databricks-architecture-icons"
_RAW = f"https://raw.githubusercontent.com/{_REPO}/"
_API_COMMIT = f"https://api.github.com/repos/{_REPO}/commits/"
_ALLOWED_HOSTS = {"raw.githubusercontent.com", "api.github.com",
                  "oieduardorabelo.github.io"}

# Curated aliases beyond the upstream catalog's former names ("aka"), for the
# names people still use after Databricks renamed the product. Source of truth
# for --refresh-manifest; edit here, then regenerate the manifest.
EXTRA_ALIASES = {
    "spark-declarative-pipelines": ["DLT", "Delta Live Tables",
                                    "Lakeflow Declarative Pipelines"],
    "lakeflow-jobs": ["Databricks Workflows", "Workflows", "Jobs"],
    "ai-search": ["Vector Search", "Mosaic AI Vector Search"],
    "genie-agents": ["Genie spaces", "AI/BI Genie"],
    "data-quality-monitoring": ["Lakehouse Monitoring"],
    "model-serving": ["Mosaic AI Model Serving"],
    "unity-catalog": ["UC"],
    "databricks-sql": ["DBSQL"],
    "compute-clusters": ["Clusters", "All-purpose compute", "Job compute"],
    "lakehouse-storage": ["Managed tables", "Delta tables"],
    "asset-bundles": ["DAB", "DABs"],
    "git-folders": ["Repos"],
    "mlflow": ["Managed MLflow"],
    "lakebase": ["OLTP", "Postgres"],
    "delta-sharing": ["Data sharing"],
}

def squish(s):
    return re.sub(r"[^a-z0-9]", "", s.lower())

def data_uri(svg_bytes):
    """SVG bytes -> marker-less base64 data URI. draw.io splits style values on
    ';', so a ';base64,' marker would truncate the image= value (issue #80);
    draw.io detects base64 by content."""
    return "data:image/svg+xml," + base64.b64encode(svg_bytes).decode()

def icon_path(product, variant):
    return f"icons/{_VARIANT_DIRS[variant]}/{product['slug']}.svg"

def search(products, query, limit):
    """Rank products against the query (squished + per-token matching) over
    slug, name, and aliases — the same scoring as aiicons.py."""
    q = squish(query)
    tokens = [t for t in re.findall(r"[a-z0-9]+", query.lower()) if t]
    scored = {}
    for i, p in enumerate(products):
        s = 0
        for key in [p["slug"], p["name"]] + p.get("aliases", []):
            b = squish(key)
            if not b:
                continue
            if q and q == b:
                s = max(s, 100)
            elif q and b.startswith(q):
                s = max(s, 60)
            elif q and q in b:
                s = max(s, 40)
            for t in tokens:
                if t == b:
                    s = max(s, 90)
                elif len(t) >= 3 and b.startswith(t):
                    s = max(s, 50)
                elif len(t) >= 3 and t in b:
                    s = max(s, 30)
        if s:
            scored[i] = s
    ranked = sorted(scored, key=lambda i: (-scored[i], products[i]["slug"]))
    return [products[i] for i in ranked[:limit]]

def resolve(products, query, limit):
    """Exact slug, then exact alias/name (case-insensitive), then ranked search."""
    q = squish(query)
    for p in products:
        if squish(p["slug"]) == q:
            return [p]
    for p in products:
        if any(squish(a) == q for a in [p["name"]] + p.get("aliases", [])):
            return [p]
    return search(products, query, limit)

# ---------------------------------------------------------------- refresh ---

def _fetch(url, accept=None):
    parsed = urllib.parse.urlparse(url)
    if parsed.scheme != "https" or parsed.hostname not in _ALLOWED_HOSTS:
        raise ValueError(f"refusing icon URL outside allowlist: {url}")
    headers = {"User-Agent": "drawio-skill-dbxicons"}
    if accept:
        headers["Accept"] = accept
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=30) as resp:
        return resp.read()

def parse_aka(aka):
    """Upstream 'aka' prose -> former-name facts.
    'Lakeflow X. Formerly Delta Live Tables (DLT)' -> two names."""
    names = []
    for part in re.split(r"[.;]", aka or ""):
        part = re.sub(r"^\s*formerly\s+", "", part.strip(), flags=re.I)
        for name in re.split(r"\s+/\s+", part):
            name = name.strip()
            if name:
                names.append(name)
    return names

def build_manifest(catalog, sha):
    """Upstream icons/catalog.json -> the facts-only manifest (no descriptions,
    no docs URLs — those stay upstream)."""
    categories = {key: {"label": val["label"], "color": val["color"]}
                  for key, val in catalog["categories"].items()}
    products = []
    for p in catalog["products"]:
        seen = {squish(p["slug"]), squish(p["name"])}
        aliases = []
        for alias in parse_aka(p.get("aka")) + EXTRA_ALIASES.get(p["slug"], []):
            if squish(alias) not in seen:
                seen.add(squish(alias))
                aliases.append(alias)
        products.append({"slug": p["slug"], "name": p["name"], "aliases": aliases,
                         "category": p["category"],
                         "categoryColor": p["categoryColor"]})
    return {"source": _SOURCE, "hostedBase": _HOSTED, "pinnedRef": sha,
            "canvas": catalog.get("canvas", "48x48"),
            "categories": categories, "products": products}

def refresh_manifest(ref):
    sha = ref if re.fullmatch(r"[0-9a-f]{40}", ref or "") else \
        _fetch(_API_COMMIT + (ref or "main"), accept="application/vnd.github.sha").decode()
    catalog = json.loads(_fetch(f"{_RAW}{sha}/icons/catalog.json"))

    slugs = {p["slug"] for p in catalog["products"]}
    for slug in EXTRA_ALIASES:
        if slug not in slugs:
            sys.stderr.write(f"warning: EXTRA_ALIASES key {slug!r} is not in the "
                             f"upstream catalog (renamed upstream?)\n")

    manifest = build_manifest(catalog, sha)

    old = {}
    if os.path.exists(MANIFEST):
        with open(MANIFEST, encoding="utf-8") as f:
            old = {p["slug"]: p for p in json.load(f).get("products", [])}
    new = {p["slug"]: p for p in manifest["products"]}
    for slug in sorted(set(new) - set(old)):
        print(f"added:   {slug}")
    for slug in sorted(set(old) - set(new)):
        print(f"removed: {slug}")
    for slug in sorted(set(old) & set(new)):
        if old[slug]["name"] != new[slug]["name"]:
            print(f"renamed: {slug}: {old[slug]['name']} -> {new[slug]['name']}")

    with open(MANIFEST, "w", encoding="utf-8", newline="\n") as f:
        json.dump(manifest, f, indent=1, ensure_ascii=False)
        f.write("\n")
    print(f"wrote {os.path.normpath(MANIFEST)}: {len(new)} products, "
          f"{len(manifest['categories'])} categories, pinned {sha}")

# ------------------------------------------------------------------- main ---

def main():
    ap = argparse.ArgumentParser(
        description="Find Databricks product icons as draw.io styles (community-hosted official artwork).")
    ap.add_argument("query", nargs="?", help='product name, e.g. "unity catalog" or "DLT"')
    ap.add_argument("--limit", type=int, default=8)
    ap.add_argument("--variant", choices=sorted(_VARIANT_DIRS), default="color",
                    help="icon style (no mono: upstream mono SVGs render black in draw.io)")
    ap.add_argument("--size", type=int, default=48, help="cell width/height in px (icons are square)")
    ap.add_argument("--embed", action="store_true",
                    help="inline the SVG as a data URI (fetches it now from the pinned commit; "
                         "portable, no network at render time)")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--list", action="store_true", help="list all products and exit")
    ap.add_argument("--refresh-manifest", action="store_true",
                    help="maintainer-facing: regenerate data/databricks-icons.json from the upstream catalog")
    ap.add_argument("--ref", help="git ref for --refresh-manifest (default: remote main HEAD)")
    args = ap.parse_args()

    if args.refresh_manifest:
        refresh_manifest(args.ref)
        return

    if not os.path.exists(MANIFEST):
        sys.exit(f"error: manifest not found at {MANIFEST}")
    with open(MANIFEST, encoding="utf-8") as f:
        manifest = json.load(f)
    hosted = urllib.parse.urlparse(manifest.get("hostedBase", ""))
    if hosted.scheme != "https" or hosted.hostname not in _ALLOWED_HOSTS:
        sys.exit("error: manifest hostedBase is outside the icon host allowlist")
    products = manifest["products"]

    if args.list:
        for p in sorted(products, key=lambda p: p["slug"]):
            print(f"{p['slug']}  {p['name']}")
        return
    if not args.query:
        ap.error("a query is required (or use --list)")

    results = []
    for p in resolve(products, args.query, args.limit):
        path = icon_path(p, args.variant)
        if args.embed:
            url = f"{_RAW}{manifest['pinnedRef']}/{path}"
            try:
                svg = _fetch(url)
            except Exception as exc:                   # noqa: BLE001 - report and skip
                sys.stderr.write(f"warning: could not fetch {url} ({exc})\n")
                continue
            image = data_uri(svg)
        else:
            image = f"{manifest['hostedBase']}/{path}"
        results.append({"product": p["slug"], "name": p["name"],
                        "category": p["category"], "categoryColor": p["categoryColor"],
                        "file": path, "w": args.size, "h": args.size,
                        "style": STYLE + image})

    if not results:
        sys.exit(f"no Databricks product for {args.query!r} — for the bare Databricks "
                 f"logo try aiicons.py 'databricks'; otherwise shapesearch.py {args.query!r}")

    if args.json:
        print(json.dumps(results, indent=2, ensure_ascii=False))
    else:
        for r in results:
            shown = r["style"] if len(r["style"]) < 160 else r["style"][:157] + "..."
            print(f"{r['product']}  {r['name']}  ({r['file']}, {r['w']}x{r['h']})\n  {shown}")

if __name__ == "__main__":
    main()
```

## File: skills/drawio-skill/scripts/diagram_ir.py
size: 59171
sha: 4c329d1bfc249cc57bc5ce5f9bacf03c81d6d11d
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/diagram_ir.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/diagram_ir.py

## File: skills/drawio-skill/scripts/diagramctl.py
size: 20804
sha: 148049913f6200781f6e96b1da32a149e2634775
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/diagramctl.py

```text
#!/usr/bin/env python3
"""Unified command surface for drawio-skill 3.x.

The existing focused scripts remain stable public building blocks.  This CLI
adds orchestration and the semantic Diagram IR used for build/sync/views/test/
query/review/what-if/story workflows.
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

from diagram_ir import (
    DEFAULT_RULES,
    accessible_description,
    impact_analysis,
    infer_profile,
    load_ir,
    normalize_ir,
    project_views,
    reconcile,
    review,
    save_ir,
    semantic_findings,
    story_html,
    write_drawio,
)
from diagram_ir import (
    query as query_ir,
)
from drawio_cli import resolve_drawio

HERE = Path(__file__).resolve().parent
IMPORTERS = {
    "python": "pyimports.py",
    "javascript": "jsimports.py",
    "js": "jsimports.py",
    "go": "goimports.py",
    "rust": "rustimports.py",
    "pyclasses": "pyclasses.py",
    "terraform": "tfimports.py",
    "kubernetes": "k8simports.py",
    "k8s": "k8simports.py",
    "compose": "composeimports.py",
    "sql": "sqlerd.py",
    "openapi": "openapiimports.py",
    "asyncapi": "asyncapiimports.py",
    "proto": "protoimports.py",
    "graphql": "graphqlerd.py",
    "ci": "ciimports.py",
}
CODE_IMPORTERS = {"python", "javascript", "js", "go", "rust", "pyclasses"}
TRANSFORMS = {
    "restyle": "restyle.py",
    "heatmap": "heatmap.py",
    "relabel": "relabel.py",
    "mermaid": "drawio2mermaid.py",
    "pptx": "drawio2pptx.py",
    "viewer": "drawiohtml.py",
    "animate": "svgflow.py",
    "compress": "compress.py",
    "runbook": "runbook.py",
    "buildup": "buildup.py",
    "explain": "explain.py",
}

def emit(value, output=None):
    text = json.dumps(value, indent=2, ensure_ascii=False) + "\n"
    if output:
        Path(output).write_text(text, encoding="utf-8")
    else:
        sys.stdout.write(text)

def detect_source(path):
    p = Path(path)
    if p.is_dir():
        if list(p.rglob("*.tf")):
            return "terraform"
        if (p / "Cargo.toml").exists():
            return "rust"
        if (p / "go.mod").exists():
            return "go"
        if (p / "package.json").exists():
            return "javascript"
        if (p / ".github" / "workflows").exists() or (p / ".gitlab-ci.yml").exists():
            return "ci"
        # Last, because a .proto or .graphql file is often one schema inside a
        # project whose own language markers above describe the repository better.
        if list(p.rglob("*.proto")):
            return "proto"
        if list(p.rglob("*.graphql")) or list(p.rglob("*.gql")):
            return "graphql"
        return "python"
    suffix = p.suffix.lower()
    if suffix == ".proto":
        return "proto"
    if suffix in {".graphql", ".gql"}:
        return "graphql"
    if suffix == ".sql":
        return "sql"
    if suffix in {".tf", ".tfvars"}:
        return "terraform"
    if suffix == ".drawio":
        return "drawio"
    if suffix == ".json":
        try:
            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):
            pass
        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:
            return "compose"
        return "kubernetes"
    return "graph"

def code_kind(prov_path, importer):
    """Semantic kind for a code-source node (v3.2 P0 source profiles).

    Package roots become `library`, entrypoints become `command`, everything
    else is an ordinary `module`. Go packages are library units by definition.
    """
    base = os.path.basename(prov_path or "")
    stem = base.rsplit(".", 1)[0].lower()
    if importer == "go" or stem in {"__init__", "lib"}:
        return "library"
    if stem in {"__main__", "main", "cli"}:
        return "command"
    return "module"

def _resolve_provenance(ir, root_abs):
    """Resolve importer-relative provenance paths against the scanned root."""
    for node in ir["nodes"]:
        prov = node.setdefault("provenance", {})
        rel = prov.get("path")
        if rel and not os.path.isabs(rel):
            prov["path"] = os.path.normpath(os.path.join(root_abs, rel))
        elif not rel:
            prov["path"] = root_abs
    for edge in ir["edges"]:
        prov = edge.get("provenance")
        if prov and prov.get("path") and not os.path.isabs(prov["path"]):
            prov["path"] = os.path.normpath(os.path.join(root_abs, prov["path"]))

def importer_ir(source, source_type, group=False):
    script = HERE / IMPORTERS[source_type]
    with tempfile.TemporaryDirectory(prefix="drawio-skill-") as td:
        graph_path = Path(td) / "graph.json"
        cmd = [sys.executable, str(script), source, "-o", str(graph_path)]
        if group and source_type in {
            "python",
            "javascript",
            "js",
            "go",
            "rust",
            "pyclasses",
            "openapi",
            "asyncapi",
            "proto",
            "graphql",
        }:
            cmd.insert(-2, "--group")
        proc = subprocess.run(cmd, text=True, capture_output=True)
        if proc.returncode:
            raise RuntimeError(
                proc.stderr.strip() or proc.stdout.strip() or f"{script.name} failed"
            )
        # pi-lens-ignore: ast-grep:unchecked-throwing-call-python
        raw = json.loads(graph_path.read_text(encoding="utf-8"))
    ir = normalize_ir(raw, source_path=source)
    ir["metadata"]["importer"] = source_type
    root_abs = os.path.abspath(source)
    _resolve_provenance(ir, root_abs)
    is_code = source_type in CODE_IMPORTERS
    for node in ir["nodes"]:
        prov = node.setdefault("provenance", {})
        prov["importer"] = source_type
        if is_code:
            # Source profile: real file kinds instead of a blanket "service".
            node["kind"] = code_kind(prov.get("path", ""), source_type)
    return ir

def source_ir(source, source_type="auto", group=False):
    source_type = detect_source(source) if source_type == "auto" else source_type
    if source_type in {"graph", "ir", "drawio"}:
        return load_ir(source), source_type
    if source_type not in IMPORTERS:
        raise ValueError(f"unsupported source type {source_type!r}")
    return importer_ir(source, source_type, group=group), source_type

def cmd_doctor(args):
    drawio = resolve_drawio()
    checks = {
        "python": {
            "status": "ok",
            "path": sys.executable,
            "version": sys.version.split()[0],
        },
        "drawio": {
            "status": "available" if drawio else "missing",
            "path": drawio,
            "note": "not executed unless --probe is passed; safe in macOS sandboxes",
        },
        "graphviz": {
            "status": "available" if shutil.which("dot") else "missing",
            "path": shutil.which("dot"),
        },
        "git": {
            "status": "available" if shutil.which("git") else "missing",
            "path": shutil.which("git"),
        },
    }
    for mod in ("yaml", "pptx", "PIL"):
        try:
            available = importlib.util.find_spec(mod) is not None
            if not available:
                raise ModuleNotFoundError(mod)
            checks[mod] = {"status": "available"}
        except (ImportError, ModuleNotFoundError, ValueError):
            checks[mod] = {"status": "optional-missing"}
    if args.probe and drawio:
        try:
            p = subprocess.run(
                [drawio, "--version"], capture_output=True, text=True, timeout=8
            )
            checks["drawio"].update(
                {
                    "probe": "ok" if p.returncode == 0 else "failed",
                    "version": (p.stdout or p.stderr).strip(),
                }
            )
        except (subprocess.TimeoutExpired, OSError) as exc:
            checks["drawio"].update({"probe": "failed", "error": str(exc)})
    checks["capabilities"] = {
        "xml_generation": True,
        "semantic_ir": True,
        "sync": True,
        "native_export": bool(drawio),
        "auto_layout": bool(shutil.which("dot")),
        "network_required": False,
    }
    emit(checks, args.output)

def cmd_build(args):
    ir, source_type = source_ir(args.source, args.source_type, group=args.group)
    ir["metadata"]["title"] = args.title or ir["metadata"].get("title")
    views = project_views(ir, args.views.split(",")) if args.views else None
    write_drawio(ir, args.output, views=views, direction=args.direction)
    if args.ir_output:
        save_ir(ir, args.ir_output)
    emit(
        {
            "output": args.output,
            "ir": args.ir_output,
            "source_type": source_type,
            "nodes": len(ir["nodes"]),
            "edges": len(ir["edges"]),
            "views": [
                {
                    "name": v["name"],
                    "nodes": len(v["nodes"]),
                    "fallback": v.get("fallback", False),
                    "fallback_reason": v.get("fallback_reason"),
                }
                for v in views
            ]
            if views
            else ["System"],
        }
    )

def cmd_inspect(args):
    ir = load_ir(args.input)
    kinds, owners, sources = {}, {}, set()
    for n in ir["nodes"]:
        kinds[n["kind"]] = kinds.get(n["kind"], 0) + 1
        owner = n.get("properties", {}).get("owner")
        if owner:
            owners[owner] = owners.get(owner, 0) + 1
        prov = n.get("provenance", {})
        if prov.get("path"):
            sources.add(prov["path"])
    emit(
        {
            "title": ir["metadata"].get("title"),
            "nodes": len(ir["nodes"]),
            "edges": len(ir["edges"]),
            "kinds": kinds,
            "owners": owners,
            "sources": sorted(sources),
            "alt_text": accessible_description(ir),
        },
        args.output,
    )

def cmd_query(args):
    if bool(args.source) != bool(args.target):
        raise ValueError("path queries require both --from and --to")
    emit(
        query_ir(
            load_ir(args.input),
            kind=args.kind,
            owner=args.owner,
            boundary=args.boundary,
            source=args.source,
            target=args.target,
        ),
        args.output,
    )

def load_rules(path):
    if not path:
        return DEFAULT_RULES
    text = Path(path).read_text(encoding="utf-8")
    try:
        data = json.loads(text)
    # pi-lens-ignore: ast-grep:unchecked-throwing-call-python
    # pi-lens-ignore: ast-grep:no-boolean-in-except
    except ValueError:
        try:
            import yaml

            data = yaml.safe_load(text)
        # pi-lens-ignore: ast-grep:unchecked-throwing-call-python
        # pi-lens-ignore: ast-grep:no-boolean-in-except
        except ImportError:
            rules, in_rules = [], False
            for line in text.splitlines():
                if line.strip() == "rules:":
                    in_rules = True
                    continue
                if in_rules and line.strip().startswith("-"):
                    rules.append(line.split("-", 1)[1].strip())
            data = {"rules": rules}
    rules = data.get("rules", data) if isinstance(data, dict) else data
    out = []
    for rule in rules or []:
        out.append(rule.get("id") if isinstance(rule, dict) else str(rule))
    return out

def cmd_test(args):
    ir = load_ir(args.input)
    findings = semantic_findings(ir, load_rules(args.rules))
    result = {
        "profile": infer_profile(ir),
        "errors": sum(f["severity"] == "error" for f in findings),
        "warnings": sum(f["severity"] == "warning" for f in findings),
        "findings": findings,
    }
    emit(result, args.output)
    if result["errors"] or (args.strict and result["warnings"]):
        return 1
    return 0

def review_markdown(report):
    lines = [
        "# Architecture Review",
        "",
        f"- Nodes: {report['summary']['nodes']}",
        f"- Edges: {report['summary']['edges']}",
        f"- Errors: {report['summary']['errors']}",
        f"- Warnings: {report['summary']['warnings']}",
        "",
        "## Findings",
        "",
    ]
    for f in report["findings"]:
        lines += [
            f"- **{f['severity'].upper()} · {f['rule']} · {f['subject']}** — {f['message']}",
            f"  - Suggested action: {f['fix']}",
        ]
    if not report["findings"]:
        lines.append("No findings.")
    return "\n".join(lines) + "\n"

def cmd_review(args):
    report = review(load_ir(args.input))
    if args.format == "markdown":
        text = review_markdown(report)
        if args.output:
            Path(args.output).write_text(text, encoding="utf-8")
        else:
            sys.stdout.write(text)
    else:
        emit(report, args.output)

def cmd_sync(args):
    ir, source_type = source_ir(args.source, args.source_type, group=args.group)
    result = reconcile(args.diagram, ir, args.output, prune=args.prune)
    result["source_type"] = source_type
    emit(result)

def cmd_views(args):
    ir = load_ir(args.input)
    views = project_views(ir, args.views.split(",") if args.views else None)
    write_drawio(ir, args.output, views=views, direction=args.direction)
    emit(
        {
            "output": args.output,
            "views": [
                {
                    "name": v["name"],
                    "nodes": len(v["nodes"]),
                    "fallback": v.get("fallback", False),
                    "fallback_reason": v.get("fallback_reason"),
                    "hint": v.get("hint"),
                }
                for v in views
            ],
        }
    )

def cmd_whatif(args):
    result = impact_analysis(load_ir(args.input), args.fail)
    if args.drawio:
        write_drawio(result.pop("diagram"), args.drawio)
        result["drawio"] = args.drawio
    elif not args.include_ir:
        result.pop("diagram")
    emit(result, args.output)

def cmd_story(args):
    ir = load_ir(args.input)
    scenario = None
    if args.fail:
        impact = impact_analysis(ir, args.fail)
        ir, scenario = (
            impact["diagram"],
            {"failed": impact["failed"], "impacted": impact["impacted"]},
        )
    Path(args.output).write_text(
        story_html(ir, title=args.title, scenario=scenario), encoding="utf-8"
    )
    emit(
        {
            "output": args.output,
            "nodes": len(ir["nodes"]),
            "accessible": True,
            "offline": True,
            "scenario": scenario,
        }
    )

def cmd_transform(args):
    script = HERE / TRANSFORMS[args.operation]
    extra = list(args.arguments)
    if extra[:1] == ["--"]:
        extra.pop(0)
    cmd = [sys.executable, str(script), args.input] + extra
    proc = subprocess.run(cmd)
    return proc.returncode

def cmd_publish(args):
    if args.format == "story" or not args.input.lower().endswith(".drawio"):
        ir = load_ir(args.input)
        Path(args.output).write_text(story_html(ir, title=args.title), encoding="utf-8")
        emit({"output": args.output, "format": "story", "offline": True})
        return 0
    proc = subprocess.run(
        [sys.executable, str(HERE / "drawiohtml.py"), args.input, "-o", args.output]
    )
    return proc.returncode

def parser():
    ap = argparse.ArgumentParser(
        prog="diagramctl",
        description="Build, sync, test, query, review and publish draw.io architecture models.",
    )
    sub = ap.add_subparsers(dest="command", required=True)
    p = sub.add_parser(
        "doctor", help="report local capabilities without launching GUI tools"
    )
    p.add_argument(
        "--probe",
        action="store_true",
        help="execute draw.io --version with an 8 second timeout",
    )
    p.add_argument("-o", "--output")
    p.set_defaults(func=cmd_doctor)

    p = sub.add_parser(
        "build",
        help="build a draw.io from IR, graph JSON, code, IaC, SQL, OpenAPI, "
        "AsyncAPI, Protobuf or GraphQL",
    )
    p.add_argument("source")
    p.add_argument("-o", "--output", required=True)
    p.add_argument(
        "--from",
        dest="source_type",
        default="auto",
        choices=["auto", "graph", "ir", "drawio"] + sorted(IMPORTERS),
    )
    p.add_argument("--group", action="store_true")
    p.add_argument("--direction", choices=["TB", "LR"], default="TB")
    p.add_argument(
        "--views", help="comma-separated executive,system,deployment,dataflow,security"
    )
    p.add_argument("--title")
    p.add_argument("--ir-output")
    p.set_defaults(func=cmd_build)

    p = sub.add_parser(
        "inspect", help="summarize structure, owners, provenance and accessible text"
    )
    p.add_argument("input")
    p.add_argument("-o", "--output")
    p.set_defaults(func=cmd_inspect)
    p = sub.add_parser("query", help="query nodes or find a directed path")
    p.add_argument("input")
    p.add_argument("--kind")
    p.add_argument("--owner")
    p.add_argument("--boundary")
    p.add_argument("--from", dest="source")
    p.add_argument("--to", dest="target")
    p.add_argument("-o", "--output")
    p.set_defaults(func=cmd_query)
    p = sub.add_parser("test", help="run semantic architecture rules")
    p.add_argument("input")
    p.add_argument("--rules")
    p.add_argument("--strict", action="store_true")
    p.add_argument("-o", "--output")
    p.set_defaults(func=cmd_test)
    p = sub.add_parser(
        "review",
        help="review ownership, resilience, trust boundaries and accessibility",
    )
    p.add_argument("input")
    p.add_argument("--format", choices=["json", "markdown"], default="markdown")
    p.add_argument("-o", "--output")
    p.set_defaults(func=cmd_review)
    for name in ("sync", "reconcile"):
        p = sub.add_parser(
            name,
            help="incrementally update a diagram while preserving manual geometry/style",
        )
        p.add_argument("diagram")
        p.add_argument("source")
        p.add_argument("-o", "--output", required=True)
        p.add_argument(
            "--from",
            dest="source_type",
            default="auto",
            choices=["auto", "graph", "ir"] + sorted(IMPORTERS),
        )
        p.add_argument("--group", action="store_true")
        p.add_argument("--prune", action="store_true")
        p.set_defaults(func=cmd_sync)
    p = sub.add_parser(
        "views", help="project one model into linked audience/concern views"
    )
    p.add_argument("input")
    p.add_argument("-o", "--output", required=True)
    p.add_argument("--views")
    p.add_argument("--direction", choices=["TB", "LR"], default="TB")
    p.set_defaults(func=cmd_views)
    p = sub.add_parser("whatif", help="simulate failure propagation")
    p.add_argument("input")
    p.add_argument("--fail", required=True)
    p.add_argument("--drawio")
    p.add_argument("--include-ir", action="store_true")
    p.add_argument("-o", "--output")
    p.set_defaults(func=cmd_whatif)
    p = sub.add_parser("story", help="publish an accessible offline guided walkthrough")
    p.add_argument("input")
    p.add_argument("-o", "--output", required=True)
    p.add_argument("--title")
    p.add_argument("--fail")
    p.set_defaults(func=cmd_story)
    p = sub.add_parser(
        "publish", help="publish as an interactive viewer or semantic story"
    )
    p.add_argument("input")
    p.add_argument("-o", "--output", required=True)
    p.add_argument("--format", choices=["viewer", "story"], default="viewer")
    p.add_argument("--title")
    p.set_defaults(func=cmd_publish)
    p = sub.add_parser(
        "transform", help="unified access to existing diagram transformations"
    )
    p.add_argument("operation", choices=sorted(TRANSFORMS))
    p.add_argument("input")
    p.add_argument("arguments", nargs=argparse.REMAINDER)
    p.set_defaults(func=cmd_transform)
    return ap

def main():
    args = parser().parse_args()
    try:
        return args.func(args) or 0
    except (ValueError, RuntimeError, OSError, json.JSONDecodeError) as exc:
        sys.stderr.write(f"error: {exc}\n")
        return 2

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: skills/drawio-skill/scripts/diagramctl_mcp.py
size: 16745
sha: ccdf31c3dd8e1e9340b52413a2d02944cd3d40d3
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/diagramctl_mcp.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/diagramctl_mcp.py

## File: skills/drawio-skill/scripts/dockerimports.py
size: 6391
sha: 9c7439642ba01dfc3d0fad3545c895259df8b9d3
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/dockerimports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/dockerimports.py

## File: skills/drawio-skill/scripts/drawio2mermaid.py
size: 5965
sha: cd582af7344723c91de8644bac7f3591e0ef0068
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawio2mermaid.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawio2mermaid.py

## File: skills/drawio-skill/scripts/drawio2pptx.py
size: 5042
sha: 645cb1783686218dc07649bc85c748c7924b2e1b
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawio2pptx.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawio2pptx.py

## File: skills/drawio-skill/scripts/drawio_cli.py
size: 2119
sha: 37fd664156832d8c68dd290666a3c8a936197a71
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawio_cli.py

```text
#!/usr/bin/env python3
"""Locate the draw.io desktop CLI for native export.

The executable name depends on the platform: Homebrew and Linux packages
install `drawio` (no dot), while the Windows installer ships `draw.io.exe`
(with the dot) and macOS also keeps `draw.io` inside the app bundle.

Callers must run the absolute path this module returns. A bare `drawio` fails
on Windows twice over: no such file exists there, and even a `.cmd` shim on
PATH is not launched, because `subprocess` on Windows uses `CreateProcess`,
which only appends `.exe`.

Usage:
    from drawio_cli import resolve_drawio
    exe = resolve_drawio()
    if not exe:
        sys.exit("error: draw.io CLI not found on PATH ...")
"""
import os
import shutil

# PATH names to try, in order. `drawio` is Homebrew/Linux, `draw.io` Windows.
NAMES = ("drawio", "draw.io")

MACOS_APP = "/Applications/draw.io.app/Contents/MacOS/draw.io"

# Windows installers: machine-wide, 32-bit, and per-user. Each entry is
# (environment variable, path components under it).
WIN_DIRS = (
    ("ProgramFiles", ("draw.io", "draw.io.exe")),
    ("ProgramFiles(x86)", ("draw.io", "draw.io.exe")),
    ("LOCALAPPDATA", ("Programs", "draw.io", "draw.io.exe")),
)

def _on_path():
    """Absolute path of the first CLI name found on PATH, or None."""
    for name in NAMES:
        found = shutil.which(name)
        if found:
            return found
    return None

def _install_paths():
    """Default install locations, for a CLI that is installed but not on PATH."""
    paths = [MACOS_APP]
    for env, parts in WIN_DIRS:
        base = os.environ.get(env)
        if base:
            paths.append(os.path.join(base, *parts))
    return paths

def resolve_drawio():
    """Absolute path to the draw.io CLI, or None when it is not installed.

    Tries both PATH names first, then the macOS app bundle and the Windows
    default install directories. Never returns a bare command name.
    """
    found = _on_path()
    if found:
        return found
    for path in _install_paths():
        if os.path.isfile(path):
            return path
    return None
```

## File: skills/drawio-skill/scripts/drawiodiff.py
size: 10854
sha: 137b0b223c2cc11b6fd88e9b73d297f427bc02f8
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawiodiff.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawiodiff.py

## File: skills/drawio-skill/scripts/drawiohtml.py
size: 11122
sha: ce1bbae417b1c9fcbfe95f5bae30d0cee9a2f62c
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawiohtml.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/drawiohtml.py

## File: skills/drawio-skill/scripts/edgeports.py
size: 9285
sha: 987cbc9d6ce97fe5cf586012ba6e7d0bf16f78ac
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/edgeports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/edgeports.py

## File: skills/drawio-skill/scripts/encode_drawio_url.py
size: 2250
sha: 5523a1b6a007f4f11de6b8f7e38855ed1f90bd8d
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/encode_drawio_url.py

```text
#!/usr/bin/env python3
"""Encode a .drawio XML file into a diagrams.net browser URL.

Used as the browser fallback when the draw.io desktop CLI is unavailable.
The diagram XML is carried in the URL fragment (after `#`), so nothing is
uploaded to any server.

Two modes:
  (default)  read-only viewer  -> https://viewer.diagrams.net/...#R<payload>
  --edit     editable editor   -> https://app.diagrams.net/...#create=<payload>

Usage: python3 encode_drawio_url.py [--edit] <path/to/input.drawio>
"""
import base64
import json
import sys
import urllib.parse
import zlib

def _deflate_b64(xml: str) -> str:
    # draw.io's loader runs JS decodeURIComponent on the inflated string, so the
    # XML MUST be percent-encoded (encodeURIComponent) BEFORE deflate — otherwise
    # a literal `%` or any non-ASCII (e.g. CJK) label makes the browser throw
    # "URI malformed" and the diagram never opens. encodeURIComponent leaves
    # only A-Za-z0-9 and -_.!~*'() unescaped, which `quote` reproduces here.
    pre = urllib.parse.quote(xml, safe="!~*'()")
    c = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
    compressed = c.compress(pre.encode("utf-8")) + c.flush()
    # Standard base64 (atob rejects url-safe -/_); strip newlines.
    return base64.b64encode(compressed).decode("utf-8").replace("\n", "")

def encode(xml: str) -> str:
    """Read-only viewer URL (mxGraph `#R` raw-inflate format)."""
    return (
        "https://viewer.diagrams.net/?tags=%7B%7D&lightbox=1&edit=_blank#R"
        + urllib.parse.quote(_deflate_b64(xml), safe="")
    )

def edit_url(xml: str) -> str:
    """Editable editor URL — opens directly in the draw.io editor."""
    payload = json.dumps({"type": "xml", "compressed": True, "data": _deflate_b64(xml)})
    return (
        "https://app.diagrams.net/?grid=0&pv=0&border=10&edit=_blank#create="
        + urllib.parse.quote(payload, safe="")
    )

if __name__ == "__main__":
    args = [a for a in sys.argv[1:] if a != "--edit"]
    if len(args) != 1:
        print("usage: encode_drawio_url.py [--edit] <path>", file=sys.stderr)
        sys.exit(2)
    with open(args[0], "r", encoding="utf-8") as f:
        xml = f.read()
    print(edit_url(xml) if "--edit" in sys.argv[1:] else encode(xml))
```

## File: skills/drawio-skill/scripts/explain.py
size: 6226
sha: 4e79e8cb904284d296ca49fc015f20ecaf43707a
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/explain.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/explain.py

## File: skills/drawio-skill/scripts/goimports.py
size: 6131
sha: bc587d3946ef7a79fc699516685eda34a723d5f3
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/goimports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/goimports.py

## File: skills/drawio-skill/scripts/graphqlerd.py
size: 16089
sha: bf0738f3bec98162b3967857e0d8e8f29541203c
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/graphqlerd.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/graphqlerd.py

## File: skills/drawio-skill/scripts/heatmap.py
size: 9176
sha: d65d4639375fc4049632c02ccb4142df4e4dde74
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/heatmap.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/heatmap.py

## File: skills/drawio-skill/scripts/jsimports.py
size: 6535
sha: 3d1e5575548c54404264f77100fc073bf0448491
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/jsimports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/jsimports.py

## File: skills/drawio-skill/scripts/k8simports.py
size: 9805
sha: 0d4566bee89299e1786d8b9d543ddc19cee90e77
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/k8simports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/k8simports.py

## File: skills/drawio-skill/scripts/openapiimports.py
size: 6786
sha: 842c94f10977cc9fb9413c93ab43b6d6b2bed613
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/openapiimports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/openapiimports.py

## File: skills/drawio-skill/scripts/prdiff.py
size: 8199
sha: 0f47f3394f84548773e812fcef20f4a2e05d37e2
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/prdiff.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/prdiff.py

## File: skills/drawio-skill/scripts/protoimports.py
size: 17956
sha: 97ee2bf7ae744c33549bd59162a8f7c63ef5a016
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/protoimports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/protoimports.py

## File: skills/drawio-skill/scripts/pyclasses.py
size: 6271
sha: ac69036188dc815801401acf22ddf226c7bd81a2
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/pyclasses.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/pyclasses.py

## File: skills/drawio-skill/scripts/pyimports.py
size: 7036
sha: 2019e0ba18a312a8e2a148d44b741436b44a8c82
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/pyimports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/pyimports.py

## File: skills/drawio-skill/scripts/raster2drawio.py
size: 7467
sha: bb88615a1d72aa6ac21dc94721dc0560b30699f9
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/raster2drawio.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/raster2drawio.py

## File: skills/drawio-skill/scripts/relabel.py
size: 4247
sha: 33a6befac5ef7c47ab0b8eb33ec772091ea830a4
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/relabel.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/relabel.py

## File: skills/drawio-skill/scripts/repair_png.py
size: 1097
sha: 7e95b7c841240cca8ffaec1e55af76575c723c7d
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/repair_png.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/repair_png.py

## File: skills/drawio-skill/scripts/restyle.py
size: 7243
sha: 023ebb358ae3b5ad5a17c064f34fedfcdb3fe6a7
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/restyle.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/restyle.py

## File: skills/drawio-skill/scripts/runbook.py
size: 10187
sha: 99ac12313577e7b3fbaa20f7d450e9ddb68205fc
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/runbook.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/runbook.py

## File: skills/drawio-skill/scripts/rustimports.py
size: 7928
sha: 996185895554007981b814b675fcb1781083acc7
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/rustimports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/rustimports.py

## File: skills/drawio-skill/scripts/seqlayout.py
size: 9917
sha: b5b8c335d477be73229a18baed3a798b899bd10a
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/seqlayout.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/seqlayout.py

## File: skills/drawio-skill/scripts/shapesearch.py
size: 5967
sha: f29656585085a1040c0c2f836a5ede2b22c1fd3b
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/shapesearch.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/shapesearch.py

## File: skills/drawio-skill/scripts/sqlerd.py
size: 6745
sha: 11e29fde04a1fa5bcfc86dab3819f66826f8adbf
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/sqlerd.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/sqlerd.py

## File: skills/drawio-skill/scripts/svgflow.py
size: 4241
sha: 6ce266cd576f62c29880608faccec18632cb5f8a
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/svgflow.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/svgflow.py

## File: skills/drawio-skill/scripts/tfimports.py
size: 11910
sha: 13a4d2ab740e9313741e8418dde5432bef43a92b
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/tfimports.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/tfimports.py

## File: skills/drawio-skill/scripts/tfstate.py
size: 5587
sha: 33496ebffe22612cf9ea85ed4d98d14517f70883
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/tfstate.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/tfstate.py

## File: skills/drawio-skill/scripts/timelapse.py
size: 11683
sha: ab5a59c128ae327dd7259c9bd6af04ee104432f7
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/timelapse.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/timelapse.py

## File: skills/drawio-skill/scripts/tubemap.py
size: 6948
sha: 4c1bd14732e447f9d0ab5bfade647e9c7941ebdc
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/tubemap.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/tubemap.py

## File: skills/drawio-skill/scripts/validate.py
size: 16591
sha: ca46a72ad97c603f9025f06c090495338d750874
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/validate.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/scripts/validate.py

## File: skills/drawio-skill/references/autolayout.md
size: 19798
sha: a87f1289ec6fe4b137bb989c78a58777059b3d4e
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/autolayout.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/autolayout.md

## File: skills/drawio-skill/references/ci-gate.md
size: 2090
sha: 2a9432cefa5aa6adbcb73001da5c1ec1ada53043
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/ci-gate.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/ci-gate.md

## File: skills/drawio-skill/references/cookbook.md
size: 7087
sha: 184fb6210c075648f3b32784d1e9d696dae35295
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/cookbook.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/cookbook.md

## File: skills/drawio-skill/references/databricks.md
size: 2625
sha: cdbf0a58ecddea73106e0698f385a1cff96daf84
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/databricks.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/databricks.md

## File: skills/drawio-skill/references/derasterize.md
size: 2526
sha: e5d3b50bd508b9ed9257b11191346a96dc473e19
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/derasterize.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/derasterize.md

## File: skills/drawio-skill/references/diagram-ir.md
size: 4847
sha: 0ee78238a1012b8a9773ad13cebbdc45372ad640
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/diagram-ir.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/diagram-ir.md

## File: skills/drawio-skill/references/diagram-types.md
size: 16691
sha: 6663fc289f33cc7974f7735930a1ab7a27399a31
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/diagram-types.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/diagram-types.md

## File: skills/drawio-skill/references/live-infra.md
size: 3670
sha: 0bb9a8d50a79fecb5593a1685f859ce3cf7fb005
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/live-infra.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/live-infra.md

## File: skills/drawio-skill/references/mcp.md
size: 3405
sha: 7c1767a15626b8427a838d50c642f207b48cfa89
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/mcp.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/mcp.md

## File: skills/drawio-skill/references/mermaid-authoring.md
size: 4978
sha: 172db4962674a70ae97ed29a0882e06cc86e2114
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/mermaid-authoring.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/mermaid-authoring.md

## File: skills/drawio-skill/references/pr-bot.md
size: 3927
sha: 20ba346116acc850f04693f5307d44567a31ece5
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/pr-bot.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/pr-bot.md

## File: skills/drawio-skill/references/security.md
size: 2082
sha: aaa5a6c8e0aaf81cefbebe294834d5c9a6222b3b
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/security.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/security.md

## File: skills/drawio-skill/references/semantic-workflows.md
size: 3043
sha: 6d5ec3aeef470cf67d2ede97358909edbd22e103
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/semantic-workflows.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/semantic-workflows.md

## File: skills/drawio-skill/references/shapes.md
size: 7155
sha: 3df5bcd0f7d6caa712281ed3781700062179d075
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/shapes.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/shapes.md

## File: skills/drawio-skill/references/style-extraction.md
size: 17575
sha: 1868f00c51f88729186ff86ac57459fc769efbc8
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/style-extraction.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/style-extraction.md

## File: skills/drawio-skill/references/style-presets.md
size: 11171
sha: cc80d882096692e41a271ce00e608bdcd07a2002
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/style-presets.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/style-presets.md

## File: skills/drawio-skill/references/toolbox.md
size: 12048
sha: 6348803b2343ae20b143f536a37127e5c8bd64ac
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/toolbox.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/toolbox.md

## File: skills/drawio-skill/references/troubleshooting.md
size: 8107
sha: 8b6710fe1c92b26e25ff3f171da2324fb0f9a838
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/troubleshooting.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/troubleshooting.md

## File: skills/drawio-skill/references/tubemap.md
size: 3275
sha: 5c0ecf3b25c0d0f5ca626604e706d55d6127e6d6
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/tubemap.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/tubemap.md

## File: skills/drawio-skill/references/xml-authoring.md
size: 15786
sha: 69d5237ea5db023496bd9590761a807526bf1a38
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/xml-authoring.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/references/xml-authoring.md

## File: skills/drawio-skill/agents/openai.yaml
size: 307
sha: 5c65e0df574e6f1c09c0e90a35e1b40f394ac081
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/agents/openai.yaml

```text
interface:
  display_name: "Draw.io Architecture Studio"
  short_description: "Build, sync, test, and publish editable diagrams"
  brand_color: "#1A73E8"
  default_prompt: "Use $drawio-skill to create an editable, validated draw.io diagram and show me the result."
policy:
  allow_implicit_invocation: true
```

## File: skills/drawio-skill/data/databricks-icons.json
size: 11762
sha: b54798874b1ec31f884e62827a867f708cf0eddb
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/databricks-icons.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/databricks-icons.json

## File: skills/drawio-skill/data/diagram-ir.schema.json
size: 1534
sha: ea90a98a365311071659281f358a54ef532072c8
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/diagram-ir.schema.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/diagram-ir.schema.json

## File: skills/drawio-skill/data/lobe-icons.json
size: 12919
sha: 34c1e364a6329538826058231f0b19b9d0da8c7b
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/lobe-icons.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/lobe-icons.json

## File: skills/drawio-skill/data/SHAPE-INDEX-NOTICE.md
size: 880
sha: 3f97ac53f5a2d5b81ee2786900004c23fbedb1fe
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/SHAPE-INDEX-NOTICE.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/SHAPE-INDEX-NOTICE.md

## File: skills/drawio-skill/data/shape-index.json.gz
size: 436148
sha: 7b6ad4b72c37da364c576662a540b9d28ea8b7c5
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/shape-index.json.gz

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/data/shape-index.json.gz

## File: skills/drawio-skill/LICENSE
size: 1069
sha: ec170ad92004bdbdab67fd639a3104a97722373d
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/LICENSE

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/LICENSE

## File: skills/drawio-skill/styles/built-in/colorblind-safe.json
size: 1472
sha: 612703d62c013d5d77fb78c2e1b524f5dcf80fc3
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/colorblind-safe.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/colorblind-safe.json

## File: skills/drawio-skill/styles/built-in/corporate.json
size: 1471
sha: 1b3f2892f7ebb9fda15a897ec7fae5c6ad799dac
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/corporate.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/corporate.json

## File: skills/drawio-skill/styles/built-in/dark.json
size: 1546
sha: 5ad6b7aa61eda82df89ab2b47cee2bae39bad120
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/dark.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/dark.json

## File: skills/drawio-skill/styles/built-in/default.json
size: 1454
sha: a202de1b6b29d87b117bcc6fa397d871a4c8a1a2
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/default.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/default.json

## File: skills/drawio-skill/styles/built-in/handdrawn.json
size: 1474
sha: 1485a5a3730bb16fbd38b755af09f385458f9498
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/handdrawn.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/built-in/handdrawn.json

## File: skills/drawio-skill/styles/schema.json
size: 5362
sha: 0d4dedf2e645e40001c097c0be99d56ec9c9dadd
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/schema.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/agents365-ai/drawio-skill/blob/HEAD/skills/drawio-skill/styles/schema.json

## File: README.md
upstream: https://github.com/agents365-ai/drawio-skill/blob/HEAD/README.md

````text
# drawio-skill — From Text to Professional Diagrams

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![GitHub stars](https://img.shields.io/github/stars/Agents365-ai/drawio-skill?style=flat&logo=github)](https://github.com/Agents365-ai/drawio-skill/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/Agents365-ai/drawio-skill?style=flat&logo=github)](https://github.com/Agents365-ai/drawio-skill/network/members)
[![Latest Release](https://img.shields.io/github/v/release/Agents365-ai/drawio-skill?logo=github)](https://github.com/Agents365-ai/drawio-skill/releases/latest)
[![Last Commit](https://img.shields.io/github/last-commit/Agents365-ai/drawio-skill?logo=github)](https://github.com/Agents365-ai/drawio-skill/commits/main)

[![SkillsMP](https://img.shields.io/badge/SkillsMP-listed-1f6feb)](https://skillsmp.com/skills/agents365-ai-drawio-skill-skills-drawio-skill-skill-md)
[![Agent Skills](https://img.shields.io/badge/Agent%20Skills-compatible-2ea44f)](https://agentskills.io)

**English** · [中文](README_CN.md) · [日本語](README_JA.md) · [📖 Online Docs](https://agents365-ai.github.io/drawio-skill/)

A skill that turns natural language and real system sources into maintainable `.drawio` architecture models. Beyond generation and export, it incrementally synchronizes without discarding manual layout, projects multiple views from one model, enforces architecture contracts, queries dependencies, simulates failure propagation, and publishes dependency-free interactive walkthroughs. Works with **Claude Code, Cursor, Copilot, OpenClaw, Codex, Autohand Code, Hermes**, and any agent compatible with the [Agent Skills](https://agentskills.io) format.

<p align="center">
  <img src="assets/hero-demo.gif" width="900" alt="Hero demo: Terraform source becomes an architecture diagram with official icons; the v2 change renders as an updated diagram">
</p>

## ✨ Highlights

**From a prompt**

- **Describe it, get an editable `.drawio`** — the skill plans the layout, writes the XML, exports, then self-checks its own PNG and auto-fixes overlaps, clipped labels, and stacked edges (up to 2 rounds), with up to 5 rounds of your feedback
- **Mermaid → native .drawio** (draw.io ≥ 30) — author 28 standard types as Mermaid text (**mindmap, gantt, timeline, journey, pie, sankey, kanban**…) and the CLI converts them into a laid-out, editable `.drawio`: structure in, layout free
- **Whiteboard photo / screenshot → editable diagram** — snap a legacy PNG or a physical whiteboard, let vision extract the graph, and `raster2drawio.py` rebuilds it as a real, editable `.drawio` honouring the original layout
- **11 diagram type presets** — ERD, UML Class, Sequence, C4, Architecture, ML/Deep Learning, Flowchart, SysML, BPMN, Network Topology, Cross-Functional Swimlane

**From real sources**

- **Visualize a codebase** — import graphs for Python / JS-TS / Go / Rust and Python class hierarchies, with Graphviz placement, transitive reduction, and nested module containers
- **IaC and live infrastructure** — Terraform, Kubernetes, and docker-compose configs become diagrams with official AWS / Azure / GCP / K8s icons; snapshot what's *actually deployed* from `terraform show -json`, `docker inspect`, or `kubectl get -o json`
- **Schemas and pipelines** — SQL DDL → ER diagram, OpenAPI/Swagger → API diagram coloured by HTTP method, AsyncAPI → event-driven architecture diagram, Protocol Buffers → message/service diagram, GraphQL SDL → entity type diagram, GitHub Actions / GitLab CI → pipeline DAG

- **Deterministic engines** — sequence diagrams with computed lifelines and activation bars; multi-page C4 models with click-to-drill-down

**Keep it true over time**

- **Architecture digital twin / Diagram IR** — separate meaning, provenance, and geometry; project executive, system, deployment, data-flow, and security views from one model
- **Incremental sync without losing manual layout** — `diagramctl sync` updates changed nodes/relations while preserving tuned coordinates, styles, and annotations; removals stay reviewable by default
- **Diagram-as-Test, in CI** — YAML/JSON architecture rules (Internet-to-database access, cycles, orphans, trust boundaries, contrast…) plus an official GitHub Action that enforces them on every PR, and a PR action that renders visual diffs
- **Query, review, what-if** — query components/owners/paths, spot articulation points and high coupling, simulate failure propagation, publish an accessible Story walkthrough
- **Drift and history** — colour-coded diffs between two diagrams or two live snapshots; a time-lapse player of how a codebase's architecture grew

**Share and restyle**

- **Repurpose with one command** — interactive HTML viewer (pan/zoom/search), PowerPoint deck (raster page images, not individually editable shapes), animated data-flow SVG, Mermaid or Markdown export, click-through runbook, exec-summary compression
- **Restyle and enrich** — style presets (yours or built-in `dark`/`corporate`/…), bilingual label variants with layout untouched, data-driven heat maps, white-to-metro tubemap mode
- **10,000+ official shapes + 321 AI/LLM logos** — resolve exact AWS / Cisco / K8s / UML icon styles instead of guessing, plus brand logos draw.io itself lacks
- **One CLI, optional MCP server** — `diagramctl doctor/build/sync/views/query/test/review/whatif/story/publish/transform`, core workflows stdlib-only and offline; the MCP server exposes them to Claude Desktop, Cursor, VS Code, Codex, and any MCP host. Portable to any Agent Skills-compatible agent, no daemon

## 🗺️ Feature Map

<div align="center">
  <img src="assets/mindmap.png" width="900" alt="drawio-skill feature map — one mind map covering every capability, itself drawn with the skill">
</div>

A bird's-eye view of everything the skill does — diagram types, import sources, layout engines, styling, export formats, and repurposing — in one map. Fittingly, this map was itself drawn with drawio-skill.

## 🚀 Installation

### 1. Install the draw.io desktop CLI

| Platform | Command |
| ---------- | --------- |
| **macOS** | `brew install --cask drawio` |
| **Windows** | [Download installer](https://github.com/jgraph/drawio-desktop/releases) |
| **Linux** | `.deb`/`.rpm` from [releases](https://github.com/jgraph/drawio-desktop/releases); `sudo apt install xvfb` for headless |

Verify with `drawio --version` (`draw.io.exe --version` on Windows). **Version ≥ 30 recommended** — it unlocks Mermaid → `.drawio` conversion and the ELK `--layout` pass (both unavailable on ≤ 29). On **WSL2** the CLI is the Windows desktop exe reached via `/mnt/c` — the skill detects this automatically (see [troubleshooting](skills/drawio-skill/references/troubleshooting.md)). Full recipes in [docs/INSTALL_CLI.md](docs/INSTALL_CLI.md).

### 2. Install the skill

```bash
# Any agent (Claude Code, Cursor, Copilot, ...)
npx skills add Agents365-ai/drawio-skill -g
```

Manual install: clone once to a persistent path, then link the skill subdirectory (Claude Code shown). Use `cp -R` instead of `ln -s` on hosts that do not follow symlinks. The destination must not exist yet, so move an existing `drawio-skill` entry aside first.

```bash
mkdir -p ~/src
git clone https://github.com/Agents365-ai/drawio-skill.git ~/src/drawio-skill
mkdir -p ~/.claude/skills
ln -s ~/src/drawio-skill/skills/drawio-skill ~/.claude/skills/drawio-skill

# Copy alternative, for hosts that do not follow symlinks
# mkdir -p ~/.claude/skills
# cp -R ~/src/drawio-skill/skills/drawio-skill ~/.claude/skills/drawio-skill
```

The skill is the `skills/drawio-skill/` subdirectory, so `SKILL.md` must sit directly under the host entry: `<skills root>/drawio-skill/SKILL.md`. Do not clone the repository root into a skills directory. Other host roots (Opencode, OpenClaw, Codex, Autohand Code global and project): [docs/INSTALL_SKILL.md](docs/INSTALL_SKILL.md).

Autohand Code also supports `autohand --skill-install` for cataloged skills, with `--proje
````
