Agent skill that turns natural language, code, Terraform/K8s, SQL, OpenAPI, AsyncAPI, Protobuf and GraphQL sources into editable, tested draw.io architecture diagrams: incremental sync, multi-view projection, drift diff, CI architecture tests, whiteboard derasterize, interactive HTML/PPTX/Mermaid exports.
Python agent-skillsarchitecturearchitecture-diagramasyncapibpmnc4-modelclaude-codediagramdiagrams-as-codedrawioflowchartgithub-actionsgraphqlimage-to-diagramkubernetesmcp-serverprotobufsysmlterraformuml
feat: structured validate diagnostics + drawiodiff moved/rerouted
Agents365-aid96c6d08f773
diff --git a/skills/drawio-skill/references/autolayout.md b/skills/drawio-skill/references/autolayout.mdindex 8d95ffa..a87f128 100644--- a/skills/drawio-skill/references/autolayout.md+++ b/skills/drawio-skill/references/autolayout.md@@ -125,14 +125,14 @@ Each code importer keeps only **intra-project** edges (third-party/stdlib import## Diffing two diagrams (`drawiodiff.py`)-`drawiodiff.py old.drawio new.drawio -o diff.json` compares two `.drawio` files and emits a colour-coded graph JSON for autolayout — one diagram showing **what changed**: nodes/edges added (green), removed (red, dashed), changed (orange, a matched node whose label moved) or unchanged (grey).+`drawiodiff.py old.drawio new.drawio -o diff.json` compares two `.drawio` files and emits a colour-coded graph JSON for autolayout — one diagram showing **what changed**: nodes/edges added (green), removed (red, dashed), changed (orange, a matched node whose label moved), moved (violet, a matched node with the same label at new coordinates) or unchanged (grey). Edges can be **rerouted** (orange): a re-point of an old edge (one endpoint kept, the other swapped for a newly added node) or a direction flip, shown once instead of as a separate added/removed pair.```bashpython3 <this-skill-dir>/scripts/drawiodiff.py old.drawio new.drawio -o diff.jsonpython3 <this-skill-dir>/scripts/autolayout.py diff.json -o diff.drawio```-Nodes match by cell **id** by default — ideal for anything the importers or live-infra snapshots produce (their ids are stable semantic keys), so *snapshot → change → snapshot → diff* shows drift directly (e.g. two `tfstate.py` or `k8simports.py` snapshots). Pass `--by-label` to match on the visible label instead, for hand-drawn diagrams whose ids are random. Only leaf vertices and their edges are compared (containers/group cells and edge labels are skipped); the diff is a flat colour-coded view, so original icons are replaced by status colours (labels are kept). Multi-page files are flattened; compressed pages are skipped with a warning (this skill always writes uncompressed XML).+Nodes match by cell **id** by default — ideal for anything the importers or live-infra snapshots produce (their ids are stable semantic keys), so *snapshot → change → snapshot → diff* shows drift directly (e.g. two `tfstate.py` or `k8simports.py` snapshots). Pass `--by-label` to match on the visible label instead, for hand-drawn diagrams whose ids are random. Movement is reported only when it is selective: if every matched node changed position, the two files come from different layout runs (the usual importer + autolayout case) and all matched nodes stay "same". Only leaf vertices and their edges are compared (containers/group cells and edge labels are skipped); the diff is a flat colour-coded view, so original icons are replaced by status colours (labels are kept). Multi-page files are flattened; compressed pages are skipped with a warning (this skill always writes uncompressed XML).## Architecture time-lapse over git history (`timelapse.py`)diff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.mdindex 2902b5b..7d83349 100644--- a/skills/drawio-skill/references/toolbox.md+++ b/skills/drawio-skill/references/toolbox.md@@ -1,6 +1,6 @@# Toolbox — every bundled script, by use-case-A map of the 31 bundled scripts grouped by what you're trying to do. The+A map of the 39 bundled scripts grouped by what you're trying to do. Theper-task routing table in `SKILL.md` says *when* to reach for each; this says*how they fit together*. Read it when you're not sure which script a requestmaps to, or you want to chain several.@@ -80,7 +80,7 @@ The **actual** counterpart to §3 — see `references/live-infra.md`.## 5. Compare & evolve-- **`drawiodiff.py`** — diff two `.drawio` (or two live snapshots) → colour-coded graph (added=green, removed=red, changed=orange). Pairs with §4 for drift.+- **`drawiodiff.py`** — diff two `.drawio` (or two live snapshots) → colour-coded graph (added=green, removed=red, changed=orange, moved=violet, rerouted edges=orange). Pairs with §4 for drift.- **`timelapse.py`** — re-run an extractor across git history → a self-contained HTML player of how the architecture grew.- **`heatmap.py`** — recolour any `.drawio` by a metrics file (CSV/JSON): each node shaded low→high on a gradient by its value (`--palette`, optional `--size`, auto legend). Turns a static architecture into a cost / latency / traffic / error-rate heat map.- **`buildup.py`** — reveal ONE diagram's cells in dependency order (topological over its edges) → self-contained HTML player (embedded PNG frames, play/pause/step/scrub); optional `--gif`. Needs the draw.io CLI.@@ -102,6 +102,6 @@ The skill runs both directions — these turn a `.drawio` back into something el- **`relabel.py`** — swap every label via a JSON map, layout untouched — `--extract` dumps an identity map of all labels (vertices, edges, UserObjects, page names), translate the values, `--map` applies them. Built for bilingual (EN/CN) variants of one diagram.- **`restyle.py`** — apply a style preset (user or built-in, e.g. `dark`) to an existing `.drawio`: palette remap by hue, font, dark-theme extras, page background. Layout, shapes, and edge routing stay put.-- **`validate.py`** — deterministic structural lint (dangling edges, dup/reserved ids, overlaps; `--score` for layout readability). Run before exporting.+- **`validate.py`** — deterministic structural lint (dangling edges, dup/reserved ids, overlaps; `--score` for layout readability). Findings render as `error: [E-DANGLING-END] ... (fix: ...)` — stable codes + fix hints; `--json` for structured output. Run before exporting.- **`repair_png.py`** — fix draw.io's truncated IEND chunk after every `-e` PNG export (issue #8).- **`encode_drawio_url.py`** — encode a `.drawio` into a diagrams.net browser URL when the CLI is unavailable (`--edit` for an editable editor URL).diff --git a/skills/drawio-skill/scripts/drawiodiff.py b/skills/drawio-skill/scripts/drawiodiff.pyindex 68f1e26..c1c9f12 100644--- a/skills/drawio-skill/scripts/drawiodiff.py+++ b/skills/drawio-skill/scripts/drawiodiff.py@@ -4,10 +4,17 @@Compares an OLD and a NEW .drawio and emits a single graph where every node andedge is tinted by what happened to it:- added (in new only) -> green- removed (in old only) -> red, dashed- changed (matched, label moved) -> orange- same (matched, unchanged) -> grey+ added (in new only) -> green+ removed (in old only) -> red, dashed+ changed (matched, label moved) -> orange+ moved (matched, same label, new x/y) -> violet+ same (matched, unchanged) -> grey++Edges can additionally be **rerouted** (orange): a new edge whose old+counterpart kept one endpoint and swapped the other for a freshly added node+("service repointed from cache to worker"), or whose direction flipped+((a,b) in old, (b,a) in new). A flipped edge suppresses its reversed old+counterpart so the pair is shown once.The output is a normal graph JSON — feed it to autolayout.py for one clean,freshly laid-out "what changed" diagram:@@ -23,6 +30,12 @@ it the natural companion to the live-infra importers: snapshot `terraform showdrift. For hand-drawn diagrams whose ids are random, pass `--by-label` to matchon the visible label text instead.+Because the output is re-laid-out by autolayout, a "moved" tint is only+reported for hand-placed coordinates — and only when it is selective. If every+matched node changed position, the two files were laid out by different runs+(the usual importer + autolayout case), so movement is layout noise, not a+fact, and all matched nodes stay "same".+Only leaf vertices and the edges between them are compared; container/groupcells and edge labels are skipped. The diff is a flat colour-coded view, so theoriginal icons/shapes are replaced by status colours (the label is kept).@@ -39,19 +52,22 @@ STYLE = {"added": "rounded=1;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;","removed": "rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;dashed=1;","changed": "rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;",+ "moved": "rounded=1;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;","same": "rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#999999;",}EDGE_STYLE = {- "added": "endArrow=classic;html=1;strokeColor=#82b366;strokeWidth=2;",- "removed": "endArrow=classic;html=1;strokeColor=#b85450;strokeWidth=2;dashed=1;",- "same": "endArrow=classic;html=1;strokeColor=#999999;",+ "added": "endArrow=classic;html=1;strokeColor=#82b366;strokeWidth=2;",+ "removed": "endArrow=classic;html=1;strokeColor=#b85450;strokeWidth=2;dashed=1;",+ "rerouted": "endArrow=classic;html=1;strokeColor=#d79b00;strokeWidth=2;",+ "same": "endArrow=classic;html=1;strokeColor=#999999;",}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)."""+ """Return (nodes, edges) for a .drawio: nodes {id: (label, style, pos)} for+ leaf vertices (pos = (x, y) or None when no geometry), edges+ {(source_id, target_id)}. Cells are flattened across pages; UserObject/object+ wrappers are unwrapped (id on the wrapper, cell inside)."""try:tree = ET.parse(path)except (ET.ParseError, OSError) as exc:@@ -89,10 +105,41 @@ def parse(path):g = c.find("mxGeometry")if g is not None and g.get("relative") == "1": # edge-label childcontinue- nodes[cid] = (labels.get(cid, ""), c.get("style") or "")+ pos = None+ if g is not None:+ try:+ pos = (float(g.get("x", "0")), float(g.get("y", "0")))+ except ValueError:+ pos = None+ nodes[cid] = (labels.get(cid, ""), c.get("style") or "", pos)return nodes, edges+def classify_rerouted(old_ek, new_ek, removed, added):+ """Edge keys that are reroutes of an old edge, not brand-new connections.++ Two decidable cases (everything else stays a plain add):+ - flip: (a,b) in old and (b,a) in new — same pair, reversed direction.+ - re-point: old (a,b) with b removed and new (a,c) with c added (the kept+ endpoint a pins the pairing; ambiguous when a kept endpoint has+ several candidate re-points, in which case nothing is flagged).+ """+ old_only, new_only = old_ek - new_ek, new_ek - old_ek+ rerouted = {(s, t) for (s, t) in new_only if (t, s) in old_only}+ for a, b in old_only:+ if (b, a) in new_only:+ continue # flip, handled above+ if b in removed and a not in removed:+ cands = [(a, c) for (s, c) in new_only if s == a and c in added]+ if len(cands) == 1:+ rerouted.add(cands[0])+ elif a in removed and b not in removed:+ cands = [(c, b) for (s, t) in new_only if t == b and s in added]+ if len(cands) == 1:+ rerouted.add(cands[0])+ return rerouted++def main():ap = argparse.ArgumentParser(description="Diff two .drawio files -> autolayout graph JSON.")ap.add_argument("old", help="baseline .drawio")@@ -111,13 +158,25 @@ def main():"""Map match-key -> label. By id (default) the key is the cell id and thevalue is its label; by label the key *is* the label."""if args.by_label:- return {lbl: lbl for lbl, _ in nodes.values()}, {i: lbl for i, (lbl, _) in nodes.items()}- return {i: lbl for i, (lbl, _) in nodes.items()}, {i: i for i in nodes}+ return {lbl: lbl for lbl, _, _ in nodes.values()}, {i: lbl for i, (lbl, _, _) in nodes.items()}+ return {i: lbl for i, (lbl, _, _) in nodes.items()}, {i: i for i in nodes}old_keys, old_id2key = keyed(old_n)new_keys, new_id2key = keyed(new_n)-- nodes, counts = [], {"added": 0, "removed": 0, "changed": 0, "same": 0}+ old_pos = {old_id2key[i]: p for i, (_, _, p) in old_n.items() if i in old_id2key}+ new_pos = {new_id2key[i]: p for i, (_, _, p) in new_n.items() if i in new_id2key}++ # Selective movement only: when every matched node changed position the two+ # files come from different layout runs, so movement carries no information.+ moved = {key for key in set(old_keys) & set(new_keys)+ if old_keys[key] == new_keys[key]+ and old_pos.get(key) and new_pos.get(key)+ and old_pos[key] != new_pos[key]}+ if moved and len(moved) == len(set(old_keys) & set(new_keys)):+ moved = set()++ nodes, counts = [], {"added": 0, "removed": 0, "changed": 0,+ "moved": 0, "same": 0}for key in sorted(set(old_keys) | set(new_keys)):if key in old_keys and key not in new_keys:status, label = "removed", old_keys[key]@@ -125,6 +184,8 @@ def main():status, label = "added", new_keys[key]elif old_keys[key] != new_keys[key]: # matched, label movedstatus, label = "changed", new_keys[key]+ elif key in moved:+ status, label = "moved", new_keys[key]else:status, label = "same", new_keys[key]counts[status] += 1@@ -139,14 +200,23 @@ def main():return outold_ek, new_ek = edge_keys(old_e, old_id2key), edge_keys(new_e, new_id2key)+ removed = set(old_keys) - set(new_keys)+ added = set(new_keys) - set(old_keys)+ rerouted = classify_rerouted(old_ek, new_ek, removed, added)node_keys = {n["id"] for n in nodes}edges = []for s, t in sorted(old_ek | new_ek):if s not in node_keys or t not in node_keys:continue- status = "same" if (s, t) in old_ek and (s, t) in new_ek else \- ("added" if (s, t) in new_ek else "removed")- edges.append({"source": s, "target": t, "style": EDGE_STYLE[status]})+ if (s, t) in old_ek and (s, t) in new_ek:+ status = "same"+ elif (s, t) in new_ek:+ status = "rerouted" if (s, t) in rerouted else "added"+ else:+ status = "removed" if (t, s) not in new_ek else None # flip: shown once+ if status:+ edges.append({"source": s, "target": t, "style": EDGE_STYLE[status]})+ rerouted_n = sum(1 for e in edges if "d79b00" in e["style"])graph = {"direction": args.direction, "nodes": nodes, "edges": edges}text = json.dumps(graph, indent=2)@@ -157,8 +227,9 @@ def main():else:sys.stdout.write(text)sys.stderr.write(f"+{counts['added']} added, -{counts['removed']} removed, "- f"~{counts['changed']} changed, ={counts['same']} unchanged\n")+ f"~{counts['changed']} changed, >{counts['moved']} moved, "+ f"={counts['same']} unchanged, {rerouted_n} edge(s) rerouted\n")if __name__ == "__main__":- main()+ main()\ No newline at end of filediff --git a/skills/drawio-skill/scripts/validate.py b/skills/drawio-skill/scripts/validate.pyindex be9cf61..ca46a72 100644--- a/skills/drawio-skill/scripts/validate.py+++ b/skills/drawio-skill/scripts/validate.py@@ -8,6 +8,16 @@ routing defects. Runs without launching draw.io, so it is a fast pre-checkbefore the visual review step.python3 validate.py diagram.drawio+ python3 validate.py diagram.drawio --json++Each finding is rendered as:++ error: [E-DANGLING-END] edge '4' target 'nope' does not exist (fix: ...)++The bracketed code is stable, and every finding carries a ``fix`` hint, so an+agent (or a script) can act on the output mechanically; ``--json`` emits the+same findings as structured objects (``code``, ``severity``, ``subject``,+``message``, ``fix``) instead of prose lines.Edge routing checks (warnings): an edge segment crossing a non-incident leafvertex ("routes through vertex"), and two edges crossing each other ("edges X@@ -26,15 +36,22 @@ Exit status is non-zero when any error (or, with --strict, any warning) isfound, so it can gate a workflow. Compressed (non-XML) diagram pages areskipped with a warning — this skill always writes uncompressed XML.-Usage: python3 validate.py <file.drawio> [--strict]+Usage: python3 validate.py <file.drawio> [--strict] [--json]"""import argparse+import jsonimport sysimport xml.etree.ElementTree as ETRESERVED = {"0", "1"}+def diag(code, severity, subject, message, fix):+ """One structured finding: stable code, the cell(s) it is about, prose, fix."""+ return {"code": code, "severity": severity, "subject": subject,+ "message": message, "fix": fix}++def rect(cell):"""Return (x, y, w, h) floats for a cell's geometry, or None if absent/bad.@@ -228,24 +245,37 @@ def geometry_warnings(cells, ids, parents):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}")+ warns.append(diag(+ "W-EDGE-THROUGH-VERTEX", "warning", eid,+ f"edge {eid!r} routes through vertex {vid!r}",+ "add waypoints (<Array as=\"points\">) so the route goes "+ "around the vertex"))# 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")+ warns.append(diag(+ "W-EDGE-CROSS", "warning", f"{ia},{ib}",+ f"edges {ia!r} and {ib!r} cross",+ "add waypoints to one edge or reroute it so the paths "+ "do not cross"))return warnsdef check_page(diagram):- """Return (errors, warnings) for one <diagram> page."""+ """Return (errors, warnings) for one <diagram> page, as structured findings."""name = diagram.get("name", "?")model = diagram.find("mxGraphModel")if model is None:if (diagram.text or "").strip():- return [], [f"page {name!r}: compressed, skipped (cannot lint)"]- return [f"page {name!r}: no <mxGraphModel>"], []+ return [], [diag("W-COMPRESSED", "warning", name,+ f"page {name!r}: compressed, skipped (cannot lint)",+ "save the page as uncompressed XML (this skill "+ "always writes uncompressed)")]+ return [diag("E-PAGE-MODEL", "error", name,+ f"page {name!r}: no <mxGraphModel>",+ "regenerate the file with this skill's writers")], []root = model.find("root")# Normalize UserObject/object wrappers (used for links & metadata): the id# lives on the wrapper, geometry/style on the inner mxCell — fold the two@@ -264,30 +294,51 @@ def check_page(diagram):for c in cells:cid = c.get("id")if cid in ids:- errors.append(f"duplicate id {cid!r}")+ errors.append(diag("E-DUP-ID", "error", cid,+ f"duplicate id {cid!r}",+ "give each cell a unique id"))ids[cid] = cparents = {c.get("parent") for c in cells} # ids that have childrenfor c in cells:cid, parent = c.get("id"), c.get("parent")is_v, is_e = c.get("vertex") == "1", c.get("edge") == "1"if parent is not None and parent not in ids:- errors.append(f"cell {cid!r} parent {parent!r} does not exist")+ errors.append(diag(+ "E-BAD-PARENT", "error", cid,+ f"cell {cid!r} parent {parent!r} does not exist",+ "add the parent container or repoint parent= at an existing cell"))for end in ("source", "target"):ref = c.get(end)if ref and ref not in ids:- errors.append(f"edge {cid!r} {end} {ref!r} does not exist")+ errors.append(diag(+ "E-DANGLING-END", "error", cid,+ f"edge {cid!r} {end} {ref!r} does not exist",+ "add the referenced cell or correct/remove the edge endpoint"))if (is_v or is_e) and cid in RESERVED:- errors.append(f"cell {cid!r} reuses reserved id 0/1")+ errors.append(diag(+ "E-RESERVED-ID", "error", cid,+ f"cell {cid!r} reuses reserved id 0/1",+ "use any other id (draw.io reserves 0/1 for the graph root)"))if is_v and not is_edge_label(c):r = rect(c)if r is None or any(v != v for v in r): # None or NaN- errors.append(f"vertex {cid!r} has missing/invalid geometry")+ errors.append(diag(+ "E-GEOMETRY", "error", cid,+ f"vertex {cid!r} has missing/invalid geometry",+ "add an <mxGeometry> with numeric x, y, width, height"))else:x, y, w, h = rif w <= 0 or h <= 0:- warns.append(f"vertex {cid!r} non-positive size {w:g}x{h:g}")+ warns.append(diag(+ "W-SIZE", "warning", cid,+ f"vertex {cid!r} non-positive size {w:g}x{h:g}",+ "set width/height to positive values"))if x < 0 or y < 0:- warns.append(f"vertex {cid!r} negative position ({x:g},{y:g})")+ warns.append(diag(+ "W-POSITION", "warning", cid,+ f"vertex {cid!r} negative position ({x:g},{y:g})",+ "shift the vertex into the positive quadrant "+ "(the draw.io canvas starts at 0,0)"))# Sibling overlap: only leaf vertices (containers legitimately wrap children).boxes = [(c.get("id"), c.get("parent"), rect(c)) for c in cellsif c.get("vertex") == "1" and c.get("id") not in parents and rect(c)@@ -296,15 +347,25 @@ def check_page(diagram):for j in range(i + 1, len(boxes)):(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.append(diag(+ "W-OVERLAP", "warning", f"{ia},{ib}",+ f"vertices {ia!r} and {ib!r} overlap",+ "move the siblings apart or nest one inside the other"))warns += geometry_warnings(cells, ids, parents)return errors, warns+def render(d, severity):+ """One finding -> the prose line format."""+ return f"{severity}: [{d['code']}] {d['message']} (fix: {d['fix']})"++def main():ap = argparse.ArgumentParser(description="Lint a .drawio file for structural errors.")ap.add_argument("file")ap.add_argument("--strict", action="store_true", help="treat warnings as failure too")+ ap.add_argument("--json", action="store_true",+ help="emit findings as structured JSON instead of prose lines")ap.add_argument("--score", action="store_true",help="also print a readability score (lower is better) — ""useful for comparing layout variants of the same graph")@@ -319,17 +380,22 @@ def main():e, w = check_page(page)errors += ewarns += w- for w in warns:- print(f"warning: {w}")- for e in errors:- print(f"error: {e}")- print(f"{len(errors)} error(s), {len(warns)} warning(s)")+ if args.json:+ print(json.dumps({"errors": len(errors), "warnings": len(warns),+ "findings": errors + warns}, indent=2))+ else:+ for w in warns:+ print(render(w, "warning"))+ for e in errors:+ print(render(e, "error"))+ print(f"{len(errors)} error(s), {len(warns)} warning(s)")if args.score:+ lines = [d["message"] for d in errors + warns]# Weighted by how badly each defect hurts readability. Comparable only# across variants of the SAME graph (same nodes/edges).- through = sum(1 for w in warns if "routes through" in w)- cross = sum(1 for w in warns if " cross" in w)- olap = sum(1 for w in warns if " overlap" in w)+ through = sum(1 for m in lines if "routes through" in m)+ cross = sum(1 for m in lines if " cross" in m)+ olap = sum(1 for m in lines if " overlap" in m)print(f"score: {20 * through + 10 * cross + 5 * olap} "f"({through} through-vertex, {cross} crossings, {olap} overlaps)")if errors or (args.strict and warns):@@ -337,4 +403,4 @@ def main():if __name__ == "__main__":- main()+ main()\ No newline at end of filediff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex c97c973..cdb5d7a 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -297,6 +297,30 @@ class TestValidateCli(unittest.TestCase):self.assertEqual(r.returncode, 1)self.assertIn("error", r.stdout)+ def test_findings_carry_code_and_fix(self):+ # Structured-diagnostic format: stable [CODE] + a (fix: ...) hint an+ # agent can act on mechanically.+ r = self._check(self.BAD)+ self.assertIn("error: [E-DANGLING-END]", r.stdout)+ self.assertIn("(fix:", r.stdout)++ def test_json_output(self):+ import json as _json+ with tempfile.NamedTemporaryFile("w", suffix=".drawio", delete=False) as f:+ f.write(self.BAD)+ path = f.name+ try:+ r = run("validate.py", path, "--json")+ finally:+ os.unlink(path)+ self.assertEqual(r.returncode, 1)+ out = _json.loads(r.stdout)+ self.assertEqual(out["errors"], 1)+ finding = out["findings"][0]+ self.assertEqual(finding["code"], "E-DANGLING-END")+ self.assertEqual(finding["severity"], "error")+ self.assertIn("fix", finding)+# A vertex wrapped in UserObject (link) — the edge references the wrapper id.LINKED = ('<mxfile><diagram name="P1"><mxGraphModel><root>''<mxCell id="0"/><mxCell id="1" parent="0"/>'@@ -669,13 +693,16 @@ class TestImportersCli(unittest.TestCase):@staticmethoddef _status(style):for tag, hue in (("added", "82b366"), ("removed", "b85450"),- ("changed", "d79b00"), ("same", "999999")):+ ("changed", "d79b00"), ("moved", "9673a6"),+ ("same", "999999")):if hue in style:return tagreturn "?"def test_drawiodiff_by_id(self):# api label moves (changed), cache removed, worker added, db unchanged.+ # The (api, worker) edge re-points (api, cache) — source kept, old target+ # removed, new target added — so it is orange "rerouted", not green.old = self._drawio([("api", "api v1"), ("db", "db"), ("cache", "cache")],[("api", "db"), ("api", "cache")])new = self._drawio([("api", "api v2"), ("db", "db"), ("worker", "worker")],@@ -688,11 +715,66 @@ class TestImportersCli(unittest.TestCase):status = {n["id"]: self._status(n["style"]) for n in graph["nodes"]}self.assertEqual(status, {"api": "changed", "db": "same","cache": "removed", "worker": "added"})- estatus = {(e["source"], e["target"]): self._status(e["style"])+ estatus = {(e["source"], e["target"]): e["style"]for e in graph["edges"]}- self.assertEqual(estatus, {("api", "db"): "same",- ("api", "cache"): "removed",- ("api", "worker"): "added"})+ self.assertIn("999999", estatus[("api", "db")]) # same+ self.assertIn("b85450", estatus[("api", "cache")]) # removed+ self.assertIn("d79b00", estatus[("api", "worker")]) # rerouted++ @staticmethod+ def _drawio_pos(nodes, edges):+ """.drawio XML from (id, label, x, y) nodes and (src, tgt) edges."""+ cells = ['<mxCell id="0"/>', '<mxCell id="1" parent="0"/>']+ for cid, label, x, y in nodes:+ cells.append(f'<mxCell id="{cid}" value="{label}" vertex="1" parent="1" '+ f'style="rounded=1;"><mxGeometry x="{x}" y="{y}" '+ 'width="120" height="60" as="geometry"/></mxCell>')+ for i, (s, t) in enumerate(edges):+ cells.append(f'<mxCell id="e{i}" edge="1" parent="1" source="{s}" '+ 'target="{}"><mxGeometry relative="1" as="geometry"/></mxCell>'.format(t))+ return ('<mxfile><diagram name="P"><mxGraphModel><root>'+ + "".join(cells) + "</root></mxGraphModel></diagram></mxfile>")++ def test_drawiodiff_moved(self):+ # Same label, same id, new coordinates -> violet "moved" (selectively).+ old = self._drawio_pos([("a", "a", 0, 0), ("b", "b", 200, 0)], [])+ new = self._drawio_pos([("a", "a", 0, 0), ("b", "b", 200, 300)], [])+ with tempfile.TemporaryDirectory() as d:+ self._write(os.path.join(d, "old.drawio"), old)+ self._write(os.path.join(d, "new.drawio"), new)+ graph = json.loads(run("drawiodiff.py", os.path.join(d, "old.drawio"),+ os.path.join(d, "new.drawio")).stdout)+ status = {n["id"]: self._status(n["style"]) for n in graph["nodes"]}+ self.assertEqual(status, {"a": "same", "b": "moved"})++ def test_drawiodiff_relayout_is_not_movement(self):+ # Every matched node changed position -> the files come from different+ # layout runs; movement is layout noise, so all nodes stay "same".+ old = self._drawio_pos([("a", "a", 0, 0), ("b", "b", 200, 0), ("c", "c", 400, 0)], [])+ new = self._drawio_pos([("a", "a", 100, 100), ("b", "b", 300, 100),+ ("c", "c", 500, 100)], [])+ with tempfile.TemporaryDirectory() as d:+ self._write(os.path.join(d, "old.drawio"), old)+ self._write(os.path.join(d, "new.drawio"), new)+ graph = json.loads(run("drawiodiff.py", os.path.join(d, "old.drawio"),+ os.path.join(d, "new.drawio")).stdout)+ status = {n["id"]: self._status(n["style"]) for n in graph["nodes"]}+ self.assertEqual(status, {"a": "same", "b": "same", "c": "same"})++ def test_drawiodiff_flip_is_rerouted(self):+ # (a,b) in old, (b,a) in new: the pair is shown once, orange, and the+ # reversed old edge is not double-counted as removed.+ old = self._drawio_pos([("a", "a", 0, 0), ("b", "b", 200, 0)], [("a", "b")])+ new = self._drawio_pos([("a", "a", 0, 0), ("b", "b", 200, 0)], [("b", "a")])+ with tempfile.TemporaryDirectory() as d:+ self._write(os.path.join(d, "old.drawio"), old)+ self._write(os.path.join(d, "new.drawio"), new)+ graph = json.loads(run("drawiodiff.py", os.path.join(d, "old.drawio"),+ os.path.join(d, "new.drawio")).stdout)+ self.assertEqual(len(graph["edges"]), 1)+ self.assertEqual((graph["edges"][0]["source"], graph["edges"][0]["target"]),+ ("b", "a"))+ self.assertIn("d79b00", graph["edges"][0]["style"]) # rerouteddef test_drawiodiff_by_label(self):# ids differ across versions; --by-label matches on the visible text.