Skip to content

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

feat: add scripts/edgeports.py — deterministic edge port assignment (#100)

Agents365.ai719fd3663b7e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14c6d44..d2e13dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,25 @@ All notable changes to **drawio-skill** are documented here. The format is based
on [Keep a Changelog](https://keepachangelog.com/), and the project follows
semantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).
+## [2.1.0] — 2026-07-25
+### Added
+- **`scripts/edgeports.py`** — deterministic edge port assignment, the real
+ replacement for the `--layout libavoid` flag removed in 2.0.0. draw.io's
+ floating connections attach every edge to the middle of whichever side faces
+ the peer, so several edges leaving the same side stack into one line — the
+ usual swimlane / cross-functional complaint (#96). The pass resolves each
+ vertex to absolute coordinates (through swimlane parents), picks the side of
+ each node facing the other endpoint, then spreads that side's edges over
+ evenly-spaced slots **ordered by the far endpoint's position** so they keep
+ their relative order instead of crossing at the boundary. Ends already pinned
+ by hand are left alone and re-running is a no-op.
+
+ It is a **port assigner, not a router**: it separates lines where they meet a
+ shape, and does *not* stop an edge crossing an unrelated shape mid-run — add
+ waypoints for that. Verified on a 3-lane swimlane (8 ends pinned, stacked
+ handoffs separated); `validate.py --score` cannot measure the improvement,
+ since it only scores edges carrying explicit waypoints.
+
## [2.0.0] — 2026-07-25
### Removed
- **`--layout libavoid` is gone from the documented interface.** It never
diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.md
index 954eae1..eb2ceeb 100644
--- a/skills/drawio-skill/SKILL.md
+++ b/skills/drawio-skill/SKILL.md
@@ -1,12 +1,12 @@
---
name: drawio-skill
-version: 2.0.0
+version: 2.1.0
description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, SysML / MBSE diagrams (block definition, internal block, requirement, parametric), BPMN business process diagrams, swimlane / cross-functional flowcharts, network topology, cloud architecture from Terraform or Kubernetes manifests, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.
license: MIT
homepage: https://github.com/Agents365-ai/drawio-skill
compatibility: Requires draw.io desktop app CLI on PATH (macOS/Linux/Windows). Self-check step requires a vision-enabled model (e.g., Claude Sonnet/Opus); gracefully skipped if unavailable. Optional auto-layout (scripts/autolayout.py) needs Graphviz (dot).
platforms: [macos, linux, windows]
-metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for optional autolayout.py","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.34.0"}
+metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io via Homebrew","os":["darwin"]},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for optional autolayout.py","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["drawio","draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"2.1.0"}
---
# Draw.io Diagrams
@@ -66,6 +66,7 @@ When the workflow references one of these, read it on demand — none of them ne
| `scripts/c4.py` | The user wants a **C4 model** (System Context / Container / Component) — levels JSON in, one multi-page `.drawio` out with official C4 shapes/colors and **click-to-drill-down** links between levels |
| `scripts/relabel.py` | The user wants a **language variant or bulk text swap of an existing `.drawio`** (e.g. an EN diagram re-labelled in Chinese for a bilingual README) — `relabel.py diagram.drawio --extract -o labels.json` dumps every label as an identity JSON map; translate the values (keep the keys), then `relabel.py diagram.drawio --map labels.json -o diagram_cn.drawio` swaps them with layout/styles/ids untouched |
| `scripts/restyle.py` | The user wants to **re-theme an EXISTING `.drawio`** ("make this dark", "apply my corporate style to this diagram") — `restyle.py diagram.drawio --preset <name>` remaps every vertex fill/stroke to the preset palette by hue, applies font/extras (dark fontColor, edge color, background), and leaves layout, shapes, and edge routing untouched. Presets resolve like Step 0 (user dir, then built-ins) |
+| `scripts/edgeports.py` | Edges **stack on top of each other where they meet a shape** — the usual swimlane/cross-functional complaint, and anywhere a node has several connections leaving the same side. `edgeports.py diagram.drawio` pins `exitX/exitY`+`entryX/entryY`: it picks the side of each node facing the other endpoint, then spreads that side's edges over evenly-spaced slots **ordered by the far endpoint's position**, so they keep their relative order instead of crossing. Resolves absolute coordinates through swimlane parents, skips ends you already pinned, and is idempotent. It is a **port assigner, not a router** — it separates lines at the shape boundary, it will not stop an edge crossing an unrelated shape mid-run (add waypoints for that) |
| `scripts/validate.py` | You generated a `.drawio` (especially via autolayout or for a large hand-placed diagram) and want a fast deterministic structural lint (dangling edges, dup/reserved ids, broken parents, overlaps) before the vision self-check. `--score` prints a readability score for comparing layout variants |
| `scripts/raster2drawio.py` | The user has an **image of a diagram** (whiteboard photo, legacy PNG, Visio screenshot) and wants an **editable `.drawio`** — read the image with your own vision, extract nodes/edges as JSON (schema + full workflow in `references/derasterize.md`), then `raster2drawio.py graph.json -o out.drawio` honours those coordinates/labels/shapes; nodes missing `x`/`y` fall back to `autolayout.py` placement |
| `scripts/buildup.py` | The user wants a diagram to **build itself node-by-node** as a video/GIF (a construction time-lapse of ONE static diagram — distinct from `timelapse.py`'s git-history animation) — `buildup.py diagram.drawio` reveals cells in topological (dependency) order into a self-contained HTML player (play/pause/step/scrub); `--gif` also exports an animated GIF (needs Pillow). Needs the draw.io CLI |
@@ -124,7 +125,7 @@ When a preset loads successfully, mention it in the first line of the reply: *"U
1. **Check deps** — **resolve which name the binary has on this system** and use that name verbatim in every subsequent command in this workflow. Try in order: (a) `drawio --version` (the canonical name for Homebrew cask, jgraph `.deb`/`.rpm`, Arch AUR), (b) `draw.io --version` (older builds, some custom symlinks, some distro packages), (c) macOS `.app` direct: `/Applications/draw.io.app/Contents/MacOS/draw.io --version`, (d) Windows: `"C:\Program Files\draw.io\draw.io.exe" --version`. The first one that prints a version is your binary; remember the exact path/name and substitute it for `drawio` in every export command below. **Do not copy the example commands verbatim if your binary is named differently** — the examples use `drawio` only because it's the most common. On macOS-Homebrew, `drawio` is just a thin wrapper script that execs `/Applications/draw.io.app/Contents/MacOS/draw.io` — they run the same engine, so candidate (c) is only needed when the `drawio` wrapper is absent (e.g. the app was installed by drag-and-drop without the cask). **Also note the major version** the command printed: **≥ 30** unlocks Mermaid→`.drawio` conversion and the ELK `--layout` pass (see `references/mermaid-authoring.md`); on **≤ 29** both are unavailable — `.mmd` input fails and `--layout` corrupts argument parsing — so never emit those flags there.
2. **Plan** — identify shapes, relationships, layout (LR or TB), group by tier/layer
-3. **Generate** — produce the `.drawio` file, choosing the authoring mode: **(a) Mermaid → CLI convert** when the diagram is a standard type with no custom styling/icon needs **and** the CLI is ≥ v30 — write a `.mmd` and run `drawio -x -f xml -o <name>.drawio <name>.mmd`, see `references/mermaid-authoring.md` (structure only; layout comes free; never `--layout` afterwards). **(b) Hand-written XML** for custom styling, vendor icons, swimlanes, precise geometry — **read `references/xml-authoring.md` first** (skeleton, cell forms, palette, spacing rules). **(c) A bundled generator** for the data-driven cases below. **For large or layout-heavy diagrams (dependency/call graphs, code structure, >~15 nodes), don't hand-place** — describe the graph as JSON and run `python3 <this-skill-dir>/scripts/autolayout.py graph.json -o <name>.drawio` to compute node positions + orthogonal edge routing via Graphviz (see `references/autolayout.md`; add `--tune` to auto-pick the more readable direction). For a **Python / JS-TS / Go / Rust project**, the matching importer (`scripts/pyimports.py`, `jsimports.py`, `goimports.py`, or `rustimports.py`) extracts the import graph (transitive-reduced; add `--group` to box modules by sub-package, nested for deep trees) ready for autolayout; for a **Python class hierarchy**, `scripts/pyclasses.py` extracts classes + inheritance instead; for **Terraform / Kubernetes / docker-compose** (`scripts/tfimports.py`, `k8simports.py`, `composeimports.py`), the importer extracts the resource/service reference graph — tf/k8s nodes resolve to their official cloud icons automatically; to draw **what is actually running** rather than the declared config, pipe `terraform show -json` into `scripts/tfstate.py` or `docker inspect $(docker ps -q)` into `scripts/dockerimports.py` (`k8simports.py` already accepts live `kubectl get ... -o json`) — see `references/live-infra.md`; for an **ER diagram from SQL DDL**, `scripts/sqlerd.py` parses `CREATE TABLE` into table nodes + crow's-foot FK edges; for an **API diagram from an OpenAPI / Swagger spec**, `scripts/openapiimports.py` maps operations (coloured by HTTP method) + component schemas into a graph for autolayout; for a **CI pipeline diagram** (GitHub Actions / GitLab CI), `scripts/ciimports.py` extracts jobs, `needs:` edges, triggers, and stage/workflow containers. To turn any generated `.drawio` into a **metric heat map** — recolour nodes by a CSV/JSON of cost/latency/traffic/errors — run `python3 <this-skill-dir>/scripts/heatmap.py <name>.drawio -m metrics.csv` (matches on cell id or label; `--palette`, `--size`, legend). For a **sequence diagram**, skip autolayout entirely — describe participants + messages as JSON and run `python3 <this-skill-dir>/scripts/seqlayout.py seq.json -o <name>.drawio` (deterministic lifeline/activation/arrow geometry; see the script docstring for the JSON schema). For a **C4 model**, `python3 <this-skill-dir>/scripts/c4.py c4.json -o <name>.drawio` emits the full multi-page Context→Container→Component set with drill-down links (schema in the script docstring). For complex architecture diagrams with many visible edge labels, give labels `labelBackgroundColor=#ffffff;fontSize=11` and use edge geometry `x`/`y` offsets plus `<mxPoint as="offset" />` to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. For hand-placed diagrams where edges cross shapes (architecture, network topology, deployment, UML), fix the routing in the XML — pin `exitX/exitY/entryX/entryY`, add `<Array as="points">` waypoints, or widen node spacing (see `references/xml-authoring.md`). **No CLI flag reroutes edges without moving nodes**: every `--layout` preset is an ELK *node* layout that re-places vertices, and an unrecognised value opens a modal error dialog that hangs headless runs. draw.io's obstacle-avoiding router is editor-side only. After generating any `.drawio`, run `python3 <this-skill-dir>/scripts/validate.py <name>.drawio` for a fast structural lint (dangling edges, dup ids, overlaps) before exporting. Default output dir is the user's working dir; if the user specified an output path or directory (e.g. `./artifacts/`, `docs/images/`), use that instead — `mkdir -p` the target dir first. Apply the same dir choice to PNG/SVG/PDF exports in steps 4 and 7.
+3. **Generate** — produce the `.drawio` file, choosing the authoring mode: **(a) Mermaid → CLI convert** when the diagram is a standard type with no custom styling/icon needs **and** the CLI is ≥ v30 — write a `.mmd` and run `drawio -x -f xml -o <name>.drawio <name>.mmd`, see `references/mermaid-authoring.md` (structure only; layout comes free; never `--layout` afterwards). **(b) Hand-written XML** for custom styling, vendor icons, swimlanes, precise geometry — **read `references/xml-authoring.md` first** (skeleton, cell forms, palette, spacing rules). **(c) A bundled generator** for the data-driven cases below. **For large or layout-heavy diagrams (dependency/call graphs, code structure, >~15 nodes), don't hand-place** — describe the graph as JSON and run `python3 <this-skill-dir>/scripts/autolayout.py graph.json -o <name>.drawio` to compute node positions + orthogonal edge routing via Graphviz (see `references/autolayout.md`; add `--tune` to auto-pick the more readable direction). For a **Python / JS-TS / Go / Rust project**, the matching importer (`scripts/pyimports.py`, `jsimports.py`, `goimports.py`, or `rustimports.py`) extracts the import graph (transitive-reduced; add `--group` to box modules by sub-package, nested for deep trees) ready for autolayout; for a **Python class hierarchy**, `scripts/pyclasses.py` extracts classes + inheritance instead; for **Terraform / Kubernetes / docker-compose** (`scripts/tfimports.py`, `k8simports.py`, `composeimports.py`), the importer extracts the resource/service reference graph — tf/k8s nodes resolve to their official cloud icons automatically; to draw **what is actually running** rather than the declared config, pipe `terraform show -json` into `scripts/tfstate.py` or `docker inspect $(docker ps -q)` into `scripts/dockerimports.py` (`k8simports.py` already accepts live `kubectl get ... -o json`) — see `references/live-infra.md`; for an **ER diagram from SQL DDL**, `scripts/sqlerd.py` parses `CREATE TABLE` into table nodes + crow's-foot FK edges; for an **API diagram from an OpenAPI / Swagger spec**, `scripts/openapiimports.py` maps operations (coloured by HTTP method) + component schemas into a graph for autolayout; for a **CI pipeline diagram** (GitHub Actions / GitLab CI), `scripts/ciimports.py` extracts jobs, `needs:` edges, triggers, and stage/workflow containers. To turn any generated `.drawio` into a **metric heat map** — recolour nodes by a CSV/JSON of cost/latency/traffic/errors — run `python3 <this-skill-dir>/scripts/heatmap.py <name>.drawio -m metrics.csv` (matches on cell id or label; `--palette`, `--size`, legend). For a **sequence diagram**, skip autolayout entirely — describe participants + messages as JSON and run `python3 <this-skill-dir>/scripts/seqlayout.py seq.json -o <name>.drawio` (deterministic lifeline/activation/arrow geometry; see the script docstring for the JSON schema). For a **C4 model**, `python3 <this-skill-dir>/scripts/c4.py c4.json -o <name>.drawio` emits the full multi-page Context→Container→Component set with drill-down links (schema in the script docstring). For complex architecture diagrams with many visible edge labels, give labels `labelBackgroundColor=#ffffff;fontSize=11` and use edge geometry `x`/`y` offsets plus `<mxPoint as="offset" />` to move long labels into nearby whitespace instead of relying on draw.io's default midpoint placement. For hand-placed diagrams where edges cross shapes (architecture, network topology, deployment, UML), fix the routing in the XML — run `python3 <this-skill-dir>/scripts/edgeports.py <name>.drawio` to distribute stacked edges over each shape's perimeter automatically, then add `<Array as="points">` waypoints or widen node spacing for any edge still crossing a shape mid-run (see `references/xml-authoring.md`). **No CLI flag reroutes edges without moving nodes**: every `--layout` preset is an ELK *node* layout that re-places vertices, and an unrecognised value opens a modal error dialog that hangs headless runs. draw.io's obstacle-avoiding router is editor-side only. After generating any `.drawio`, run `python3 <this-skill-dir>/scripts/validate.py <name>.drawio` for a fast structural lint (dangling edges, dup ids, overlaps) before exporting. Default output dir is the user's working dir; if the user specified an output path or directory (e.g. `./artifacts/`, `docs/images/`), use that instead — `mkdir -p` the target dir first. Apply the same dir choice to PNG/SVG/PDF exports in steps 4 and 7.
4. **Export draft** — run CLI to produce a preview PNG. **Do NOT pass `-e`** at this step — the embedded `zTXt mxGraphModel` chunk it adds causes vision APIs (Claude included) to return 400 "Could not process image" in step 5. **Cap the preview width with `--width 2000` (not `-s 2`)** — Claude's vision API rejects images larger than 2576×2576px with "Unable to resize image — dimensions exceed the 2576x2576px limit", and `-s 2` on a medium-or-larger diagram easily overshoots that ceiling. Save the clean preview as `<name>.png` (single extension). Embedding and full-resolution scale are for the final export only (step 7).
5. **Self-check** — use the agent's built-in vision capability to read the exported PNG, catch obvious issues, auto-fix before showing user (requires a vision-enabled model such as Claude Sonnet/Opus). If reading the PNG returns a 400 / "Could not process image" error, you almost certainly exported with `-e` by mistake — re-export without `-e` and retry once. If it still fails, skip self-check and continue to step 6.
6. **Review loop** — show image to user, collect feedback, apply targeted XML edits, re-export, repeat until approved
diff --git a/skills/drawio-skill/references/autolayout.md b/skills/drawio-skill/references/autolayout.md
index 90b37c4..8d95ffa 100644
--- a/skills/drawio-skill/references/autolayout.md
+++ b/skills/drawio-skill/references/autolayout.md
@@ -161,7 +161,13 @@ Dot already routes edges orthogonally as part of its layout pass (`splines=ortho
**There is no CLI flag that reroutes edges without moving nodes.** `--layout` only accepts ELK *node* layout presets (`verticalFlow`, `horizontalFlow`, `verticalTree`, `horizontalTree`, `radialTree`, `organic`) or a JSON layout array — every one of them re-places vertices. Passing an unrecognised value (e.g. `libavoid`) makes draw.io open a modal `Unknown layout:` error dialog, which **hangs a headless run until it is killed**.
-When the output still has edges cutting across shapes, fix it at authoring time instead — pin `exitX/exitY/entryX/entryY`, add `<Array as="points">` waypoints, or increase node spacing (see `xml-authoring.md` "Edge style rules"). draw.io's obstacle-avoiding connector router is editor-side only: open the `.drawio` in draw.io desktop and re-route there.
+When the output still has edges cutting across shapes, fix it at authoring time instead:
+
+```bash
+python3 edgeports.py diagram.drawio # spread stacked edges over each perimeter
+```
+
+`edgeports.py` handles the common case — several edges leaving the same side of a node all landing on the same point. It is a port assigner, not a router: for an edge crossing an unrelated shape mid-run, add `<Array as="points">` waypoints or increase node spacing (see `xml-authoring.md` "Edge style rules"). draw.io's obstacle-avoiding connector router is editor-side only: open the `.drawio` in draw.io desktop and re-route there.
## Limitations
diff --git a/skills/drawio-skill/references/xml-authoring.md b/skills/drawio-skill/references/xml-authoring.md
index 58b9c5c..075ea73 100644
--- a/skills/drawio-skill/references/xml-authoring.md
+++ b/skills/drawio-skill/references/xml-authoring.md
@@ -118,7 +118,7 @@ For architecture diagrams with nested elements, use draw.io's parent-child conta
**Edge style rules:**
- **Animated connectors:** add `flowAnimation=1;` to any edge style to show a moving dot animation along the arrow. Works in SVG export and draw.io desktop — ideal for data-flow and pipeline diagrams. Example: `style="edgeStyle=orthogonalEdgeStyle;flowAnimation=1;rounded=1;..."`
- **Always** include `rounded=1;orthogonalLoop=1;jettySize=auto` — these enable smart routing that avoids overlaps
-- Pin `exitX/exitY/entryX/entryY` on every edge when a node has 2+ connections — distributes lines across the shape perimeter
+- Pin `exitX/exitY/entryX/entryY` on every edge when a node has 2+ connections — distributes lines across the shape perimeter. `scripts/edgeports.py <file>` does this for a whole diagram: it picks the side facing each peer and spreads that side's edges over even slots ordered by the far endpoint, so they don't stack or cross at the boundary. It skips ends you pinned by hand and is idempotent
- Add `<Array as="points">` waypoints when an edge must detour around an intermediate shape
- **Leave room for arrowheads:** the final straight segment between the last bend and the target shape must be ≥20px long. If too short, the arrowhead overlaps the bend and looks broken. Fix by increasing node spacing or adding explicit waypoints
- **libavoid obstacle-avoiding routing (editor-side, draw.io ≥ 30):** draw.io has a newer connector router that recomputes edge paths to run *around* shapes (fanning out parallel edges) without moving any node. It runs interactively in the draw.io desktop editor (or via jgraph's MCP app-server `routing:"libavoid"`) — it is **not** a headless CLI flag. Passing `--layout libavoid` opens a modal `Unknown layout:` error dialog and hangs the run; the CLI `--layout` values are ELK *node* layout presets, a different thing (see `mermaid-authoring.md`). For CLI-authored files keep the orthogonal rules above; if a dense diagram still has crossings after export, open the `.drawio` in draw.io desktop once and let libavoid re-route. Don't stack it on an ELK `--layout` pass — pick one router, not both.
diff --git a/skills/drawio-skill/scripts/edgeports.py b/skills/drawio-skill/scripts/edgeports.py
new file mode 100755
index 0000000..987cbc9
--- /dev/null
+++ b/skills/drawio-skill/scripts/edgeports.py
@@ -0,0 +1,211 @@
+#!/usr/bin/env python3
+"""Assign edge connection points (ports) on an existing .drawio file.
+
+draw.io's floating connections attach every edge of a node to the middle of
+whichever side faces the other endpoint. When a node has several connections
+leaving the same side they all land on the same point, so the lines stack and
+overlap — the usual complaint on swimlane / cross-functional flowcharts, where
+handoff edges between lanes share long orthogonal corridors.
+
+This pass pins ``exitX/exitY`` and ``entryX/entryY`` instead:
+
+1. Resolve every vertex to absolute coordinates (through swimlane/container
+ parents, via ``validate.abs_rect``).
+2. For each edge end, pick the side of the node that faces the other endpoint
+ (whichever of dx/dy dominates, measured centre-to-centre).
+3. Group the ends by (node, side) and sort each group along the side by the far
+ endpoint's position across that axis. Sorting by the far endpoint is what
+ removes crossings: two edges leaving the same side keep their relative order
+ instead of swapping over each other.
+4. Spread the group evenly over the side — k ends get slots 1/(k+1) .. k/(k+1).
+
+Only sides with 2+ ends are touched. Edges that already pin a port are left
+alone, so hand-tuned geometry survives a re-run. Idempotent: running it twice
+produces the same file.
+
+This is a *port* assignment, not a router — it fixes lines stacking at the
+shape boundary, not an edge crossing an unrelated shape in the middle of its
+run. For that, add waypoints (see references/xml-authoring.md).
+
+Usage:
+ python3 edgeports.py diagram.drawio # in place
+ python3 edgeports.py diagram.drawio -o routed.drawio
+ python3 edgeports.py diagram.drawio --dry-run # report only
+"""
+
+import argparse
+import importlib.util
+import os
+import sys
+import xml.etree.ElementTree as ET
+
+_spec = importlib.util.spec_from_file_location(
+ "validate", os.path.join(os.path.dirname(os.path.abspath(__file__)), "validate.py"))
+validate = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(validate)
+
+# Port coordinates per side. Each entry is (fixed_axis_value, varies_along_x).
+# 'varies_along_x' says which coordinate the evenly-spaced slot fills in.
+SIDES = {
+ "N": (0.0, True), # top edge: y=0, x varies
+ "S": (1.0, True), # bottom edge: y=1, x varies
+ "W": (0.0, False), # left edge: x=0, y varies
+ "E": (1.0, False), # right edge: x=1, y varies
+}
+
+
+def centre(r):
+ x, y, w, h = r
+ return (x + w / 2.0, y + h / 2.0)
+
+
+def side_facing(src_rect, dst_rect):
+ """Which side of src faces dst: whichever of dx/dy dominates."""
+ sx, sy = centre(src_rect)
+ dx_, dy_ = centre(dst_rect)
+ dx, dy = dx_ - sx, dy_ - sy
+ if abs(dx) >= abs(dy):
+ return "E" if dx >= 0 else "W"
+ return "S" if dy >= 0 else "N"
+
+
+def has_port(style, end):
+ """True if the edge already pins this end's port (hand-tuned — leave it)."""
+ prefix = "exit" if end == "source" else "entry"
+ return (validate.style_num(style, prefix + "X") is not None
+ and validate.style_num(style, prefix + "Y") is not None)
+
+
+def set_style(style, end, px, py):
+ """Return style with this end's port keys set, other keys order-preserved."""
+ prefix = "exit" if end == "source" else "entry"
+ drop = {prefix + "X", prefix + "Y", prefix + "Dx", prefix + "Dy"}
+ parts = [p for p in (style or "").split(";")
+ if p and p.split("=", 1)[0] not in drop]
+ # Dx/Dy are perpendicular offsets in px; reset them so a re-run is stable.
+ parts += [f"{prefix}X={px:g}", f"{prefix}Y={py:g}",
+ f"{prefix}Dx=0", f"{prefix}Dy=0"]
+ return ";".join(parts) + ";"
+
+
+def assign(cells, by_id):
+ """Compute {(edge_elem, end): (px, py)} for every end worth pinning."""
+ rects = {}
+ for c in cells:
+ if c.get("vertex") == "1" and not validate.is_edge_label(c):
+ r = validate.abs_rect(c, by_id)
+ if r and not any(v != v for v in r): # NaN width/height guard
+ rects[c.get("id")] = r
+
+ # Collect ends: one entry per (edge, end) whose node and peer are known.
+ groups = {}
+ for e in cells:
+ if e.get("edge") != "1":
+ continue
+ style = e.get("style") or ""
+ src, dst = e.get("source"), e.get("target")
+ if src not in rects or dst not in rects:
+ continue # dangling — validate.py's job
+ for end, me, peer in (("source", src, dst), ("target", dst, src)):
+ if has_port(style, end):
+ continue
+ side = side_facing(rects[me], rects[peer])
+ groups.setdefault((me, side), []).append((e, end, rects[peer]))
+
+ ports = {}
+ for (node_id, side), ends in groups.items():
+ if len(ends) < 2:
+ continue # single edge: centre is fine
+ fixed, along_x = SIDES[side]
+ # Sort by the far endpoint's position across the axis we spread along.
+ # Tie-break on the other axis, then edge id, so the order is total and
+ # the output is deterministic.
+ ends.sort(key=lambda t: (centre(t[2])[0] if along_x else centre(t[2])[1],
+ centre(t[2])[1] if along_x else centre(t[2])[0],
+ t[0].get("id") or ""))
+ for i, (edge, end, _) in enumerate(ends):
+ slot = (i + 1) / float(len(ends) + 1)
+ ports[(edge, end)] = (slot, fixed) if along_x else (fixed, slot)
+ return ports
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("file", help="input .drawio")
+ ap.add_argument("-o", "--output", help="output path (default: edit in place)")
+ ap.add_argument("--dry-run", action="store_true",
+ help="report what would change, write nothing")
+ args = ap.parse_args()
+
+ try:
+ tree = ET.parse(args.file)
+ except ET.ParseError as exc:
+ sys.exit(f"error: {args.file} is not parseable XML ({exc}). "
+ "Compressed .drawio files must be saved uncompressed first.")
+
+ total = 0
+ for model in tree.getroot().iter("mxGraphModel"):
+ cells = list(model.iter("mxCell"))
+ by_id = {c.get("id"): c for c in cells if c.get("id")}
+ ports = assign(cells, by_id)
+ for (edge, end), (px, py) in ports.items():
+ edge.set("style", set_style(edge.get("style") or "", end, px, py))
+ total += len(ports)
+
+ if args.dry_run:
+ print(f"{total} edge end(s) would be pinned in {args.file}")
+ return
+ out = args.output or args.file
+ tree.write(out, encoding="utf-8", xml_declaration=False)
+ print(f"{total} edge end(s) pinned -> {out}")
+
+
+def demo():
+ """Self-check: three edges leaving one node's east side get distinct,
+ non-crossing ports, and a re-run is a no-op."""
+ xml = """<mxfile><diagram><mxGraphModel><root>
+ <mxCell id="0"/><mxCell id="1" parent="0"/>
+ <mxCell id="lane" vertex="1" parent="1">
+ <mxGeometry x="100" y="0" width="400" height="400" as="geometry"/></mxCell>
+ <mxCell id="hub" vertex="1" parent="lane">
+ <mxGeometry x="0" y="150" width="80" height="40" as="geometry"/></mxCell>
+ <mxCell id="a" vertex="1" parent="1">
+ <mxGeometry x="600" y="300" width="80" height="40" as="geometry"/></mxCell>
+ <mxCell id="b" vertex="1" parent="1">
+ <mxGeometry x="600" y="100" width="80" height="40" as="geometry"/></mxCell>
+ <mxCell id="c" vertex="1" parent="1">
+ <mxGeometry x="600" y="200" width="80" height="40" as="geometry"/></mxCell>
+ <mxCell id="e1" edge="1" parent="1" source="hub" target="a" style="rounded=1;"/>
+ <mxCell id="e2" edge="1" parent="1" source="hub" target="b" style="rounded=1;"/>
+ <mxCell id="e3" edge="1" parent="1" source="hub" target="c" style="rounded=1;"/>
+ <mxCell id="e4" edge="1" parent="1" source="hub" target="a"
+ style="rounded=1;exitX=1;exitY=0.9;"/>
+ </root></mxGraphModel></diagram></mxfile>"""
+ root = ET.fromstring(xml)
+ cells = list(root.iter("mxCell"))
+ by_id = {c.get("id"): c for c in cells if c.get("id")}
+
+ # hub sits inside 'lane' (x=100), so its absolute x is 100, not 0. Without
+ # parent resolution every target would look like it was to the west.
+ assert validate.abs_rect(by_id["hub"], by_id)[0] == 100.0
+
+ ports = assign(cells, by_id)
+ exits = {e.get("id"): p for (e, end), p in ports.items() if end == "source"}
+ assert set(exits) == {"e1", "e2", "e3"}, exits # e4 pre-pinned, untouched
+ assert all(x == 1.0 for x, _ in exits.values()) # all leave the east side
+ ys = [exits[i][1] for i in ("e2", "e3", "e1")] # targets ordered top->bottom
+ assert ys == sorted(ys), ys # ports follow => no crossing
+ assert len(set(ys)) == 3, ys # and no two stack
+
+ for (edge, end), (px, py) in ports.items():
+ edge.set("style", set_style(edge.get("style"), end, px, py))
+ assert not assign(cells, by_id), "second run must be a no-op"
+ print("ok")
+
+
+if __name__ == "__main__":
+ if "--demo" in sys.argv:
+ demo()
+ else:
+ main()