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(validate): deterministic edge-through-vertex and edge-crossing detection (#44)

David R Oliver765a95b14b9c
diff --git a/skills/drawio-skill/scripts/validate.py b/skills/drawio-skill/scripts/validate.py
index 9f3a918..299d3b2 100644
--- a/skills/drawio-skill/scripts/validate.py
+++ b/skills/drawio-skill/scripts/validate.py
@@ -3,11 +3,25 @@
Catches the class of mistakes a vision self-check is slow and unreliable at:
dangling edge endpoints, duplicate or reserved ids, broken parent references,
-and (as warnings) off-grid geometry and overlapping sibling nodes. Runs without
-launching draw.io, so it is a fast pre-check before the visual review step.
+and (as warnings) off-grid geometry, overlapping sibling nodes, and edge
+routing defects. Runs without launching draw.io, so it is a fast pre-check
+before the visual review step.
python3 validate.py diagram.drawio
+Edge routing checks (warnings): an edge segment crossing a non-incident leaf
+vertex ("routes through vertex"), and two edges crossing each other ("edges X
+and Y cross") — the two defects the SKILL.md step-5 self-check looks for
+("Edge-shape overlap", "Stacked edges"), but caught here deterministically.
+
+Routing is only knowable from the XML when an edge carries explicit waypoints
+(``<Array as="points">``) — exactly the hand-routed case the SKILL.md tells
+authors to use to route around shapes. Edges with no waypoints are auto-routed
+by draw.io at render time (the path is not stored), so they are NOT geometry-
+checked here, keeping these warnings free of false positives. Endpoints honour
+``exitX/exitY``/``entryX/entryY`` when present, else the node centre, and
+absolute positions are resolved through parent containers.
+
Exit status is non-zero when any error (or, with --strict, any warning) is
found, so it can gate a workflow. Compressed (non-XML) diagram pages are
skipped with a warning — this skill always writes uncompressed XML.
@@ -58,6 +72,172 @@ def overlap(a, b):
return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
+# --- Edge routing geometry -------------------------------------------------
+#
+# These helpers reason about edge paths. They only apply to edges with explicit
+# waypoints (the route is otherwise computed by draw.io at render time and not
+# stored in the XML), so the checks never guess an auto-routed path.
+
+def style_num(style, key):
+ """Return float value of ``key=`` in a draw.io style string, or None."""
+ for part in (style or "").split(";"):
+ if part.startswith(key + "="):
+ try:
+ return float(part.split("=", 1)[1])
+ except ValueError:
+ return None
+ return None
+
+
+def abs_rect(cell, by_id):
+ """Absolute (x, y, w, h) of a vertex, summing parent-container offsets.
+
+ Children of a container use coordinates relative to the container origin, so
+ an edge spanning containers needs absolute positions to be compared.
+ """
+ r = rect(cell)
+ if r is None or any(v != v for v in r):
+ return None
+ x, y, w, h = r
+ parent, seen = cell.get("parent"), set()
+ while parent and parent in by_id and parent not in seen:
+ seen.add(parent)
+ p = by_id[parent]
+ if p.get("vertex") == "1":
+ pr = rect(p)
+ if pr and not any(v != v for v in pr):
+ x += pr[0]
+ y += pr[1]
+ parent = p.get("parent")
+ return (x, y, w, h)
+
+
+def endpoint(edge, end, by_id):
+ """Absolute (x, y) where ``edge`` meets its source/target vertex.
+
+ Honours exitX/exitY (source) and entryX/entryY (target) if the style pins
+ them; otherwise the vertex centre. Returns None if the vertex is unresolved.
+ """
+ vid = edge.get(end)
+ if not vid or vid not in by_id:
+ return None
+ box = abs_rect(by_id[vid], by_id)
+ if box is None:
+ return None
+ x, y, w, h = box
+ style = edge.get("style") or ""
+ fx = style_num(style, "exitX" if end == "source" else "entryX")
+ fy = style_num(style, "exitY" if end == "source" else "entryY")
+ return (x + (fx if fx is not None else 0.5) * w,
+ y + (fy if fy is not None else 0.5) * h)
+
+
+def edge_waypoints(edge):
+ """Explicit <Array as="points"> waypoints of an edge as [(x, y), ...]."""
+ g = edge.find("mxGeometry")
+ if g is None:
+ return []
+ arr = g.find("Array")
+ if arr is None:
+ return []
+ pts = []
+ for pt in arr.findall("mxPoint"):
+ px, py = pt.get("x"), pt.get("y")
+ if px is not None and py is not None:
+ try:
+ pts.append((float(px), float(py)))
+ except ValueError:
+ pass
+ return pts
+
+
+def edge_route(edge, by_id):
+ """Absolute polyline [(x, y), ...] for a waypointed edge, or None.
+
+ Returns None when the edge has no explicit waypoints (auto-routed; path
+ unknown) or an endpoint cannot be resolved.
+ """
+ waypoints = edge_waypoints(edge)
+ if not waypoints:
+ return None
+ s, t = endpoint(edge, "source", by_id), endpoint(edge, "target", by_id)
+ if s is None or t is None:
+ return None
+ return [s] + waypoints + [t]
+
+
+def _orient(a, b, c):
+ v = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
+ return 0 if abs(v) < 1e-9 else (1 if v > 0 else -1)
+
+
+def segments_cross(p1, p2, p3, p4):
+ """True if segments p1p2 and p3p4 properly cross (interior intersection).
+
+ Proper crossing only: collinear overlap and shared-endpoint touches return
+ False, so edges meeting at a common node or grazing a corner are not flagged.
+ """
+ o1, o2 = _orient(p1, p2, p3), _orient(p1, p2, p4)
+ o3, o4 = _orient(p3, p4, p1), _orient(p3, p4, p2)
+ return o1 != o2 and o3 != o4 and 0 not in (o1, o2, o3, o4)
+
+
+def _point_in_rect(p, box, eps=1e-6):
+ x, y, w, h = box
+ return x + eps < p[0] < x + w - eps and y + eps < p[1] < y + h - eps
+
+
+def route_hits_rect(points, box):
+ """True if a polyline enters a rectangle's interior or crosses a border."""
+ x, y, w, h = box
+ corners = [(x, y), (x + w, y), (x + w, y + h), (x, y + h)]
+ borders = list(zip(corners, corners[1:] + corners[:1]))
+ for a, b in zip(points, points[1:]):
+ if _point_in_rect(a, box) or _point_in_rect(b, box):
+ return True
+ if any(segments_cross(a, b, c, d) for c, d in borders):
+ return True
+ return False
+
+
+def routes_cross(pa, pb):
+ """True if any segment of polyline pa properly crosses any of pb."""
+ for a1, a2 in zip(pa, pa[1:]):
+ for b1, b2 in zip(pb, pb[1:]):
+ if segments_cross(a1, a2, b1, b2):
+ return True
+ return False
+
+
+def geometry_warnings(cells, ids, parents):
+ """Edge-through-vertex and edge-crossing warnings for waypointed edges."""
+ warns = []
+ routed = [] # (edge_id, polyline, {source, target})
+ for c in cells:
+ if c.get("edge") == "1":
+ pts = edge_route(c, ids)
+ if pts:
+ routed.append((c.get("id"), pts,
+ {c.get("source"), c.get("target")}))
+ # Edge routes through an unrelated leaf vertex (containers wrap children, so
+ # an edge legitimately traverses them — restrict to leaves, as overlap does).
+ leaves = [(c.get("id"), abs_rect(c, ids)) for c in cells
+ if c.get("vertex") == "1" and c.get("id") not in parents
+ and not is_edge_label(c)]
+ leaves = [(vid, box) for vid, box in leaves if box]
+ for eid, pts, ends in routed:
+ for vid, box in leaves:
+ if vid not in ends and route_hits_rect(pts, box):
+ warns.append(f"edge {eid!r} routes through vertex {vid!r}")
+ # Edge-edge crossings (both routes known).
+ for i in range(len(routed)):
+ for j in range(i + 1, len(routed)):
+ (ia, pa, _), (ib, pb, _) = routed[i], routed[j]
+ if routes_cross(pa, pb):
+ warns.append(f"edges {ia!r} and {ib!r} cross")
+ return warns
+
+
def check_page(diagram):
"""Return (errors, warnings) for one <diagram> page."""
name = diagram.get("name", "?")
@@ -106,6 +286,7 @@ def check_page(diagram):
(ia, pa, ra), (ib, pb, rb) = boxes[i], boxes[j]
if pa == pb and overlap(ra, rb):
warns.append(f"vertices {ia!r} and {ib!r} overlap")
+ warns += geometry_warnings(cells, ids, parents)
return errors, warns
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 2939f8d..837da17 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -232,6 +232,120 @@ class TestValidateCli(unittest.TestCase):
self.assertNotIn("error:", r.stdout)
+class TestValidateGeometry(unittest.TestCase):
+ """Edge routing geometry checks (waypointed edges only)."""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.m = load("validate")
+
+ @staticmethod
+ def _ids(xml):
+ import xml.etree.ElementTree as ET
+ root = ET.fromstring(xml)
+ return {c.get("id"): c for c in root.iter("mxCell")}
+
+ # --- pure-function unit tests ---
+ def test_segments_cross(self):
+ c = self.m.segments_cross
+ self.assertTrue(c((0, 0), (10, 10), (0, 10), (10, 0))) # an X
+ self.assertFalse(c((0, 0), (10, 0), (0, 5), (10, 5))) # parallel
+ self.assertFalse(c((0, 0), (10, 0), (10, 0), (10, 10))) # touch at endpoint
+
+ def test_route_hits_rect(self):
+ h = self.m.route_hits_rect
+ self.assertTrue(h([(0, 50), (100, 50)], (40, 40, 20, 20))) # cuts through
+ self.assertFalse(h([(0, 0), (100, 0)], (40, 40, 20, 20))) # clear of box
+
+ def test_abs_rect_resolves_container_offset(self):
+ ids = self._ids(
+ '<root>'
+ '<mxCell id="c" vertex="1" parent="1">'
+ '<mxGeometry x="100" y="100" width="200" height="200" as="geometry"/></mxCell>'
+ '<mxCell id="ch" vertex="1" parent="c">'
+ '<mxGeometry x="10" y="10" width="40" height="40" as="geometry"/></mxCell>'
+ '</root>')
+ self.assertEqual(self.m.abs_rect(ids["ch"], ids), (110, 110, 40, 40))
+
+ def test_endpoint_honours_exit_point(self):
+ ids = self._ids(
+ '<root>'
+ '<mxCell id="s" vertex="1" parent="1">'
+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="e" edge="1" parent="1" source="s" target="s" '
+ 'style="exitX=1;exitY=0.5;"><mxGeometry relative="1" as="geometry"/></mxCell>'
+ '</root>')
+ self.assertEqual(self.m.endpoint(ids["e"], "source", ids), (80, 20))
+
+ # --- CLI integration tests ---
+ def _check(self, xml):
+ with tempfile.NamedTemporaryFile("w", suffix=".drawio", delete=False) as f:
+ f.write(xml)
+ path = f.name
+ try:
+ return run("validate.py", path)
+ finally:
+ os.unlink(path)
+
+ # Two waypointed edges forming an X that crosses at (300,300).
+ CROSS = ('<mxfile><diagram name="P1"><mxGraphModel><root>'
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<mxCell id="n1" vertex="1" parent="1"><mxGeometry x="80" y="80" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="n2" vertex="1" parent="1"><mxGeometry x="80" y="480" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="n3" vertex="1" parent="1"><mxGeometry x="480" y="80" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="n4" vertex="1" parent="1"><mxGeometry x="480" y="480" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="e1" edge="1" parent="1" source="n1" target="n4"><mxGeometry relative="1" as="geometry">'
+ '<Array as="points"><mxPoint x="200" y="200"/></Array></mxGeometry></mxCell>'
+ '<mxCell id="e2" edge="1" parent="1" source="n2" target="n3"><mxGeometry relative="1" as="geometry">'
+ '<Array as="points"><mxPoint x="200" y="400"/></Array></mxGeometry></mxCell>'
+ '</root></mxGraphModel></diagram></mxfile>')
+
+ # A waypointed edge whose route passes straight through obstacle vertex 'v'.
+ THROUGH = ('<mxfile><diagram name="P1"><mxGraphModel><root>'
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<mxCell id="n1" vertex="1" parent="1"><mxGeometry x="80" y="80" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="n2" vertex="1" parent="1"><mxGeometry x="480" y="80" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="v" vertex="1" parent="1"><mxGeometry x="280" y="80" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="e" edge="1" parent="1" source="n1" target="n2"><mxGeometry relative="1" as="geometry">'
+ '<Array as="points"><mxPoint x="300" y="100"/></Array></mxGeometry></mxCell>'
+ '</root></mxGraphModel></diagram></mxfile>')
+
+ # Same geometry as THROUGH but the edge has NO waypoints — auto-routed, so
+ # its path is unknown and must NOT be geometry-checked (no false positive).
+ AUTOROUTE = ('<mxfile><diagram name="P1"><mxGraphModel><root>'
+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'
+ '<mxCell id="n1" vertex="1" parent="1"><mxGeometry x="80" y="80" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="n2" vertex="1" parent="1"><mxGeometry x="480" y="80" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="v" vertex="1" parent="1"><mxGeometry x="280" y="80" width="40" height="40" as="geometry"/></mxCell>'
+ '<mxCell id="e" edge="1" parent="1" source="n1" target="n2">'
+ '<mxGeometry relative="1" as="geometry"/></mxCell>'
+ '</root></mxGraphModel></diagram></mxfile>')
+
+ def test_edge_crossing_warns(self):
+ r = self._check(self.CROSS)
+ self.assertIn("edges 'e1' and 'e2' cross", r.stdout)
+ self.assertEqual(r.returncode, 0) # warning, not error
+
+ def test_edge_crossing_strict_fails(self):
+ with tempfile.NamedTemporaryFile("w", suffix=".drawio", delete=False) as f:
+ f.write(self.CROSS)
+ path = f.name
+ try:
+ self.assertEqual(run("validate.py", path, "--strict").returncode, 1)
+ finally:
+ os.unlink(path)
+
+ def test_edge_through_vertex_warns(self):
+ r = self._check(self.THROUGH)
+ self.assertIn("edge 'e' routes through vertex 'v'", r.stdout)
+
+ def test_autorouted_edge_not_checked(self):
+ # No waypoints -> path unknown -> no geometry warning (FP-free).
+ r = self._check(self.AUTOROUTE)
+ self.assertNotIn("routes through", r.stdout)
+ self.assertEqual(r.returncode, 0)
+
+
class TestImportersCli(unittest.TestCase):
@staticmethod
def _write(path, text):