Skip to content

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

refactor: split SKILL.md into references and scripts (v1.5.0)

Agents365-ai10317370cbdb
diff --git a/SKILL.md b/SKILL.md
index acfe25a..cce4fe2 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -5,7 +5,7 @@ license: MIT
homepage: https://github.com/Agents365-ai/drawio-skill
compatibility: Requires draw.io desktop app CLI on PATH (macOS/Linux/Windows). Self-check step requires a vision-enabled model (e.g., Claude Sonnet/Opus); gracefully skipped if unavailable.
platforms: [macos, linux, windows]
-metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["draw.io"],"label":"Install draw.io via Homebrew","os":["darwin"]}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.4.3"}
+metadata: {"openclaw":{"requires":{"anyBins":["draw.io","drawio"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["draw.io"],"label":"Install draw.io via Homebrew","os":["darwin"]}]},"hermes":{"tags":["drawio","diagram","flowchart","architecture","visualization","uml"],"category":"design","requires_tools":["draw.io"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"1.5.0"}
---
# Draw.io Diagrams
@@ -18,16 +18,18 @@ Generate `.drawio` XML files and export to PNG/SVG/PDF/JPG locally using the nat
PNG, SVG, and PDF exports support `--embed-diagram` (`-e`) — the exported file contains the full diagram XML, so opening it in draw.io recovers the editable diagram. Use double extensions (`name.drawio.png`) to signal embedded XML.
-## When to Use
+## Bundled resources
-**Explicit triggers:** user says "diagram", "visualize", "flowchart", "draw", "architecture diagram", "process flow", "ER diagram", "UML", "sequence diagram", "class diagram", "neural network", "model architecture"
+When the workflow references one of these, read it on demand — none of them need to be in context up front.
-**Proactive triggers:**
-- Explaining a system with 3+ interacting components
-- Describing a multi-step process or decision tree
-- Comparing architectures or approaches side by side
-
-**Skip when:** a simple list or table suffices, or user is in a quick Q&A flow
+| File | Read it when |
+|---|---|
+| `references/diagram-types.md` | The user names a specific diagram type (ERD, UML class, sequence, architecture, ML/DL, flowchart) |
+| `references/style-presets.md` | The user asks to learn / save / list / set-default / delete a style preset, or you've resolved an active preset and need the application rules |
+| `references/style-extraction.md` | You're inside the Learn flow and need the extraction procedure (called from `style-presets.md`) |
+| `references/troubleshooting.md` | An export fails, vision rejects a PNG, or a rendering looks wrong |
+| `scripts/repair_png.py` | After every `-e` PNG export — fixes draw.io's truncated IEND chunk (issue #8) |
+| `scripts/encode_drawio_url.py` | The CLI is unavailable and you need a browser-fallback diagrams.net URL |
## Prerequisites
@@ -94,7 +96,7 @@ When a preset loads successfully, mention it in the first line of the reply: *"U
4. **Export draft** — run CLI to produce a preview PNG. **Do NOT pass `-e`** at this step — the embedded `zTXt mxGraphModel` chunk it adds causes vision APIs (Claude included) to return 400 "Could not process image" in step 5. Save the clean preview as `<name>.png` (single extension). Embedding is for the final export only (step 7).
5. **Self-check** — use the agent's built-in vision capability to read the exported PNG, catch obvious issues, auto-fix before showing user (requires a vision-enabled model such as Claude Sonnet/Opus). If reading the PNG returns a 400 / "Could not process image" error, you almost certainly exported with `-e` by mistake — re-export without `-e` and retry once. If it still fails, skip self-check and continue to step 6.
6. **Review loop** — show image to user, collect feedback, apply targeted XML edits, re-export, repeat until approved
-7. **Final export** — re-export the approved version to all requested formats. Use `-e` here (PNG/SVG/PDF) so the deliverable stays editable in draw.io; save as `<name>.drawio.png` to signal embedded XML. **For PNG with `-e`, run the IEND repair snippet immediately after** — draw.io's CLI truncates the IEND chunk in `-e` PNG output (8 bytes missing), producing a corrupt file that vision APIs and strict PNG decoders reject (issue #8). See **Export → Post-export PNG repair**. Report file paths.
+7. **Final export** — re-export the approved version to all requested formats. Use `-e` here (PNG/SVG/PDF) so the deliverable stays editable in draw.io; save as `<name>.drawio.png` to signal embedded XML. **For PNG with `-e`, run `python3 <this-skill-dir>/scripts/repair_png.py <name>.drawio.png` immediately after** — draw.io's CLI truncates the IEND chunk in `-e` PNG output (8 bytes missing), producing a corrupt file that vision APIs and strict PNG decoders reject (issue #8). Report file paths.
### Step 5: Self-Check
@@ -149,81 +151,15 @@ Once the user approves:
## Style Presets
-A **style preset** is a named JSON file that captures a user's visual preferences — palette, shape vocabulary, fonts, edge style. When a preset is active, it fully replaces the built-in conventions described in the `### Applying a preset` subsection below (under `## Draw.io XML Structure`).
-
-**Locations, in lookup order:**
-1. `~/.drawio-skill/styles/<name>.json` — user presets (survive `git pull`).
-2. `<this-skill-dir>/styles/built-in/<name>.json` — built-ins shipped with the skill (`default`, `corporate`, `handdrawn`).
-
-A user preset shadows a built-in of the same name.
-
-Only user presets can have `"default": true`. When the user says *"make `<built-in-name>` my default"*, copy the built-in JSON to `~/.drawio-skill/styles/<name>.json` first, then set `default: true` on the copy — leave the shipped built-in untouched.
-
-**Name normalisation:** always lowercase the user-provided name before writing or looking up files (the preset schema enforces lowercase; uppercase names will fail validation).
-
-### Learn flow
-
-**Triggers:** "learn my style from `<path>` as `<name>`", "save this as `<name>` style", "remember this style as `<name>`".
-
-**Dispatch by file extension:**
-- `.drawio`, `.xml` → XML path
-- `.png`, `.jpg`, `.jpeg`, `.svg` (rasterized flat image) → image path
-
-**Steps:**
-
-1. **Load the extraction reference.** Read `references/style-extraction.md` into context.
-2. **Extract** following the XML path or image path procedure in the reference.
-3. **Normalize and build candidate.** Convert the user-provided preset name to lowercase. Use this normalized name for ALL file paths in this flow. Build the candidate preset JSON and write it to `/tmp/drawio-preset-<name>.json` (where `<name>` is the already-normalized name). Do **not** save to `~/.drawio-skill/styles/<name>.json` yet.
-4. **Render a sample** using the sample-diagram skeleton in `references/style-extraction.md`, parameterized by the candidate preset. Export PNG to `./preset-<name>-sample.png` using the same `draw.io -x -f png -e -s 2 -o ./preset-<name>-sample.png /tmp/drawio-preset-<name>.drawio` command the main workflow uses.
-5. **Show the user:**
- - Preset summary table (palette hex values, shapes per role, font, edge style, extras).
- - The sample PNG path (and embed the image if the environment supports it).
- - Provenance line: `source.type`, `source.path`, `extracted_at`, `confidence`.
-6. **Wait for approval:**
- - "save" / "looks good" → write candidate to `~/.drawio-skill/styles/<name>.json`. Create `~/.drawio-skill/styles/` if it doesn't exist. Delete tempfile and sample PNG.
- - "change `<field>` to `<value>`" → edit the in-memory candidate, re-render, re-ask.
- - "cancel" / "abort" / "no" → delete tempfile and sample PNG; nothing saved.
-
-**Error behavior:**
-
-| Failure | Behavior |
-|---|---|
-| Source path does not exist | Stop; report path not found. |
-| XML parse fails | Stop; report the parse error; suggest opening the file in drawio desktop to repair. |
-| Image vision unavailable | Stop; tell user to re-run on a vision-capable model or provide the `.drawio` file. |
-| Extraction yields 0 vertices / shapes | Stop; refuse to save. |
-| Extraction yields <3 distinct color pairs | Continue; mark `confidence: "low"` (image) or `"medium"` (XML); warn in summary. |
-| Preset name collides with existing user preset | Ask: overwrite, or pick a new name. |
-| Preset name collides with a built-in preset | Save to user dir (shadows the built-in); warn once. |
-| Sample render fails | Still show summary; note "could not render sample — saving on your OK anyway". Do not block. |
-
-### Management operations
+A **style preset** is a named JSON file capturing a user's visual preferences (palette, shapes, font, edges). When active, it fully replaces the built-in color/shape conventions in this skill.
-All operations are natural language — no slash commands.
+**Lookup order** when SKILL.md's step 0.5 resolves a preset name:
+1. `~/.drawio-skill/styles/<name>.json` — user presets (survive `git pull`)
+2. `<this-skill-dir>/styles/built-in/<name>.json` — shipped built-ins (`default`, `corporate`, `handdrawn`)
-*Apply name normalisation (lowercase) to all `<name>`, `<a>`, `<b>` arguments before any file operation.*
+Always lowercase the user-provided name before any file operation — the schema enforces lowercase.
-| User says | Agent does |
-|---|---|
-| "list my styles", "what styles do I have", "show me my style presets" | Read `~/.drawio-skill/styles/` and `<this-skill-dir>/styles/built-in/`. Print a table: `name`, `location` (user/built-in), `source.type`, `confidence`, `default` flag. Built-ins shadowed by a user preset are marked so. |
-| "show my `<name>` style", "what's in `<name>`" | Print the preset JSON (pretty-printed) + a one-line summary (source, confidence, is-default). |
-| "make `<name>` the default", "set `<name>` as default" | If `<name>` is a user preset: set `default: true` on it; clear `default` on any other user preset that had it; save both files. If `<name>` is a built-in: copy `<this-skill-dir>/styles/built-in/<name>.json` → `~/.drawio-skill/styles/<name>.json` first, then set `default: true` on the copy. Never mutate the shipped built-in. |
-| "remove default", "unset default" | Clear `default: true` from whichever user preset has it. |
-| "delete `<name>`", "remove `<name>`" | Confirm first. Then `rm ~/.drawio-skill/styles/<name>.json`. Refuse to delete files under `<this-skill-dir>/styles/built-in/` — suggest shadowing with a user preset of the same name. |
-| "rename `<a>` to `<b>`" | `mv ~/.drawio-skill/styles/<a>.json ~/.drawio-skill/styles/<b>.json`, then update the `name` field inside. Fails if `<a>` is a built-in (offer to copy-then-rename instead). |
-| "learn my style from `<path>` as `<name>`" | Dispatch to the Learn flow above. |
-
-### Preset file validation
-
-When loading any preset (for generation or management), do a lightweight structural check:
-- Required top-level fields present (`name`, `version`, `palette`, `roles`, `shapes`, `font`, `edges`).
-- `version === 1`.
-- Every populated palette slot has both `fillColor` and `strokeColor` as `#RRGGBB`.
-- `confidence` ∈ {`"low"`, `"medium"`, `"high"`} if present.
-
-On validation failure:
-- **During generation:** warn the user, fall back to built-in conventions for this one diagram, do not mutate the file.
-- **During learn:** refuse to save the candidate; report which field failed.
+**For everything else — Learn flow (extracting a preset from a file), management ops (list/default/delete/rename), application rules (color lookup, shape keywords, edges, fonts, extras, interaction with diagram-type presets), and validation — read `references/style-presets.md`.** It's only needed when the user invokes those flows or when an active preset must be applied to the current generation.
## Draw.io XML Structure
@@ -359,32 +295,6 @@ When multiple edges connect to the same shape, assign different entry/exit point
**Rule:** if a shape has N connections on one side, space them evenly (e.g., 3 connections on bottom → exitX = 0.25, 0.5, 0.75)
-### Applying a preset
-
-When the Workflow's step *Resolve active preset* identified a preset, it fully replaces the built-in palette, shape keywords, edge defaults, and font for this diagram — do not mix values from the built-in color table below.
-
-**Color lookup.** For each role a shape plays (service / database / queue / gateway / error / external / security), resolve `preset.roles[role]` to a slot name, then `preset.palette[<slot>]` to the `(fillColor, strokeColor)` pair. If `roles[role]` is unset or the resolved slot is `null`, follow this fallback ladder:
-
-1. Try the role's canonical slot (`service→primary`, `database→success`, `queue→warning`, `gateway→accent`, `error→danger`, `external→neutral`, `security→secondary`).
-2. If that slot is also empty, pick the most-populated non-null slot in the preset.
-3. Never reach into the built-in color table below — the preset is authoritative.
-
-**Decision and container shapes** are not in `preset.roles` — they have shape vocabulary (`preset.shapes.decision`, `preset.shapes.container`) but no role-to-slot mapping. Pick their colors as follows:
-- **Decision** (rhombus) → use `preset.palette.warning` (the canonical yellow slot in the built-in conventions). If `warning` is empty, apply the slot-fallback ladder above starting from `warning`.
-- **Container** (swimlane) → use the palette slot matching the tier/grouping the container represents (e.g., a "Services" tier container uses `primary`; a "Data" tier uses `success`). If no tier signal is available, default to `primary`.
-
-**Shape keywords.** Use `preset.shapes[role]` as the **prefix** of the vertex style string (before `whiteSpace=wrap;html=1;...`). Example: for a database role, if `preset.shapes.database = "shape=cylinder3"`, the vertex style starts `shape=cylinder3;whiteSpace=wrap;html=1;fillColor=...`. The six named shape keys are `service`, `database`, `queue`, `decision`, `external`, `container`. Roles `gateway`, `error`, and `security` reuse `preset.shapes.service` unless the preset explicitly populates a key with their name.
-
-**Edges.** Use `preset.edges.style` as the base edge style string. Append `preset.edges.arrow`. Per-edge routing keys (`exitX/exitY/entryX/entryY/...`) are still added by the usual routing rules in the rest of this document. If the flow between two shapes matches a token from `preset.edges.dashedFor` (either because the user's prompt used that word, or because one end of the edge plays a role whose typical relation is "optional"), append `;dashed=1` to the edge style.
-
-**Fonts.** Append `fontFamily=<preset.font.fontFamily>;fontSize=<preset.font.fontSize>` to every vertex style. Container headers and swimlane titles additionally get `fontSize=<preset.font.titleFontSize>;fontStyle=1` when `preset.font.titleBold` is `true`.
-
-**Extras.**
-- `preset.extras.sketch === true` → append `sketch=1` to every vertex style and every edge style.
-- `preset.extras.globalStrokeWidth !== 1` (any value other than the drawio default of 1, including `0.5`) → append `strokeWidth=<n>` to every vertex style and every edge style.
-
-**Interaction with diagram-type presets (ERD / UML / Sequence / ML / Flowchart).** Diagram-type presets earlier in this document set structural style keywords that the user preset must preserve (e.g., ERD tables rely on `shape=table;startSize=30;container=1;childLayout=tableLayout;...`). The rule: keep the diagram-type preset's structural keywords, then layer the user preset's color / font / edge / extras on top. When a diagram-type preset hardcodes a color (`fillColor=#dae8fc`, etc.) that conflicts with the user preset, the user preset's color wins. Exception: `fillColor=none` is structural — do not replace it with a palette color.
-
### Color palette (fillColor / strokeColor)
*Used only when no preset is active (see "Applying a preset" above).*
@@ -471,30 +381,20 @@ mkdir -p ./artifacts && draw.io -x -f png -e -s 2 -o ./artifacts/diagram.drawio.
### Post-export PNG repair (required after `-e` PNG export)
-draw.io CLI truncates the IEND chunk when emitting `-e` PNGs — the file ends with the 4-byte IEND length field but the `IEND` type + CRC (8 bytes) are missing. Result: vision APIs return 400 "Could not process image" and strict PNG decoders error out. SVG/PDF are unaffected (no IEND chunk).
+draw.io CLI truncates the IEND chunk when emitting `-e` PNGs — the file ends with the 4-byte IEND length field but the `IEND` type + CRC (8 bytes) are missing. Result: vision APIs return 400 "Could not process image" and strict PNG decoders error out. SVG/PDF are unaffected.
Run this immediately after every `-e` PNG export:
```bash
-python3 - "diagram.drawio.png" <<'PY'
-import sys
-p = sys.argv[1]
-data = open(p, 'rb').read()
-IEND = b'\x00\x00\x00\x00IEND\xaeB`\x82'
-if not data.endswith(IEND):
- if data.endswith(b'\x00\x00\x00\x00'): # truncated length field
- data = data[:-4]
- open(p, 'wb').write(data + IEND)
- print(f"repaired {p}")
-PY
+python3 <this-skill-dir>/scripts/repair_png.py diagram.drawio.png
```
-The `endswith(IEND)` guard makes this a no-op if draw.io fixes the bug upstream — safe to run unconditionally.
+The script's `endswith(IEND)` guard makes it a no-op once draw.io fixes the bug upstream — safe to run unconditionally.
**Key flags:**
- `-x` — export mode (required)
- `-f` — format: `png`, `svg`, `pdf`, `jpg`
-- `-e` — embed diagram XML in output (PNG, SVG, PDF) — exported file remains editable in draw.io. **Skip for the preview PNG used in step 5 self-check** — `-e` PNGs have a truncated IEND chunk that vision APIs reject (issue #8). For final PNG export, keep `-e` and run the IEND repair snippet (see Post-export PNG repair). SVG/PDF unaffected.
+- `-e` — embed diagram XML in output (PNG, SVG, PDF) — exported file remains editable in draw.io. **Skip for the preview PNG used in step 5 self-check** — `-e` PNGs have a truncated IEND chunk that vision APIs reject (issue #8). For final PNG export, keep `-e` and run `scripts/repair_png.py` (see Post-export PNG repair). SVG/PDF unaffected.
- `-s` — scale: `1`, `2`, `3` (2 recommended for PNG)
- `-o` — output file path; accepts any directory (e.g. `./artifacts/diagram.drawio.png`) — `mkdir -p` the target dir first. Use `.drawio.png` double extension when embedding.
- `-b` — border width around diagram (default: 0, recommend 10)
@@ -503,23 +403,13 @@ The `endswith(IEND)` guard makes this a no-op if draw.io fixes the bug upstream
### Browser fallback (no CLI needed)
-When the draw.io desktop CLI is unavailable, generate a browser-editable URL by deflate-compressing and base64-encoding the XML:
+When the draw.io desktop CLI is unavailable, generate a client-side viewer URL:
```bash
-# Encode .drawio XML into a diagrams.net URL
-python3 -c "
-import zlib, base64, urllib.parse, sys
-xml = open(sys.argv[1]).read()
-# Raw deflate (no zlib header) — diagrams.net uses mxGraph's raw inflate
-c = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
-compressed = c.compress(xml.encode('utf-8')) + c.flush()
-# Standard base64 (atob rejects url-safe -/_); strip any newlines
-encoded = base64.b64encode(compressed).decode('utf-8').replace('\n', '')
-print('https://viewer.diagrams.net/?tags=%7B%7D&lightbox=1&edit=_blank#R' + urllib.parse.quote(encoded, safe=''))
-" input.drawio
+python3 <this-skill-dir>/scripts/encode_drawio_url.py input.drawio
```
-This produces a client-side URL that opens the diagram in the browser for viewing and editing. No data is uploaded to any server — the entire diagram XML is encoded in the URL fragment (after `#`), which is never sent to the server. Useful when the user cannot install the desktop app.
+Prints a `https://viewer.diagrams.net/...` URL with the diagram XML deflate-compressed and base64-encoded into the URL fragment. The fragment (after `#`) is never sent to the server, so nothing is uploaded — the diagram opens client-side for viewing and editing. Useful when the user cannot install the desktop app.
### Fallback chain
@@ -548,104 +438,19 @@ fi
## Common Mistakes
-| Mistake | Fix |
-|---------|-----|
-| Missing `id="0"` and `id="1"` root cells | Always include both at the top of `<root>` |
-| Shapes not connected | `source` and `target` on edge must match existing shape `id` values |
-| Export command not found on macOS | Try full path `/Applications/draw.io.app/Contents/MacOS/draw.io` |
-| Linux: blank/error output headlessly | Prefix command with `xvfb-run -a` |
-| Linux: `--no-sandbox` placed before input file (parsed as filename) | Move `--no-sandbox` to the very end of the command (drawio-desktop#249, #1056) |
-| Linux: `Failed to get 'appData' path` / `Home directory not accessible` | `export HOME=/tmp` before invoking drawio (drawio-desktop#127) |
-| Linux server: segfault / EGL / MESA `failed to load driver` errors | Add `--disable-gpu` (suppresses Chromium GL init when no GPU available) |
-| PDF export fails | Ensure Chromium is available (draw.io bundles it on desktop) |
-| Background color wrong in CLI export | Known CLI bug; add `--transparent` flag or set background via style |
-| Overlapping shapes | Scale spacing with complexity (200–350px); leave routing corridors |
-| Edges crossing through shapes | Add waypoints, distribute entry/exit points, or increase spacing |
-| Special characters in `value` | Use XML entities: `&amp;` `&lt;` `&gt;` `&quot;` |
-| Iteration loop never ends | After 5 rounds, suggest user open .drawio in draw.io desktop for fine-tuning |
-| Self-closing edge `mxCell` | Always use expanded form with `<mxGeometry>` child — self-closing edges won't render |
-| `--` inside XML comments | Illegal per XML spec — use single hyphens or rephrase |
-| Arrowhead overlaps bend | Final edge segment before target must be ≥20px — increase spacing or add waypoints |
-| Literal `\n` in label text | Use `&#xa;` for line breaks in `value` attributes |
-| Vision returns 400 "Could not process image" on draft PNG | Re-export the preview without `-e` (issue #8). Root cause is actually a truncated IEND chunk in `-e` PNGs (issue #8), not the `zTXt` chunk itself — but the simplest fix for the preview is just to skip `-e`. |
-| Final `-e` PNG won't open in image viewers / vision APIs | Run the IEND repair snippet (Export → Post-export PNG repair). draw.io CLI emits `-e` PNGs with an 8-byte truncation at IEND. SVG/PDF unaffected. |
+When something looks wrong (export fails, vision rejects a PNG, layout broken, edges misroute), see `references/troubleshooting.md` for a row-by-row mistake → fix table.
## Diagram Type Presets
-When the user requests a specific diagram type, apply the matching preset below for shapes, styles, and layout conventions.
-
-### ERD (Entity-Relationship Diagram)
-
-| Element | Style | Notes |
-|---------|-------|-------|
-| Table | `shape=table;startSize=30;container=1;collapsible=1;childLayout=tableLayout;fixedRows=1;rowLines=0;fontStyle=1;strokeColor=#6c8ebf;fillColor=#dae8fc;` | Each table is a container |
-| Row (column) | `shape=tableRow;horizontal=0;startSize=0;swimlaneHead=0;swimlaneBody=0;fillColor=none;collapsible=0;dropTarget=0;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;fontSize=12;` | Child of table, `parent=tableId` |
-| PK column | Bold text: `fontStyle=1` on the row | Mark with `PK` prefix or key icon |
-| FK relationship | Dashed edge: `dashed=1;endArrow=ERmandOne;startArrow=ERmandOne;` | Use ER notation arrows |
-| Layout | TB, tables spaced 300px apart | Group related tables vertically |
-
-### UML Class Diagram
-
-| Element | Style | Notes |
-|---------|-------|-------|
-| Class box | `swimlane;fontStyle=1;align=center;startSize=26;html=1;` | 3-section: title / attributes / methods |
-| Separator | `line;strokeWidth=1;fillColor=none;align=left;verticalAlign=middle;spacingTop=-1;spacingLeft=3;spacingRight=10;rotatable=0;labelPosition=left;points=[];portConstraint=eastwest;` | Between sections |
-| Inheritance | `endArrow=block;endFill=0;` | Hollow triangle arrow |
-| Implementation | `endArrow=block;endFill=0;dashed=1;` | Dashed + hollow triangle |
-| Composition | `endArrow=diamondThin;endFill=1;` | Filled diamond |
-| Aggregation | `endArrow=diamondThin;endFill=0;` | Hollow diamond |
-| Layout | TB, classes 250px apart | Interfaces above implementations |
-
-### Sequence Diagram
-
-| Element | Style | Notes |
-|---------|-------|-------|
-| Actor/Object | `shape=umlLifeline;perimeter=lifelinePerimeter;whiteSpace=wrap;html=1;container=1;collapsible=0;recursiveResize=0;outlineConnect=0;portConstraint=eastwest;` | Lifeline with dashed vertical line |
-| Sync message | `html=1;verticalAlign=bottom;endArrow=block;` | Solid line, filled arrowhead |
-| Async message | `html=1;verticalAlign=bottom;endArrow=open;dashed=1;` | Dashed line, open arrowhead |
-| Return message | `html=1;verticalAlign=bottom;endArrow=open;dashed=1;strokeColor=#999999;` | Grey dashed |
-| Activation box | `shape=umlFrame;whiteSpace=wrap;` on the lifeline | Narrow rectangle on lifeline |
-| Layout | LR, lifelines spaced 200px apart | Time flows top to bottom |
-
-### Architecture Diagram
-
-| Element | Style | Notes |
-|---------|-------|-------|
-| Layer/tier | `swimlane;startSize=30;` | Containers for grouping: Client / API / Service / Data |
-| Service | `rounded=1;whiteSpace=wrap;html=1;` + tier color | Use color palette by tier |
-| Database | `shape=cylinder3;whiteSpace=wrap;html=1;` | Green palette |
-| Queue/Bus | `rounded=1;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;` | Yellow — place centrally for hub pattern |
-| Gateway/LB | `shape=mxgraph.aws4.resourceIcon;` or `rounded=1;` with orange | Orange palette |
-| External | `rounded=1;dashed=1;fillColor=#f5f5f5;strokeColor=#666666;` | Dashed border for external systems |
-| Layout | TB or LR by tier count; ≥4 tiers → TB | Hub nodes centered |
-
-### ML / Deep Learning Model Diagram
-
-For neural network architecture diagrams — ideal for papers targeting NeurIPS, ICML, ICLR.
-
-| Element | Style | Notes |
-|---------|-------|-------|
-| Layer block | `rounded=1;whiteSpace=wrap;html=1;` + type color | Main building block |
-| Input/Output | `fillColor=#d5e8d4;strokeColor=#82b366;` | Green |
-| Conv / Pooling | `fillColor=#dae8fc;strokeColor=#6c8ebf;` | Blue |
-| Attention / Transformer | `fillColor=#e1d5e7;strokeColor=#9673a6;` | Purple |
-| RNN / LSTM / GRU | `fillColor=#fff2cc;strokeColor=#d6b656;` | Yellow |
-| FC / Linear | `fillColor=#ffe6cc;strokeColor=#d79b00;` | Orange |
-| Loss / Activation | `fillColor=#f8cecc;strokeColor=#b85450;` | Red/Pink |
-| Skip connection | `dashed=1;endArrow=block;curved=1;` | Dashed curved arrow |
-| Tensor shape label | Add shape annotation as secondary label: `value="Conv2D&#xa;(B, 64, 32, 32)"` | Use `&#xa;` for multi-line |
-| Layout | TB (data flows top→bottom), layers 150px apart | Group encoder/decoder as swimlanes |
-
-**Tensor shape convention:** annotate each layer with input/output tensor dimensions in `(B, C, H, W)` or `(B, T, D)` format. Place dimensions as the second line of the label using `&#xa;`.
-
-### Flowchart (enhanced)
-
-| Element | Style | Notes |
-|---------|-------|-------|
-| Start/End | `ellipse;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;` | Green oval |
-| Process | `rounded=0;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;` | Blue rectangle |
-| Decision | `rhombus;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;` | Yellow diamond |
-| I/O | `shape=parallelogram;perimeter=parallelogramPerimeter;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;` | Orange parallelogram |
-| Subprocess | `rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;` + double border | Purple |
-| Yes/No labels | `value="Yes"` / `value="No"` on decision edges | Always label decision branches |
-| Layout | TB, 200px vertical gap | Decisions branch LR, merge back to center |
+When the user requests a specific diagram type, read `references/diagram-types.md` for the matching preset (shapes, edges, layout direction). Pick by user phrasing:
+
+| User says | Section in `references/diagram-types.md` |
+|---|---|
+| "ER diagram", "schema diagram", "data model" | ERD |
+| "UML class diagram", "class diagram" | UML Class |
+| "sequence diagram", "interaction diagram", "lifeline" | Sequence |
+| "architecture", "system diagram", "service diagram" | Architecture |
+| "neural network", "model architecture", "ML diagram", "deep learning" | ML / Deep Learning Model |
+| "flowchart", "decision tree", "process flow" | Flowchart |
+
+The diagram-type preset sets **structural** style keywords. If a user style preset is also active (see `## Style Presets`), keep the structural keywords and layer color/font/edge/extras on top — read `references/style-presets.md` → "Interaction with diagram-type presets" for the merge rules.
diff --git a/references/diagram-types.md b/references/diagram-types.md
new file mode 100644
index 0000000..c053b15
--- /dev/null
+++ b/references/diagram-types.md
@@ -0,0 +1,83 @@
+# Diagram Type Presets
+
+When the user requests a specific diagram type, apply the matching preset below for shapes, styles, and layout conventions. These presets set **structural** style keywords (e.g. ERD's `shape=table;childLayout=tableLayout`); a user style preset (see `references/style-presets.md`) layers color/font/edge/extras on top.
+
+Read this file when:
+- The user names one of these diagram types (ERD, UML class, sequence, architecture, ML/DL model, flowchart)
+- You're choosing shape vocabulary or layout direction for a new diagram
+
+## ERD (Entity-Relationship Diagram)
+
+| Element | Style | Notes |
+|---------|-------|-------|
+| Table | `shape=table;startSize=30;container=1;collapsible=1;childLayout=tableLayout;fixedRows=1;rowLines=0;fontStyle=1;strokeColor=#6c8ebf;fillColor=#dae8fc;` | Each table is a container |
+| Row (column) | `shape=tableRow;horizontal=0;startSize=0;swimlaneHead=0;swimlaneBody=0;fillColor=none;collapsible=0;dropTarget=0;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;fontSize=12;` | Child of table, `parent=tableId` |
+| PK column | Bold text: `fontStyle=1` on the row | Mark with `PK` prefix or key icon |
+| FK relationship | Dashed edge: `dashed=1;endArrow=ERmandOne;startArrow=ERmandOne;` | Use ER notation arrows |
+| Layout | TB, tables spaced 300px apart | Group related tables vertically |
+
+## UML Class Diagram
+
+| Element | Style | Notes |
+|---------|-------|-------|
+| Class box | `swimlane;fontStyle=1;align=center;startSize=26;html=1;` | 3-section: title / attributes / methods |
+| Separator | `line;strokeWidth=1;fillColor=none;align=left;verticalAlign=middle;spacingTop=-1;spacingLeft=3;spacingRight=10;rotatable=0;labelPosition=left;points=[];portConstraint=eastwest;` | Between sections |
+| Inheritance | `endArrow=block;endFill=0;` | Hollow triangle arrow |
+| Implementation | `endArrow=block;endFill=0;dashed=1;` | Dashed + hollow triangle |
+| Composition | `endArrow=diamondThin;endFill=1;` | Filled diamond |
+| Aggregation | `endArrow=diamondThin;endFill=0;` | Hollow diamond |
+| Layout | TB, classes 250px apart | Interfaces above implementations |
+
+## Sequence Diagram
+
+| Element | Style | Notes |
+|---------|-------|-------|
+| Actor/Object | `shape=umlLifeline;perimeter=lifelinePerimeter;whiteSpace=wrap;html=1;container=1;collapsible=0;recursiveResize=0;outlineConnect=0;portConstraint=eastwest;` | Lifeline with dashed vertical line |
+| Sync message | `html=1;verticalAlign=bottom;endArrow=block;` | Solid line, filled arrowhead |
+| Async message | `html=1;verticalAlign=bottom;endArrow=open;dashed=1;` | Dashed line, open arrowhead |
+| Return message | `html=1;verticalAlign=bottom;endArrow=open;dashed=1;strokeColor=#999999;` | Grey dashed |
+| Activation box | `shape=umlFrame;whiteSpace=wrap;` on the lifeline | Narrow rectangle on lifeline |
+| Layout | LR, lifelines spaced 200px apart | Time flows top to bottom |
+
+## Architecture Diagram
+
+| Element | Style | Notes |
+|---------|-------|-------|
+| Layer/tier | `swimlane;startSize=30;` | Containers for grouping: Client / API / Service / Data |
+| Service | `rounded=1;whiteSpace=wrap;html=1;` + tier color | Use color palette by tier |
+| Database | `shape=cylinder3;whiteSpace=wrap;html=1;` | Green palette |
+| Queue/Bus | `rounded=1;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;` | Yellow — place centrally for hub pattern |
+| Gateway/LB | `shape=mxgraph.aws4.resourceIcon;` or `rounded=1;` with orange | Orange palette |
+| External | `rounded=1;dashed=1;fillColor=#f5f5f5;strokeColor=#666666;` | Dashed border for external systems |
+| Layout | TB or LR by tier count; ≥4 tiers → TB | Hub nodes centered |
+
+## ML / Deep Learning Model Diagram
+
+For neural network architecture diagrams — ideal for papers targeting NeurIPS, ICML, ICLR.
+
+| Element | Style | Notes |
+|---------|-------|-------|
+| Layer block | `rounded=1;whiteSpace=wrap;html=1;` + type color | Main building block |
+| Input/Output | `fillColor=#d5e8d4;strokeColor=#82b366;` | Green |
+| Conv / Pooling | `fillColor=#dae8fc;strokeColor=#6c8ebf;` | Blue |
+| Attention / Transformer | `fillColor=#e1d5e7;strokeColor=#9673a6;` | Purple |
+| RNN / LSTM / GRU | `fillColor=#fff2cc;strokeColor=#d6b656;` | Yellow |
+| FC / Linear | `fillColor=#ffe6cc;strokeColor=#d79b00;` | Orange |
+| Loss / Activation | `fillColor=#f8cecc;strokeColor=#b85450;` | Red/Pink |
+| Skip connection | `dashed=1;endArrow=block;curved=1;` | Dashed curved arrow |
+| Tensor shape label | Add shape annotation as secondary label: `value="Conv2D&#xa;(B, 64, 32, 32)"` | Use `&#xa;` for multi-line |
+| Layout | TB (data flows top→bottom), layers 150px apart | Group encoder/decoder as swimlanes |
+
+**Tensor shape convention:** annotate each layer with input/output tensor dimensions in `(B, C, H, W)` or `(B, T, D)` format. Place dimensions as the second line of the label using `&#xa;`.
+
+## Flowchart (enhanced)
+
+| Element | Style | Notes |
+|---------|-------|-------|
+| Start/End | `ellipse;whiteSpace=wrap;html=1;fillColor=#d5e8d4;strokeColor=#82b366;` | Green oval |
+| Process | `rounded=0;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;` | Blue rectangle |
+| Decision | `rhombus;whiteSpace=wrap;html=1;fillColor=#fff2cc;strokeColor=#d6b656;` | Yellow diamond |
+| I/O | `shape=parallelogram;perimeter=parallelogramPerimeter;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;` | Orange parallelogram |
+| Subprocess | `rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;` + double border | Purple |
+| Yes/No labels | `value="Yes"` / `value="No"` on decision edges | Always label decision branches |
+| Layout | TB, 200px vertical gap | Decisions branch LR, merge back to center |
diff --git a/references/style-presets.md b/references/style-presets.md
new file mode 100644
index 0000000..5721189
--- /dev/null
+++ b/references/style-presets.md
@@ -0,0 +1,110 @@
+# Style Presets — Learn, Apply, Manage
+
+A **style preset** is a named JSON file capturing a user's visual preferences — palette, shape vocabulary, fonts, edge style. When a preset is active, it fully replaces the built-in conventions in SKILL.md's color/shape/edge tables.
+
+Read this file when:
+- The user asks to "learn", "save", "remember", or "extract" a style from a file
+- The user wants to manage existing presets (list, set default, delete, rename)
+- You've resolved an active preset in step 0.5 and need the application rules
+- You need to validate a preset file before loading it
+
+## Locations and lookup order
+
+1. `~/.drawio-skill/styles/<name>.json` — user presets (survive `git pull`).
+2. `<this-skill-dir>/styles/built-in/<name>.json` — built-ins shipped with the skill (`default`, `corporate`, `handdrawn`).
+
+A user preset shadows a built-in of the same name.
+
+Only user presets can have `"default": true`. When the user says *"make `<built-in-name>` my default"*, copy the built-in JSON to `~/.drawio-skill/styles/<name>.json` first, then set `default: true` on the copy — leave the shipped built-in untouched.
+
+**Name normalisation:** always lowercase the user-provided name before writing or looking up files (the preset schema enforces lowercase; uppercase names will fail validation).
+
+## Applying a preset
+
+When SKILL.md's step 0.5 identified a preset, it fully replaces the built-in palette, shape keywords, edge defaults, and font for this diagram — do not mix values from the built-in color table.
+
+**Color lookup.** For each role a shape plays (service / database / queue / gateway / error / external / security), resolve `preset.roles[role]` to a slot name, then `preset.palette[<slot>]` to the `(fillColor, strokeColor)` pair. If `roles[role]` is unset or the resolved slot is `null`, follow this fallback ladder:
+
+1. Try the role's canonical slot (`service→primary`, `database→success`, `queue→warning`, `gateway→accent`, `error→danger`, `external→neutral`, `security→secondary`).
+2. If that slot is also empty, pick the most-populated non-null slot in the preset.
+3. Never reach into the built-in color table — the preset is authoritative.
+
+**Decision and container shapes** are not in `preset.roles` — they have shape vocabulary (`preset.shapes.decision`, `preset.shapes.container`) but no role-to-slot mapping. Pick their colors as follows:
+- **Decision** (rhombus) → use `preset.palette.warning` (the canonical yellow slot in the built-in conventions). If `warning` is empty, apply the slot-fallback ladder above starting from `warning`.
+- **Container** (swimlane) → use the palette slot matching the tier/grouping the container represents (e.g. a "Services" tier container uses `primary`; a "Data" tier uses `success`). If no tier signal is available, default to `primary`.
+
+**Shape keywords.** Use `preset.shapes[role]` as the **prefix** of the vertex style string (before `whiteSpace=wrap;html=1;...`). Example: for a database role, if `preset.shapes.database = "shape=cylinder3"`, the vertex style starts `shape=cylinder3;whiteSpace=wrap;html=1;fillColor=...`. The six named shape keys are `service`, `database`, `queue`, `decision`, `external`, `container`. Roles `gateway`, `error`, and `security` reuse `preset.shapes.service` unless the preset explicitly populates a key with their name.
+
+**Edges.** Use `preset.edges.style` as the base edge style string. Append `preset.edges.arrow`. Per-edge routing keys (`exitX/exitY/entryX/entryY/...`) are still added by the usual routing rules in SKILL.md. If the flow between two shapes matches a token from `preset.edges.dashedFor` (either because the user's prompt used that word, or because one end of the edge plays a role whose typical relation is "optional"), append `;dashed=1` to the edge style.
+
+**Fonts.** Append `fontFamily=<preset.font.fontFamily>;fontSize=<preset.font.fontSize>` to every vertex style. Container headers and swimlane titles additionally get `fontSize=<preset.font.titleFontSize>;fontStyle=1` when `preset.font.titleBold` is `true`.
+
+**Extras.**
+- `preset.extras.sketch === true` → append `sketch=1` to every vertex style and every edge style.
+- `preset.extras.globalStrokeWidth !== 1` (any value other than the drawio default of 1, including `0.5`) → append `strokeWidth=<n>` to every vertex style and every edge style.
+
+**Interaction with diagram-type presets** (ERD / UML / Sequence / ML / Flowchart). Diagram-type presets set structural style keywords that the user preset must preserve (e.g. ERD tables rely on `shape=table;startSize=30;container=1;childLayout=tableLayout;...`). The rule: keep the diagram-type preset's structural keywords, then layer the user preset's color / font / edge / extras on top. When a diagram-type preset hardcodes a color (`fillColor=#dae8fc`, etc.) that conflicts with the user preset, the user preset's color wins. Exception: `fillColor=none` is structural — do not replace it with a palette color.
+
+## Learn flow
+
+**Triggers:** "learn my style from `<path>` as `<name>`", "save this as `<name>` style", "remember this style as `<name>`".
+
+**Dispatch by file extension:**
+- `.drawio`, `.xml` → XML path
+- `.png`, `.jpg`, `.jpeg`, `.svg` (rasterized flat image) → image path
+
+**Steps:**
+
+1. **Load the extraction reference.** Read `references/style-extraction.md` into context.
+2. **Extract** following the XML path or image path procedure in the reference.
+3. **Normalize and build candidate.** Convert the user-provided preset name to lowercase. Use this normalized name for ALL file paths in this flow. Build the candidate preset JSON and write it to `/tmp/drawio-preset-<name>.json` (where `<name>` is the already-normalized name). Do **not** save to `~/.drawio-skill/styles/<name>.json` yet.
+4. **Render a sample** using the sample-diagram skeleton in `references/style-extraction.md`, parameterized by the candidate preset. Export PNG to `./preset-<name>-sample.png` using the same `draw.io -x -f png -e -s 2 -o ./preset-<name>-sample.png /tmp/drawio-preset-<name>.drawio` command the main workflow uses.
+5. **Show the user:**
+ - Preset summary table (palette hex values, shapes per role, font, edge style, extras).
+ - The sample PNG path (and embed the image if the environment supports it).
+ - Provenance line: `source.type`, `source.path`, `extracted_at`, `confidence`.
+6. **Wait for approval:**
+ - "save" / "looks good" → write candidate to `~/.drawio-skill/styles/<name>.json`. Create `~/.drawio-skill/styles/` if it doesn't exist. Delete tempfile and sample PNG.
+ - "change `<field>` to `<value>`" → edit the in-memory candidate, re-render, re-ask.
+ - "cancel" / "abort" / "no" → delete tempfile and sample PNG; nothing saved.
+
+**Error behavior:**
+
+| Failure | Behavior |
+|---|---|
+| Source path does not exist | Stop; report path not found. |
+| XML parse fails | Stop; report the parse error; suggest opening the file in drawio desktop to repair. |
+| Image vision unavailable | Stop; tell user to re-run on a vision-capable model or provide the `.drawio` file. |
+| Extraction yields 0 vertices / shapes | Stop; refuse to save. |
+| Extraction yields <3 distinct color pairs | Continue; mark `confidence: "low"` (image) or `"medium"` (XML); warn in summary. |
+| Preset name collides with existing user preset | Ask: overwrite, or pick a new name. |
+| Preset name collides with a built-in preset | Save to user dir (shadows the built-in); warn once. |
+| Sample render fails | Still show summary; note "could not render sample — saving on your OK anyway". Do not block. |
+
+## Management operations
+
+All operations are natural language — no slash commands.
+
+*Apply name normalisation (lowercase) to all `<name>`, `<a>`, `<b>` arguments before any file operation.*
+
+| User says | Agent does |
+|---|---|
+| "list my styles", "what styles do I have", "show me my style presets" | Read `~/.drawio-skill/styles/` and `<this-skill-dir>/styles/built-in/`. Print a table: `name`, `location` (user/built-in), `source.type`, `confidence`, `default` flag. Built-ins shadowed by a user preset are marked so. |
+| "show my `<name>` style", "what's in `<name>`" | Print the preset JSON (pretty-printed) + a one-line summary (source, confidence, is-default). |
+| "make `<name>` the default", "set `<name>` as default" | If `<name>` is a user preset: set `default: true` on it; clear `default` on any other user preset that had it; save both files. If `<name>` is a built-in: copy `<this-skill-dir>/styles/built-in/<name>.json` → `~/.drawio-skill/styles/<name>.json` first, then set `default: true` on the copy. Never mutate the shipped built-in. |
+| "remove default", "unset default" | Clear `default: true` from whichever user preset has it. |
+| "delete `<name>`", "remove `<name>`" | Confirm first. Then `rm ~/.drawio-skill/styles/<name>.json`. Refuse to delete files under `<this-skill-dir>/styles/built-in/` — suggest shadowing with a user preset of the same name. |
+| "rename `<a>` to `<b>`" | `mv ~/.drawio-skill/styles/<a>.json ~/.drawio-skill/styles/<b>.json`, then update the `name` field inside. Fails if `<a>` is a built-in (offer to copy-then-rename instead). |
+| "learn my style from `<path>` as `<name>`" | Dispatch to the Learn flow above. |
+
+## Preset file validation
+
+When loading any preset (for generation or management), do a lightweight structural check:
+- Required top-level fields present (`name`, `version`, `palette`, `roles`, `shapes`, `font`, `edges`).
+- `version === 1`.
+- Every populated palette slot has both `fillColor` and `strokeColor` as `#RRGGBB`.
+- `confidence` ∈ {`"low"`, `"medium"`, `"high"`} if present.
+
+On validation failure:
+- **During generation:** warn the user, fall back to built-in conventions for this one diagram, do not mutate the file.
+- **During learn:** refuse to save the candidate; report which field failed.
diff --git a/references/troubleshooting.md b/references/troubleshooting.md
new file mode 100644
index 0000000..0ff83f6
--- /dev/null
+++ b/references/troubleshooting.md
@@ -0,0 +1,25 @@
+# Troubleshooting — Common Mistakes
+
+Read this when something looks wrong in the output (rendering, export, layout, edges) or when a CLI invocation fails. Most rows have a one-line fix.
+
+| Mistake | Fix |
+|---------|-----|
+| Missing `id="0"` and `id="1"` root cells | Always include both at the top of `<root>` |
+| Shapes not connected | `source` and `target` on edge must match existing shape `id` values |
+| Self-closing edge `mxCell` (`<mxCell ... edge="1" />`) | Use the expanded form with `<mxGeometry relative="1" as="geometry" />` child — self-closing edges won't render |
+| `--` inside XML comments | Illegal per XML spec — use single hyphens or rephrase |
+| Special characters in `value` | Use XML entities: `&amp;` `&lt;` `&gt;` `&quot;` |
+| Literal `\n` in label text | Use `&#xa;` for line breaks in `value` attributes |
+| Overlapping shapes | Scale spacing with complexity (200–350px); leave routing corridors |
+| Edges crossing through shapes | Add waypoints, distribute entry/exit points, or increase spacing |
+| Arrowhead overlaps bend | Final edge segment before target must be ≥20px — increase spacing or add waypoints |
+| Iteration loop never ends | After 5 rounds, suggest user open .drawio in draw.io desktop for fine-tuning |
+| Export command not found on macOS | Try full path `/Applications/draw.io.app/Contents/MacOS/draw.io` |
+| Linux: blank/error output headlessly | Prefix command with `xvfb-run -a` |
+| Linux: `--no-sandbox` placed before input file (parsed as filename) | Move `--no-sandbox` to the very end of the command (drawio-desktop#249, #1056) |
+| Linux: `Failed to get 'appData' path` / `Home directory not accessible` | `export HOME=/tmp` before invoking drawio (drawio-desktop#127) |
+| Linux server: segfault / EGL / MESA `failed to load driver` errors | Add `--disable-gpu` (suppresses Chromium GL init when no GPU available) |
+| PDF export fails | Ensure Chromium is available (draw.io bundles it on desktop) |
+| Background color wrong in CLI export | Known CLI bug; add `--transparent` flag or set background via style |
+| Vision returns 400 "Could not process image" on draft PNG | Re-export the preview without `-e` (issue #8). Root cause is a truncated IEND chunk in `-e` PNGs, not the `zTXt` chunk itself — but skipping `-e` for the preview is the simplest fix. |
+| Final `-e` PNG won't open in image viewers / vision APIs | Run `python3 <this-skill-dir>/scripts/repair_png.py <path>`. draw.io CLI emits `-e` PNGs with an 8-byte truncation at IEND. SVG/PDF unaffected. |
diff --git a/scripts/encode_drawio_url.py b/scripts/encode_drawio_url.py
new file mode 100755
index 0000000..c73e9a1
--- /dev/null
+++ b/scripts/encode_drawio_url.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python3
+"""Encode a .drawio XML file into a diagrams.net viewer URL.
+
+Used as the browser fallback when the draw.io desktop CLI is unavailable.
+Produces a client-side URL — the diagram XML is encoded in the URL
+fragment (after `#`), so nothing is uploaded to any server.
+
+Usage: python3 encode_drawio_url.py <path/to/input.drawio>
+"""
+import base64
+import sys
+import urllib.parse
+import zlib
+
+
+def encode(xml: str) -> str:
+ # Raw deflate (no zlib header) — diagrams.net uses mxGraph's raw inflate
+ c = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
+ compressed = c.compress(xml.encode("utf-8")) + c.flush()
+ # Standard base64 (atob rejects url-safe -/_); strip newlines
+ encoded = base64.b64encode(compressed).decode("utf-8").replace("\n", "")
+ return (
+ "https://viewer.diagrams.net/?tags=%7B%7D&lightbox=1&edit=_blank#R"
+ + urllib.parse.quote(encoded, safe="")
+ )
+
+
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ print("usage: encode_drawio_url.py <path>", file=sys.stderr)
+ sys.exit(2)
+ with open(sys.argv[1], "r", encoding="utf-8") as f:
+ print(encode(f.read()))
diff --git a/scripts/repair_png.py b/scripts/repair_png.py
new file mode 100755
index 0000000..7e95b7c
--- /dev/null
+++ b/scripts/repair_png.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+"""Repair truncated IEND chunk in draw.io -e PNG exports (issue #8).
+
+draw.io's CLI emits -e PNGs with the 4-byte IEND length field but missing
+the 8 bytes of "IEND" type + CRC. Strict PNG decoders and vision APIs
+(Anthropic included) reject the file with 400 "Could not process image".
+SVG/PDF are unaffected.
+
+Usage: python3 repair_png.py <path/to/diagram.drawio.png>
+
+Idempotent: the endswith(IEND) guard makes this a no-op once draw.io
+fixes the bug upstream, so it's safe to run unconditionally after every
+-e PNG export.
+"""
+import sys
+
+IEND = b"\x00\x00\x00\x00IEND\xaeB`\x82"
+
+
+def repair(path: str) -> bool:
+ with open(path, "rb") as f:
+ data = f.read()
+ if data.endswith(IEND):
+ return False
+ if data.endswith(b"\x00\x00\x00\x00"):
+ data = data[:-4]
+ with open(path, "wb") as f:
+ f.write(data + IEND)
+ return True
+
+
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ print("usage: repair_png.py <path>", file=sys.stderr)
+ sys.exit(2)
+ if repair(sys.argv[1]):
+ print(f"repaired {sys.argv[1]}")