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: add 5 new scripts (image→drawio, buildup, compress, runbook, PR bot)
Agents365-ai56f954df4933
diff --git a/.github/actions/drawio-diff/action.yml b/.github/actions/drawio-diff/action.ymlnew file mode 100644index 0000000..294cbf7--- /dev/null+++ b/.github/actions/drawio-diff/action.yml@@ -0,0 +1,95 @@+name: 'draw.io PR Diagram Diff'+description: >-+ Renders base/head/diff PNGs for every .drawio file changed in a pull+ request and posts a Markdown report as a sticky PR comment + job summary.+author: 'drawio-skill'++inputs:+ base-sha:+ description: 'Base commit SHA to diff from'+ required: false+ default: ${{ github.event.pull_request.base.sha }}+ head-sha:+ description: 'Head commit SHA to diff to'+ required: false+ default: ${{ github.sha }}+ out-dir:+ description: 'Directory for the exported PNGs + report'+ required: false+ default: 'drawio-pr'+ github-token:+ description: 'Token used to read/post the sticky PR comment (needs pull-requests: write)'+ required: false+ default: ${{ github.token }}+ skip-tool-install:+ description: 'Skip installing draw.io + Graphviz (set true if the runner already provides them)'+ required: false+ default: 'false'++runs:+ using: 'composite'+ steps:+ - name: Checkout (full history, for base..head diffing)+ uses: actions/checkout@v4+ with:+ fetch-depth: 0++ # Same recipe as docs/CI.md "Option A" in this repo: draw.io desktop's CLI+ # is Electron-based, so it needs Graphviz (autolayout) + Xvfb (headless+ # display) on the runner. Skip this step (skip-tool-install: true) if your+ # runner/container already has `drawio` and `dot` on PATH.+ - name: Install draw.io CLI + Graphviz+ if: inputs.skip-tool-install != 'true'+ shell: bash+ run: |+ set -euo pipefail+ sudo apt-get update+ sudo apt-get install -y graphviz xvfb libgtk-3-0 libnotify4 libnss3 libgbm1 libasound2t64+ URL=$(curl -s https://api.github.com/repos/jgraph/drawio-desktop/releases/latest \+ | grep -o 'https://[^"]*amd64[^"]*\.deb' | head -1)+ curl -sL "$URL" -o /tmp/drawio.deb+ sudo apt-get install -y /tmp/drawio.deb++ - name: Render base/head/diff PNGs + Markdown report+ shell: bash+ run: |+ set -euo pipefail+ export HOME=${HOME:-/tmp}+ mkdir -p "${{ inputs.out-dir }}"+ xvfb-run -a --server-args="-screen 0 1280x1024x24" \+ python3 skills/drawio-skill/scripts/prdiff.py \+ --base "${{ inputs.base-sha }}" \+ --head "${{ inputs.head-sha }}" \+ --out-dir "${{ inputs.out-dir }}" \+ -o "${{ inputs.out-dir }}/report.md"++ - name: Write job summary+ shell: bash+ run: cat "${{ inputs.out-dir }}/report.md" >> "$GITHUB_STEP_SUMMARY"++ - name: Upload PNGs + report artifact+ uses: actions/upload-artifact@v4+ with:+ name: drawio-pr-diff+ path: ${{ inputs.out-dir }}++ - name: Post/update sticky PR comment+ if: github.event_name == 'pull_request'+ shell: bash+ env:+ GH_TOKEN: ${{ inputs.github-token }}+ run: |+ set -euo pipefail+ marker="<!-- drawio-pr-diff-bot -->"+ body_file="$(mktemp)"+ printf '%s\n' "$marker" > "$body_file"+ cat "${{ inputs.out-dir }}/report.md" >> "$body_file"+ pr_number="${{ github.event.pull_request.number }}"+ existing_id=$(gh api "repos/${{ github.repository }}/issues/${pr_number}/comments" --paginate \+ --jq ".[] | select(.body | startswith(\"$marker\")) | .id" | head -n1)+ if [ -n "$existing_id" ]; then+ gh api --method PATCH "repos/${{ github.repository }}/issues/comments/${existing_id}" \+ -f body=@"$body_file"+ else+ gh pr comment "$pr_number" --body-file "$body_file"+ fidiff --git a/.github/workflows/drawio-pr-diff.example.yml b/.github/workflows/drawio-pr-diff.example.ymlnew file mode 100644index 0000000..fce04e7--- /dev/null+++ b/.github/workflows/drawio-pr-diff.example.yml@@ -0,0 +1,42 @@+# TEMPLATE — not a live workflow in this repo.+#+# This is a ready-to-copy example for USERS who install this skill in their+# OWN project and want a "PR diagram bot" that renders base/head/diff PNGs+# for every .drawio changed in a pull request. It is named ".example.yml"+# (so GitHub Actions never auto-picks it up as `drawio-pr-diff.yml`) AND the+# job is gated with `if: false` below, so simply merging this file into THIS+# repo does NOT start any CI here.+#+# To adopt it in your own repo:+# 1. Copy this file to `.github/workflows/drawio-pr-diff.yml` (drop+# `.example`).+# 2. Delete (or flip) the `if: false` guard on the `diagram-diff` job.+# 3. Uncomment the `pull_request` trigger below (and drop/keep+# `workflow_dispatch` as you like — it's kept for manual testing).+# 4. Make sure the job has `pull-requests: write` permission (below) so+# the sticky PR comment can be posted.+# 5. See skills/drawio-skill/references/pr-bot.md for the full adoption+# guide (runner tool requirements, token scopes, how the sticky+# comment works).++name: drawio-pr-diff (example)++on:+ workflow_dispatch: {}+ # pull_request:+ # paths:+ # - "**/*.drawio"++permissions:+ contents: read+ pull-requests: write++jobs:+ diagram-diff:+ if: false # remove this line in your own repo once you've adopted the workflow above+ runs-on: ubuntu-latest+ steps:+ - uses: ./.github/actions/drawio-diff+ with:+ base-sha: ${{ github.event.pull_request.base.sha }}+ head-sha: ${{ github.sha }}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 88cbf61..0a58805 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,43 @@ All notable changes to **drawio-skill** are documented here. The format is basedon [Keep a Changelog](https://keepachangelog.com/), and the project followssemantic-ish versioning (the `version:` field in `skills/drawio-skill/SKILL.md`).+## [1.33.0] — 2026-07-14+### Added+- **`scripts/raster2drawio.py`** — image → editable `.drawio`. Converts a+ vision-extracted image graph (JSON: nodes with `x`/`y`/`shape`/`fill`, edges with+ `dashed`/`arrow`) — read off a whiteboard photo, legacy PNG, or Visio screenshot —+ into an editable `.drawio` honouring those coordinates; nodes missing positions fall+ back to shelling out to `autolayout.py`. Stdlib-only. Vision-extraction workflow in+ `references/derasterize.md`.+- **`scripts/buildup.py`** — turns ONE static `.drawio` into a self-contained HTML+ "build-up" player: reveals nodes/edges in topological (dependency) order, one PNG+ frame per step via the draw.io CLI, assembled into a base64-embedded+ play/pause/step/scrub viewer. `--gif` optionally exports an animated GIF (Pillow;+ skipped with a warning if absent — HTML still written). Distinct from `timelapse.py`+ (git-history animation); this animates a single diagram assembling itself.+- **`scripts/compress.py`** — big `.drawio` → boardroom executive summary. Clusters via+ deterministic pure-Python label propagation (no networkx dep), names each cluster by+ common label prefix / highest-degree member, aggregates cross-cluster edges, and emits+ a 2-page `.drawio` (exec view autolaid-out via `autolayout.py`, page 2 = the original+ diagram verbatim with `UserObject` drill-down links). Requires Graphviz `dot`.+- **`scripts/runbook.py`** — flowchart/decision-tree `.drawio` → self-contained+ click-through HTML runbook (current-step text, per-edge choice buttons, breadcrumb+ trail, Back/Restart, end-state on terminal nodes). Infers start/decision/io/process+ from shape style; start = the in-degree-0 start node. Pure XML parsing — no deps, no+ draw.io CLI needed.+- **`scripts/prdiff.py`** + **`.github/actions/drawio-diff/`** — PR diagram diff bot:+ for every `.drawio` changed between two git refs, exports base/head PNGs and a+ `drawiodiff.py`→`autolayout.py` colour-coded diff PNG via the draw.io CLI, and emits a+ pure, unit-testable Markdown report. Ships a composite GitHub Action plus an opt-in+ example workflow (`.github/workflows/drawio-pr-diff.example.yml`,+ `workflow_dispatch`-gated so it never auto-runs in this repo) that posts/updates a+ sticky PR comment. Needs git (fatal if missing); missing draw.io CLI degrades to a+ file-list-only report instead of failing. See `references/pr-bot.md`.+- Routing entries in SKILL.md's Bundled-resources table (5 rows), toolbox quick-guide+ (5 rows) + §1/§5/§6 bullets, README/README_CN example block, and 5 new per-feature+ test files. Scripts: 31 → 36; tests: 81 → 116 (`test_derasterize` 5, `test_buildup` 7,+ `test_prdiff` 8, `test_compress` 9, `test_runbook` 6).+## [1.32.0] — 2026-07-14### Added- **`scripts/ciimports.py`** — CI pipelines as diagrams. Reads GitHub Actionsdiff --git a/README.md b/README.mdindex 3509d3e..fb87b0c 100644--- a/README.md+++ b/README.md@@ -212,6 +212,21 @@ python3 scripts/heatmap.py architecture.drawio -m latency.csv --size -o hot.d# any extractor → auto-layout → editable .drawiopython3 scripts/autolayout.py graph.json -o diagram.drawio++# Image → editable .drawio — your vision extracts the graph JSON, this rebuilds it+python3 scripts/raster2drawio.py whiteboard-graph.json -o out.drawio++# Watch a diagram build itself, node by node → HTML player (+ optional GIF)+python3 scripts/buildup.py architecture.drawio --gif build.gif # → buildup.html++# Big diagram → boardroom exec summary (clustered) + click-to-drill-down to full+python3 scripts/compress.py big.drawio -o exec.drawio++# Decision-tree flowchart → click-through HTML triage runbook (no draw.io CLI needed)+python3 scripts/runbook.py triage.drawio -o triage.html++# CI: render base/head/diff PNGs + Markdown report for every .drawio a PR changed+python3 scripts/prdiff.py --base origin/main --head HEAD -o drawio-pr/report.md```| Piece | What it does |diff --git a/README_CN.md b/README_CN.mdindex 2349ef2..bb25a1a 100644--- a/README_CN.md+++ b/README_CN.md@@ -210,6 +210,21 @@ python3 scripts/heatmap.py architecture.drawio -m latency.csv --size -o hot.d# 任一提取器 → 自动布局 → 可编辑的 .drawiopython3 scripts/autolayout.py graph.json -o diagram.drawio++# 图片 → 可编辑 .drawio —— 由你的视觉提取出图结构 JSON,本脚本据此重建+python3 scripts/raster2drawio.py whiteboard-graph.json -o out.drawio++# 看一张图按节点依赖顺序逐步"画出来" → HTML 播放器(可选 GIF)+python3 scripts/buildup.py architecture.drawio --gif build.gif # → buildup.html++# 大图 → 高管摘要(聚类)+ 点击下钻回到完整图+python3 scripts/compress.py big.drawio -o exec.drawio++# 决策树流程图 → 点击式 HTML 排查手册(无需 draw.io CLI)+python3 scripts/runbook.py triage.drawio -o triage.html++# CI:为 PR 改动的每个 .drawio 渲染 base/head/diff PNG + Markdown 报告+python3 scripts/prdiff.py --base origin/main --head HEAD -o drawio-pr/report.md```| 组件 | 作用 |diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex 0bf5783..7b5f9ef 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -1,6 +1,6 @@---name: drawio-skill-version: 1.32.0+version: 1.33.0description: Use when the user requests diagrams, flowcharts, architecture diagrams, ER diagrams, UML / sequence / class diagrams, SysML / MBSE diagrams (block definition, internal block, requirement, parametric), BPMN business process diagrams, swimlane / cross-functional flowcharts, network topology, cloud architecture from Terraform or Kubernetes manifests, ML/DL model figures (Transformer/CNN/LSTM), mind maps, or any visualization. Also use proactively when explaining systems with 3+ components, complex data flows, or relationships that benefit from visual representation. Best suited when the diagram needs custom styling, rich shape vocabulary, swimlanes, or exportable images (PNG/SVG/PDF/JPG). Generates .drawio XML and exports locally via the native draw.io desktop CLI.license: MIThomepage: https://github.com/Agents365-ai/drawio-skill@@ -66,6 +66,11 @@ When the workflow references one of these, read it on demand — none of them ne| `scripts/relabel.py` | The user wants a **language variant or bulk text swap of an existing `.drawio`** (e.g. an EN diagram re-labelled in Chinese for a bilingual README) — `relabel.py diagram.drawio --extract -o labels.json` dumps every label as an identity JSON map; translate the values (keep the keys), then `relabel.py diagram.drawio --map labels.json -o diagram_cn.drawio` swaps them with layout/styles/ids untouched || `scripts/restyle.py` | The user wants to **re-theme an EXISTING `.drawio`** ("make this dark", "apply my corporate style to this diagram") — `restyle.py diagram.drawio --preset <name>` remaps every vertex fill/stroke to the preset palette by hue, applies font/extras (dark fontColor, edge color, background), and leaves layout, shapes, and edge routing untouched. Presets resolve like Step 0 (user dir, then built-ins) || `scripts/validate.py` | You generated a `.drawio` (especially via autolayout or for a large hand-placed diagram) and want a fast deterministic structural lint (dangling edges, dup/reserved ids, broken parents, overlaps) before the vision self-check. `--score` prints a readability score for comparing layout variants |+| `scripts/raster2drawio.py` | The user has an **image of a diagram** (whiteboard photo, legacy PNG, Visio screenshot) and wants an **editable `.drawio`** — read the image with your own vision, extract nodes/edges as JSON (schema + full workflow in `references/derasterize.md`), then `raster2drawio.py graph.json -o out.drawio` honours those coordinates/labels/shapes; nodes missing `x`/`y` fall back to `autolayout.py` placement |+| `scripts/buildup.py` | The user wants a diagram to **build itself node-by-node** as a video/GIF (a construction time-lapse of ONE static diagram — distinct from `timelapse.py`'s git-history animation) — `buildup.py diagram.drawio` reveals cells in topological (dependency) order into a self-contained HTML player (play/pause/step/scrub); `--gif` also exports an animated GIF (needs Pillow). Needs the draw.io CLI |+| `scripts/compress.py` | The user wants an **executive / boardroom summary of a big diagram** — collapses clusters (pure-Python label propagation, no networkx) into one labeled node each with aggregated inter-cluster edges, emitting a 2-page `.drawio` (exec view + click-to-drill-down into the full original). Claude can rename clusters semantically afterward. Needs Graphviz `dot` |+| `scripts/runbook.py` | The user wants a flowchart/decision-tree `.drawio` turned into a **click-through triage app** (on-call runbook) — `runbook.py flow.drawio` reads the XML (no draw.io CLI needed) and emits a self-contained HTML runbook: current-step text, per-edge choice buttons, breadcrumb trail, Back/Restart, end-state on terminal nodes |+| `scripts/prdiff.py` | You're setting up **automated PR diagram review** in CI — for every `.drawio` changed between two git refs it renders base/head/diff PNGs and emits a Markdown report; ships with a composite GitHub Action (`.github/actions/drawio-diff/`) that posts a sticky PR comment. See `references/pr-bot.md` |## Prerequisitesdiff --git a/skills/drawio-skill/references/derasterize.md b/skills/drawio-skill/references/derasterize.mdnew file mode 100644index 0000000..e5d3b50--- /dev/null+++ b/skills/drawio-skill/references/derasterize.md@@ -0,0 +1,54 @@+# De-rasterizing an image into an editable diagram++Goal: turn a whiteboard photo, a legacy PNG export, or a Visio screenshot+into an EDITABLE `.drawio` file. Claude's own vision does the extraction;+`scripts/raster2drawio.py` only turns the extracted JSON into XML.++## Workflow++1. **Look at the image.** Read it with your normal vision — no OCR tool+ needed. For every box/shape in the picture, note:+ - `id` — any short stable slug (`n1`, `api-gw`, …)+ - `label` — the text verbatim, exactly as written (fix obvious typos only+ if the source is clearly a typo, not a stylistic choice)+ - `x`, `y` — estimate the pixel position of the shape's top-left corner+ from the image (a rough grid read is fine; exact pixel-matching isn't+ the goal)+ - `w`, `h` — estimate width/height in pixels (defaults to 120x60 if you+ can't tell)+ - `shape` — classify: `rect`, `rounded`, `ellipse`, `rhombus`/`diamond`,+ `cylinder`, `parallelogram`, `cloud`, `hexagon`+ - `fill`, `stroke` — sample the approximate fill/border color as a hex+ value (skip if the source is plain black-and-white)++ For every arrow/line, note `source`, `target`, the label text if any+ (e.g. "Yes"/"No" on a decision arrow), whether it's `dashed`, and whether+ it has a visible `arrow` head (false for a plain connecting line).++2. **Write the JSON** to a file:+ ```json+ {"nodes": [{"id": "n1", "label": "API Gateway", "x": 120, "y": 60,+ "w": 160, "h": 60, "shape": "rect",+ "fill": "#dae8fc", "stroke": "#6c8ebf"}],+ "edges": [{"source": "n1", "target": "n2", "label": "HTTPS",+ "dashed": false, "arrow": true}]}+ ```++3. **Convert it**:+ ```bash+ python3 scripts/raster2drawio.py graph.json -o out.drawio+ ```+ If any node is missing `x`/`y`, don't guess coordinates by hand — leave+ them out and the script auto-places the whole graph via `autolayout.py`+ (Graphviz `dot` required), noting this on stderr.++4. **Continue the standard workflow**: `validate.py` for structural issues,+ export a preview PNG, then a vision self-check — compare the rendered+ PNG side-by-side against the ORIGINAL image and look for missed shapes,+ wrong labels, or misrouted edges. Fix and re-run as needed.++## Honest limitation++Hand sketches with ambiguous, crossing, or arrowhead-less connections are+genuinely ambiguous — expect one review round where you correct a+misattributed edge after seeing the first render next to the original.diff --git a/skills/drawio-skill/references/pr-bot.md b/skills/drawio-skill/references/pr-bot.mdnew file mode 100644index 0000000..5ce016a--- /dev/null+++ b/skills/drawio-skill/references/pr-bot.md@@ -0,0 +1,73 @@+# PR Diagram Bot — reviewing `.drawio` changes as pictures++Goal: in CI, for every `.drawio` file a pull request touches, render the base+version, the head version, and a colour-coded diff, then post them as a+sticky PR comment (and the job summary) so reviewers see pictures instead of+raw XML diffs.++Read this when you're setting up (or troubleshooting) automated PR diagram+review for a repo.++## Pieces++- `scripts/prdiff.py` — the script. `changed_drawios()` finds what changed+ (`git diff --name-status`); for each file it exports base/head PNGs via the+ draw.io CLI and, for modified files, chains `drawiodiff.py` ->+ `autolayout.py` -> CLI export into a third diff PNG; `render_markdown()`+ turns all of that into one Markdown report.+- `.github/actions/drawio-diff/action.yml` — a composite action that checks+ out full history, installs draw.io + Graphviz, runs `prdiff.py`, uploads+ the PNGs + report as a build artifact, writes the report to+ `$GITHUB_STEP_SUMMARY`, and posts/updates a sticky PR comment.+- `.github/workflows/drawio-pr-diff.example.yml` — a template workflow that+ wires the action to `pull_request` events. It ships as `.example.yml` and+ gated with `if: false` so it does **nothing** until you copy and adapt it+ in your own repo (see the comment at the top of that file).++## Adopting it in your own repo++1. Copy `.github/actions/drawio-diff/` and `skills/drawio-skill/` (or at+ least `scripts/prdiff.py`, `scripts/drawiodiff.py`, `scripts/autolayout.py`)+ into your repo.+2. Copy `.github/workflows/drawio-pr-diff.example.yml` to+ `.github/workflows/drawio-pr-diff.yml`, drop the `if: false` guard, and+ uncomment the `pull_request: paths: ["**/*.drawio"]` trigger.+3. Give the job `permissions: pull-requests: write` (already set in the+ example) — the sticky comment step needs it; `contents: read` covers the+ checkout.+4. Push a PR that touches a `.drawio` file and watch it run.++## Runner tooling++The draw.io desktop CLI is Electron-based, so headless CI needs the same+setup documented in `docs/CI.md` "Option A" of this repo: Graphviz (`dot`,+for `autolayout.py`) and a virtual display (`xvfb-run`). The composite action+installs both by default (latest `drawio-desktop` `.deb` + `apt-get+graphviz xvfb`); pass `skip-tool-install: true` if your runner/container+already provides `drawio` and `dot` on PATH.++If the draw.io CLI is missing (or fails), `prdiff.py` does **not** hard-fail+the run — the Markdown report still lists every changed file and its status,+just without images, with a note that image export was skipped. `git`+missing (or `--repo` not being a git repository) IS fatal, since without git+there is nothing to diff.++## How the sticky comment works++The action tags its comment body with an HTML marker+(`<!-- drawio-pr-diff-bot -->`) and, before posting, searches the PR's+existing comments (via `gh api .../issues/<n>/comments`) for one starting+with that marker. If found, it `PATCH`es that comment in place; otherwise it+creates a new one with `gh pr comment`. This keeps one running comment per PR+instead of a new comment on every push.++## Running it locally++```+python3 skills/drawio-skill/scripts/prdiff.py --base origin/main --head HEAD \+ --out-dir drawio-pr -o drawio-pr/report.md+```++`--base`/`--head` are any git refs or SHAs (`--head` defaults to `HEAD`);+`--repo` points at a different working tree (default: current directory).+Open `drawio-pr/report.md` to preview exactly what the PR comment will say.diff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.mdindex 832fdc2..ef70086 100644--- a/skills/drawio-skill/references/toolbox.md+++ b/skills/drawio-skill/references/toolbox.md@@ -38,6 +38,11 @@ exports it:| a `.drawio` | the same diagram in another language | `relabel` (extract → translate → apply) || a `.drawio` | it re-themed (dark / corporate preset) | `restyle` || a shape/icon need | the exact style string | `shapesearch` · `aiicons` (AI/LLM logos) |+| a photo/screenshot of a diagram | an editable `.drawio` | `raster2drawio` (your vision → JSON → draw.io) |+| ONE `.drawio` | it building itself, as a video/GIF | `buildup` (→ HTML player; `--gif`) |+| a big/sprawling diagram | a boardroom exec summary + drill-down | `compress` |+| a decision-tree flowchart | a click-through triage app | `runbook` (→ HTML, no CLI) |+| a PR touching `.drawio` | rendered before/after/diff for reviewers | `prdiff` (+ GitHub Action) |## 1. Author & place@@ -45,6 +50,7 @@ exports it:- **`seqlayout.py`** — participants + messages JSON → sequence diagram with computed lifelines/activation bars (no Graphviz).- **`c4.py`** — levels JSON → one multi-page `.drawio` (Context→Container→Component) with click-to-drill-down links.- **`shapesearch.py`** — search 10k+ official shapes for their exact `style=` string. **`aiicons.py`** — draw.io `image` styles for AI/LLM brand logos.+- **`raster2drawio.py`** — a vision-extracted image graph JSON (from a whiteboard photo / legacy PNG / Visio screenshot) → editable `.drawio` honouring the read coordinates; missing positions fall back to `autolayout.py`. See `references/derasterize.md`.## 2. Code → diagram@@ -75,6 +81,9 @@ The **actual** counterpart to §3 — see `references/live-infra.md`.- **`drawiodiff.py`** — diff two `.drawio` (or two live snapshots) → colour-coded graph (added=green, removed=red, changed=orange). Pairs with §4 for drift.- **`timelapse.py`** — re-run an extractor across git history → a self-contained HTML player of how the architecture grew.- **`heatmap.py`** — recolour any `.drawio` by a metrics file (CSV/JSON): each node shaded low→high on a gradient by its value (`--palette`, optional `--size`, auto legend). Turns a static architecture into a cost / latency / traffic / error-rate heat map.+- **`buildup.py`** — reveal ONE diagram's cells in dependency order (topological over its edges) → self-contained HTML player (embedded PNG frames, play/pause/step/scrub); optional `--gif`. Needs the draw.io CLI.+- **`compress.py`** — big `.drawio` → 2-page executive summary. Pure-Python label-propagation clustering (no networkx), one auto-named node per cluster with a drill-down link to the full original on page 2, aggregated cross-cluster edges. Needs Graphviz.+- **`prdiff.py`** — for every `.drawio` changed between two git refs, render base/head/`drawiodiff`-diff PNGs + a Markdown report for a PR comment; ships a composite GitHub Action (`.github/actions/drawio-diff/`). See `references/pr-bot.md`.## 6. Diagram → other formats (reverse / interop)@@ -85,6 +94,7 @@ The skill runs both directions — these turn a `.drawio` back into something el- **`drawio2pptx.py`** — → a 16:9 **PowerPoint** deck, one page per slide (needs `python-pptx`).- **`svgflow.py`** — → an **animated SVG** (edges flow as marching ants); renders on GitHub.- **`drawio2mermaid.py`** — → **Mermaid** `flowchart` text (diagrams-as-code GitHub renders).+- **`runbook.py`** — a flowchart/decision-tree → a self-contained **click-through HTML runbook** (current-step text, per-edge choice buttons, breadcrumb, Back/Restart). Reads the XML directly — no draw.io CLI needed.## 7. Utilities & qualitydiff --git a/skills/drawio-skill/scripts/buildup.py b/skills/drawio-skill/scripts/buildup.pynew file mode 100644index 0000000..cd473dd--- /dev/null+++ b/skills/drawio-skill/scripts/buildup.py@@ -0,0 +1,331 @@+#!/usr/bin/env python3+"""Animate a static .drawio building itself, node by node -> HTML player.++Reveals a diagram's cells incrementally in dependency order — topological over+its edges, so a source always appears before the targets it points to, with+ties (and any leftover cycle members) falling back to document order — and+assembles a self-contained HTML player (base64-embedded PNG frames, play /+pause / step / scrub) of the diagram constructing itself, like a build+time-lapse.++ python3 buildup.py architecture.drawio+ # -> architecture.drawio's directory / buildup.html+ python3 buildup.py architecture.drawio -o build.html --gif build.gif++Each frame is a temp copy of the diagram with not-yet-revealed cells removed+from <root> (not opacity — draw.io ignores that on headless export). An edge+is only shown once BOTH its endpoints are revealed. Container/group cells are+always shown (only leaf vertices and the edges between them build up one step+at a time). The page size is pinned to the FULL diagram's bounding box on+every frame so nothing jumps around as cells appear. Needs the draw.io CLI;+`--gif` additionally needs Pillow (skipped with a warning if absent — the+HTML is written regardless).++Usage: python3 buildup.py <file.drawio> [-o out.html] [--gif out.gif]+ [--fps N] [--hold N] [--keep-frames]+"""+import argparse+import base64+import copy+import io+import json+import os+import shutil+import subprocess+import sys+import tempfile+import xml.etree.ElementTree as ET+++def parse_page(path):+ """First page of a .drawio -> (tree, cells).++ cells: list of dicts {id, el, vertex, edge, parent, source, target, style,+ relative, x, y, w, h} in document order. `el` is the TOP-LEVEL <root>+ child (mxCell / UserObject / object) so it can be removed directly;+ vertex/edge/geometry attributes are read off the inner mxCell for wrapped+ cells (UserObject/object), same unwrapping as drawiodiff.parse().+ """+ try:+ tree = ET.parse(path)+ except (ET.ParseError, OSError) as exc:+ sys.exit(f"error: cannot parse {path}: {exc}")+ pages = tree.getroot().findall("diagram")+ if not pages:+ sys.exit(f"error: no <diagram> pages in {path}")+ if len(pages) > 1:+ sys.stderr.write(f"warning: {path} has {len(pages)} pages, animating the first only\n")+ model = pages[0].find("mxGraphModel")+ root = model.find("root") if model is not None else None+ if root is None:+ sys.exit(f"error: {path}: page is compressed, cannot buildup")++ cells = []+ for el in root:+ inner = el if el.tag == "mxCell" else el.find("mxCell")+ if inner is None:+ continue+ g = inner.find("mxGeometry")+ relative = g is not None and g.get("relative") == "1"+ if g is not None and not relative and g.get("x") is not None and g.get("width") is not None:+ x, y = float(g.get("x")), float(g.get("y", 0))+ w, h = float(g.get("width")), float(g.get("height", 0))+ else:+ x = y = w = h = None+ cells.append({+ "id": el.get("id"), "el": el,+ "vertex": inner.get("vertex") == "1", "edge": inner.get("edge") == "1",+ "parent": inner.get("parent"), "source": inner.get("source"),+ "target": inner.get("target"), "style": inner.get("style") or "",+ "relative": relative, "x": x, "y": y, "w": w, "h": h,+ })+ return tree, cells+++def classify(cells):+ """cells -> (leaf_vertex_ids in doc order, container_ids, edges[(id,source,target)]).++ Mirrors drawiodiff.parse(): a vertex that is some other cell's `parent` is+ a container/group (always shown, never an individual reveal step); an+ edge-label sub-cell (relative geometry or an `edgeLabel` style) is neither+ a node nor revealed on its own — it rides along once its parent edge is.+ """+ parents = {c["parent"] for c in cells if c["parent"]}+ leaves, containers, edges = [], set(), []+ for c in cells:+ if c["edge"]:+ if c["source"] and c["target"]:+ edges.append((c["id"], c["source"], c["target"]))+ elif c["vertex"]:+ if c["relative"] or "edgeLabel" in c["style"]:+ continue+ if c["id"] in parents:+ containers.add(c["id"])+ else:+ leaves.append(c["id"])+ return leaves, containers, edges+++def bounding_box(cells, margin=40):+ """(width, height) of the full diagram from every absolute cell geometry,+ with a margin — used to pin pageWidth/pageHeight so frames don't jump."""+ xs = [c["x"] + c["w"] for c in cells if c["x"] is not None]+ ys = [c["y"] + c["h"] for c in cells if c["y"] is not None]+ if not xs or not ys:+ return 850, 1100+ return int(max(xs)) + margin, int(max(ys)) + margin+++def reveal_order(node_ids, edges):+ """Kahn topological order over node_ids given directed (source, target)+ edges. Ties among ready nodes, and any nodes left over from a cycle, fall+ back to document order (node_ids' input order)."""+ doc = list(dict.fromkeys(node_ids)) # de-dup, keep doc order+ idx = {nid: i for i, nid in enumerate(doc)}+ adj = {nid: [] for nid in doc}+ indeg = {nid: 0 for nid in doc}+ for s, t in edges:+ if s in idx and t in idx and s != t:+ adj[s].append(t)+ indeg[t] += 1++ import heapq+ ready = list({idx[n] for n in doc if indeg[n] == 0})+ heapq.heapify(ready)+ order, seen = [], set()+ while ready:+ nid = doc[heapq.heappop(ready)]+ seen.add(nid)+ order.append(nid)+ for nxt in adj[nid]:+ indeg[nxt] -= 1+ if indeg[nxt] == 0:+ heapq.heappush(ready, idx[nxt])+ for nid in doc: # cycle remnants, document order+ if nid not in seen:+ order.append(nid)+ return order+++def reveal_steps(node_order, edges):+ """-> (node_step {id: int}, edge_step {edge_id: int}). An edge's step is+ the LATER of its two endpoints' steps, so it only appears once both are+ revealed (endpoints outside node_order, e.g. a container, count as step 0+ — already shown)."""+ node_step = {nid: i for i, nid in enumerate(node_order)}+ edge_step = {eid: max(node_step.get(s, 0), node_step.get(t, 0)) for eid, s, t in edges}+ return node_step, edge_step+++def label_of(el):+ """Visible text of a root child (mxCell or UserObject/object wrapper)."""+ if el.tag == "mxCell":+ return el.get("value") or el.get("id") or ""+ return el.get("label") or el.get("value") or el.get("id") or ""+++def build_html(frames, title):+ """Self-contained HTML player. frames: [(png_bytes, label, step, total)]."""+ data = [{"img": "data:image/png;base64," + base64.b64encode(png).decode(),+ "label": label, "step": step, "total": total}+ for png, label, step, total in frames]+ payload = json.dumps(data).replace("</", "<\\/")+ return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>{title}</title><style>+:root{{color-scheme:light dark}}+*{{box-sizing:border-box}}+body{{margin:0;font:14px/1.5 system-ui,-apple-system,Segoe UI,sans-serif;+background:#f6f7f9;color:#1a1a1a}}+@media(prefers-color-scheme:dark){{body{{background:#15171a;color:#e8e8e8}}}}+header{{padding:16px 20px 4px}}h1{{margin:0;font-size:17px;font-weight:600}}+main{{max-width:1100px;margin:0 auto;padding:8px 16px 28px}}+#stage{{background:#fff;border:1px solid #0001;border-radius:10px;+min-height:60vh;display:flex;align-items:center;justify-content:center;padding:12px}}+@media(prefers-color-scheme:dark){{#stage{{background:#1e2226;border-color:#fff2}}}}+#stage img{{max-width:100%;max-height:74vh;object-fit:contain}}+.cap{{display:flex;gap:14px;flex-wrap:wrap;align-items:baseline;+padding:12px 4px 6px;color:#556;font-size:13px}}+@media(prefers-color-scheme:dark){{.cap{{color:#9aa}}}}+.cap .lbl{{color:#1a1a1a;font-weight:600}}+@media(prefers-color-scheme:dark){{.cap .lbl{{color:#e8e8e8}}}}+.bar{{height:6px;border-radius:3px;background:#0d99ff;transition:width .3s}}+.barwrap{{height:6px;background:#0001;border-radius:3px;margin:2px 4px 12px}}+.ctl{{display:flex;gap:10px;align-items:center;padding:4px}}+button{{font:inherit;padding:6px 12px;border:1px solid #0002;border-radius:8px;+background:#fff;cursor:pointer;color:inherit}}+@media(prefers-color-scheme:dark){{button{{background:#262b31;border-color:#fff2}}}}+button:hover{{border-color:#0d99ff}}+input[type=range]{{flex:1;accent-color:#0d99ff}}+</style></head><body>+<header><h1>{title}</h1></header>+<main>+<div id="stage"><img id="img" alt="build-up frame"></div>+<div class="cap">+ <span><b id="idx"></b></span>+ <span>+ <span class="lbl" id="label"></span></span>+</div>+<div class="barwrap"><div class="bar" id="bar"></div></div>+<div class="ctl">+ <button id="prev">‹ Prev</button>+ <button id="play">▶ Play</button>+ <button id="next">Next ›</button>+ <input type="range" id="scrub" min="0" value="0">+</div>+</main>+<script>+const F={payload};+let i=0,timer=null;+const $=id=>document.getElementById(id);+$("scrub").max=F.length-1;+function show(k){{+ i=(k+F.length)%F.length;const f=F[i];+ $("img").src=f.img;$("idx").textContent=`Step ${{f.step}} / ${{f.total}}`;+ $("label").textContent=f.label;+ $("bar").style.width=(6+94*f.step/f.total)+"%";$("scrub").value=i;+}}+function stop(){{clearInterval(timer);timer=null;$("play").textContent="▶ Play";}}+$("prev").onclick=()=>{{stop();show(i-1);}};+$("next").onclick=()=>{{stop();show(i+1);}};+$("scrub").oninput=e=>{{stop();show(+e.target.value);}};+$("play").onclick=()=>{{+ if(timer){{stop();return;}}+ $("play").textContent="⏸ Pause";+ timer=setInterval(()=>{{if(i>=F.length-1){{show(0);}}else{{show(i+1);}}}},700);+}};+show(0);+</script></body></html>"""+++def make_gif(pngs, out_path, fps, hold):+ """Assemble PNG frame bytes into an animated GIF via Pillow. Skips with a+ stderr warning (not fatal) if Pillow isn't installed."""+ try:+ from PIL import Image+ except ImportError:+ sys.stderr.write("warning: Pillow not installed, skipping --gif (pip install Pillow)\n")+ return+ frames = [Image.open(io.BytesIO(p)).convert("RGB") for p in pngs]+ duration = [int(1000 / fps)] * (len(frames) - 1) + [int(hold * 1000)]+ frames[0].save(out_path, save_all=True, append_images=frames[1:],+ duration=duration, loop=0)+ sys.stderr.write(f"wrote {out_path} ({len(frames)} frames)\n")+++def main():+ ap = argparse.ArgumentParser(description="Animate a .drawio building itself -> self-contained HTML player.")+ ap.add_argument("file", help="input .drawio (uncompressed)")+ ap.add_argument("-o", "--output", help="output .html (default: buildup.html alongside input)")+ ap.add_argument("--gif", help="also assemble frames into an animated GIF (needs Pillow)")+ ap.add_argument("--fps", type=float, default=2.0, help="GIF frames per second (default 2)")+ ap.add_argument("--hold", type=float, default=1.5, help="seconds to hold the final GIF frame")+ ap.add_argument("--keep-frames", action="store_true", help="also write the PNG frames next to the output")+ args = ap.parse_args()++ if not os.path.isfile(args.file):+ sys.exit(f"error: {args.file} not found")+ if not shutil.which("drawio"):+ sys.exit("error: draw.io CLI not found on PATH (is the draw.io CLI installed?)")++ tree, cells = parse_page(args.file)+ leaves, containers, edge_list = classify(cells)+ if not leaves:+ sys.exit(f"error: no revealable vertices found in {args.file}")++ order = reveal_order(leaves, [(s, t) for _, s, t in edge_list])+ node_step, edge_step = reveal_steps(order, edge_list)+ width, height = bounding_box(cells)+ labels = {c["id"]: label_of(c["el"]) for c in cells}+ n_total = len(order)++ out = args.output or os.path.join(+ os.path.dirname(os.path.abspath(args.file)) or ".", "buildup.html")++ frames = []+ with tempfile.TemporaryDirectory() as tmp:+ for k in range(n_total):+ revealed_nodes = set(order[:k + 1])+ revealed_edges = {eid for eid, _, _ in edge_list if edge_step[eid] <= k}+ keep = {"0", "1"} | containers | revealed_nodes | revealed_edges+ keep |= {c["id"] for c in cells if c["id"] not in keep and c["parent"] in keep}++ frame_tree = copy.deepcopy(tree)+ model = frame_tree.getroot().find("diagram").find("mxGraphModel")+ model.set("pageWidth", str(width))+ model.set("pageHeight", str(height))+ froot = model.find("root")+ for child in list(froot):+ if child.get("id") not in keep:+ froot.remove(child)++ src = os.path.join(tmp, f"step{k:03d}.drawio")+ frame_tree.write(src, encoding="utf-8", xml_declaration=False)+ png_path = os.path.join(tmp, f"step{k:03d}.png")+ r = subprocess.run(["drawio", "-x", "-f", "png", "--page-index", "1",+ "--width", "2000", "-o", png_path, src], capture_output=True)+ if r.returncode != 0 or not os.path.exists(png_path):+ sys.stderr.write(f"warning: step {k + 1}/{n_total} export failed — skipped\n")+ continue+ with open(png_path, "rb") as f:+ png = f.read()+ label = labels.get(order[k], order[k])+ frames.append((png, label, k + 1, n_total))+ if args.keep_frames:+ with open(f"{os.path.splitext(out)[0]}-frame{k + 1:03d}.png", "wb") as f:+ f.write(png)+ sys.stderr.write(f"[{k + 1}/{n_total}] revealed {label!r}\n")++ if not frames:+ sys.exit("error: no frames exported (is the draw.io CLI installed?)")++ title = os.path.splitext(os.path.basename(args.file))[0] + " — build-up"+ with open(out, "w", encoding="utf-8") as f:+ f.write(build_html(frames, title))+ sys.stderr.write(f"wrote {out} ({len(frames)} frames)\n")++ if args.gif:+ make_gif([f[0] for f in frames], args.gif, args.fps, args.hold)+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/compress.py b/skills/drawio-skill/scripts/compress.pynew file mode 100644index 0000000..ac4ce49--- /dev/null+++ b/skills/drawio-skill/scripts/compress.py@@ -0,0 +1,257 @@+#!/usr/bin/env python3+"""Collapse a big .drawio into a boardroom-friendly executive summary.++Detects clusters in a large diagram with a deterministic pure-Python label+propagation pass (no networkx), replaces each cluster with ONE labeled group+node, keeps aggregated inter-cluster edges, and emits a 2-page .drawio: page 1+is the executive view (auto-laid-out via autolayout.py), page 2 is the+original full diagram, copied verbatim. Each executive node is wrapped in a+draw.io UserObject `data:page/id,...` drill-down link to page 2, so clicking+"Auth (5)" jumps straight into the full detail.++Community detection is unsupervised — it finds however many clusters the+graph naturally has; `--clusters` is only a soft hint and may be ignored.+Clusters are named after the longest common leading token shared by their+members' labels (falling back to the highest-degree member's label), with the+member count appended, e.g. "Auth (5)". Rename them by hand afterward for a+more semantic label — label propagation does not know what your system does.++Requires Graphviz `dot` on PATH (shells out to autolayout.py to place the+executive nodes).++ python3 compress.py big-system.drawio -o exec-view.drawio++Usage: python3 compress.py <diagram.drawio> [-o out.drawio] [--clusters N]+"""+import argparse+import copy+import json+import os+import re+import subprocess+import sys+import tempfile+import xml.etree.ElementTree as ET++HERE = os.path.dirname(os.path.abspath(__file__))+++def parse(path):+ """Return (nodes, edges) for a .drawio: nodes {id: (label, style)} for leaf+ vertices, edges {(source_id, target_id)}. Cells are flattened across pages;+ UserObject/object wrappers are unwrapped (id on the wrapper, cell inside).+ Copied from drawiodiff.parse() — see SHARED CONVENTIONS."""+ try:+ tree = ET.parse(path)+ except (ET.ParseError, OSError) as exc:+ sys.exit(f"error: cannot parse {path}: {exc}")+ pages = tree.getroot().findall("diagram") or [tree.getroot()]+ cells, labels = [], {}+ for page in pages:+ model = page.find("mxGraphModel")+ root = model.find("root") if model is not None else None+ if root is None:+ if (page.text or "").strip():+ sys.stderr.write(f"warning: {path}: a page is compressed, skipped\n")+ continue+ for child in root:+ if child.tag == "mxCell":+ cells.append(child)+ labels[child.get("id")] = child.get("value") or ""+ elif child.tag in ("UserObject", "object"):+ inner = child.find("mxCell")+ if inner is not None:+ inner.set("id", child.get("id", ""))+ cells.append(inner)+ labels[child.get("id")] = child.get("label") or child.get("value") or ""+ parents = {c.get("parent") for c in cells} # ids that have children+ nodes, edges = {}, set()+ for c in cells:+ cid = c.get("id")+ if c.get("edge") == "1":+ s, t = c.get("source"), c.get("target")+ if s and t:+ edges.add((s, t))+ elif c.get("vertex") == "1" and cid not in parents: # leaf vertices only+ if "edgeLabel" in (c.get("style") or ""):+ continue+ g = c.find("mxGeometry")+ if g is not None and g.get("relative") == "1": # edge-label child+ continue+ nodes[cid] = (labels.get(cid, ""), c.get("style") or "")+ return nodes, edges+++def label_propagation(node_ids, edges, max_passes=20):+ """Deterministic pure-Python label propagation for community detection.++ Edges are treated as undirected for clustering. Each pass computes every+ node's new label synchronously from the PREVIOUS pass's labels (most+ frequent label among neighbours, ties -> smallest label), then applies+ them all at once — this keeps a thin bridge between two dense clusters+ from cascading a merge within a single pass. Stops early once no label+ changes, else after `max_passes`. Returns {node_id: community_label}.+ """+ nodes = sorted(set(node_ids))+ neighbours = {n: set() for n in nodes}+ for s, t in edges:+ if s in neighbours and t in neighbours and s != t:+ neighbours[s].add(t)+ neighbours[t].add(s)+ labels = {n: n for n in nodes}+ for _ in range(max_passes):+ new_labels = {}+ for n in nodes:+ if not neighbours[n]:+ new_labels[n] = labels[n]+ continue+ counts = {}+ for nb in neighbours[n]:+ lbl = labels[nb]+ counts[lbl] = counts.get(lbl, 0) + 1+ best = max(counts.values())+ new_labels[n] = min(lbl for lbl, c in counts.items() if c == best)+ if new_labels == labels:+ break+ labels = new_labels+ return labels+++def compute_degree(node_ids, edges):+ """Undirected degree per node (used as the naming tiebreak)."""+ degree = {n: 0 for n in node_ids}+ for s, t in edges:+ if s in degree:+ degree[s] += 1+ if t in degree:+ degree[t] += 1+ return degree+++def aggregate_edges(edges, community_of):+ """Roll original edges up to inter-community edges: for every edge whose+ endpoints fall in two different communities, count crossings by+ (source_community, target_community) and dedupe into one entry per pair.+ Same-community (internal) edges are dropped. Returns+ {(src_community, tgt_community): crossing_count}."""+ counts = {}+ for s, t in edges:+ cs, ct = community_of.get(s), community_of.get(t)+ if cs is None or ct is None or cs == ct:+ continue+ counts[(cs, ct)] = counts.get((cs, ct), 0) + 1+ return counts+++def cluster_name(member_ids, node_labels, degree):+ """Heuristic community name: the longest common leading token shared by+ every member's label (split on whitespace), else the highest-degree+ member's label. The member count is appended, e.g. "Auth (5)"."""+ token_lists = [str(node_labels.get(m, m)).split() for m in member_ids]+ common = []+ if token_lists and all(token_lists):+ for tokens in zip(*token_lists):+ if len(set(tokens)) == 1:+ common.append(tokens[0])+ else:+ break+ if common:+ base = " ".join(common)+ else:+ top = max(member_ids, key=lambda m: (degree.get(m, 0), m))+ base = node_labels.get(top) or top+ return f"{base} ({len(member_ids)})"+++def layout_exec_page(graph):+ """Shell out to autolayout.py to place the executive nodes; return the+ rendered <diagram>...</diagram> page, renamed to a friendlier id/title."""+ with tempfile.TemporaryDirectory() as d:+ gpath = os.path.join(d, "exec.json")+ with open(gpath, "w", encoding="utf-8") as f:+ json.dump(graph, f)+ opath = os.path.join(d, "exec.drawio")+ r = subprocess.run(+ [sys.executable, os.path.join(HERE, "autolayout.py"), gpath, "-o", opath],+ capture_output=True, text=True,+ )+ if r.returncode != 0 or not os.path.exists(opath):+ sys.exit(f"error: autolayout failed: {r.stderr.strip()}")+ with open(opath, encoding="utf-8") as f:+ xml = f.read()+ m = re.search(r"(<diagram\b.*?</diagram>)", xml, re.S)+ if not m:+ sys.exit("error: autolayout produced no page")+ page = m.group(1).replace('id="autolayout"', 'id="exec-view"', 1)+ page = page.replace('name="Page-1"', 'name="Executive View"', 1)+ return page + "\n"+++def copy_original_page(path, page2_id):+ """Copy the source's first page verbatim (cells untouched) into a new+ <diagram> with id=page2_id, so exec-node drill-down links resolve to it."""+ try:+ tree = ET.parse(path)+ except (ET.ParseError, OSError) as exc:+ sys.exit(f"error: cannot parse {path}: {exc}")+ pages = tree.getroot().findall("diagram") or [tree.getroot()]+ page = copy.deepcopy(pages[0])+ if page.find("mxGraphModel/root") is None:+ sys.exit(f"error: {path}: page is compressed (no <root>), cannot copy verbatim")+ page.set("id", page2_id)+ page.set("name", "Full Diagram")+ return ET.tostring(page, encoding="unicode") + "\n"+++def main():+ ap = argparse.ArgumentParser(+ description="Collapse a big .drawio into an executive-summary view with drill-down.")+ ap.add_argument("input", help="source .drawio")+ ap.add_argument("-o", "--output", help="output .drawio path (default: stdout)")+ ap.add_argument("--clusters", type=int,+ help="soft hint for cluster count; label propagation picks the "+ "count automatically and may ignore this")+ args = ap.parse_args()++ if args.clusters:+ sys.stderr.write("note: --clusters is a soft hint; label propagation "+ "determines the actual cluster count automatically\n")++ nodes, edges = parse(args.input)+ if not nodes:+ sys.exit(f"error: no leaf vertices found in {args.input}")++ community_of = label_propagation(nodes.keys(), edges)+ communities = {}+ for nid in sorted(nodes):+ communities.setdefault(community_of[nid], []).append(nid)++ degree = compute_degree(nodes.keys(), edges)+ node_labels = {nid: label for nid, (label, _style) in nodes.items()}+ names = {c: cluster_name(members, node_labels, degree) for c, members in communities.items()}++ crossings = aggregate_edges(edges, community_of)++ page2_id = "full-diagram"+ exec_nodes = [{"id": f"c_{c}", "label": names[c], "link": f"data:page/id,{page2_id}"}+ for c in communities]+ exec_edges = [{"source": f"c_{s}", "target": f"c_{t}", "label": str(n) if n > 1 else ""}+ for (s, t), n in sorted(crossings.items())]+ exec_graph = {"direction": "TB", "nodes": exec_nodes, "edges": exec_edges}++ page1 = layout_exec_page(exec_graph)+ page2 = copy_original_page(args.input, page2_id)+ xml = "<mxfile>\n" + page1 + page2 + "</mxfile>\n"++ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(xml)+ sys.stderr.write(f"wrote {args.output} ({len(nodes)} nodes -> "+ f"{len(communities)} clusters)\n")+ else:+ sys.stdout.write(xml)+ sys.stderr.write(f"{len(nodes)} nodes -> {len(communities)} clusters\n")+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/prdiff.py b/skills/drawio-skill/scripts/prdiff.pynew file mode 100644index 0000000..ae0fd83--- /dev/null+++ b/skills/drawio-skill/scripts/prdiff.py@@ -0,0 +1,191 @@+#!/usr/bin/env python3+"""Render base/head/diff PNGs for every .drawio changed between two git refs.++For each `.drawio` that differs between `--base` and `--head`, exports the+base and head pages as PNGs via the draw.io CLI, and — for files present on+both sides — chains `drawiodiff.py` -> `autolayout.py` -> CLI export into a+third colour-coded diff PNG. Added/removed files just get the one side that+exists. Emits a Markdown report with one section per changed file (status ++image links) and a summary count, suitable for a PR comment or CI job+summary; pair with `.github/actions/drawio-diff/`.++ python3 prdiff.py --base origin/main --head HEAD -o drawio-pr/report.md++Missing draw.io CLI degrades gracefully: the Markdown still lists every+changed file, just without images (a review comment listing the files is+still useful). Missing git, or `--repo` not a git repository, is fatal.++Usage: python3 prdiff.py --base <ref> [--head <ref>] [--repo <dir>] [--out-dir <dir>] [-o report.md]+"""+import argparse+import os+import shutil+import subprocess+import sys+import tempfile++HERE = os.path.dirname(os.path.abspath(__file__))+++def changed_drawios(base, head, repo):+ """List of (path, status) for .drawio files that differ between base and head.++ status is "added", "removed", or "modified" (renames/copies count as+ modified, keyed on the new path). Shells to `git diff --name-status`.+ """+ try:+ r = subprocess.run(+ ["git", "-C", repo, "diff", "--name-status", f"{base}..{head}", "--", "*.drawio"],+ capture_output=True, text=True)+ except FileNotFoundError:+ sys.exit("error: not a git repo / git not found (git not on PATH)")+ if r.returncode != 0:+ sys.exit(f"error: not a git repo / git not found: {r.stderr.strip()}")+ entries = []+ for line in r.stdout.splitlines():+ if not line.strip():+ continue+ parts = line.split("\t")+ code, path = parts[0], parts[-1]+ status = "added" if code.startswith("A") else "removed" if code.startswith("D") else "modified"+ entries.append((path, status))+ return entries+++def git_show_file(repo, ref, path, dest):+ """Write the blob at ref:path (in repo) to dest. False if it doesn't exist there."""+ r = subprocess.run(["git", "-C", repo, "show", f"{ref}:{path}"], capture_output=True)+ if r.returncode != 0:+ return False+ with open(dest, "wb") as f:+ f.write(r.stdout)+ return True+++def export_png(src_drawio, out_png):+ """CLI-export page 1 of src_drawio to out_png. True on success."""+ r = subprocess.run(["drawio", "-x", "-f", "png", "--page-index", "1", "-o", out_png, src_drawio],+ capture_output=True)+ return r.returncode == 0 and os.path.exists(out_png)+++def export_diff_png(base_drawio, head_drawio, out_png, tmp):+ """drawiodiff.py -> autolayout.py -> CLI export a coloured diff PNG. True on success."""+ diff_json = os.path.join(tmp, "diff.json")+ diff_drawio = os.path.join(tmp, "diff.drawio")+ r1 = subprocess.run([sys.executable, os.path.join(HERE, "drawiodiff.py"),+ base_drawio, head_drawio, "-o", diff_json], capture_output=True)+ if r1.returncode != 0 or not os.path.exists(diff_json):+ return False+ r2 = subprocess.run([sys.executable, os.path.join(HERE, "autolayout.py"),+ diff_json, "-o", diff_drawio], capture_output=True)+ if r2.returncode != 0 or not os.path.exists(diff_drawio):+ return False+ return export_png(diff_drawio, out_png)+++def build_entry(repo, base, head, path, status, out_dir, drawio_available):+ """One render_markdown entry: fetch both sides, export whatever PNGs it can."""+ entry = {"path": path, "status": status}+ if not drawio_available:+ entry["skipped"] = True+ return entry+ slug = path.replace("/", "__")+ with tempfile.TemporaryDirectory() as tmp:+ base_drawio = os.path.join(tmp, "base.drawio")+ head_drawio = os.path.join(tmp, "head.drawio")+ have_base = git_show_file(repo, base, path, base_drawio)+ have_head = git_show_file(repo, head, path, head_drawio)+ if have_base:+ p = os.path.join(out_dir, f"{slug}.base.png")+ if export_png(base_drawio, p):+ entry["base_png"] = p+ if have_head:+ p = os.path.join(out_dir, f"{slug}.head.png")+ if export_png(head_drawio, p):+ entry["head_png"] = p+ if have_base and have_head:+ p = os.path.join(out_dir, f"{slug}.diff.png")+ if export_diff_png(base_drawio, head_drawio, p, tmp):+ entry["diff_png"] = p+ return entry+++def render_markdown(entries, out_dir):+ """Pure: Markdown PR report from prdiff entries. No I/O, no CLI.++ entries: list of {"path", "status", "base_png"?, "head_png"?, "diff_png"?,+ "skipped"?} — image paths (if any) are made relative to out_dir for the+ Markdown links. "skipped" means the draw.io CLI was unavailable.+ """+ counts = {"added": 0, "removed": 0, "modified": 0}+ for e in entries:+ counts[e["status"]] = counts.get(e["status"], 0) + 1+ lines = [+ "# draw.io diagram changes",+ "",+ f"{len(entries)} file(s) changed: +{counts.get('added', 0)} added, "+ f"-{counts.get('removed', 0)} removed, ~{counts.get('modified', 0)} modified",+ ]+ if not entries:+ lines.append("")+ lines.append("No `.drawio` files changed.")+ return "\n".join(lines) + "\n"++ def rel(png):+ return os.path.relpath(png, out_dir).replace(os.sep, "/") if png else None++ for e in entries:+ lines.append("")+ lines.append(f"## {e['path']} ({e['status']})")+ if e.get("skipped"):+ lines.append("")+ lines.append("_draw.io CLI not available — images skipped._")+ continue+ base_r, head_r, diff_r = rel(e.get("base_png")), rel(e.get("head_png")), rel(e.get("diff_png"))+ lines.append("")+ if base_r:+ lines.append(f"")+ if head_r:+ lines.append(f"")+ if diff_r:+ lines.append(f"")+ if not (base_r or head_r or diff_r):+ lines.append("_no image produced._")+ return "\n".join(lines) + "\n"+++def main():+ ap = argparse.ArgumentParser(description="Render PNGs + a Markdown report for .drawio files "+ "changed between two git refs.")+ ap.add_argument("--base", required=True, help="base git ref/sha")+ ap.add_argument("--head", default="HEAD", help="head git ref/sha (default HEAD)")+ ap.add_argument("--repo", default=".", help="path to the git repo (default: current directory)")+ ap.add_argument("--out-dir", default="drawio-pr", help="directory for exported PNGs (default: ./drawio-pr)")+ ap.add_argument("-o", "--output", help="write the Markdown report here (default: stdout)")+ args = ap.parse_args()++ changed = changed_drawios(args.base, args.head, args.repo)+ if not changed:+ sys.stderr.write("no .drawio files changed\n")++ drawio_available = shutil.which("drawio") is not None+ if not drawio_available and changed:+ sys.stderr.write("warning: draw.io CLI not found - image export skipped, "+ "Markdown will list files only (is the draw.io CLI installed?)\n")+ os.makedirs(args.out_dir, exist_ok=True)++ entries = [build_entry(args.repo, args.base, args.head, path, status, args.out_dir, drawio_available)+ for path, status in changed]+ report = render_markdown(entries, args.out_dir)++ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(report)+ sys.stderr.write(f"wrote {args.output}\n")+ else:+ sys.stdout.write(report)+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/raster2drawio.py b/skills/drawio-skill/scripts/raster2drawio.pynew file mode 100644index 0000000..bb88615--- /dev/null+++ b/skills/drawio-skill/scripts/raster2drawio.py@@ -0,0 +1,196 @@+#!/usr/bin/env python3+"""De-rasterize an image-extracted graph (JSON) into an editable .drawio.++Turns a whiteboard photo, legacy PNG, or Visio screenshot into an editable+diagram: Claude's own vision reads the image and extracts a JSON description+of the nodes/edges (the workflow is documented in+references/derasterize.md); this script turns that JSON into `.drawio` XML,+honoring the coordinates, labels, shapes, and colors Claude read off the+image.++ python3 raster2drawio.py graph.json -o out.drawio++Input JSON:+ {"nodes": [{"id": "n1", "label": "API Gateway", "x": 120, "y": 60,+ "w": 160, "h": 60, "shape": "rect",+ "fill": "#dae8fc", "stroke": "#6c8ebf"},+ {"id": "n2", "label": "Auth DB", "x": 360, "y": 60,+ "shape": "cylinder"}],+ "edges": [{"source": "n1", "target": "n2", "label": "HTTPS",+ "dashed": false, "arrow": true}]}++Only "id" is required per node; label defaults to id, w/h default to+120/60, shape defaults to "rect" (choices: rect, rounded, ellipse,+rhombus/diamond, cylinder, parallelogram, cloud, hexagon), fill/stroke+default to the skill's palette blue. Edge "arrow" defaults to true+(endArrow=none when false); "dashed" defaults to false.++If ANY node is missing x or y, positions are not guessed: the graph is+handed to autolayout.py (shelled out, requires Graphviz `dot`) to place it,+and a note is written to stderr.++Usage: python3 raster2drawio.py <graph.json|-> [-o out.drawio]+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+from xml.sax.saxutils import escape++DEFAULT_W, DEFAULT_H = 120, 60+DEFAULT_FILL, DEFAULT_STROKE = "#dae8fc", "#6c8ebf"+SHAPES = {+ "rect": "whiteSpace=wrap;html=1;",+ "rounded": "rounded=1;whiteSpace=wrap;html=1;",+ "ellipse": "ellipse;whiteSpace=wrap;html=1;",+ "rhombus": "rhombus;whiteSpace=wrap;html=1;",+ "diamond": "rhombus;whiteSpace=wrap;html=1;",+ "cylinder": "shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;size=15;",+ "parallelogram": "shape=parallelogram;whiteSpace=wrap;html=1;",+ "cloud": "ellipse;shape=cloud;whiteSpace=wrap;html=1;",+ "hexagon": "shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;",+}+EDGE_BASE = "edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;"+++def attr(value):+ # Newlines in labels become 
 so draw.io renders a line break (a raw+ # newline inside an XML attribute is normalized to a space by parsers).+ return escape(str(value), {'"': """, "\n": "
"})+++def node_style(node):+ base = SHAPES.get(node.get("shape", "rect"), SHAPES["rect"])+ fill = node.get("fill", DEFAULT_FILL)+ stroke = node.get("stroke", DEFAULT_STROKE)+ return f"{base}fillColor={fill};strokeColor={stroke};"+++def edge_style(edge):+ style = EDGE_BASE+ if edge.get("dashed"):+ style += "dashed=1;"+ if edge.get("arrow") is False:+ style += "endArrow=none;"+ return style+++def to_drawio(nodes, edges):+ """Direct build: every node already has x/y. Mirrors autolayout.py's+ to_drawio() string-building, without the dot layout pass."""+ cells = []+ for node in nodes:+ w, h = node.get("w", DEFAULT_W), node.get("h", DEFAULT_H)+ cells.append(+ f' <mxCell id="{attr(node["id"])}" value="{attr(node.get("label", node["id"]))}" '+ f'style="{attr(node_style(node))}" vertex="1" parent="1">\n'+ f' <mxGeometry x="{node["x"]}" y="{node["y"]}" width="{w}" height="{h}" as="geometry"/>\n'+ f" </mxCell>"+ )+ for i, edge in enumerate(edges):+ cells.append(+ f' <mxCell id="e{i}" value="{attr(edge.get("label", ""))}" '+ f'style="{attr(edge_style(edge))}" edge="1" parent="1" '+ f'source="{attr(edge["source"])}" target="{attr(edge["target"])}">\n'+ f' <mxGeometry relative="1" as="geometry"/>\n'+ f" </mxCell>"+ )+ return (+ "<mxfile>\n"+ ' <diagram id="raster2drawio" name="Page-1">\n'+ ' <mxGraphModel dx="800" dy="600" grid="1" gridSize="10" guides="1" '+ 'tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" '+ 'pageWidth="850" pageHeight="1100" math="0" shadow="0">\n'+ " <root>\n"+ ' <mxCell id="0"/>\n'+ ' <mxCell id="1" parent="0"/>\n'+ + "\n".join(cells)+ + "\n </root>\n </mxGraphModel>\n </diagram>\n</mxfile>\n"+ )+++def build_autolayout_graph(nodes, edges):+ """Same graph, in autolayout.py's input shape (positions dropped —+ dot will compute fresh ones for every node)."""+ return {+ "direction": "TB",+ "nodes": [+ {"id": n["id"], "label": n.get("label", n["id"]), "style": node_style(n),+ "width": n.get("w", DEFAULT_W), "height": n.get("h", DEFAULT_H)}+ for n in nodes+ ],+ "edges": [+ {"source": e["source"], "target": e["target"], "label": e.get("label", ""),+ "style": edge_style(e)}+ for e in edges+ ],+ }+++def run_autolayout(graph):+ """Shell out to the sibling autolayout.py; return the .drawio XML text."""+ here = os.path.dirname(os.path.abspath(__file__))+ autolayout = os.path.join(here, "autolayout.py")+ fd, graph_path = tempfile.mkstemp(suffix=".json")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ json.dump(graph, f)+ r = subprocess.run([sys.executable, autolayout, graph_path],+ capture_output=True, text=True)+ finally:+ os.unlink(graph_path)+ if r.returncode != 0:+ sys.exit(f"error: autolayout.py failed: {r.stderr.strip()}")+ return r.stdout+++def main():+ ap = argparse.ArgumentParser(+ description="Convert an image-extracted graph JSON into an editable .drawio.")+ ap.add_argument("input", help="graph JSON file, or - for stdin")+ ap.add_argument("-o", "--output", help="output .drawio path (default: stdout)")+ args = ap.parse_args()++ if args.input == "-":+ raw = sys.stdin.read()+ else:+ try:+ with open(args.input, encoding="utf-8") as f:+ raw = f.read()+ except OSError as exc:+ sys.exit(f"error: cannot read {args.input}: {exc}")+ try:+ graph = json.loads(raw)+ except json.JSONDecodeError as exc:+ sys.exit(f"error: invalid JSON: {exc}")++ nodes = graph.get("nodes") or []+ edges = graph.get("edges") or []+ if not nodes:+ sys.exit("error: no nodes in input")+ for n in nodes:+ if "id" not in n:+ sys.exit("error: every node needs an 'id'")+ for e in edges:+ if "source" not in e or "target" not in e:+ sys.exit("error: every edge needs 'source' and 'target'")++ if any(n.get("x") is None or n.get("y") is None for n in nodes):+ xml = run_autolayout(build_autolayout_graph(nodes, edges))+ sys.stderr.write(+ "note: some nodes had no x/y — positions were auto-placed via autolayout.py\n")+ else:+ xml = to_drawio(nodes, edges)++ if args.output:+ with open(args.output, "w", encoding="utf-8") as f:+ f.write(xml)+ sys.stderr.write(f"wrote {args.output} ({len(nodes)} nodes, {len(edges)} edges)\n")+ else:+ sys.stdout.write(xml)+++if __name__ == "__main__":+ main()diff --git a/skills/drawio-skill/scripts/runbook.py b/skills/drawio-skill/scripts/runbook.pynew file mode 100644index 0000000..99ac123--- /dev/null+++ b/skills/drawio-skill/scripts/runbook.py@@ -0,0 +1,241 @@+#!/usr/bin/env python3+"""Turn a flowchart / decision-tree .drawio into a click-through HTML runbook.++Parses the nodes and edges out of a .drawio and infers a node "type" from its+shape style (ellipse -> start/end, rhombus -> decision, parallelogram -> io,+else process). The ellipse with no incoming edges is taken as the start node.+The output is a single self-contained HTML page: the current node's text+front and center, one button per outgoing edge (labeled with the edge's+choice text, or "Continue" when a node has a single unlabeled successor), a+breadcrumb trail of visited nodes, Back/Restart controls, and an "end" state+on terminal nodes (no outgoing edges). No draw.io CLI is needed -- the XML is+read and the HTML is built directly, so the whole script is testable without+any external tool.++ python3 runbook.py triage.drawio -o triage.html++Usage: python3 runbook.py <file.drawio> [-o out.html]+"""+import argparse+import html+import json+import os+import sys+import xml.etree.ElementTree as ET+++def parse(path):+ """Return (nodes, edges, start_id).++ nodes: {id: {"label": str, "type": "start"|"end"|"decision"|"io"|"process"}}+ edges: [{"source": id, "target": id, "label": str}, ...] in document order.+ Cells are flattened across pages; UserObject/object wrappers are unwrapped+ (id on the wrapper, cell inside) -- mirrors drawiodiff.py parse().+ """+ try:+ tree = ET.parse(path)+ except (ET.ParseError, OSError) as exc:+ sys.exit(f"error: cannot parse {path}: {exc}")+ pages = tree.getroot().findall("diagram") or [tree.getroot()]+ cells, labels = [], {}+ for page in pages:+ model = page.find("mxGraphModel")+ root = model.find("root") if model is not None else None+ if root is None:+ if (page.text or "").strip():+ sys.stderr.write(f"warning: {path}: a page is compressed, skipped\n")+ continue+ for child in root:+ if child.tag == "mxCell":+ cells.append(child)+ labels[child.get("id")] = child.get("value") or ""+ elif child.tag in ("UserObject", "object"):+ inner = child.find("mxCell")+ if inner is not None:+ inner.set("id", child.get("id", ""))+ cells.append(inner)+ labels[child.get("id")] = child.get("label") or child.get("value") or ""++ parents = {c.get("parent") for c in cells} # ids that have children+ order, styles, edges = [], {}, []+ for c in cells:+ cid = c.get("id")+ if c.get("edge") == "1":+ s, t = c.get("source"), c.get("target")+ if s and t:+ edges.append({"source": s, "target": t, "label": labels.get(cid, "")})+ elif c.get("vertex") == "1" and cid not in parents: # leaf vertices only+ style = c.get("style") or ""+ if "edgeLabel" in style:+ continue+ g = c.find("mxGeometry")+ if g is not None and g.get("relative") == "1": # edge-label child+ continue+ order.append(cid)+ styles[cid] = style++ indeg = {i: 0 for i in order}+ outdeg = {i: 0 for i in order}+ for e in edges:+ if e["source"] in outdeg:+ outdeg[e["source"]] += 1+ if e["target"] in indeg:+ indeg[e["target"]] += 1++ nodes = {}+ for nid in order:+ style = styles[nid]+ if "ellipse" in style:+ ntype = "end" if outdeg[nid] == 0 and indeg[nid] > 0 else "start"+ elif "rhombus" in style:+ ntype = "decision"+ elif "parallelogram" in style:+ ntype = "io"+ else:+ ntype = "process"+ nodes[nid] = {"label": labels.get(nid, ""), "type": ntype}++ edges = [e for e in edges if e["source"] in nodes and e["target"] in nodes]++ # Start node: the ellipse with no incoming edges; else the unique in-degree-0+ # node; else the first node in document order. Warn to stderr if ambiguous.+ ellipse_zero_in = [nid for nid in order if "ellipse" in styles[nid] and indeg[nid] == 0]+ if len(ellipse_zero_in) == 1:+ start_id = ellipse_zero_in[0]+ elif len(ellipse_zero_in) > 1:+ sys.stderr.write("warning: multiple ellipse nodes with in-degree 0; picking the first\n")+ start_id = ellipse_zero_in[0]+ else:+ zero_in = [nid for nid in order if indeg[nid] == 0]+ if len(zero_in) == 1:+ start_id = zero_in[0]+ elif len(zero_in) > 1:+ sys.stderr.write("warning: no unique in-degree-0 node; picking the first\n")+ start_id = zero_in[0]+ elif order:+ sys.stderr.write("warning: no start node found by heuristics; using the first node\n")+ start_id = order[0]+ else:+ start_id = None+ return nodes, edges, start_id+++def build_html(title, nodes, edges, start_id):+ """One self-contained click-through page. nodes: {id:{label,type}}; edges:+ [{source,target,label}, ...]; start_id: node id to begin the walk at."""+ adjacency = {}+ for e in edges:+ adjacency.setdefault(e["source"], []).append({"target": e["target"], "label": e["label"]})+ payload = json.dumps({"nodes": nodes, "edges": adjacency, "start": start_id}).replace("</", "<\\/")+ return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>{html.escape(title)}</title><style>+:root{{color-scheme:light dark}}+*{{box-sizing:border-box}}+body{{margin:0;font:15px/1.5 system-ui,-apple-system,Segoe UI,sans-serif;+background:#f6f7f9;color:#1a1a1a;min-height:100vh;display:flex;flex-direction:column;align-items:center}}+@media(prefers-color-scheme:dark){{body{{background:#15171a;color:#e8e8e8}}}}+header{{width:100%;max-width:640px;padding:16px 20px 4px}}+h1{{margin:0;font-size:16px;font-weight:600}}+#crumbs{{width:100%;max-width:640px;padding:6px 20px;display:flex;flex-wrap:wrap;gap:4px;+font-size:12px;color:#667}}+@media(prefers-color-scheme:dark){{#crumbs{{color:#9aa}}}}+#crumbs span:not(:last-child)::after{{content:" \\2192 ";margin:0 2px}}+main{{width:100%;max-width:640px;padding:12px 20px 28px;flex:1}}+#card{{background:#fff;border:1px solid #0002;border-left:4px solid #0d99ff;border-radius:12px;+padding:24px;box-shadow:0 1px 3px #0001}}+@media(prefers-color-scheme:dark){{#card{{background:#1e2226;border-color:#fff2;border-left-color:#0d99ff}}}}+#card.decision{{border-left-color:#d79b00}}+#card.end{{border-left-color:#82b366}}+#card.io{{border-left-color:#9673a6}}+#type{{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:#889;margin:0 0 8px}}+#label{{font-size:19px;font-weight:600;white-space:pre-wrap;margin:0 0 20px}}+.choices{{display:flex;flex-direction:column;gap:8px}}+.choices button{{font:inherit;text-align:left;padding:10px 14px;border:1px solid #0002;+border-radius:8px;background:#fff;cursor:pointer;color:inherit}}+@media(prefers-color-scheme:dark){{.choices button{{background:#262b31;border-color:#fff2}}}}+.choices button:hover{{border-color:#0d99ff;color:#0d99ff}}+.ctl{{display:flex;gap:10px;margin-top:20px}}+.ctl button{{font:inherit;padding:6px 14px;border:1px solid #0002;border-radius:8px;+background:#fff;cursor:pointer;color:inherit}}+@media(prefers-color-scheme:dark){{.ctl button{{background:#262b31;border-color:#fff2}}}}+.ctl button:hover{{border-color:#0d99ff}}+.ctl button:disabled{{opacity:.4;cursor:default}}+#endmsg{{display:none;color:#82b366;font-weight:600;margin:0}}+</style></head><body>+<header><h1>{html.escape(title)}</h1></header>+<div id="crumbs"></div>+<main>+<div id="card">+<p id="type"></p>+<p id="label"></p>+<div class="choices" id="choices"></div>+<p id="endmsg">End of path -- nothing more to check.</p>+</div>+<div class="ctl">+ <button id="back">← Back</button>+ <button id="restart">↻ Restart</button>+</div>+</main>+<script>+const DATA={payload};+let path=[DATA.start];+const $=id=>document.getElementById(id);+function render(){{+ const cur=path[path.length-1];+ const node=DATA.nodes[cur]||{{label:String(cur),type:"process"}};+ $("card").className=node.type;+ $("type").textContent=node.type;+ $("label").textContent=node.label;+ const choices=DATA.edges[cur]||[];+ const box=$("choices");box.innerHTML="";+ $("endmsg").style.display=choices.length?"none":"block";+ choices.forEach(c=>{{+ const b=document.createElement("button");+ const target=DATA.nodes[c.target]||{{}};+ b.textContent=c.label||(choices.length===1?"Continue":(target.label||c.target));+ b.onclick=()=>{{path.push(c.target);render();}};+ box.appendChild(b);+ }});+ $("back").disabled=path.length<2;+ const crumbs=$("crumbs");crumbs.innerHTML="";+ path.forEach((id,i)=>{{+ const s=document.createElement("span");+ s.textContent=(DATA.nodes[id]||{{}}).label||id;+ if(i<path.length-1){{+ s.style.cursor="pointer";+ s.onclick=()=>{{path=path.slice(0,i+1);render();}};+ }}+ crumbs.appendChild(s);+ }});+}}+$("back").onclick=()=>{{if(path.length>1){{path.pop();render();}}}};+$("restart").onclick=()=>{{path=[DATA.start];render();}};+render();+</script></body></html>+"""+++def main():+ ap = argparse.ArgumentParser(description="Turn a flowchart .drawio into a click-through HTML runbook.")+ ap.add_argument("file")+ ap.add_argument("-o", "--output", help="output .html (default: alongside input)")+ args = ap.parse_args()++ if not os.path.isfile(args.file):+ sys.exit(f"error: {args.file} not found")+ nodes, edges, start_id = parse(args.file)+ if not nodes:+ sys.exit(f"error: no nodes found in {args.file}")+ if start_id is None:+ sys.exit(f"error: no start node found in {args.file}")++ title = os.path.splitext(os.path.basename(args.file))[0]+ out = args.output or os.path.splitext(args.file)[0] + ".html"+ with open(out, "w", encoding="utf-8") as f:+ f.write(build_html(title, nodes, edges, start_id))+ sys.stderr.write(f"wrote {out} ({len(nodes)} nodes, {len(edges)} edges)\n")+++if __name__ == "__main__":+ main()diff --git a/tests/test_buildup.py b/tests/test_buildup.pynew file mode 100644index 0000000..a551984--- /dev/null+++ b/tests/test_buildup.py@@ -0,0 +1,149 @@+#!/usr/bin/env python3+"""Tests for scripts/buildup.py — the build-up "video" HTML player.++Run from the repo root:+ python3 -m unittest tests.test_buildup -v+"""+import importlib.util+import os+import shutil+import subprocess+import sys+import tempfile+import unittest++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+SCRIPTS = os.path.join(ROOT, "skills", "drawio-skill", "scripts")+++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)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++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)+++# a, b -> c: two independent sources feeding one sink.+PAGE = (+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="a" value="A" vertex="1" parent="1" style="rounded=1;">'+ '<mxGeometry x="0" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="b" value="B" vertex="1" parent="1" style="rounded=1;">'+ '<mxGeometry x="200" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="c" value="C" vertex="1" parent="1" style="rounded=1;">'+ '<mxGeometry x="400" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="e1" value="" edge="1" parent="1" source="a" target="c">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+ '<mxCell id="e2" value="" edge="1" parent="1" source="b" target="c">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+)+DOC = f'<mxfile><diagram name="P1"><mxGraphModel><root>{PAGE}</root></mxGraphModel></diagram></mxfile>'+++class TestParseClassify(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("buildup")++ def _write(self, path, text):+ with open(path, "w", encoding="utf-8") as f:+ f.write(text)++ def test_classify_leaves_and_edges(self):+ with tempfile.TemporaryDirectory() as d:+ path = os.path.join(d, "diagram.drawio")+ self._write(path, DOC)+ _, cells = self.m.parse_page(path)+ leaves, containers, edges = self.m.classify(cells)+ self.assertEqual(leaves, ["a", "b", "c"])+ self.assertEqual(containers, set())+ self.assertEqual(edges, [("e1", "a", "c"), ("e2", "b", "c")])++ def test_bounding_box_from_full_diagram(self):+ with tempfile.TemporaryDirectory() as d:+ path = os.path.join(d, "diagram.drawio")+ self._write(path, DOC)+ _, cells = self.m.parse_page(path)+ width, height = self.m.bounding_box(cells)+ # rightmost cell C: x=400,w=80 -> 480 + 40 margin; tallest: 0+40+40+ self.assertEqual(width, 520)+ self.assertEqual(height, 80)+++class TestRevealOrder(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("buildup")++ def test_sources_precede_targets(self):+ # diamond: a,b -> c -> d+ order = self.m.reveal_order(["a", "b", "c", "d"],+ [("a", "c"), ("b", "c"), ("c", "d")])+ self.assertEqual(set(order), {"a", "b", "c", "d"})+ self.assertLess(order.index("a"), order.index("c"))+ self.assertLess(order.index("b"), order.index("c"))+ self.assertLess(order.index("c"), order.index("d"))++ def test_cycle_falls_back_to_document_order(self):+ order = self.m.reveal_order(["x", "y"], [("x", "y"), ("y", "x")])+ self.assertEqual(order, ["x", "y"]) # no crash, no infinite loop++ def test_edge_step_is_at_or_after_both_endpoints(self):+ order = self.m.reveal_order(["a", "b", "c", "d"],+ [("a", "c"), ("b", "c"), ("c", "d")])+ edges = [("e1", "a", "c"), ("e2", "b", "c"), ("e3", "c", "d")]+ node_step, edge_step = self.m.reveal_steps(order, edges)+ for eid, s, t in edges:+ self.assertGreaterEqual(edge_step[eid], node_step[s])+ self.assertGreaterEqual(edge_step[eid], node_step[t])+ # e3 (c->d) can't reveal before c does+ self.assertGreaterEqual(edge_step["e3"], node_step["c"])+++class TestBuildHtml(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("buildup")++ def test_build_html_self_contained(self):+ frames = [(b"\x89PNG-1", "A", 1, 3),+ (b"\x89PNG-2", "B", 2, 3),+ (b"\x89PNG-3", "C", 3, 3)]+ html = self.m.build_html(frames, "Test Buildup")+ self.assertEqual(html.count("data:image/png;base64,"), 3)+ self.assertNotIn("http://", html)+ self.assertNotIn("https://", html) # no CDN/external refs+ for ctl in ('id="play"', 'id="scrub"', 'id="bar"'):+ self.assertIn(ctl, html)+ self.assertIn('"label": "C"', html)+ self.assertIn('"step": 3', html)+ self.assertIn('"total": 3', html)+++class TestBuildupCli(unittest.TestCase):+ def test_full_run_produces_one_frame_per_node(self):+ if not shutil.which("drawio"):+ self.skipTest("draw.io CLI not installed")+ with tempfile.TemporaryDirectory() as d:+ src = os.path.join(d, "diagram.drawio")+ with open(src, "w", encoding="utf-8") as f:+ f.write(DOC)+ out = os.path.join(d, "out.html")+ r = run("buildup.py", src, "-o", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertTrue(os.path.exists(out))+ with open(out, encoding="utf-8") as f:+ html = f.read()+ self.assertEqual(html.count("data:image/png;base64,"), 3) # a, b, c+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_compress.py b/tests/test_compress.pynew file mode 100644index 0000000..ece0831--- /dev/null+++ b/tests/test_compress.py@@ -0,0 +1,176 @@+#!/usr/bin/env python3+"""Tests for compress.py (big .drawio -> executive-summary compressor).++Run from the repo root:+ python3 -m unittest tests.test_compress -v+"""+import importlib.util+import os+import shutil+import subprocess+import sys+import tempfile+import unittest++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+SCRIPTS = os.path.join(ROOT, "skills", "drawio-skill", "scripts")+++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)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++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)+++# Two K3 triangles {a,b,c} and {d,e,f} joined by exactly one bridge edge c-d.+TRIANGLES_NODES = ["a", "b", "c", "d", "e", "f"]+TRIANGLES_EDGES = [("a", "b"), ("a", "c"), ("b", "c"),+ ("d", "e"), ("d", "f"), ("e", "f"), ("c", "d")]+++class TestLabelPropagation(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("compress")++ def test_two_triangles_split_into_two_communities(self):+ labels = self.m.label_propagation(TRIANGLES_NODES, TRIANGLES_EDGES)+ communities = {}+ for n in TRIANGLES_NODES:+ communities.setdefault(labels[n], []).append(n)+ self.assertEqual(len(communities), 2)+ members = sorted(sorted(m) for m in communities.values())+ self.assertEqual(members, [["a", "b", "c"], ["d", "e", "f"]])++ def test_deterministic_across_runs(self):+ r1 = self.m.label_propagation(TRIANGLES_NODES, TRIANGLES_EDGES)+ r2 = self.m.label_propagation(list(reversed(TRIANGLES_NODES)), TRIANGLES_EDGES)+ self.assertEqual(r1, r2)++ def test_isolated_node_is_its_own_community(self):+ labels = self.m.label_propagation(["a", "b", "z"], [("a", "b")])+ self.assertEqual(labels["z"], "z")+++class TestAggregateEdges(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("compress")++ def test_cross_edges_dedupe_with_count(self):+ # a,b in community X; c,d in community Y; two edges cross X->Y.+ community_of = {"a": "X", "b": "X", "c": "Y", "d": "Y"}+ edges = [("a", "c"), ("b", "d")]+ agg = self.m.aggregate_edges(edges, community_of)+ self.assertEqual(agg, {("X", "Y"): 2})++ def test_internal_edges_are_dropped(self):+ community_of = {"a": "X", "b": "X"}+ agg = self.m.aggregate_edges([("a", "b")], community_of)+ self.assertEqual(agg, {})+++class TestClusterName(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("compress")++ def test_common_leading_token(self):+ labels = {"s1": "Auth Service", "s2": "Auth DB", "s3": "Auth Cache"}+ name = self.m.cluster_name(["s1", "s2", "s3"], labels, {"s1": 1, "s2": 1, "s3": 1})+ self.assertEqual(name, "Auth (3)")++ def test_fallback_to_highest_degree_label(self):+ labels = {"s1": "Payments", "s2": "Ledger"}+ degree = {"s1": 1, "s2": 5}+ name = self.m.cluster_name(["s1", "s2"], labels, degree)+ self.assertEqual(name, "Ledger (2)")+++class TestParse(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("compress")++ # A container ("Tier") holding a leaf vertex, plus an edge with a label+ # child (edgeLabel vertex) that must NOT be treated as a node.+ DOC = ('<mxfile><diagram name="P1"><mxGraphModel><root>'+ '<mxCell id="0"/><mxCell id="1" parent="0"/>'+ '<mxCell id="grp" value="Tier" vertex="1" parent="1">'+ '<mxGeometry x="0" y="0" width="240" height="120" as="geometry"/></mxCell>'+ '<mxCell id="a" value="A" vertex="1" parent="grp">'+ '<mxGeometry x="10" y="10" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="b" value="B" vertex="1" parent="1">'+ '<mxGeometry x="300" y="0" width="80" height="40" as="geometry"/></mxCell>'+ '<mxCell id="e1" edge="1" parent="1" source="a" target="b">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>'+ '<mxCell id="lbl" value="calls" style="edgeLabel;html=1;" vertex="1" '+ 'connectable="0" parent="e1">'+ '<mxGeometry x="0" y="0" relative="1" as="geometry"/></mxCell>'+ '</root></mxGraphModel></diagram></mxfile>')++ def test_leaf_vertices_only_skips_containers_and_edge_labels(self):+ with tempfile.TemporaryDirectory() as d:+ path = os.path.join(d, "x.drawio")+ with open(path, "w", encoding="utf-8") as f:+ f.write(self.DOC)+ nodes, edges = self.m.parse(path)+ self.assertEqual(set(nodes), {"a", "b"}) # grp is a container, lbl is an edge label+ self.assertEqual(nodes["a"][0], "A")+ self.assertEqual(edges, {("a", "b")})+++class TestAssembly(unittest.TestCase):+ """Full CLI run: needs Graphviz `dot` (autolayout.py places the exec nodes)."""++ @staticmethod+ def _drawio(nodes, 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'<mxGeometry x="{i * 150}" 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="{t}">'+ '<mxGeometry relative="1" as="geometry"/></mxCell>')+ return ('<mxfile><diagram id="orig" name="Original"><mxGraphModel><root>'+ + "".join(cells) + "</root></mxGraphModel></diagram></mxfile>")++ def setUp(self):+ if not shutil.which("dot"):+ self.skipTest("Graphviz dot not installed")++ def test_two_page_output_with_drilldown(self):+ nodes = [(n, n.upper()) for n in TRIANGLES_NODES]+ doc = self._drawio(nodes, TRIANGLES_EDGES)+ with tempfile.TemporaryDirectory() as d:+ src = os.path.join(d, "big.drawio")+ with open(src, "w", encoding="utf-8") as f:+ f.write(doc)+ out = os.path.join(d, "exec.drawio")+ r = run("compress.py", src, "-o", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("2 clusters", r.stderr)+ with open(out, encoding="utf-8") as f:+ xml = f.read()+ self.assertEqual(xml.count("<diagram"), 2)+ self.assertIn('link="data:page/id,full-diagram"', xml)+ self.assertIn('id="full-diagram"', xml)+ # page 2 keeps the original leaf labels verbatim+ for _, label in nodes:+ self.assertIn(f'value="{label}"', xml)+ v = run("validate.py", out)+ self.assertEqual(v.returncode, 0, v.stdout)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_derasterize.py b/tests/test_derasterize.pynew file mode 100644index 0000000..7a106d2--- /dev/null+++ b/tests/test_derasterize.py@@ -0,0 +1,123 @@+#!/usr/bin/env python3+"""Tests for raster2drawio.py (image graph JSON -> editable .drawio).++Run from the repo root:+ python3 -m unittest tests.test_derasterize -v+"""+import importlib.util+import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+import xml.etree.ElementTree as ET++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+SCRIPTS = os.path.join(ROOT, "skills", "drawio-skill", "scripts")+++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)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++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)+++class TestRaster2Drawio(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("raster2drawio")++ def test_positioned_nodes_and_shapes(self):+ nodes = [+ {"id": "n1", "label": "API Gateway", "x": 120, "y": 60, "w": 160, "h": 60,+ "shape": "rect", "fill": "#dae8fc", "stroke": "#6c8ebf"},+ {"id": "n2", "label": "Auth DB", "x": 360, "y": 60, "shape": "cylinder"},+ {"id": "n3", "label": "Decide", "x": 600, "y": 60, "shape": "rhombus"},+ ]+ xml = self.m.to_drawio(nodes, [])+ root = ET.fromstring(xml)+ cells = {c.get("id"): c for c in root.iter("mxCell") if c.get("vertex") == "1"}+ self.assertEqual(set(cells), {"n1", "n2", "n3"})++ n1, geo1 = cells["n1"], cells["n1"].find("mxGeometry")+ self.assertEqual((geo1.get("x"), geo1.get("y"), geo1.get("width"), geo1.get("height")),+ ("120", "60", "160", "60"))+ self.assertIn("fillColor=#dae8fc", n1.get("style"))+ self.assertIn("strokeColor=#6c8ebf", n1.get("style"))++ self.assertIn("shape=cylinder3", cells["n2"].get("style"))+ self.assertIn("rhombus", cells["n3"].get("style"))++ def test_default_shape_size_and_fill(self):+ nodes = [{"id": "n1", "x": 0, "y": 0}]+ xml = self.m.to_drawio(nodes, [])+ root = ET.fromstring(xml)+ cell = next(c for c in root.iter("mxCell") if c.get("id") == "n1")+ geo = cell.find("mxGeometry")+ self.assertEqual((geo.get("width"), geo.get("height")), ("120", "60"))+ self.assertIn("fillColor=#dae8fc", cell.get("style"))+ self.assertIn("strokeColor=#6c8ebf", cell.get("style"))+ # default shape ("rect") is a plain box: no rounded=1, no shape=+ self.assertNotIn("rounded=1", cell.get("style"))++ def test_edge_dashed_and_no_arrow(self):+ nodes = [{"id": "n1", "x": 0, "y": 0}, {"id": "n2", "x": 200, "y": 0}]+ edges = [+ {"source": "n1", "target": "n2", "label": "HTTPS", "dashed": True},+ {"source": "n2", "target": "n1", "arrow": False},+ ]+ xml = self.m.to_drawio(nodes, edges)+ root = ET.fromstring(xml)+ edge_cells = [c for c in root.iter("mxCell") if c.get("edge") == "1"]+ self.assertEqual(len(edge_cells), 2)+ dashed = next(c for c in edge_cells if c.get("source") == "n1")+ no_arrow = next(c for c in edge_cells if c.get("source") == "n2")+ self.assertIn("dashed=1", dashed.get("style"))+ self.assertIn("endArrow=none", no_arrow.get("style"))+ # every edge cell has a relative geometry child+ for c in edge_cells:+ geo = c.find("mxGeometry")+ self.assertIsNotNone(geo)+ self.assertEqual(geo.get("relative"), "1")+ # layer cell footgun: id=1 must carry parent="0"+ layer = next(c for c in root.iter("mxCell") if c.get("id") == "1")+ self.assertEqual(layer.get("parent"), "0")++ def test_label_escaping(self):+ nodes = [{"id": "n1", "x": 0, "y": 0, "label": 'A & B <C> "D"\nsecond line'}]+ xml = self.m.to_drawio(nodes, [])+ self.assertIn("A & B <C> "D"
second line", xml)+ self.assertNotIn('"D"\n', xml)++ def test_missing_position_autoplace(self):+ if shutil.which("dot") is None:+ self.skipTest("Graphviz dot not on PATH")+ graph = {+ "nodes": [{"id": "n1", "label": "A"}, {"id": "n2", "label": "B", "x": 100, "y": 0}],+ "edges": [{"source": "n1", "target": "n2", "label": "calls"}],+ }+ with tempfile.TemporaryDirectory() as tmp:+ src = os.path.join(tmp, "graph.json")+ with open(src, "w", encoding="utf-8") as f:+ json.dump(graph, f)+ r = run("raster2drawio.py", src)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("auto-placed", r.stderr)+ root = ET.fromstring(r.stdout)+ ids = {c.get("id") for c in root.iter("mxCell") if c.get("vertex") == "1"}+ self.assertEqual(ids, {"n1", "n2"})+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_prdiff.py b/tests/test_prdiff.pynew file mode 100644index 0000000..742aa8c--- /dev/null+++ b/tests/test_prdiff.py@@ -0,0 +1,166 @@+#!/usr/bin/env python3+"""Tests for scripts/prdiff.py — the PR diagram diff bot.++Run from the repo root:+ python3 -m unittest tests.test_prdiff -v+"""+import importlib.util+import os+import shutil+import subprocess+import tempfile+import unittest++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+SCRIPTS = os.path.join(ROOT, "skills", "drawio-skill", "scripts")+++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)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def make_repo(tmp):+ """Init a throwaway git repo (local config only) in tmp."""+ subprocess.run(["git", "init", "-q", tmp], check=True)+ subprocess.run(["git", "-C", tmp, "config", "user.email", "[email protected]"], check=True)+ subprocess.run(["git", "-C", tmp, "config", "user.name", "Test"], check=True)+++def write_commit(tmp, name, content, message):+ with open(os.path.join(tmp, name), "w", encoding="utf-8") as f:+ f.write(content)+ subprocess.run(["git", "-C", tmp, "add", name], check=True)+ subprocess.run(["git", "-C", tmp, "commit", "-q", "-m", message], check=True)+++V1 = """<mxfile>+ <diagram id="p1" name="Page-1">+ <mxGraphModel dx="800" dy="600" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">+ <root>+ <mxCell id="0"/>+ <mxCell id="1" parent="0"/>+ <mxCell id="n1" value="A" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">+ <mxGeometry x="40" y="40" width="120" height="60" as="geometry"/>+ </mxCell>+ <mxCell id="n2" value="B" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">+ <mxGeometry x="240" y="40" width="120" height="60" as="geometry"/>+ </mxCell>+ <mxCell id="e1" style="html=1;" edge="1" parent="1" source="n1" target="n2">+ <mxGeometry relative="1" as="geometry"/>+ </mxCell>+ </root>+ </mxGraphModel>+ </diagram>+</mxfile>+"""++V2 = V1.replace('value="B"', 'value="B2"')+++class TestChangedDrawios(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("prdiff")++ def test_modified(self):+ with tempfile.TemporaryDirectory() as tmp:+ make_repo(tmp)+ write_commit(tmp, "a.drawio", V1, "v1")+ write_commit(tmp, "a.drawio", V2, "v2")+ self.assertEqual(self.m.changed_drawios("HEAD~1", "HEAD", tmp), [("a.drawio", "modified")])++ def test_added(self):+ with tempfile.TemporaryDirectory() as tmp:+ make_repo(tmp)+ write_commit(tmp, "a.drawio", V1, "v1")+ write_commit(tmp, "b.drawio", V1, "add b")+ self.assertEqual(self.m.changed_drawios("HEAD~1", "HEAD", tmp), [("b.drawio", "added")])++ def test_removed(self):+ with tempfile.TemporaryDirectory() as tmp:+ make_repo(tmp)+ write_commit(tmp, "a.drawio", V1, "v1")+ os.remove(os.path.join(tmp, "a.drawio"))+ subprocess.run(["git", "-C", tmp, "add", "-A"], check=True, cwd=tmp)+ subprocess.run(["git", "-C", tmp, "commit", "-q", "-m", "remove a"], check=True)+ self.assertEqual(self.m.changed_drawios("HEAD~1", "HEAD", tmp), [("a.drawio", "removed")])++ def test_non_drawio_files_ignored(self):+ with tempfile.TemporaryDirectory() as tmp:+ make_repo(tmp)+ write_commit(tmp, "a.drawio", V1, "v1")+ write_commit(tmp, "notes.txt", "hello", "add notes")+ self.assertEqual(self.m.changed_drawios("HEAD~1", "HEAD", tmp), [])+++class TestRenderMarkdown(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("prdiff")++ def test_sections_statuses_and_links(self):+ entries = [+ {"path": "a.drawio", "status": "modified",+ "base_png": "/out/a.base.png", "head_png": "/out/a.head.png", "diff_png": "/out/a.diff.png"},+ {"path": "b.drawio", "status": "added", "head_png": "/out/b.head.png"},+ {"path": "c.drawio", "status": "removed", "base_png": "/out/c.base.png"},+ ]+ md = self.m.render_markdown(entries, "/out")+ self.assertIn("## a.drawio (modified)", md)+ self.assertIn("## b.drawio (added)", md)+ self.assertIn("## c.drawio (removed)", md)+ self.assertIn("", md)+ self.assertIn("", md)+ self.assertIn("", md)+ self.assertIn("", md)+ self.assertIn("", md)+ self.assertIn("3 file(s) changed", md)+ self.assertIn("+1 added", md)+ self.assertIn("-1 removed", md)+ self.assertIn("~1 modified", md)++ def test_no_changes(self):+ md = self.m.render_markdown([], "/out")+ self.assertIn("No `.drawio` files changed", md)++ def test_skipped_cli_note(self):+ entries = [{"path": "a.drawio", "status": "modified", "skipped": True}]+ md = self.m.render_markdown(entries, "/out")+ self.assertIn("## a.drawio (modified)", md)+ self.assertIn("images skipped", md)+ self.assertNotIn("![", md)+++class TestFullPipeline(unittest.TestCase):+ """Exercises the real draw.io CLI (and Graphviz, via drawiodiff+autolayout)."""++ @classmethod+ def setUpClass(cls):+ cls.m = load("prdiff")++ def test_build_entry_exports_base_head_diff_pngs(self):+ if shutil.which("drawio") is None:+ self.skipTest("draw.io CLI not installed")+ if shutil.which("dot") is None:+ self.skipTest("Graphviz `dot` not installed (needed by drawiodiff -> autolayout)")+ with tempfile.TemporaryDirectory() as tmp:+ repo = os.path.join(tmp, "repo")+ os.makedirs(repo)+ make_repo(repo)+ write_commit(repo, "a.drawio", V1, "v1")+ write_commit(repo, "a.drawio", V2, "v2")+ out_dir = os.path.join(tmp, "out")+ os.makedirs(out_dir)+ entry = self.m.build_entry(repo, "HEAD~1", "HEAD", "a.drawio", "modified", out_dir, True)+ self.assertTrue(os.path.exists(entry["base_png"]))+ self.assertTrue(os.path.exists(entry["head_png"]))+ self.assertTrue(os.path.exists(entry["diff_png"]))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_runbook.py b/tests/test_runbook.pynew file mode 100644index 0000000..e632815--- /dev/null+++ b/tests/test_runbook.py@@ -0,0 +1,104 @@+#!/usr/bin/env python3+"""Tests for runbook.py -- pure XML-parsing + HTML-building, no CLI needed.++Run from the repo root:+ python3 -m unittest tests.test_runbook -v+"""+import importlib.util+import os+import tempfile+import unittest++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+SCRIPTS = os.path.join(ROOT, "skills", "drawio-skill", "scripts")+++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)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++# Start (ellipse) -> Decision (rhombus) --Yes--> Escalate (process)+# --No---> Close ticket (process)+FLOWCHART = """<mxfile><diagram id="p1" name="Page-1"><mxGraphModel><root>+<mxCell id="0"/>+<mxCell id="1" parent="0"/>+<mxCell id="start" value="Start" vertex="1" parent="1" style="ellipse;whiteSpace=wrap;html=1;">+<mxGeometry x="40" y="40" width="120" height="60" as="geometry"/></mxCell>+<mxCell id="dec" value="Is it broken?" vertex="1" parent="1" style="rhombus;whiteSpace=wrap;html=1;">+<mxGeometry x="40" y="140" width="120" height="80" as="geometry"/></mxCell>+<mxCell id="a" value="Escalate" vertex="1" parent="1" style="rounded=1;whiteSpace=wrap;html=1;">+<mxGeometry x="0" y="260" width="120" height="60" as="geometry"/></mxCell>+<mxCell id="b" value="Close ticket" vertex="1" parent="1" style="rounded=1;whiteSpace=wrap;html=1;">+<mxGeometry x="160" y="260" width="120" height="60" as="geometry"/></mxCell>+<mxCell id="e1" edge="1" parent="1" source="start" target="dec" style="endArrow=classic;html=1;">+<mxGeometry relative="1" as="geometry"/></mxCell>+<mxCell id="e2" value="Yes" edge="1" parent="1" source="dec" target="a" style="endArrow=classic;html=1;">+<mxGeometry relative="1" as="geometry"/></mxCell>+<mxCell id="e3" value="No" edge="1" parent="1" source="dec" target="b" style="endArrow=classic;html=1;">+<mxGeometry relative="1" as="geometry"/></mxCell>+</root></mxGraphModel></diagram></mxfile>"""+++class TestRunbook(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.m = load("runbook")++ def _parse(self, xml_text):+ with tempfile.TemporaryDirectory() as d:+ path = os.path.join(d, "flow.drawio")+ with open(path, "w", encoding="utf-8") as f:+ f.write(xml_text)+ return self.m.parse(path)++ def test_node_types_inferred_from_style(self):+ nodes, _, _ = self._parse(FLOWCHART)+ self.assertEqual(nodes["start"], {"label": "Start", "type": "start"})+ self.assertEqual(nodes["dec"]["type"], "decision")+ self.assertEqual(nodes["a"]["type"], "process")+ self.assertEqual(nodes["b"]["type"], "process")++ def test_edges_carry_choice_labels(self):+ _, edges, _ = self._parse(FLOWCHART)+ self.assertEqual(len(edges), 3)+ by_target = {e["target"]: e["label"] for e in edges}+ self.assertEqual(by_target["a"], "Yes")+ self.assertEqual(by_target["b"], "No")+ # unlabeled edge (Start -> Decision) has an empty choice label+ e1 = next(e for e in edges if e["source"] == "start" and e["target"] == "dec")+ self.assertEqual(e1["label"], "")++ def test_start_node_is_ellipse_with_indegree_zero(self):+ _, _, start_id = self._parse(FLOWCHART)+ self.assertEqual(start_id, "start")++ def test_build_html_self_contained_with_all_labels_and_choices(self):+ nodes, edges, start_id = self._parse(FLOWCHART)+ out = self.m.build_html("Triage", nodes, edges, start_id)+ for label in ("Start", "Is it broken?", "Escalate", "Close ticket"):+ self.assertIn(label, out)+ self.assertIn('"Yes"', out)+ self.assertIn('"No"', out)+ self.assertIn('"start": "start"', out)+ self.assertNotIn("http://", out)+ self.assertNotIn("https://", out)++ def test_label_xml_entities_decoded(self):+ xml_text = FLOWCHART.replace('value="Start"', 'value="A & B <end>"')+ nodes, _, _ = self._parse(xml_text)+ self.assertEqual(nodes["start"]["label"], "A & B <end>")++ def test_terminal_nodes_have_no_outgoing_edges(self):+ _, edges, _ = self._parse(FLOWCHART)+ sources = {e["source"] for e in edges}+ self.assertNotIn("a", sources)+ self.assertNotIn("b", sources)+++if __name__ == "__main__":+ unittest.main()