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: semantic fidelity (v3.1 roadmap P0)
Agents365-ai040491302aee
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2293fa2..4d57905 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,33 @@ on [Keep a Changelog](https://keepachangelog.com/), and the project followssemantic-ish versioning (the `metadata.version` field in`skills/drawio-skill/SKILL.md`).+## [3.2.0] — 2026-09-01++### Added++- **Semantic fidelity (v3.1 roadmap P0)** for code-backed diagrams:+ - **Source-kind profiles**: `diagramctl.py build --from python|js|go|rust|pyclasses`+ now labels source modules `module` / `library` / `command` from the file+ name (package roots `__init__.py`/`lib.rs` = library, entrypoints+ `__main__.py`/`main.rs`/`cli.py` = command) instead of a blanket+ `service`. Source importers also record per-file `provenance` (resolved to+ the real path), and Python edges carry the import statement line number.+ - **Architecture contracts stop misfiring on source modules**: ownership+ (`every-service-has-owner`) and observability+ (`production-has-observability`) rules no longer fire on ordinary+ `module`/`library`/`command` kinds.+ - **Profile reporting**: `diagramctl test` now reports a `profile` field+ (`code` vs `architecture`), so a CI gate can see what it is enforcing.+ - **View fallback reporting**: `views`/`build --views` emit per-view+ `fallback` / `fallback_reason` / `hint` when a projection had no metadata+ and fell back to the whole model, instead of failing silently.++### Changed++- Tests: 171 → 174 (source-profile build, view-fallback metadata gap, profile+ inference). Dogfood re-run against the repository's own toolbox now produces+ `module` kinds and zero ownership/observability noise.+## [3.1.0] — 2026-09-01### Addeddiff --git a/docs/ROADMAP_V3_1.md b/docs/ROADMAP_V3_1.mdindex 860107e..1707756 100644--- a/docs/ROADMAP_V3_1.md+++ b/docs/ROADMAP_V3_1.md@@ -3,16 +3,16 @@This backlog is based on the 3.0 release gate, checked showcase, and dogfood runagainst this repository. It is intentionally ordered by observed usefulness.-## P0 — semantic fidelity--- Add source profiles so code modules use kinds such as `module`, `library`,- `adapter`, and `command` instead of defaulting to `service`.-- Scope architecture contracts by kind/profile; ownership and production- observability rules should not fire on ordinary source modules.-- Emit exact file-and-line provenance from language importers rather than only- the scanned root path.-- Report when a projected view falls back to the entire model, including which- metadata would make that view distinctive.+## P0 — semantic fidelity ✅ shipped in 3.2.0++- ~~Add source profiles so code modules use kinds such as `module`, `library`,+ `adapter`, and `command` instead of defaulting to `service`.~~ ✅ (`module`/`library`/`command`)+- ~~Scope architecture contracts by kind/profile; ownership and production+ observability rules should not fire on ordinary source modules.~~ ✅ (kinds + `profile` field)+- ~~Emit exact file-and-line provenance from language importers rather than only+ the scanned root path.~~ ✅ (per-file path + Python edge line numbers)+- ~~Report when a projected view falls back to the entire model, including which+ metadata would make that view distinctive.~~ ✅ (`fallback`/`fallback_reason`/`hint`)## P1 — richer analysisdiff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex a9becdb..4de11be 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -3,7 +3,7 @@ name: drawio-skilldescription: Create, edit, synchronize, inspect, test, and publish editable draw.io diagrams. Use when the user explicitly requests draw.io/diagrams.net, needs a polished architecture, ERD, UML, sequence, C4, SysML, BPMN, network, swimlane, ML, or infrastructure diagram, wants code/IaC/SQL/OpenAPI converted into a diagram, or wants an existing diagram queried, reviewed, diffed, restyled, kept in sync, or made interactive. Prefer Mermaid/PlantUML elsewhere when the requested artifact is diagrams-as-code rather than an editable draw.io file.license: MITallowed-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.1.0","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"]}+metadata: {"openclaw":{"requires":{"anyBins":["python3"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io for native exports","os":["darwin"],"optional":true},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for automatic layout","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","architecture","visualization","uml"],"category":"design","requires_tools":["python3"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"3.2.0","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 Studiodiff --git a/skills/drawio-skill/references/diagram-ir.md b/skills/drawio-skill/references/diagram-ir.mdindex ee23828..b9e0ba2 100644--- a/skills/drawio-skill/references/diagram-ir.md+++ b/skills/drawio-skill/references/diagram-ir.md@@ -95,7 +95,29 @@ Views are pages over the same model rather than copied models. Nodes carry thesame `data-model-id`; nodes present in several pages link to the next applicableview. The executive view selects at most twelve high-importance/high-degreenodes. Deployment/data/security views use semantic properties and fall back to-the complete model when metadata is insufficient.+the complete model when metadata is insufficient. Each view reports a+`fallback` flag with a `fallback_reason` and a `hint` naming the metadata that+would make it distinctive, so a fallback is never silent:++```bash+python3 scripts/diagramctl.py views model.ir.json -o views.drawio+# views[].fallback / fallback_reason / hint+```++## v3.2 semantic fidelity++- **Source-kind profiles**: building from a code importer (`--from python`,+ `js`, `go`, `rust`, `pyclasses`) assigns real `module` / `library` /+ `command` kinds from the file name instead of a blanket `service` — package+ roots (`__init__.py`, `lib.rs`) are `library`, entrypoints+ (`__main__.py`, `main.rs`, `cli.py`) are `command`, everything else is+ `module`. Ownership / observability contract rules therefore do not fire on+ ordinary source modules.+- **Precise provenance**: importer node provenance records the exact file+ path (resolved against the scanned root), and Python edges carry the line+ of the import statement that pulled them in.+- **Profile reporting**: `diagramctl test` reports a `profile` field —+ `code` for module/library/command graphs, `architecture` otherwise.## Compatibilitydiff --git a/skills/drawio-skill/scripts/diagram_ir.py b/skills/drawio-skill/scripts/diagram_ir.pyindex d18f9c9..f7e5a29 100644--- a/skills/drawio-skill/scripts/diagram_ir.py+++ b/skills/drawio-skill/scripts/diagram_ir.py@@ -19,11 +19,10 @@ import mathimport osimport reimport urllib.parse+import xml.etree.ElementTree as ETimport zlibfrom collections import defaultdict, dequefrom datetime import datetime, timezone-import xml.etree.ElementTree as ET-SCHEMA = "drawio-skill/diagram-ir/v1"DEFAULT_NODE_STYLE = (@@ -215,11 +214,14 @@ def normalize_ir(raw, source_path=None):def load_ir(path):if str(path).lower().endswith((".drawio", ".xml")):return drawio_to_ir(path)+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(path, encoding="utf-8") as fh:+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonreturn normalize_ir(json.load(fh), source_path=path)def save_ir(ir, path):+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(path, "w", encoding="utf-8") as fh:json.dump(normalize_ir(ir), fh, indent=2, ensure_ascii=False)fh.write("\n")@@ -319,9 +321,10 @@ def drawio_to_ir(path):node["properties"][key] = valueif geom is not None:for key in ("x", "y", "width", "height"):- if geom.get(key) is not None:+ value = geom.get(key)+ if value is not None:try:- node[key] = float(geom.get(key))+ node[key] = float(value)except ValueError:passprov = _json_attr(holder, "data-provenance") or _json_attr(@@ -407,12 +410,14 @@ def ir_to_graph(ir, node_ids=None, prefix="", links=None):def _load_autolayout():path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "autolayout.py")spec = importlib.util.spec_from_file_location("drawio_skill_autolayout", path)+ assert spec is not None and spec.loader is not Nonemod = importlib.util.module_from_spec(spec)spec.loader.exec_module(mod)return moddef _grid_page(graph, page_id, name):+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythoncols = max(1, int(math.ceil(math.sqrt(max(1, len(graph["nodes"]))))))cells = []for i, node in enumerate(graph["nodes"]):@@ -523,11 +528,19 @@ def write_drawio(ir, path, views=None, direction="TB"):root.append(ET.fromstring(page_xml))ET.indent(root, space=" ")ET.ElementTree(root).write(path, encoding="unicode", xml_declaration=False)+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(path, "a", encoding="utf-8") as fh:fh.write("\n")def project_views(ir, names=None):+ """Project a model into audience/concern views.++ Each returned view carries an optional `fallback` flag: when a projection+ had no metadata to work with and therefore fell back to the complete node+ set, `fallback` is True, `fallback_reason` says which metadata was+ missing, and `hint` says what would make that view distinctive.+ """ir = normalize_ir(ir)nodes = {n["id"]: n for n in ir["nodes"]}degree = defaultdict(int)@@ -535,6 +548,16 @@ def project_views(ir, names=None):degree[e["source"]] += 1degree[e["target"]] += 1wanted = names or ["executive", "system", "deployment", "dataflow", "security"]++ def view(name, selected, fallback=False, reason=None, hint=None):+ d = {"id": slug(name), "name": name.title(), "nodes": list(selected)}+ if fallback:+ d["fallback"] = True+ d["fallback_reason"] = reason+ d["hint"] = hint+ return d++ all_ids = list(nodes)out = []for name in wanted:key = name.lower()@@ -542,12 +565,27 @@ def project_views(ir, names=None):ranked = sorted(nodes,key=lambda nid: (+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python-int(nodes[nid].get("properties", {}).get("importance", 0)),-degree[nid],nid,),)selected = ranked[:12]+ has_importance = any(+ "importance" in nodes[nid].get("properties", {}) for nid in nodes+ )+ out.append(+ view(+ name,+ selected,+ fallback=not has_importance,+ reason="no properties.importance metadata; ranked by connection degree only",+ hint="set properties.importance on the components that matter to executives",+ )+ if not has_importance+ else view(name, selected)+ )elif key == "deployment":selected = [nid@@ -557,7 +595,15 @@ def project_views(ir, names=None):for k in ("environment", "region", "runtime", "host", "deployment"))]- selected = selected or list(nodes)+ out.append(+ view(+ name,+ selected or all_ids,+ fallback=not selected,+ reason="no deployment metadata (properties.environment/region/runtime/host) on any node",+ hint="set properties.environment/runtime on deployed components",+ )+ )elif key == "dataflow":data_edges = [e@@ -570,7 +616,16 @@ def project_views(ir, names=None):]selected = sorted({x for e in data_edges for x in (e["source"], e["target"])}- ) or list(nodes)+ )+ out.append(+ view(+ name,+ selected or all_ids,+ fallback=not selected,+ reason="no data-flow edges (kind data/read/write/async or data-event labels)",+ hint="set edge kind=data/async or label edges with data verbs (publish, consume, read)",+ )+ )elif key == "security":selected = [nid@@ -584,10 +639,18 @@ def project_views(ir, names=None):"properties", {}).get("trust_boundary"):selected.extend([e["source"], e["target"]])- selected = list(dict.fromkeys(selected)) or list(nodes)+ selected = list(dict.fromkeys(selected))+ out.append(+ view(+ name,+ selected or all_ids,+ fallback=not selected,+ reason="no trust boundaries (properties.trust_boundary) and no external/database/actor/gateway nodes",+ hint="set properties.trust_boundary on components or mark external systems with kind=external",+ )+ )else:- selected = list(nodes)- out.append({"id": slug(name), "name": name.title(), "nodes": selected})+ out.append(view(name, all_ids))return out@@ -679,6 +742,30 @@ DEFAULT_RULES = ["accessible-contrast",]+ARCHITECTURE_KINDS = {+ "service",+ "gateway",+ "database",+ "queue",+ "external",+ "actor",+ "cache",+ "topic",+}+CODE_KINDS = {"module", "library", "command", "adapter"}+++def infer_profile(ir):+ """Return 'code' when the model is a source-code graph (module/library/+ command kinds and no architecture kinds), else 'architecture'."""+ ir = normalize_ir(ir)+ kinds = {n.get("kind") for n in ir["nodes"]}+ if kinds & ARCHITECTURE_KINDS:+ return "architecture"+ if kinds & CODE_KINDS:+ return "code"+ return "architecture"+def semantic_findings(ir, rule_ids=None):ir = normalize_ir(ir)@@ -1277,6 +1364,7 @@ def reconcile(existing_path, incoming_ir, output_path, prune=False):tree.getroot().set("modified", utc_now())ET.indent(tree.getroot(), space=" ")tree.write(output_path, encoding="unicode", xml_declaration=False)+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(output_path, "a", encoding="utf-8") as fh:fh.write("\n")return {@@ -1303,6 +1391,7 @@ def story_html(ir, title=None, scenario=None):title = title or ir["metadata"].get("title") or "Architecture Story"nodes = ir["nodes"]edges = ir["edges"]+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythoncols = max(1, int(math.ceil(math.sqrt(max(1, len(nodes))))))positions = {n["id"]: (100 + (i % cols) * 240, 90 + (i // cols) * 150)diff --git a/skills/drawio-skill/scripts/diagramctl.py b/skills/drawio-skill/scripts/diagramctl.pyindex f07e552..b2d3114 100644--- a/skills/drawio-skill/scripts/diagramctl.py+++ b/skills/drawio-skill/scripts/diagramctl.py@@ -22,10 +22,10 @@ from diagram_ir import (DEFAULT_RULES,accessible_description,impact_analysis,+ infer_profile,load_ir,normalize_ir,project_views,- query as query_ir,reconcile,review,save_ir,@@ -33,7 +33,9 @@ from diagram_ir import (story_html,write_drawio,)-+from diagram_ir import (+ query as query_ir,+)HERE = Path(__file__).resolve().parentIMPORTERS = {@@ -51,6 +53,7 @@ IMPORTERS = {"openapi": "openapiimports.py","ci": "ciimports.py",}+CODE_IMPORTERS = {"python", "javascript", "js", "go", "rust", "pyclasses"}TRANSFORMS = {"restyle": "restyle.py","heatmap": "heatmap.py",@@ -115,6 +118,36 @@ def detect_source(path):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:@@ -135,13 +168,19 @@ def importer_ir(source, source_type, group=False):raise RuntimeError(proc.stderr.strip() or proc.stdout.strip() or f"{script.name} failed")+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonraw = 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_IMPORTERSfor node in ir["nodes"]:- node.setdefault("provenance", {}).update(- {"importer": source_type, "path": os.path.abspath(source)}- )+ 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@@ -224,7 +263,17 @@ def cmd_build(args):"source_type": source_type,"nodes": len(ir["nodes"]),"edges": len(ir["edges"]),- "views": [v["name"] for v in views] if views else ["System"],+ "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"],})@@ -276,11 +325,15 @@ def load_rules(path):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-exceptexcept ValueError:try:import yamldata = yaml.safe_load(text)+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python+ # pi-lens-ignore: ast-grep:no-boolean-in-exceptexcept ImportError:rules, in_rules = [], Falsefor line in text.splitlines():@@ -298,8 +351,10 @@ def load_rules(path):def cmd_test(args):- findings = semantic_findings(load_ir(args.input), load_rules(args.rules))+ 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,@@ -358,7 +413,16 @@ def cmd_views(args):emit({"output": args.output,- "views": [{"name": v["name"], "nodes": len(v["nodes"])} for v in views],+ "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+ ],})diff --git a/skills/drawio-skill/scripts/goimports.py b/skills/drawio-skill/scripts/goimports.pyindex ae135c2..bc587d3 100644--- a/skills/drawio-skill/scripts/goimports.py+++ b/skills/drawio-skill/scripts/goimports.py@@ -17,6 +17,7 @@ are skipped.Usage: python3 goimports.py <module_dir> [-o graph.json] [--direction TB|LR][--group] [--no-reduce]"""+import argparseimport jsonimport os@@ -35,6 +36,7 @@ def module_path(root):gomod = os.path.join(root, "go.mod")if not os.path.exists(gomod):return None+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(gomod, encoding="utf-8", errors="ignore") as f:m = MODULE.search(f.read())return m.group(1) if m else None@@ -45,10 +47,14 @@ def discover(root, modpath):root = os.path.abspath(root)pkgs = {}for dirpath, dirs, files in os.walk(root):- dirs[:] = [d for d in dirs- if d not in ("vendor", "testdata") and not d.startswith(".")]- gofiles = [os.path.join(dirpath, f) for f in files- if f.endswith(".go") and not f.endswith("_test.go")]+ dirs[:] = [+ d for d in dirs if d not in ("vendor", "testdata") and not d.startswith(".")+ ]+ gofiles = [+ os.path.join(dirpath, f)+ for f in files+ if f.endswith(".go") and not f.endswith("_test.go")+ ]if not gofiles:continuerel = os.path.relpath(dirpath, root).replace(os.sep, "/")@@ -81,24 +87,36 @@ def transitive_reduce(nodes, edges):idx = {n: i for i, n in enumerate(nodes)}dot = "digraph{" + "".join(f"{idx[s]}->{idx[t]};" for s, t in edges) + "}"try:- out = subprocess.run(["tred"], input=dot, capture_output=True,- text=True, check=True).stdout+ out = subprocess.run(+ ["tred"], input=dot, capture_output=True, text=True, check=True+ ).stdoutexcept (FileNotFoundError, subprocess.CalledProcessError) as exc:sys.stderr.write(f"warning: tred unavailable, keeping all edges ({exc})\n")return edgesrev = {i: n for n, i in idx.items()}- return [(rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)]+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python+ return [+ (rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)+ ]def main():- ap = argparse.ArgumentParser(description="Go import graph -> autolayout graph JSON.")+ ap = argparse.ArgumentParser(+ description="Go import graph -> autolayout graph JSON."+ )ap.add_argument("module", help="module directory (contains go.mod)")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 nodes into containers by top-level package dir")- ap.add_argument("--no-reduce", action="store_true",- help="keep every edge (skip transitive reduction)")+ ap.add_argument(+ "--group",+ action="store_true",+ help="group nodes into containers by top-level package dir",+ )+ ap.add_argument(+ "--no-reduce",+ action="store_true",+ help="keep every edge (skip transitive reduction)",+ )args = ap.parse_args()modpath = module_path(args.module)@@ -107,21 +125,37 @@ def main():pkgs = discover(args.module, modpath)if not pkgs:sys.exit(f"error: no Go packages found under {args.module}")- edges = sorted({(ip, t) for ip, files in pkgs.items()- for t in imports_of(files, modpath, pkgs) if t != ip})+ edges = sorted(+ {+ (ip, t)+ for ip, files in pkgs.items()+ for t in imports_of(files, modpath, pkgs)+ if t != ip+ }+ )raw = len(edges)if not args.no_reduce:edges = transitive_reduce(list(pkgs), edges)# Drop the module prefix from labels for readability; ids stay full.strip = modpath + "/"- label = lambda ip: ip[len(strip):] if ip.startswith(strip) else os.path.basename(ip)+ label = (+ lambda ip: ip[len(strip) :] if ip.startswith(strip) else os.path.basename(ip)+ )def node(ip):- d = {"id": ip, "label": label(ip)}+ d = {+ "id": ip,+ "label": label(ip),+ "provenance": {+ "path": os.path.relpath(os.path.dirname(pkgs[ip][0]), args.module)+ },+ }if args.group:rest = label(ip).split("/")- if len(rest) > 1: # nested under a sub-package- d["group"] = "/".join(rest[:-1]) # full sub-package path -> nested boxes+ if len(rest) > 1: # nested under a sub-package+ d["group"] = "/".join(+ rest[:-1]+ ) # full sub-package path -> nested boxesreturn dgraph = {@@ -131,6 +165,7 @@ def main():}text = json.dumps(graph, indent=2)if args.output:+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(args.output, "w", encoding="utf-8") as f:f.write(text)sys.stderr.write(f"wrote {args.output}\n")diff --git a/skills/drawio-skill/scripts/jsimports.py b/skills/drawio-skill/scripts/jsimports.pyindex 6908ea8..3d1e557 100644--- a/skills/drawio-skill/scripts/jsimports.py+++ b/skills/drawio-skill/scripts/jsimports.py@@ -19,6 +19,7 @@ specifier inside a comment or string literal is counted in rare cases.Usage: python3 jsimports.py <src_dir> [-o graph.json] [--direction TB|LR][--group] [--no-reduce]"""+import argparseimport jsonimport os@@ -29,9 +30,9 @@ import sysEXTS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs")SPEC = re.compile(r"(?:import|export)\b[^'\";]*?\bfrom\s*['\"]([^'\"]+)['\"]" # import/export ... from "x"- r"|import\s*['\"]([^'\"]+)['\"]" # import "x" (side effect)- r"|require\s*\(\s*['\"]([^'\"]+)['\"]\s*\)" # require("x")- r"|import\s*\(\s*['\"]([^'\"]+)['\"]\s*\)" # import("x") dynamic+ r"|import\s*['\"]([^'\"]+)['\"]" # import "x" (side effect)+ r"|require\s*\(\s*['\"]([^'\"]+)['\"]\s*\)" # require("x")+ r"|import\s*\(\s*['\"]([^'\"]+)['\"]\s*\)" # import("x") dynamic)@@ -63,9 +64,11 @@ def resolve(spec, importer, root, modules):if not spec.startswith("."):return Nonebase = os.path.normpath(os.path.join(os.path.dirname(importer), spec))- candidates = ([base + e for e in EXTS]- + [os.path.join(base, "index" + e) for e in EXTS]- + [base])+ candidates = (+ [base + e for e in EXTS]+ + [os.path.join(base, "index" + e) for e in EXTS]+ + [base]+ )for cand in candidates:mid = modid(cand, root)if mid in modules and modules[mid] != importer:@@ -94,13 +97,17 @@ def transitive_reduce(nodes, edges):idx = {n: i for i, n in enumerate(nodes)}dot = "digraph{" + "".join(f"{idx[s]}->{idx[t]};" for s, t in edges) + "}"try:- out = subprocess.run(["tred"], input=dot, capture_output=True,- text=True, check=True).stdout+ out = subprocess.run(+ ["tred"], input=dot, capture_output=True, text=True, check=True+ ).stdoutexcept (FileNotFoundError, subprocess.CalledProcessError) as exc:sys.stderr.write(f"warning: tred unavailable, keeping all edges ({exc})\n")return edgesrev = {i: n for n, i in idx.items()}- return [(rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)]+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python+ return [+ (rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)+ ]def common_dir(ids):@@ -115,33 +122,46 @@ def common_dir(ids):def main():- ap = argparse.ArgumentParser(description="JS/TS import graph -> autolayout graph JSON.")+ ap = argparse.ArgumentParser(+ description="JS/TS import graph -> autolayout graph JSON."+ )ap.add_argument("src", help="source directory")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 nodes into containers by top-level directory")- ap.add_argument("--no-reduce", action="store_true",- help="keep every edge (skip transitive reduction)")+ ap.add_argument(+ "--group",+ action="store_true",+ help="group nodes into containers by top-level directory",+ )+ ap.add_argument(+ "--no-reduce",+ action="store_true",+ help="keep every edge (skip transitive reduction)",+ )args = ap.parse_args()modules, root = discover(args.src)if not modules:sys.exit(f"error: no JS/TS modules found under {args.src}")- edges = sorted({(m, t) for m, p in modules.items()- for t in edges_of(m, p, root, modules)})+ edges = sorted(+ {(m, t) for m, p in modules.items() for t in edges_of(m, p, root, modules)}+ )raw = len(edges)if not args.no_reduce:edges = transitive_reduce(list(modules), edges)strip = common_dir(list(modules))- label = lambda m: (m[len(strip):] if strip and m.startswith(strip) else m) or m+ label = lambda m: (m[len(strip) :] if strip and m.startswith(strip) else m) or mdef node(m):- d = {"id": m, "label": label(m)}+ d = {+ "id": m,+ "label": label(m),+ "provenance": {"path": os.path.relpath(modules[m], root)},+ }if args.group:rest = label(m).split("/")- if len(rest) > 1: # has a sub-directory- d["group"] = "/".join(rest[:-1]) # full directory path -> nested boxes+ if len(rest) > 1: # has a sub-directory+ d["group"] = "/".join(rest[:-1]) # full directory path -> nested boxesreturn dgraph = {@@ -151,6 +171,7 @@ def main():}text = json.dumps(graph, indent=2)if args.output:+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(args.output, "w", encoding="utf-8") as f:f.write(text)sys.stderr.write(f"wrote {args.output}\n")diff --git a/skills/drawio-skill/scripts/pyimports.py b/skills/drawio-skill/scripts/pyimports.pyindex 6a498bb..2019e0b 100644--- a/skills/drawio-skill/scripts/pyimports.py+++ b/skills/drawio-skill/scripts/pyimports.py@@ -15,6 +15,7 @@ are kept — third-party and stdlib imports are ignored.Usage: python3 pyimports.py <project_dir> [-o graph.json] [--direction TB|LR] [--no-reduce]"""+import argparseimport astimport json@@ -29,7 +30,11 @@ def discover(root):package prefix. If root is itself a package (has __init__.py), module namesare qualified with its name so the project's own absolute imports resolve."""root = os.path.abspath(root)- base = os.path.basename(root) if os.path.exists(os.path.join(root, "__init__.py")) else ""+ base = (+ os.path.basename(root)+ if os.path.exists(os.path.join(root, "__init__.py"))+ else ""+ )modules = {}for dirpath, _, files in os.walk(root):for fn in files:@@ -38,7 +43,7 @@ def discover(root):rel = os.path.relpath(os.path.join(dirpath, fn), root)[:-3] # strip .pyparts = rel.split(os.sep)if parts[-1] == "__init__":- parts = parts[:-1] # package = its dir+ parts = parts[:-1] # package = its dirparts = ([base] + parts) if base else partsif parts:modules[".".join(parts)] = os.path.join(dirpath, fn)@@ -57,36 +62,47 @@ def resolve(name, current, modules):def edges_of(name, path, modules):- """Intra-project modules imported by `name`."""- pkg = name if path.endswith("__init__.py") else name.rsplit(".", 1)[0] if "." in name else ""- found = set()+ """Map each intra-project module imported by `name` to the first line of+ the import statement that pulls it in."""+ pkg = (+ name+ if path.endswith("__init__.py")+ else name.rsplit(".", 1)[0]+ if "." in name+ else ""+ )+ found = {}try:with open(path, encoding="utf-8") as f:tree = ast.parse(f.read(), filename=path)except SyntaxError:return foundfor node in ast.walk(tree):- if isinstance(node, ast.Import): # import a.b.c+ if isinstance(node, ast.Import): # import a.b.cfor alias in node.names:target = resolve(alias.name, name, modules)if target:- found.add(target)- elif isinstance(node, ast.ImportFrom): # from a.b import c- if node.level: # relative: climb level-1 packages+ found.setdefault(target, node.lineno)+ elif isinstance(node, ast.ImportFrom): # from a.b import c+ if node.level: # relative: climb level-1 packagesbase = pkg.split(".") if pkg else []base = base[: len(base) - (node.level - 1)]prefix = ".".join(base)- mod = f"{prefix}.{node.module}" if prefix and node.module else (node.module or prefix)+ mod = (+ f"{prefix}.{node.module}"+ if prefix and node.module+ else (node.module or prefix)+ )else:mod = node.module or ""target = resolve(mod, name, modules)if target:- found.add(target)- for alias in node.names: # `from pkg import submodule`+ found.setdefault(target, node.lineno)+ for alias in node.names: # `from pkg import submodule`sub = f"{mod}.{alias.name}" if mod else alias.nametarget = resolve(sub, name, modules)if target:- found.add(target)+ found.setdefault(target, node.lineno)return found@@ -95,53 +111,79 @@ def transitive_reduce(nodes, edges):idx = {n: i for i, n in enumerate(nodes)}dot = "digraph{" + "".join(f"{idx[s]}->{idx[t]};" for s, t in edges) + "}"try:- out = subprocess.run(["tred"], input=dot, capture_output=True,- text=True, check=True).stdout+ out = subprocess.run(+ ["tred"], input=dot, capture_output=True, text=True, check=True+ ).stdoutexcept (FileNotFoundError, subprocess.CalledProcessError) as exc:sys.stderr.write(f"warning: tred unavailable, keeping all edges ({exc})\n")return edgesrev = {i: n for n, i in idx.items()}- return [(rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)]+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python+ return [+ (rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)+ ]def main():- ap = argparse.ArgumentParser(description="Python import graph -> autolayout graph JSON.")+ ap = argparse.ArgumentParser(+ description="Python import graph -> autolayout graph JSON."+ )ap.add_argument("project", help="package or project directory")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 nodes into containers by sub-package")- ap.add_argument("--no-reduce", action="store_true",- help="keep every edge (skip transitive reduction)")+ ap.add_argument(+ "--group",+ action="store_true",+ help="group nodes into containers by sub-package",+ )+ ap.add_argument(+ "--no-reduce",+ action="store_true",+ help="keep every edge (skip transitive reduction)",+ )args = ap.parse_args()modules, base = discover(args.project)if not modules:sys.exit(f"error: no .py modules found under {args.project}")- edges = sorted({(name, t) for name, path in modules.items()- for t in edges_of(name, path, modules)})+ edge_prov = {+ (name, t): {"path": os.path.relpath(path, args.project), "line": line}+ for name, path in modules.items()+ for t, line in edges_of(name, path, modules).items()+ }+ edges = sorted(edge_prov)raw = len(edges)if not args.no_reduce:edges = transitive_reduce(list(modules), edges)# Drop the shared package prefix from labels for readability; ids stay full.strip = base + "." if base else ""- label = lambda m: m[len(strip):] if strip and m.startswith(strip) else m+ label = lambda m: m[len(strip) :] if strip and m.startswith(strip) else mdef node(m):- d = {"id": m, "label": label(m)}+ d = {+ "id": m,+ "label": label(m),+ "provenance": {"path": os.path.relpath(modules[m], args.project)},+ }if args.group:rest = label(m).split(".")- if len(rest) > 1: # nested under a sub-package- d["group"] = "/".join(rest[:-1]) # full sub-package path -> nested boxes+ if len(rest) > 1: # nested under a sub-package+ d["group"] = "/".join(+ rest[:-1]+ ) # full sub-package path -> nested boxesreturn dgraph = {"direction": args.direction,"nodes": [node(m) for m in modules],- "edges": [{"source": s, "target": t} for s, t in edges],+ "edges": [+ {"source": s, "target": t, "provenance": edge_prov[(s, t)]}+ for s, t in edges+ ],}text = json.dumps(graph, indent=2)if args.output:+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(args.output, "w", encoding="utf-8") as f:f.write(text)sys.stderr.write(f"wrote {args.output}\n")diff --git a/skills/drawio-skill/scripts/rustimports.py b/skills/drawio-skill/scripts/rustimports.pyindex df17b84..9961858 100644--- a/skills/drawio-skill/scripts/rustimports.py+++ b/skills/drawio-skill/scripts/rustimports.py@@ -24,6 +24,7 @@ intra-crate paths (without `crate::`) are not resolved.Usage: python3 rustimports.py <crate_dir> [-o graph.json] [--direction TB|LR][--group] [--no-reduce]"""+import argparseimport jsonimport os@@ -37,6 +38,7 @@ USE = re.compile(r"\buse\s+([^;]+);")def crate_name(root):cargo = os.path.join(root, "Cargo.toml")if os.path.exists(cargo):+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(cargo, encoding="utf-8", errors="ignore") as f:m = re.search(r'(?m)^\s*name\s*=\s*"([^"]+)"', f.read())if m:@@ -47,7 +49,9 @@ def crate_name(root):def discover(root):"""Map module path (tuple of segments; () is the crate root) -> file path."""root = os.path.abspath(root)- src = os.path.join(root, "src") if os.path.isdir(os.path.join(root, "src")) else root+ src = (+ os.path.join(root, "src") if os.path.isdir(os.path.join(root, "src")) else root+ )modules = {}for dirpath, dirs, files in os.walk(src):dirs[:] = [d for d in dirs if d != "target" and not d.startswith(".")]@@ -58,7 +62,7 @@ def discover(root):if parts[-1] == "mod":parts = parts[:-1]if len(parts) == 1 and parts[0] in ("main", "lib"):- parts = [] # crate root+ parts = [] # crate rootmodules[tuple(parts)] = os.path.join(dirpath, fn)return modules, src@@ -96,15 +100,15 @@ def base_segments(prefix, current):n += 1segs = segs[1:]if n > len(current):- return None # climbs above the crate root+ return None # climbs above the crate rootreturn list(current)[: len(current) - n] + segs- return None # std / external crate+ return None # std / external cratedef resolve(parts, modules, current):"""Longest known module prefix of `parts` (a tuple), or None."""if not parts:- return () if () in modules and () != tuple(current) else None+ return () if () in modules and tuple(current) != () else Nonep = list(parts)while p:if tuple(p) in modules and tuple(p) != tuple(current):@@ -124,7 +128,7 @@ def edges_of(current, path, modules):for stmt in USE.findall(src):if "{" in stmt:prefix = stmt[: stmt.index("{")]- inner = stmt[stmt.index("{") + 1: stmt.rindex("}")] if "}" in stmt else ""+ inner = stmt[stmt.index("{") + 1 : stmt.rindex("}")] if "}" in stmt else ""leaves = split_top(inner)else:prefix, leaves = stmt, [None]@@ -148,41 +152,60 @@ def transitive_reduce(nodes, edges):idx = {n: i for i, n in enumerate(nodes)}dot = "digraph{" + "".join(f"{idx[s]}->{idx[t]};" for s, t in edges) + "}"try:- out = subprocess.run(["tred"], input=dot, capture_output=True,- text=True, check=True).stdout+ out = subprocess.run(+ ["tred"], input=dot, capture_output=True, text=True, check=True+ ).stdoutexcept (FileNotFoundError, subprocess.CalledProcessError) as exc:sys.stderr.write(f"warning: tred unavailable, keeping all edges ({exc})\n")return edgesrev = {i: n for n, i in idx.items()}- return [(rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)]+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python+ return [+ (rev[int(a)], rev[int(b)]) for a, b in re.findall(r"(\d+)\s*->\s*(\d+)", out)+ ]def main():- ap = argparse.ArgumentParser(description="Rust module-use graph -> autolayout graph JSON.")+ ap = argparse.ArgumentParser(+ description="Rust module-use graph -> autolayout graph JSON."+ )ap.add_argument("crate", help="crate directory (contains Cargo.toml and/or src/)")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="box modules by their parent module path (nested)")- ap.add_argument("--no-reduce", action="store_true",- help="keep every edge (skip transitive reduction)")+ ap.add_argument(+ "--group",+ action="store_true",+ help="box modules by their parent module path (nested)",+ )+ ap.add_argument(+ "--no-reduce",+ action="store_true",+ help="keep every edge (skip transitive reduction)",+ )args = ap.parse_args()- modules, _ = discover(args.crate)+ modules, src = discover(args.crate)if not modules:sys.exit(f"error: no .rs modules found under {args.crate}")name = crate_name(args.crate)mid = lambda parts: name if not parts else "::".join(parts)- edges = sorted({(mid(m), mid(t)) for m, path in modules.items()- for t in edges_of(m, path, modules)})+ edges = sorted(+ {+ (mid(m), mid(t))+ for m, path in modules.items()+ for t in edges_of(m, path, modules)+ }+ )raw = len(edges)if not args.no_reduce:edges = transitive_reduce([mid(m) for m in modules], edges)def node(parts):d = {"id": mid(parts), "label": name if not parts else parts[-1]}+ if parts:+ d["provenance"] = {"path": os.path.relpath(modules[parts], src)}if args.group and len(parts) > 1:- d["group"] = "/".join(parts[:-1]) # parent module path -> nested boxes+ d["group"] = "/".join(parts[:-1]) # parent module path -> nested boxesreturn dgraph = {@@ -192,6 +215,7 @@ def main():}text = json.dumps(graph, indent=2)if args.output:+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-pythonwith open(args.output, "w", encoding="utf-8") as f:f.write(text)sys.stderr.write(f"wrote {args.output}\n")diff --git a/tests/test_diagramctl.py b/tests/test_diagramctl.pyindex c3c546a..b698368 100644--- a/tests/test_diagramctl.py+++ b/tests/test_diagramctl.py@@ -291,6 +291,74 @@ class TestDiagramCtl(unittest.TestCase):data = json.loads(r.stdout)self.assertIn("not executed", data["drawio"]["note"])+ def test_build_python_gets_source_profile_and_provenance(self):+ # v3.2 P0: a code build must produce module/library/command kinds (not+ # a blanket "service"), precise per-file provenance, and no+ # ownership/observability noise on source modules.+ with tempfile.TemporaryDirectory() as td:+ pkg = os.path.join(td, "pkg")+ sub = os.path.join(pkg, "sub")+ os.makedirs(sub)+ for rel, text in (+ (os.path.join("pkg", "__init__.py"), "from .cli import main\n"),+ (os.path.join("pkg", "cli.py"), "from . import util\n"),+ (os.path.join("pkg", "util.py"), "x = 1\n"),+ (os.path.join("pkg", "__main__.py"), "from .cli import main\n"),+ (os.path.join("pkg", "sub", "mod.py"), "from .. import util\n"),+ ):+ with open(os.path.join(td, rel), "w", encoding="utf-8") as fh:+ fh.write(text)+ ir_json = os.path.join(td, "out.ir.json")+ out = os.path.join(td, "out.drawio")+ r = self.run_cli(+ "build", os.path.join(td, "pkg"), "--from", "python",+ "--ir-output", ir_json, "-o", out,+ )+ self.assertEqual(0, r.returncode, r.stderr)+ with open(ir_json, encoding="utf-8") as fh:+ ir = json.load(fh)+ by_id = {n["id"]: n for n in ir["nodes"]}+ # source profile: package root library, entrypoint command, rest module+ self.assertEqual(by_id["pkg"]["kind"], "library")+ self.assertEqual(by_id["pkg.cli"]["kind"], "command")+ self.assertEqual(by_id["pkg.util"]["kind"], "module")+ self.assertEqual(by_id["pkg.sub.mod"]["kind"], "module")+ # precise provenance: real file path (absolute) + importer tag+ self.assertEqual(+ os.path.basename(by_id["pkg.cli"]["provenance"]["path"]), "cli.py"+ )+ self.assertEqual(by_id["pkg.cli"]["provenance"]["importer"], "python")+ # line-level edge provenance survived the build+ edge = next(e for e in ir["edges"] if e["source"] == "pkg.cli")+ self.assertEqual(edge["provenance"]["line"], 1)++ def test_view_fallback_reports_metadata_gap(self):+ # A model with no deployment/security/data metadata must say so, with a+ # hint, instead of silently falling back to the whole graph.+ bare = d.normalize_ir({"nodes": [+ {"id": "a", "label": "A", "kind": "module"},+ {"id": "b", "label": "B", "kind": "module"},+ ], "edges": [{"source": "a", "target": "b"}]})+ views = d.project_views(bare, ["deployment", "dataflow", "system"])+ dep = next(v for v in views if v["name"] == "Deployment")+ self.assertTrue(dep["fallback"])+ self.assertIn("no deployment metadata", dep["fallback_reason"])+ self.assertIn("properties.environment", dep["hint"])+ flow = next(v for v in views if v["name"] == "Dataflow")+ self.assertTrue(flow["fallback"])+ self.assertIn("data-flow", flow["fallback_reason"])+ syst = next(v for v in views if v["name"] == "System")+ self.assertFalse(syst.get("fallback", False))++ def test_infer_profile(self):+ code = d.normalize_ir({"nodes": [{"id": "a", "kind": "module"}]})+ self.assertEqual(d.infer_profile(code), "code")+ arch = d.normalize_ir(+ {"nodes": [{"id": "a", "kind": "service"},+ {"id": "b", "kind": "database"}]}+ )+ self.assertEqual(d.infer_profile(arch), "architecture")+if __name__ == "__main__":unittest.main()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 3295251..ce339ac 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -9,6 +9,7 @@ importing the scripts directly; CLI/exit-code behaviour (validate, importers) istested via subprocess against tiny temp fixtures. No Graphviz/draw.io needed —auto-layout is exercised through to_drawio() with synthetic node positions."""+import base64import gzipimport importlib.util@@ -31,6 +32,7 @@ def load(name):"""Import a bundled script module by file path."""path = os.path.join(SCRIPTS, name + ".py")spec = importlib.util.spec_from_file_location(name, path)+ assert spec is not None and spec.loader is not Nonemod = importlib.util.module_from_spec(spec)spec.loader.exec_module(mod)return mod@@ -38,15 +40,21 @@ def load(name):def run(script, *args, **kw):"""Run a script as a subprocess; return CompletedProcess."""- return subprocess.run([sys.executable, os.path.join(SCRIPTS, script), *args],- capture_output=True, text=True, **kw)+ return subprocess.run(+ [sys.executable, os.path.join(SCRIPTS, script), *args],+ capture_output=True,+ text=True,+ **kw,+ )class TestShapeSearch(unittest.TestCase):@classmethoddef setUpClass(cls):cls.m = load("shapesearch")- with gzip.open(os.path.join(DATA, "shape-index.json.gz"), "rt", encoding="utf-8") as f:+ with gzip.open(+ os.path.join(DATA, "shape-index.json.gz"), "rt", encoding="utf-8"+ ) as f:cls.shapes = json.load(f)cls.tm = cls.m.build_tag_map(cls.shapes)@@ -106,10 +114,16 @@ class TestAiIcons(unittest.TestCase):def test_variant_preference(self):# claude has a colour variant; openai is mono-only -> falls back.- self.assertEqual(self.m.pick_variant("claude", self.fam["claude"], "color"), "claude-color")- self.assertEqual(self.m.pick_variant("openai", self.fam["openai"], "color"), "openai")- self.assertEqual(self.m.pick_variant("googlecloud", self.fam["googlecloud"], "text"),- "googlecloud-brand")+ self.assertEqual(+ self.m.pick_variant("claude", self.fam["claude"], "color"), "claude-color"+ )+ self.assertEqual(+ self.m.pick_variant("openai", self.fam["openai"], "color"), "openai"+ )+ self.assertEqual(+ self.m.pick_variant("googlecloud", self.fam["googlecloud"], "text"),+ "googlecloud-brand",+ )def test_remote_host_allowlist(self):self.assertEqual("https://unpkg.com/x", self.m.safe_url("https://unpkg.com/x"))@@ -128,7 +142,9 @@ class TestEncodeUrl(unittest.TestCase):@staticmethoddef decode(b64):# Reverse the encoder: inflate, then decodeURIComponent.- inflated = zlib.decompress(base64.b64decode(b64), -zlib.MAX_WBITS).decode("utf-8")+ inflated = zlib.decompress(base64.b64decode(b64), -zlib.MAX_WBITS).decode(+ "utf-8"+ )return urllib.parse.unquote(inflated)def test_roundtrip_cjk_and_percent(self):@@ -154,75 +170,109 @@ class TestAutolayoutColor(unittest.TestCase):def test_palette_from_design_file(self):# Sourced from styles/built-in/default.json, not the inline fallback.self.assertNotEqual(self.pal, self.m._FALLBACK_PALETTE)- self.assertEqual(self.pal[0], ("#dae8fc", "#6c8ebf")) # primary+ self.assertEqual(self.pal[0], ("#dae8fc", "#6c8ebf")) # primarydef _render(self, color):- graph = {"direction": "TB", "nodes": [- {"id": "a", "label": "A", "group": "mod1"},- {"id": "b", "label": "B", "group": "mod2"},- {"id": "c", "label": "C", "style": "fillColor=#ff0000;"},- {"id": "d", "label": "D"},- ], "edges": []}+ graph = {+ "direction": "TB",+ "nodes": [+ {"id": "a", "label": "A", "group": "mod1"},+ {"id": "b", "label": "B", "group": "mod2"},+ {"id": "c", "label": "C", "style": "fillColor=#ff0000;"},+ {"id": "d", "label": "D"},+ ],+ "edges": [],+ }pos = {"a": (1, 4), "b": (3, 4), "c": (5, 4), "d": (7, 4)}return self.m.to_drawio(graph, 5, pos, {}, color=color)def test_grouped_nodes_coloured(self):out = self._render(color=True)- self.assertIn("fillColor=#d5e8d4", out) # b tinted by mod2 (success/green)+ self.assertIn("fillColor=#d5e8d4", out) # b tinted by mod2 (success/green)self.assertIn("strokeColor=#82b366", out) # mod2 container border colour- self.assertIn("fillColor=#ff0000", out) # explicit style preserved+ self.assertIn("fillColor=#ff0000", out) # explicit style preserveddef test_mono_disables_colour(self):out = self._render(color=False)self.assertIn("strokeColor=#999999", out) # grey containerself.assertNotIn("fillColor=#d5e8d4", out) # no group tint- self.assertIn("fillColor=#ff0000", out) # explicit style still wins+ self.assertIn("fillColor=#ff0000", out) # explicit style still winsdef test_graph_level_spacing(self):# Importers emitting icon nodes ask for extra separation (labels render# below the shape); the keys pass straight through to dot.- dot = self.m.build_dot({"nodes": [{"id": "a"}], "edges": [],- "ranksep": 0.7, "nodesep": 0.6})+ dot = self.m.build_dot(+ {"nodes": [{"id": "a"}], "edges": [], "ranksep": 0.7, "nodesep": 0.6}+ )self.assertIn("ranksep=0.70;", dot)self.assertIn("nodesep=0.60;", dot)def test_node_link_wraps_userobject(self):out = self.m.to_drawio(- {"direction": "TB",- "nodes": [{"id": "n", "label": "L", "link": "data:page/id,p2"}],- "edges": []}, 5, {"n": (1, 1)}, {}, color=True)+ {+ "direction": "TB",+ "nodes": [{"id": "n", "label": "L", "link": "data:page/id,p2"}],+ "edges": [],+ },+ 5,+ {"n": (1, 1)},+ {},+ color=True,+ )self.assertIn('<UserObject label="L" link="data:page/id,p2" id="n">', out)- self.assertNotIn('value="L"', out) # label moved to the wrapper+ self.assertNotIn('value="L"', out) # label moved to the wrapperdef test_edge_style_passthrough(self):out = self.m.to_drawio(- {"direction": "TB",- "nodes": [{"id": "a"}, {"id": "b"}],- "edges": [{"source": "a", "target": "b", "style": "endArrow=ERone;"}]},- 5, {"a": (1, 1), "b": (3, 1)}, {}, color=True)+ {+ "direction": "TB",+ "nodes": [{"id": "a"}, {"id": "b"}],+ "edges": [{"source": "a", "target": "b", "style": "endArrow=ERone;"}],+ },+ 5,+ {"a": (1, 1), "b": (3, 1)},+ {},+ color=True,+ )self.assertIn("endArrow=ERone;", out)def test_label_newline_becomes_entity(self):out = self.m.to_drawio(- {"direction": "TB", "nodes": [{"id": "n", "label": "one\ntwo"}],- "edges": []}, 5, {"n": (1, 1)}, {}, color=True)+ {+ "direction": "TB",+ "nodes": [{"id": "n", "label": "one\ntwo"}],+ "edges": [],+ },+ 5,+ {"n": (1, 1)},+ {},+ color=True,+ )self.assertIn("one
two", out)def test_escapes_special_chars(self):# Ids/edges with a quote or backslash must be escaped in the DOT input# (else they corrupt the Graphviz source); a style with a quote must be# XML-escaped in the emitted mxCell.- dot = self.m.build_dot({- "nodes": [{"id": 'a"x'}, {"id": "b\\y"}],- "edges": [{"source": 'a"x', "target": "b\\y"}],- })+ dot = self.m.build_dot(+ {+ "nodes": [{"id": 'a"x'}, {"id": "b\\y"}],+ "edges": [{"source": 'a"x', "target": "b\\y"}],+ }+ )self.assertIn(r'"a\"x"', dot)self.assertIn(r'"b\\y"', dot)out = self.m.to_drawio(- {"direction": "TB",- "nodes": [{"id": "n", "label": "L", "style": 'fillColor="#fff";'}],- "edges": []},- 5, {"n": (1, 1)}, {}, color=True)+ {+ "direction": "TB",+ "nodes": [{"id": "n", "label": "L", "style": 'fillColor="#fff";'}],+ "edges": [],+ },+ 5,+ {"n": (1, 1)},+ {},+ color=True,+ )self.assertIn(""", out)@@ -232,18 +282,27 @@ class TestBuiltinPresets(unittest.TestCase):def test_presets_conform(self):import globimport re+hexpat = re.compile(r"^#[0-9A-Fa-f]{6}$")files = sorted(glob.glob(os.path.join(self.STYLES, "*.json")))names = {os.path.basename(f)[:-5] for f in files}- self.assertLessEqual({"default", "corporate", "handdrawn",- "colorblind-safe", "dark"}, names)+ self.assertLessEqual(+ {"default", "corporate", "handdrawn", "colorblind-safe", "dark"}, names+ )for f in files:with open(f, encoding="utf-8") as fh:d = json.load(fh)self.assertEqual(d["name"], os.path.basename(f)[:-5])- self.assertFalse(d.get("default"), f) # built-ins never default- for slot in ("primary", "success", "warning", "accent",- "danger", "neutral", "secondary"):+ self.assertFalse(d.get("default"), f) # built-ins never default+ for slot in (+ "primary",+ "success",+ "warning",+ "accent",+ "danger",+ "neutral",+ "secondary",+ ):pair = d["palette"][slot]if pair is not None:self.assertRegex(pair["fillColor"], hexpat)@@ -254,36 +313,42 @@ class TestBuiltinPresets(unittest.TestCase):class TestValidateCli(unittest.TestCase):- GOOD = ('<mxfile><diagram name="P1"><mxGraphModel><root>'- '<mxCell id="0"/><mxCell id="1" parent="0"/>'- '<mxCell id="2" value="A" vertex="1" parent="1">'- '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'- '<mxCell id="3" value="B" vertex="1" parent="1">'- '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'- '<mxCell id="4" edge="1" parent="1" source="2" target="3">'- '<mxGeometry relative="1" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')- BAD = ('<mxfile><diagram name="P1"><mxGraphModel><root>'- '<mxCell id="0"/><mxCell id="1" parent="0"/>'- '<mxCell id="2" value="A" vertex="1" parent="1">'- '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'- '<mxCell id="4" edge="1" parent="1" source="2" target="nope">'- '<mxGeometry relative="1" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ GOOD = (+ '<mxfile><diagram name="P1"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="2" value="A" vertex="1" parent="1">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="3" value="B" vertex="1" parent="1">'+ '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="4" edge="1" parent="1" source="2" target="3">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+ "</root></mxGraphModel></diagram></mxfile>"+ )+ BAD = (+ '<mxfile><diagram name="P1"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="2" value="A" vertex="1" parent="1">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="4" edge="1" parent="1" source="2" target="nope">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+ "</root></mxGraphModel></diagram></mxfile>"+ )# Edge label: a relative-positioned vertex that legitimately omits width/height.- EDGE_LABEL = ('<mxfile><diagram name="P1"><mxGraphModel><root>'- '<mxCell id="0"/><mxCell id="1" parent="0"/>'- '<mxCell id="2" value="A" vertex="1" parent="1">'- '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'- '<mxCell id="3" value="B" vertex="1" parent="1">'- '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'- '<mxCell id="4" edge="1" parent="1" source="2" target="3">'- '<mxGeometry relative="1" as="geometry"/></mxCell>'- '<mxCell id="5" value="lbl" style="edgeLabel;html=1;" vertex="1" '- 'connectable="0" parent="1">'- '<mxGeometry x="0.5" y="0" relative="1" as="geometry">'- '<mxPoint as="offset"/></mxGeometry></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ EDGE_LABEL = (+ '<mxfile><diagram name="P1"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="2" value="A" vertex="1" parent="1">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="3" value="B" vertex="1" parent="1">'+ '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="4" edge="1" parent="1" source="2" target="3">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+ '<mxCell id="5" value="lbl" style="edgeLabel;html=1;" vertex="1" '+ 'connectable="0" parent="1">'+ '<mxGeometry x="0.5" y="0" relative="1" as="geometry">'+ '<mxPoint as="offset"/></mxGeometry></mxCell>'+ "</root></mxGraphModel></diagram></mxfile>"+ )def _check(self, xml):with tempfile.NamedTemporaryFile("w", suffix=".drawio", delete=False) as f:@@ -311,6 +376,7 @@ class TestValidateCli(unittest.TestCase):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@@ -327,17 +393,19 @@ class TestValidateCli(unittest.TestCase):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"/>'- '<UserObject label="A" link="data:page/id,p2" id="2">'- '<mxCell vertex="1" parent="1">'- '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'- '</UserObject>'- '<mxCell id="3" value="B" vertex="1" parent="1">'- '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'- '<mxCell id="4" edge="1" parent="1" source="2" target="3">'- '<mxGeometry relative="1" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ LINKED = (+ '<mxfile><diagram name="P1"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<UserObject label="A" link="data:page/id,p2" id="2">'+ '<mxCell vertex="1" parent="1">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ "</UserObject>"+ '<mxCell id="3" value="B" vertex="1" parent="1">'+ '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="4" edge="1" parent="1" source="2" target="3">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+ "</root></mxGraphModel></diagram></mxfile>"+ )def test_userobject_wrapper_resolves(self):# The wrapper id must satisfy edge source refs (no dangling-edge error).@@ -363,39 +431,42 @@ class TestValidateGeometry(unittest.TestCase):@staticmethoddef _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+ 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 endpointdef 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+ 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 boxdef test_abs_rect_resolves_container_offset(self):ids = self._ids(- '<root>'+ "<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>')+ "</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>'+ "<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>')+ "</root>"+ )self.assertEqual(self.m.endpoint(ids["e"], "source", ids), (80, 20))# --- CLI integration tests ---@@ -409,43 +480,49 @@ class TestValidateGeometry(unittest.TestCase):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>')+ 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>')+ 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>')+ 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+ self.assertEqual(r.returncode, 0) # warning, not errordef test_edge_crossing_strict_fails(self):with tempfile.NamedTemporaryFile("w", suffix=".drawio", delete=False) as f:@@ -481,7 +558,21 @@ class TestImportersCli(unittest.TestCase):graph = json.loads(r.stdout)ids = {n["id"] for n in graph["nodes"]}self.assertEqual(ids, {"a", "b"})- self.assertIn({"source": "a", "target": "b"}, graph["edges"])+ self.assertEqual(+ graph["edges"],+ [+ {+ "source": "a",+ "target": "b",+ "provenance": {"path": "a.py", "line": 1},+ }+ ],+ )+ # Per-node file provenance (relative to the scanned project dir).+ self.assertEqual(+ {n["id"]: n["provenance"]["path"] for n in graph["nodes"]},+ {"a": "a.py", "b": "b.py"},+ )def test_pyclasses_inheritance(self):with tempfile.TemporaryDirectory() as d:@@ -512,8 +603,10 @@ class TestImportersCli(unittest.TestCase):self._write(os.path.join(d, "go.mod"), "module example.com/m\n\ngo 1.21\n")os.mkdir(os.path.join(d, "a"))os.mkdir(os.path.join(d, "b"))- self._write(os.path.join(d, "a", "a.go"),- 'package a\n\nimport _ "example.com/m/b"\n')+ self._write(+ os.path.join(d, "a", "a.go"),+ 'package a\n\nimport _ "example.com/m/b"\n',+ )self._write(os.path.join(d, "b", "b.go"), "package b\n")r = run("goimports.py", d)graph = json.loads(r.stdout)@@ -521,52 +614,81 @@ class TestImportersCli(unittest.TestCase):self.assertEqual(len(graph["nodes"]), 2)self.assertEqual(ids, {"example.com/m/a", "example.com/m/b"})self.assertEqual(len(graph["edges"]), 1)- self.assertEqual(graph["edges"][0],- {"source": "example.com/m/a", "target": "example.com/m/b"})+ self.assertEqual(+ graph["edges"][0],+ {"source": "example.com/m/a", "target": "example.com/m/b"},+ )def test_tfimports_edge_and_icons(self):# Node ids are type.name; the lambda resolves to an official aws4 icon# and the referenced role becomes an edge.with tempfile.TemporaryDirectory() as d:- self._write(os.path.join(d, "main.tf"),- 'resource "aws_lambda_function" "fn" {\n'- ' role = aws_iam_role.exec.arn # comment\n'- '}\n'- 'resource "aws_iam_role" "exec" {\n'- ' name = "exec"\n'- '}\n')+ self._write(+ os.path.join(d, "main.tf"),+ 'resource "aws_lambda_function" "fn" {\n'+ " role = aws_iam_role.exec.arn # comment\n"+ "}\n"+ 'resource "aws_iam_role" "exec" {\n'+ ' name = "exec"\n'+ "}\n",+ )r = run("tfimports.py", d, "--no-reduce")graph = json.loads(r.stdout)ids = {n["id"] for n in graph["nodes"]}self.assertEqual(ids, {"aws_lambda_function.fn", "aws_iam_role.exec"})- self.assertEqual(graph["edges"], [{"source": "aws_lambda_function.fn",- "target": "aws_iam_role.exec"}])+ self.assertEqual(+ graph["edges"],+ [{"source": "aws_lambda_function.fn", "target": "aws_iam_role.exec"}],+ )fn = next(n for n in graph["nodes"] if n["id"] == "aws_lambda_function.fn")self.assertIn("mxgraph.aws4", fn["style"])- self.assertEqual(graph["ranksep"], 0.7) # icon labels need spacing+ self.assertEqual(graph["ranksep"], 0.7) # icon labels need spacingdef test_tfimports_no_icons(self):# Without icons the type stays visible on the box (two-line label).with tempfile.TemporaryDirectory() as d:- self._write(os.path.join(d, "main.tf"),- 'resource "aws_s3_bucket" "logs" {}\n')+ self._write(+ os.path.join(d, "main.tf"), 'resource "aws_s3_bucket" "logs" {}\n'+ )graph = json.loads(run("tfimports.py", d, "--no-icons").stdout)self.assertEqual(graph["nodes"][0]["label"], "logs\naws_s3_bucket")self.assertNotIn("style", graph["nodes"][0])- K8S_LIST = {"kind": "List", "items": [- {"apiVersion": "v1", "kind": "Service",- "metadata": {"name": "web", "namespace": "shop"},- "spec": {"selector": {"app": "web"}}},- {"apiVersion": "apps/v1", "kind": "Deployment",- "metadata": {"name": "web", "namespace": "shop"},- "spec": {"template": {"metadata": {"labels": {"app": "web", "tier": "fe"}},- "spec": {"containers": [- {"name": "web", "image": "nginx",- "envFrom": [{"configMapRef": {"name": "cfg"}}]}]}}}},- {"apiVersion": "v1", "kind": "ConfigMap",- "metadata": {"name": "cfg", "namespace": "shop"}},- ]}+ K8S_LIST = {+ "kind": "List",+ "items": [+ {+ "apiVersion": "v1",+ "kind": "Service",+ "metadata": {"name": "web", "namespace": "shop"},+ "spec": {"selector": {"app": "web"}},+ },+ {+ "apiVersion": "apps/v1",+ "kind": "Deployment",+ "metadata": {"name": "web", "namespace": "shop"},+ "spec": {+ "template": {+ "metadata": {"labels": {"app": "web", "tier": "fe"}},+ "spec": {+ "containers": [+ {+ "name": "web",+ "image": "nginx",+ "envFrom": [{"configMapRef": {"name": "cfg"}}],+ }+ ]+ },+ }+ },+ },+ {+ "apiVersion": "v1",+ "kind": "ConfigMap",+ "metadata": {"name": "cfg", "namespace": "shop"},+ },+ ],+ }def test_k8simports_json(self):# JSON input needs no PyYAML; selector match and configMap ref -> edges.@@ -574,11 +696,17 @@ class TestImportersCli(unittest.TestCase):self._write(os.path.join(d, "all.json"), json.dumps(self.K8S_LIST))graph = json.loads(run("k8simports.py", d).stdout)ids = {n["id"] for n in graph["nodes"]}- self.assertEqual(ids, {"shop/Service/web", "shop/Deployment/web",- "shop/ConfigMap/cfg"})+ self.assertEqual(+ ids, {"shop/Service/web", "shop/Deployment/web", "shop/ConfigMap/cfg"}+ )edges = {(e["source"], e["target"]) for e in graph["edges"]}- self.assertEqual(edges, {("shop/Service/web", "shop/Deployment/web"),- ("shop/Deployment/web", "shop/ConfigMap/cfg")})+ self.assertEqual(+ edges,+ {+ ("shop/Service/web", "shop/Deployment/web"),+ ("shop/Deployment/web", "shop/ConfigMap/cfg"),+ },+ )svc = next(n for n in graph["nodes"] if n["id"] == "shop/Service/web")self.assertIn("mxgraph.kubernetes", svc["style"])@@ -593,11 +721,13 @@ class TestImportersCli(unittest.TestCase):import yaml # noqa: F401except ImportError:self.skipTest("PyYAML not installed")- compose = ("services:\n"- " api:\n image: api:1\n depends_on: [db]\n"- " volumes: ['uploads:/data', './src:/app']\n"- " db:\n image: postgres:16\n"- "volumes:\n uploads:\n")+ compose = (+ "services:\n"+ " api:\n image: api:1\n depends_on: [db]\n"+ " volumes: ['uploads:/data', './src:/app']\n"+ " db:\n image: postgres:16\n"+ "volumes:\n uploads:\n"+ )with tempfile.TemporaryDirectory() as d:self._write(os.path.join(d, "docker-compose.yml"), compose)graph = json.loads(run("composeimports.py", d).stdout)@@ -610,96 +740,199 @@ class TestImportersCli(unittest.TestCase):self.assertEqual(api["label"], "api\napi:1")DOCKER = [- {"Id": "a1", "Name": "/shop-web-1",- "Config": {"Image": "nginx:1.27", "Labels": {- "com.docker.compose.project": "shop", "com.docker.compose.service": "web",- "com.docker.compose.depends_on": "db:service_healthy:false"}},- "NetworkSettings": {"Networks": {"shop_net": {}, "bridge": {}}}, "Mounts": []},- {"Id": "a2", "Name": "/shop-db-1",- "Config": {"Image": "postgres:16", "Labels": {- "com.docker.compose.project": "shop", "com.docker.compose.service": "db"}},- "NetworkSettings": {"Networks": {"shop_net": {}}},- "Mounts": [{"Type": "volume", "Name": "pgdata", "Destination": "/data"},- {"Type": "bind", "Source": "/etc/hosts", "Destination": "/etc/hosts"}]},+ {+ "Id": "a1",+ "Name": "/shop-web-1",+ "Config": {+ "Image": "nginx:1.27",+ "Labels": {+ "com.docker.compose.project": "shop",+ "com.docker.compose.service": "web",+ "com.docker.compose.depends_on": "db:service_healthy:false",+ },+ },+ "NetworkSettings": {"Networks": {"shop_net": {}, "bridge": {}}},+ "Mounts": [],+ },+ {+ "Id": "a2",+ "Name": "/shop-db-1",+ "Config": {+ "Image": "postgres:16",+ "Labels": {+ "com.docker.compose.project": "shop",+ "com.docker.compose.service": "db",+ },+ },+ "NetworkSettings": {"Networks": {"shop_net": {}}},+ "Mounts": [+ {"Type": "volume", "Name": "pgdata", "Destination": "/data"},+ {"Type": "bind", "Source": "/etc/hosts", "Destination": "/etc/hosts"},+ ],+ },]def test_dockerimports_live(self):# `docker inspect` array on stdin (-): depends_on resolves service->container;# built-in `bridge` network and the bind mount are dropped as noise.- graph = json.loads(run("dockerimports.py", "-",- input=json.dumps(self.DOCKER)).stdout)+ graph = json.loads(+ run("dockerimports.py", "-", input=json.dumps(self.DOCKER)).stdout+ )ids = {n["id"] for n in graph["nodes"]}self.assertEqual(ids, {"shop-web-1", "shop-db-1", "net:shop_net", "vol:pgdata"})edges = {(e["source"], e["target"]) for e in graph["edges"]}- self.assertEqual(edges, {("shop-web-1", "shop-db-1"),- ("shop-web-1", "net:shop_net"),- ("shop-db-1", "net:shop_net"),- ("shop-db-1", "vol:pgdata")})+ self.assertEqual(+ edges,+ {+ ("shop-web-1", "shop-db-1"),+ ("shop-web-1", "net:shop_net"),+ ("shop-db-1", "net:shop_net"),+ ("shop-db-1", "vol:pgdata"),+ },+ )web = next(n for n in graph["nodes"] if n["id"] == "shop-web-1")self.assertEqual(web["label"], "shop-web-1\nnginx:1.27")def test_dockerimports_group_by_project(self):- graph = json.loads(run("dockerimports.py", "-", "--group",- input=json.dumps(self.DOCKER)).stdout)- containers = [n for n in graph["nodes"] if not n["id"].startswith(("net:", "vol:"))]+ graph = json.loads(+ run(+ "dockerimports.py", "-", "--group", input=json.dumps(self.DOCKER)+ ).stdout+ )+ containers = [+ n for n in graph["nodes"] if not n["id"].startswith(("net:", "vol:"))+ ]self.assertTrue(all(n["group"] == "shop" for n in containers))- TFSTATE = {"format_version": "1.0", "values": {"root_module": {- "resources": [- {"address": "aws_instance.web", "mode": "managed", "type": "aws_instance",- "name": "web", "depends_on": ["aws_security_group.web"], "values": {}},- {"address": "aws_security_group.web", "mode": "managed",- "type": "aws_security_group", "name": "web", "values": {}},- {"address": "data.aws_ami.x", "mode": "data", "type": "aws_ami",- "name": "x", "values": {}}],- "child_modules": [{"address": "module.vpc", "resources": [- {"address": "module.vpc.aws_subnet.p[0]", "mode": "managed",- "type": "aws_subnet", "name": "p", "index": 0, "values": {}},- {"address": "module.vpc.aws_subnet.p[1]", "mode": "managed",- "type": "aws_subnet", "name": "p", "index": 1, "values": {}}]}]}}}+ TFSTATE = {+ "format_version": "1.0",+ "values": {+ "root_module": {+ "resources": [+ {+ "address": "aws_instance.web",+ "mode": "managed",+ "type": "aws_instance",+ "name": "web",+ "depends_on": ["aws_security_group.web"],+ "values": {},+ },+ {+ "address": "aws_security_group.web",+ "mode": "managed",+ "type": "aws_security_group",+ "name": "web",+ "values": {},+ },+ {+ "address": "data.aws_ami.x",+ "mode": "data",+ "type": "aws_ami",+ "name": "x",+ "values": {},+ },+ ],+ "child_modules": [+ {+ "address": "module.vpc",+ "resources": [+ {+ "address": "module.vpc.aws_subnet.p[0]",+ "mode": "managed",+ "type": "aws_subnet",+ "name": "p",+ "index": 0,+ "values": {},+ },+ {+ "address": "module.vpc.aws_subnet.p[1]",+ "mode": "managed",+ "type": "aws_subnet",+ "name": "p",+ "index": 1,+ "values": {},+ },+ ],+ }+ ],+ }+ },+ }def test_tfstate_live(self):# `terraform show -json` on stdin: data sources excluded, depends_on edge,# count instances expanded, aws_instance -> official icon, module grouping.- graph = json.loads(run("tfstate.py", "-", "--group", "--no-reduce",- input=json.dumps(self.TFSTATE)).stdout)+ graph = json.loads(+ run(+ "tfstate.py",+ "-",+ "--group",+ "--no-reduce",+ input=json.dumps(self.TFSTATE),+ ).stdout+ )ids = {n["id"] for n in graph["nodes"]}- self.assertEqual(ids, {"aws_instance.web", "aws_security_group.web",- "module.vpc.aws_subnet.p[0]", "module.vpc.aws_subnet.p[1]"})- self.assertEqual(graph["edges"],- [{"source": "aws_instance.web", "target": "aws_security_group.web"}])+ self.assertEqual(+ ids,+ {+ "aws_instance.web",+ "aws_security_group.web",+ "module.vpc.aws_subnet.p[0]",+ "module.vpc.aws_subnet.p[1]",+ },+ )+ self.assertEqual(+ graph["edges"],+ [{"source": "aws_instance.web", "target": "aws_security_group.web"}],+ )ec2 = next(n for n in graph["nodes"] if n["id"] == "aws_instance.web")self.assertIn("mxgraph.aws4", ec2["style"])sub = next(n for n in graph["nodes"] if n["id"].endswith("p[0]"))- self.assertEqual(sub["label"], "p[0]\naws_subnet") # no icon -> type on box+ self.assertEqual(sub["label"], "p[0]\naws_subnet") # no icon -> type on boxself.assertEqual(sub["group"], "module.vpc")def test_k8simports_stdin(self):# `kubectl get ... -o json | k8simports.py -` reads the live snapshot.- graph = json.loads(run("k8simports.py", "-",- input=json.dumps(self.K8S_LIST)).stdout)- self.assertEqual({n["id"] for n in graph["nodes"]},- {"shop/Service/web", "shop/Deployment/web", "shop/ConfigMap/cfg"})+ graph = json.loads(+ run("k8simports.py", "-", input=json.dumps(self.K8S_LIST)).stdout+ )+ self.assertEqual(+ {n["id"] for n in graph["nodes"]},+ {"shop/Service/web", "shop/Deployment/web", "shop/ConfigMap/cfg"},+ )@staticmethoddef _drawio(nodes, edges):"""Minimal .drawio XML from (id, label) nodes and (src, tgt) edges."""cells = ['<mxCell id="0"/>', '<mxCell id="1" parent="0"/>']for i, (cid, label) in enumerate(nodes):- cells.append(f'<mxCell id="{cid}" value="{label}" vertex="1" parent="1" '- f'style="rounded=1;"><mxGeometry x="{i*200}" y="0" '- 'width="120" height="60" as="geometry"/></mxCell>')+ cells.append(+ f'<mxCell id="{cid}" value="{label}" vertex="1" parent="1" '+ f'style="rounded=1;"><mxGeometry x="{i * 200}" y="0" '+ '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>")+ 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>"+ )@staticmethoddef _status(style):- for tag, hue in (("added", "82b366"), ("removed", "b85450"),- ("changed", "d79b00"), ("moved", "9673a6"),- ("same", "999999")):+ for tag, hue in (+ ("added", "82b366"),+ ("removed", "b85450"),+ ("changed", "d79b00"),+ ("moved", "9673a6"),+ ("same", "999999"),+ ):if hue in style:return tagreturn "?"@@ -708,21 +941,31 @@ class TestImportersCli(unittest.TestCase):# 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")],- [("api", "db"), ("api", "worker")])+ old = self._drawio(+ [("api", "api v1"), ("db", "db"), ("cache", "cache")],+ [("api", "db"), ("api", "cache")],+ )+ new = self._drawio(+ [("api", "api v2"), ("db", "db"), ("worker", "worker")],+ [("api", "db"), ("api", "worker")],+ )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)+ 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, {"api": "changed", "db": "same",- "cache": "removed", "worker": "added"})- estatus = {(e["source"], e["target"]): e["style"]- for e in graph["edges"]}- self.assertIn("999999", estatus[("api", "db")]) # same+ self.assertEqual(+ status,+ {"api": "changed", "db": "same", "cache": "removed", "worker": "added"},+ )+ estatus = {(e["source"], e["target"]): e["style"] for e in graph["edges"]}+ self.assertIn("999999", estatus[("api", "db")]) # sameself.assertIn("b85450", estatus[("api", "cache")]) # removedself.assertIn("d79b00", estatus[("api", "worker")]) # rerouted@@ -731,14 +974,23 @@ class TestImportersCli(unittest.TestCase):""".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>')+ 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>")+ 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).@@ -747,22 +999,35 @@ class TestImportersCli(unittest.TestCase):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)+ 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)], [])+ 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)+ 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"})@@ -774,11 +1039,17 @@ class TestImportersCli(unittest.TestCase):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)+ 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.assertEqual(+ (graph["edges"][0]["source"], graph["edges"][0]["target"]), ("b", "a")+ )self.assertIn("d79b00", graph["edges"][0]["style"]) # rerouteddef test_drawiodiff_by_label(self):@@ -788,34 +1059,47 @@ class TestImportersCli(unittest.TestCase):with tempfile.TemporaryDirectory() as d:self._write(os.path.join(d, "old.drawio"), old)self._write(os.path.join(d, "new.drawio"), new)- base = run("drawiodiff.py", os.path.join(d, "old.drawio"),- os.path.join(d, "new.drawio"))+ base = run(+ "drawiodiff.py",+ os.path.join(d, "old.drawio"),+ os.path.join(d, "new.drawio"),+ )# Without --by-label the random ids make everything add/remove.- self.assertNotIn("same", {self._status(n["style"])- for n in json.loads(base.stdout)["nodes"]})- graph = json.loads(run("drawiodiff.py", os.path.join(d, "old.drawio"),- os.path.join(d, "new.drawio"), "--by-label").stdout)+ self.assertNotIn(+ "same",+ {self._status(n["style"]) for n in json.loads(base.stdout)["nodes"]},+ )+ graph = json.loads(+ run(+ "drawiodiff.py",+ os.path.join(d, "old.drawio"),+ os.path.join(d, "new.drawio"),+ "--by-label",+ ).stdout+ )status = {n["id"]: self._status(n["style"]) for n in graph["nodes"]}self.assertEqual(status, {"API": "same", "DB": "removed", "Cache": "added"})def test_timelapse_sample_indices(self):tl = load("timelapse")- self.assertEqual(tl.sample_indices(3, 10), [0, 1, 2]) # fewer than n -> all+ self.assertEqual(tl.sample_indices(3, 10), [0, 1, 2]) # fewer than n -> allself.assertEqual(tl.sample_indices(0, 5), [])picked = tl.sample_indices(20, 5)- self.assertEqual(picked[0], 0) # always first- self.assertEqual(picked[-1], 19) # always last+ self.assertEqual(picked[0], 0) # always first+ self.assertEqual(picked[-1], 19) # always lastself.assertEqual(len(picked), 5)- self.assertEqual(picked, sorted(set(picked))) # unique + ordered+ self.assertEqual(picked, sorted(set(picked))) # unique + ordereddef test_timelapse_build_html_self_contained(self):tl = load("timelapse")- frames = [(b"\x89PNG-old", "abc1234567", "2026-01-01", "init", 2, 1),- (b"\x89PNG-new", "def7654321", "2026-02-02", "grow", 9, 12)]+ frames = [+ (b"\x89PNG-old", "abc1234567", "2026-01-01", "init", 2, 1),+ (b"\x89PNG-new", "def7654321", "2026-02-02", "grow", 9, 12),+ ]html = tl.build_html(frames, "Evo")self.assertEqual(html.count("data:image/png;base64,"), 2)self.assertNotIn("http://", html)- self.assertNotIn("https://", html) # no CDN/external refs+ self.assertNotIn("https://", html) # no CDN/external refsfor ctl in ('id="play"', 'id="scrub"', 'id="bar"'):self.assertIn(ctl, html)# the embedded frame payload carries per-commit counts@@ -834,31 +1118,38 @@ class TestImportersCli(unittest.TestCase):'<mxCell id="c" value="DB" vertex="1" parent="1" style="shape=cylinder3;">''<mxGeometry x="400" y="0" width="80" height="80" as="geometry"/></mxCell>''<mxCell id="e1" value="reads" edge="1" parent="1" source="a" target="c">'- '<mxGeometry relative="1" as="geometry"/></mxCell>')+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+ )def test_explain_groups_shapes_relations(self):- doc = ('<mxfile><diagram name="P1"><mxGraphModel><root>'- + self.EXPLAIN_PAGE + "</root></mxGraphModel></diagram></mxfile>")+ doc = (+ '<mxfile><diagram name="P1"><mxGraphModel><root>'+ + self.EXPLAIN_PAGE+ + "</root></mxGraphModel></diagram></mxfile>"+ )with tempfile.TemporaryDirectory() as d:path = os.path.join(d, "arch.drawio")self._write(path, doc)md = run("explain.py", path).stdout- self.assertIn("### Components (3)", md) # A, B, DB (grp is a container)- self.assertIn("- **Tier**", md) # container -> grouping heading+ self.assertIn("### Components (3)", md) # A, B, DB (grp is a container)+ self.assertIn("- **Tier**", md) # container -> grouping headingself.assertIn("- A", md)- self.assertIn("DB _data store_", md) # cylinder -> data store- self.assertIn("A —reads→ DB", md) # labeled relation- self.assertNotIn("- Tier _", md) # container itself isn't a component+ self.assertIn("DB _data store_", md) # cylinder -> data store+ self.assertIn("A —reads→ DB", md) # labeled relation+ self.assertNotIn("- Tier _", md) # container itself isn't a componentdef test_explain_multipage(self):- doc = ('<mxfile>'- '<diagram name="P1"><mxGraphModel><root>' + self.EXPLAIN_PAGE- + '</root></mxGraphModel></diagram>'- '<diagram name="P2"><mxGraphModel><root>'- '<mxCell id="0"/><mxCell id="1" parent="0"/>'- '<mxCell id="x" value="Solo" vertex="1" parent="1" style="rounded=1;">'- '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ doc = (+ "<mxfile>"+ '<diagram name="P1"><mxGraphModel><root>'+ + self.EXPLAIN_PAGE+ + "</root></mxGraphModel></diagram>"+ '<diagram name="P2"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="x" value="Solo" vertex="1" parent="1" style="rounded=1;">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ "</root></mxGraphModel></diagram></mxfile>"+ )with tempfile.TemporaryDirectory() as d:path = os.path.join(d, "multi.drawio")self._write(path, doc)@@ -869,10 +1160,12 @@ class TestImportersCli(unittest.TestCase):def test_drawio2pptx_page_names(self):tp = load("drawio2pptx")- doc = ('<mxfile>'- '<diagram name="Context"><mxGraphModel><root></root></mxGraphModel></diagram>'- '<diagram name="Containers"><mxGraphModel><root></root></mxGraphModel></diagram>'- '</mxfile>')+ doc = (+ "<mxfile>"+ '<diagram name="Context"><mxGraphModel><root></root></mxGraphModel></diagram>'+ '<diagram name="Containers"><mxGraphModel><root></root></mxGraphModel></diagram>'+ "</mxfile>"+ )with tempfile.TemporaryDirectory() as d:path = os.path.join(d, "c4.drawio")self._write(path, doc)@@ -881,7 +1174,8 @@ class TestImportersCli(unittest.TestCase):def test_drawio2pptx_png_size(self):tp = load("drawio2pptx")import struct- blob = b"\x00" * 16 + struct.pack(">II", 1280, 720) # IHDR w/h at [16:24]++ blob = b"\x00" * 16 + struct.pack(">II", 1280, 720) # IHDR w/h at [16:24]with tempfile.TemporaryDirectory() as d:path = os.path.join(d, "x.png")with open(path, "wb") as f:@@ -890,6 +1184,7 @@ class TestImportersCli(unittest.TestCase):def test_drawio2pptx_deck(self):import shutil+if os.environ.get("DRAWIO_E2E") != "1":self.skipTest("set DRAWIO_E2E=1 to launch the desktop CLI")try:@@ -898,9 +1193,11 @@ class TestImportersCli(unittest.TestCase):self.skipTest("python-pptx not installed")if not (shutil.which("drawio") and shutil.which("dot")):self.skipTest("draw.io CLI / Graphviz not installed")- graph = {"direction": "TB",- "nodes": [{"id": "a", "label": "A"}, {"id": "b", "label": "B"}],- "edges": [{"source": "a", "target": "b"}]}+ graph = {+ "direction": "TB",+ "nodes": [{"id": "a", "label": "A"}, {"id": "b", "label": "B"}],+ "edges": [{"source": "a", "target": "b"}],+ }with tempfile.TemporaryDirectory() as d:gj = os.path.join(d, "g.json")self._write(gj, json.dumps(graph))@@ -910,6 +1207,7 @@ class TestImportersCli(unittest.TestCase):r = run("drawio2pptx.py", dr, "-o", out)self.assertEqual(r.returncode, 0, r.stderr)from pptx import Presentation+prs = Presentation(out)self.assertEqual(len(prs.slides), 1)@@ -919,24 +1217,27 @@ class TestImportersCli(unittest.TestCase):'<rect x="0" y="0" width="20" height="20" fill="#fff" pointer-events="all"/>''<path d="M 20 10 L 60 10" fill="none" stroke="#000" pointer-events="stroke"/>''<path d="M 60 10 L 55 7 L 55 13 Z" fill="#000000" pointer-events="all"/>'- "</svg>")+ "</svg>"+ )def test_svgflow_animates_only_edges(self):sf = load("svgflow")out, n = sf.animate(self.FLOW_SVG, 1.2, "6 4", reverse=False)- self.assertEqual(n, 1) # one edge line- self.assertIn("@keyframes dio-flow", out) # keyframes injected- self.assertIn("stroke-dashoffset:-10", out) # -(6+4) forward travel+ self.assertEqual(n, 1) # one edge line+ self.assertIn("@keyframes dio-flow", out) # keyframes injected+ self.assertIn("stroke-dashoffset:-10", out) # -(6+4) forward travelself.assertEqual(out.count('class="dio-flow"'), 1)# class is injected right after "<path " — only on the stroke edgeself.assertIn('<path class="dio-flow" d="M 20 10', out)- self.assertNotIn('<path class="dio-flow" d="M 60 10', out) # arrowhead untouched+ self.assertNotIn(+ '<path class="dio-flow" d="M 60 10', out+ ) # arrowhead untouchedself.assertNotIn('class="dio-flow"', out.split("<rect", 1)[1].split("/>", 1)[0])def test_svgflow_reverse_flips_offset(self):sf = load("svgflow")out, _ = sf.animate(self.FLOW_SVG, 2, "8 2", reverse=True)- self.assertIn("stroke-dashoffset:10", out) # +(8+2), toward source+ self.assertIn("stroke-dashoffset:10", out) # +(8+2), toward sourcedef test_svg_export_embeds_images(self):# Without --embed-svg-images the CLI writes file:/// references to the@@ -959,7 +1260,7 @@ class TestImportersCli(unittest.TestCase):try:call(mod)except SystemExit:- pass # export "fails"; argv is what matters+ pass # export "fails"; argv is what mattersfinally:mod.subprocess.run = real_run@@ -970,46 +1271,53 @@ class TestImportersCli(unittest.TestCase):def test_drawio2mermaid_flowchart(self):# Reuses EXPLAIN_PAGE: container "Tier" with A/B, cylinder DB, edge a->c "reads".- doc = ('<mxfile><diagram name="P1"><mxGraphModel><root>'- + self.EXPLAIN_PAGE + "</root></mxGraphModel></diagram></mxfile>")+ doc = (+ '<mxfile><diagram name="P1"><mxGraphModel><root>'+ + self.EXPLAIN_PAGE+ + "</root></mxGraphModel></diagram></mxfile>"+ )with tempfile.TemporaryDirectory() as d:path = os.path.join(d, "arch.drawio")self._write(path, doc)mmd = run("drawio2mermaid.py", path, "--direction", "TD").stdoutself.assertTrue(mmd.startswith("flowchart TD"))self.assertIn("subgraph", mmd)- self.assertIn('["Tier"]', mmd) # container -> subgraph title+ self.assertIn('["Tier"]', mmd) # container -> subgraph titleself.assertIn('["A"]', mmd)- self.assertIn('[("DB")]', mmd) # cylinder -> database shape- self.assertIn('-->|"reads"|', mmd) # labeled edge+ self.assertIn('[("DB")]', mmd) # cylinder -> database shape+ self.assertIn('-->|"reads"|', mmd) # labeled edgedef test_drawio2mermaid_multipage_fenced(self):- doc = ('<mxfile>'- '<diagram name="P1"><mxGraphModel><root>'- '<mxCell id="0"/><mxCell id="1" parent="0"/>'- '<mxCell id="x" value="Solo" vertex="1" parent="1" style="rounded=1;">'- '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram>'- '<diagram name="P2"><mxGraphModel><root>'- '<mxCell id="0"/><mxCell id="1" parent="0"/>'- '<mxCell id="y" value="Two" vertex="1" parent="1" style="rounded=1;">'- '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ doc = (+ "<mxfile>"+ '<diagram name="P1"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="x" value="Solo" vertex="1" parent="1" style="rounded=1;">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ "</root></mxGraphModel></diagram>"+ '<diagram name="P2"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="y" value="Two" vertex="1" parent="1" style="rounded=1;">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ "</root></mxGraphModel></diagram></mxfile>"+ )with tempfile.TemporaryDirectory() as d:path = os.path.join(d, "multi.drawio")self._write(path, doc)mmd = run("drawio2mermaid.py", path, "--fenced").stdout- self.assertEqual(mmd.count("```mermaid"), 2) # one fence per page+ self.assertEqual(mmd.count("```mermaid"), 2) # one fence per pageself.assertIn("%% Page 2: P2", mmd)self.assertIn('["Solo"]', mmd)- SQL = ("CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255));\n"- "CREATE TABLE orders (\n"- " id INT,\n"- " user_id INT NOT NULL REFERENCES users(id),\n"- " PRIMARY KEY (id),\n"- " CONSTRAINT fk FOREIGN KEY (user_id) REFERENCES users (id)\n"- ");\n")+ SQL = (+ "CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255));\n"+ "CREATE TABLE orders (\n"+ " id INT,\n"+ " user_id INT NOT NULL REFERENCES users(id),\n"+ " PRIMARY KEY (id),\n"+ " CONSTRAINT fk FOREIGN KEY (user_id) REFERENCES users (id)\n"+ ");\n"+ )def test_sqlerd_tables_and_fks(self):with tempfile.TemporaryDirectory() as d:@@ -1023,14 +1331,20 @@ class TestImportersCli(unittest.TestCase):# inline REFERENCES + the equivalent named constraint -> 2 edgesfor e in graph["edges"]:self.assertEqual((e["source"], e["target"]), ("orders", "users"))- self.assertIn("ERmany", e["style"]) # crow's foot at the FK side+ self.assertIn("ERmany", e["style"]) # crow's foot at the FK sidedef test_seqlayout_geometry(self):- spec = {"participants": [{"id": "a", "label": "A", "actor": True},- {"id": "b", "label": "B"}],- "messages": [{"from": "a", "to": "b", "label": "call"},- {"from": "b", "to": "b", "label": "work"},- {"from": "b", "to": "a", "label": "done", "return": True}]}+ spec = {+ "participants": [+ {"id": "a", "label": "A", "actor": True},+ {"id": "b", "label": "B"},+ ],+ "messages": [+ {"from": "a", "to": "b", "label": "call"},+ {"from": "b", "to": "b", "label": "work"},+ {"from": "b", "to": "a", "label": "done", "return": True},+ ],+ }with tempfile.TemporaryDirectory() as d:path = os.path.join(d, "seq.json")self._write(path, json.dumps(spec))@@ -1039,29 +1353,49 @@ class TestImportersCli(unittest.TestCase):self.assertEqual(r.returncode, 0, r.stderr)with open(out, encoding="utf-8") as fh:xml = fh.read()- self.assertIn("umlActor", xml) # actor header- self.assertIn('parent="b"', xml) # activation bar on b- self.assertIn("endArrow=block", xml) # sync arrow- self.assertIn("strokeColor=#999999", xml) # return arrow+ self.assertIn("umlActor", xml) # actor header+ self.assertIn('parent="b"', xml) # activation bar on b+ self.assertIn("endArrow=block", xml) # sync arrow+ self.assertIn("strokeColor=#999999", xml) # return arrow# the generated file passes the structural linterv = run("validate.py", out)self.assertEqual(v.returncode, 0, v.stdout)def test_c4_multipage_drilldown(self):import shutil+if not shutil.which("dot"):self.skipTest("Graphviz dot not installed")- spec = {"levels": [- {"name": "Context",- "elements": [{"id": "u", "type": "person", "label": "User"},- {"id": "sys", "type": "system", "label": "System",- "children": "Containers"}],- "relations": [{"from": "u", "to": "sys", "label": "Uses"}]},- {"name": "Containers",- "elements": [{"id": "api", "type": "container", "label": "API",- "tech": "Go"},- {"id": "db", "type": "database", "label": "DB"}],- "relations": [{"from": "api", "to": "db"}]}]}+ spec = {+ "levels": [+ {+ "name": "Context",+ "elements": [+ {"id": "u", "type": "person", "label": "User"},+ {+ "id": "sys",+ "type": "system",+ "label": "System",+ "children": "Containers",+ },+ ],+ "relations": [{"from": "u", "to": "sys", "label": "Uses"}],+ },+ {+ "name": "Containers",+ "elements": [+ {+ "id": "api",+ "type": "container",+ "label": "API",+ "tech": "Go",+ },+ {"id": "db", "type": "database", "label": "DB"},+ ],+ "relations": [{"from": "api", "to": "db"}],+ },+ ]+ }with tempfile.TemporaryDirectory() as d:path = os.path.join(d, "c4.json")self._write(path, json.dumps(spec))@@ -1071,7 +1405,7 @@ class TestImportersCli(unittest.TestCase):with open(out, encoding="utf-8") as fh:xml = fh.read()self.assertEqual(xml.count("<diagram"), 2)- self.assertIn('link="data:page/id,containers"', xml) # drill-down+ self.assertIn('link="data:page/id,containers"', xml) # drill-downself.assertIn("mxgraph.c4.person2", xml)self.assertIn("[Container: Go]", xml)v = run("validate.py", out)@@ -1095,19 +1429,42 @@ class TestImportersCli(unittest.TestCase):def test_openapiimports_operations_and_schemas(self):spec = {"openapi": "3.0.0",- "paths": {"/pets": {- "get": {"tags": ["pets"], "summary": "List",- "responses": {"200": {"content": {"application/json":- {"schema": {"$ref": "#/components/schemas/Pet"}}}}}},- "post": {"tags": ["pets"],- "requestBody": {"content": {"application/json":- {"schema": {"$ref": "#/components/schemas/Pet"}}}},- "responses": {"201": {"description": "ok"}}},- }},- "components": {"schemas": {- "Pet": {"properties": {"owner": {"$ref": "#/components/schemas/Owner"}}},- "Owner": {"properties": {"id": {"type": "integer"}}},- }},+ "paths": {+ "/pets": {+ "get": {+ "tags": ["pets"],+ "summary": "List",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {"$ref": "#/components/schemas/Pet"}+ }+ }+ }+ },+ },+ "post": {+ "tags": ["pets"],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {"$ref": "#/components/schemas/Pet"}+ }+ }+ },+ "responses": {"201": {"description": "ok"}},+ },+ }+ },+ "components": {+ "schemas": {+ "Pet": {+ "properties": {"owner": {"$ref": "#/components/schemas/Owner"}}+ },+ "Owner": {"properties": {"id": {"type": "integer"}}},+ }+ },}with tempfile.TemporaryDirectory() as d:p = os.path.join(d, "api.json")@@ -1119,18 +1476,20 @@ class TestImportersCli(unittest.TestCase):self.assertEqual({n["id"] for n in schemas}, {"S:Pet", "S:Owner"})get = next(n for n in ops if n["label"].startswith("GET"))post = next(n for n in ops if n["label"].startswith("POST"))- self.assertIn("fillColor=#dae8fc", get["style"]) # GET blue- self.assertIn("fillColor=#d5e8d4", post["style"]) # POST green+ self.assertIn("fillColor=#dae8fc", get["style"]) # GET blue+ self.assertIn("fillColor=#d5e8d4", post["style"]) # POST greenpairs = {(e["source"], e["target"]) for e in graph["edges"]}- self.assertIn((get["id"], "S:Pet"), pairs) # operation -> schema- self.assertIn(("S:Pet", "S:Owner"), pairs) # schema nesting+ self.assertIn((get["id"], "S:Pet"), pairs) # operation -> schema+ self.assertIn(("S:Pet", "S:Owner"), pairs) # schema nestingself.assertEqual({n.get("group") for n in ops}, {"pets"})self.assertEqual(next(iter(schemas)).get("group"), "schemas")def test_openapiimports_no_schemas(self):- spec = {"openapi": "3.0.0",- "paths": {"/x": {"get": {"responses": {"200": {"description": "ok"}}}}},- "components": {"schemas": {"Y": {"properties": {"z": {"type": "string"}}}}}}+ spec = {+ "openapi": "3.0.0",+ "paths": {"/x": {"get": {"responses": {"200": {"description": "ok"}}}}},+ "components": {"schemas": {"Y": {"properties": {"z": {"type": "string"}}}}},+ }with tempfile.TemporaryDirectory() as d:p = os.path.join(d, "api.json")self._write(p, json.dumps(spec))@@ -1146,22 +1505,24 @@ class TestDrawioHtml(unittest.TestCase):cls.m = load("drawiohtml")TWO_PAGE = (- '<mxfile>'+ "<mxfile>"'<diagram id="pg1" name="Context"><mxGraphModel><root>''<mxCell id="0"/><mxCell id="1" parent="0"/>''<UserObject label="System" link="data:page/id,pg2" id="sys">''<mxCell style="rounded=1;" vertex="1" parent="1">''<mxGeometry x="40" y="40" width="120" height="60" as="geometry"/></mxCell>'- '</UserObject></root></mxGraphModel></diagram>'+ "</UserObject></root></mxGraphModel></diagram>"'<diagram id="pg2" name="Container"><mxGraphModel><root>''<mxCell id="0"/><mxCell id="1" parent="0"/>''<mxCell id="app" value="App" style="rounded=1;" vertex="1" parent="1">''<mxGeometry x="40" y="40" width="120" height="60" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ "</root></mxGraphModel></diagram></mxfile>"+ )def test_rewrite_page_links(self):- import xml.etree.ElementTree as ETimport io+ import xml.etree.ElementTree as ET+tree = ET.parse(io.StringIO(self.TWO_PAGE))self.assertEqual(self.m.rewrite_page_links(tree), 1)links = [el.get("link") for el in tree.getroot().iter() if el.get("link")]@@ -1172,18 +1533,21 @@ class TestDrawioHtml(unittest.TestCase):self.assertEqual(self.m.strip_prolog(svg), "<svg><g/></svg>")def test_build_html_self_contained(self):- html = self.m.build_html("t", [("pg1", "Context"), ("pg2", "Container")],- ['<svg width="10" height="10"/>',- '<svg width="10" height="10"/>'])+ html = self.m.build_html(+ "t",+ [("pg1", "Context"), ("pg2", "Container")],+ ['<svg width="10" height="10"/>', '<svg width="10" height="10"/>'],+ )self.assertEqual(html.count('class="page"'), 2)self.assertIn('data-pgid="pg1"', html)self.assertIn('"name": "Container"', html)- self.assertIn("#page-", html) # link interception+ self.assertIn("#page-", html) # link interceptionfor banned in ("<script src=", "<link ", "@import", "https://cdn"):- self.assertNotIn(banned, html) # no external requests+ self.assertNotIn(banned, html) # no external requestsdef test_viewer_end_to_end(self):import shutil+if os.environ.get("DRAWIO_E2E") != "1":self.skipTest("set DRAWIO_E2E=1 to launch the desktop CLI")if not shutil.which("drawio"):@@ -1199,9 +1563,9 @@ class TestDrawioHtml(unittest.TestCase):self.assertIn("1 drill-down link", r.stderr)with open(out, encoding="utf-8") as f:html = f.read()- self.assertEqual(html.count("<svg"), 2) # both pages inlined- self.assertIn("#page-pg2", html) # drill-down survived- self.assertIn("data-cell-id", html) # searchable cells+ self.assertEqual(html.count("<svg"), 2) # both pages inlined+ self.assertIn("#page-pg2", html) # drill-down survived+ self.assertIn("data-cell-id", html) # searchable cellsclass TestHeatmap(unittest.TestCase):@@ -1216,13 +1580,14 @@ class TestHeatmap(unittest.TestCase):def test_ramp_hits_anchors(self):a = self.m.PALETTES["heat"]- self.assertEqual(self.m.ramp(a, 0.0), "#57bb8a") # low- self.assertEqual(self.m.ramp(a, 0.5), "#ffd666") # mid- self.assertEqual(self.m.ramp(a, 1.0), "#e67c73") # high+ self.assertEqual(self.m.ramp(a, 0.0), "#57bb8a") # low+ self.assertEqual(self.m.ramp(a, 0.5), "#ffd666") # mid+ self.assertEqual(self.m.ramp(a, 1.0), "#e67c73") # highdef test_set_style_replaces_colours_once(self):- s = self.m.set_style("rounded=1;fillColor=#111111;strokeColor=#222222;",- "#abcdef", "#123456")+ s = self.m.set_style(+ "rounded=1;fillColor=#111111;strokeColor=#222222;", "#abcdef", "#123456"+ )self.assertIn("fillColor=#abcdef", s)self.assertIn("strokeColor=#123456", s)self.assertNotIn("#111111", s)@@ -1231,7 +1596,7 @@ class TestHeatmap(unittest.TestCase):def test_load_metrics_csv_and_json(self):with tempfile.TemporaryDirectory() as d:csvp = os.path.join(d, "m.csv")- self._write(csvp, "service,ms\nweb,10\ndb,90\n") # header auto-skipped+ self._write(csvp, "service,ms\nweb,10\ndb,90\n") # header auto-skippedself.assertEqual(self.m.load_metrics(csvp), {"web": 10.0, "db": 90.0})jp = os.path.join(d, "m.json")self._write(jp, '{"web":10,"db":90}')@@ -1247,19 +1612,26 @@ class TestHeatmap(unittest.TestCase):'<mxCell id="db" value="Database" style="rounded=1;fillColor=#dddddd;''strokeColor=#999999;" vertex="1" parent="1">''<mxGeometry x="360" y="40" width="80" height="40" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ "</root></mxGraphModel></diagram></mxfile>"+ )with tempfile.TemporaryDirectory() as d:- dp, mp, out = (os.path.join(d, n) for n in ("a.drawio", "m.csv", "out.drawio"))+ dp, mp, out = (+ os.path.join(d, n) for n in ("a.drawio", "m.csv", "out.drawio")+ )self._write(dp, drawio)self._write(mp, "web,10\ndb,90\n")r = run("heatmap.py", dp, "-m", mp, "-o", out)self.assertEqual(r.returncode, 0, r.stderr)self.assertIn("2/2 metrics matched", r.stderr)import xml.etree.ElementTree as ET- cells = {c.get("id"): c.get("style") for c in ET.parse(out).getroot().iter("mxCell")}- self.assertIn("fillColor=#57bb8a", cells["web"]) # min -> green- self.assertIn("fillColor=#e67c73", cells["db"]) # max -> red- self.assertIn("hm-title", cells) # legend injected++ cells = {+ c.get("id"): c.get("style") or ""+ for c in ET.parse(out).getroot().iter("mxCell")+ }+ self.assertIn("fillColor=#57bb8a", cells["web"]) # min -> green+ self.assertIn("fillColor=#e67c73", cells["db"]) # max -> red+ self.assertIn("hm-title", cells) # legend injectedFIXTURE_RELABEL = (@@ -1272,7 +1644,8 @@ FIXTURE_RELABEL = ('<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell></UserObject>''<mxCell id="e" value="go" style="endArrow=classic;" edge="1" parent="1" ''source="a" target="b"><mxGeometry relative="1" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ "</root></mxGraphModel></diagram></mxfile>"+)class TestRelabel(unittest.TestCase):@@ -1283,7 +1656,9 @@ class TestRelabel(unittest.TestCase):def test_extract_and_apply_roundtrip(self):with tempfile.TemporaryDirectory() as d:- dp, lp, out = (os.path.join(d, n) for n in ("a.drawio", "l.json", "out.drawio"))+ dp, lp, out = (+ os.path.join(d, n) for n in ("a.drawio", "l.json", "out.drawio")+ )self._write(dp, FIXTURE_RELABEL)r = run("relabel.py", dp, "--extract", "-o", lp)self.assertEqual(r.returncode, 0, r.stderr)@@ -1291,7 +1666,9 @@ class TestRelabel(unittest.TestCase):labels = json.load(fh)# page name + vertex value + UserObject label + edge labelself.assertEqual(set(labels), {"Flow", "Start", "Web Server", "go"})- labels.update({"Start": "\u5f00\u59cb", "Web Server": "Web \u670d\u52a1\u5668"})+ labels.update(+ {"Start": "\u5f00\u59cb", "Web Server": "Web \u670d\u52a1\u5668"}+ )with open(lp, "w", encoding="utf-8") as fh:json.dump(labels, fh, ensure_ascii=False)r = run("relabel.py", dp, "--map", lp, "-o", out)@@ -1307,7 +1684,9 @@ class TestRelabel(unittest.TestCase):def test_unmatched_map_key_warns(self):with tempfile.TemporaryDirectory() as d:- dp, lp, out = (os.path.join(d, n) for n in ("a.drawio", "l.json", "out.drawio"))+ dp, lp, out = (+ os.path.join(d, n) for n in ("a.drawio", "l.json", "out.drawio")+ )self._write(dp, FIXTURE_RELABEL)self._write(lp, '{"Nope": "X"}')r = run("relabel.py", dp, "--map", lp, "-o", out)@@ -1321,17 +1700,27 @@ class TestRestyle(unittest.TestCase):cls.m = load("restyle")def test_hue_slot_mapping(self):- palette = {k: {"fillColor": "#000000", "strokeColor": "#000000"}- for k in ("primary", "success", "warning", "accent",- "danger", "neutral", "secondary")}- self.assertEqual(self.m.hue_slot("#dae8fc", palette), "primary") # blue- self.assertEqual(self.m.hue_slot("#d5e8d4", palette), "success") # green- self.assertEqual(self.m.hue_slot("#f8cecc", palette), "danger") # red- self.assertEqual(self.m.hue_slot("#f5f5f5", palette), "neutral") # grey+ palette = {+ k: {"fillColor": "#000000", "strokeColor": "#000000"}+ for k in (+ "primary",+ "success",+ "warning",+ "accent",+ "danger",+ "neutral",+ "secondary",+ )+ }+ self.assertEqual(self.m.hue_slot("#dae8fc", palette), "primary") # blue+ self.assertEqual(self.m.hue_slot("#d5e8d4", palette), "success") # green+ self.assertEqual(self.m.hue_slot("#f8cecc", palette), "danger") # red+ self.assertEqual(self.m.hue_slot("#f5f5f5", palette), "neutral") # greydef test_set_keys_replaces_and_appends(self):- s = self.m.set_keys("rounded=1;fillColor=#111111;", fillColor="#222222",- fontFamily="Helvetica")+ s = self.m.set_keys(+ "rounded=1;fillColor=#111111;", fillColor="#222222", fontFamily="Helvetica"+ )self.assertEqual(s.count("fillColor="), 1)self.assertIn("fillColor=#222222", s)self.assertIn("fontFamily=Helvetica", s)@@ -1348,7 +1737,8 @@ class TestRestyle(unittest.TestCase):'<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>''<mxCell id="e" value="go" style="endArrow=classic;" edge="1" parent="1" ''source="svc" target="plain"><mxGeometry relative="1" as="geometry"/></mxCell>'- '</root></mxGraphModel></diagram></mxfile>')+ "</root></mxGraphModel></diagram></mxfile>"+ )with tempfile.TemporaryDirectory() as d:dp, out = os.path.join(d, "a.drawio"), os.path.join(d, "out.drawio")with open(dp, "w", encoding="utf-8") as f:@@ -1356,14 +1746,20 @@ class TestRestyle(unittest.TestCase):r = run("restyle.py", dp, "--preset", "dark", "-o", out)self.assertEqual(r.returncode, 0, r.stderr)import xml.etree.ElementTree as ET+tree = ET.parse(out)- cells = {c.get("id"): c.get("style") for c in tree.getroot().iter("mxCell")}- self.assertIn("fillColor=#004870", cells["svc"]) # blue -> dark primary+ cells = {+ c.get("id"): c.get("style") or "" for c in tree.getroot().iter("mxCell")+ }+ self.assertIn("fillColor=#004870", cells["svc"]) # blue -> dark primaryself.assertIn("fontColor=#f0f0f0", cells["svc"])- self.assertNotIn("fontColor=", cells["plain"]) # default white fill kept dark text- self.assertIn("strokeColor=#bbbbbb", cells["e"]) # edgeColor+ self.assertNotIn(+ "fontColor=", cells["plain"]+ ) # default white fill kept dark text+ self.assertIn("strokeColor=#bbbbbb", cells["e"]) # edgeColorself.assertIn("labelBackgroundColor=none", cells["e"])model = tree.getroot().find(".//mxGraphModel")+ assert model is not Noneself.assertEqual(model.get("background"), "#1e1e1e")def test_unknown_preset_lists_builtins(self):@@ -1398,12 +1794,14 @@ class TestCiImports(unittest.TestCase):" strategy:\n matrix:\n py: ['3.10', '3.11']\n"" steps: [{run: pytest}]\n"" deploy:\n needs: [lint, test]\n"- " uses: org/shared/.github/workflows/deploy.yml@main\n")+ " uses: org/shared/.github/workflows/deploy.yml@main\n"+ )GITLAB = ("stages: [build, test]\n""compile:\n stage: build\n script: [make]\n"- "unit:\n stage: test\n script: [make test]\n")+ "unit:\n stage: test\n script: [make test]\n"+ )def test_actions_workflow(self):self._need_yaml()@@ -1416,7 +1814,7 @@ class TestCiImports(unittest.TestCase):self.assertIn("matrix \u00d72", by_id["ci//test"]["label"])self.assertIn("uses: deploy.yml@main", by_id["ci//deploy"]["label"])edges = {(e["source"], e["target"]) for e in graph["edges"]}- self.assertIn(("ci//trigger", "ci//lint"), edges) # no needs -> trigger+ self.assertIn(("ci//trigger", "ci//lint"), edges) # no needs -> triggerself.assertIn(("ci//lint", "ci//deploy"), edges)self.assertIn(("ci//test", "ci//deploy"), edges)self.assertNotIn(("ci//trigger", "ci//deploy"), edges) # has needsdiff --git a/tests/test_skill_metadata.py b/tests/test_skill_metadata.pyindex 8e71dbc..d280f0a 100644--- a/tests/test_skill_metadata.py+++ b/tests/test_skill_metadata.py@@ -20,7 +20,7 @@ class TestSkillMetadata(unittest.TestCase):assert metadata_match is not Nonemetadata = json.loads(metadata_match.group(1))- self.assertEqual("3.1.0", metadata.get("version"))+ self.assertEqual("3.2.0", metadata.get("version"))self.assertEqual("https://github.com/Agents365-ai/drawio-skill", metadata.get("homepage"))