Restructure to skill-manager conventions

- Move the TypeScript project under scripts/ (src, tsconfig,
  package.json, pnpm lockfile/workspace, canonical .gitignore);
  drop the npm package-lock
- Add scripts/Taskfile.yml aggregator plus .scripts modules
  (loggers, base, cli) with build, run, and validate tasks
- Move the six SKILL-*.md docs into references/ with kebab names
  and extract the connector-routing sections from SKILL.md into
  references/routing-best-practices.md (SKILL.md 666 -> ~310 lines)
- Add license/metadata/compatibility frontmatter, an Available
  scripts section, and update all CLI paths in README and references

skill-manager validate: 13/13 passed, 0 warnings.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-27 15:20:26 +03:00
co-authored by Claude Fable 5
parent 99f1fd07e3
commit 77655d1d97
72 changed files with 1089 additions and 1828 deletions
+60
View File
@@ -0,0 +1,60 @@
# drawio-main — Capabilities
This file lists all capabilities an agent can use from this skill.
---
## Capability 1 — Diagram generation
Create `.drawio` files (and optionally export to PNG/SVG/PDF) from a description or requirements.
See [SKILL.md](./SKILL.md) for the generation workflow, XML format, page sizes, element shapes, and well-formedness rules.
See [rules-layout.md](./rules-layout.md) for mandatory connector and layout rules.
---
## Capability 2 — Diagram analysis (drawio-tools CLI)
A **TypeScript / Node.js** CLI tool for programmatic analysis of `.drawio` files.
Entry point: `node dist/cli/commands.js` (run from the skill's `scripts/` directory), or `task run -- --file=… --action=…`.
### Usage
```bash
cd <skill>/scripts
node dist/cli/commands.js --file <path-to-file.drawio> --action <action> [--page <index>]
# short flags: -f, -a, -p, -h
```
`--page` selects the diagram tab (0-based, default 0). Ignored by `summary` (processes all pages).
Always prints YAML to stdout. Exit code `0` on success, `1` on error.
### Actions
#### Inventory
| Action | Scope | Description |
|---|---|---|
| `summary` | All pages | Full inventory of shapes + edges for every page/tab |
| `page-summary` | Single page (`--page`) | Full inventory of shapes + edges for one page |
| `page-hierarchy` | Page 0 | Recursive containment tree with totalLevels (nesting depth count) |
| `page-hierarchy-full` | Page 0 | Same as page-hierarchy + full geometry (x, y, width, height) per shape at each nesting level |
| `page-connectors-summary` | Page 0 | Per-connector details: type, label, waypoints, source/target names |
#### Validation
| Action | Scope | Description |
|---|---|---|
| `validate` | All pages | **Mandatory final gate** — XML well-formedness + maxGraph compile + sanity check (vertices/edges > 0). Run before finishing any diagram work |
| `page-connectors-validation` | Page 0 | Connector-shape overlaps + connector crossings |
| `page-labels-validation` | Page 0 | Empty labels, duplicate labels, labels > 80 chars |
| `page-shape-bbox-validation` | Page 0 | Non-containment bounding box overlaps between shapes |
| `page-orphans` | Page 0 | Isolated shapes (no edges) + dangling connectors (missing endpoints) |
#### Layout
| Action | Scope | Description |
|---|---|---|
| `page-recommendations` | Page 0 | Smallest standard page size (A4→A3→A2→A1→custom) that fits content with 80 px margin |
> For install/build instructions, source structure, and how to add new actions, see [maintenance.md](./maintenance.md).
+178
View File
@@ -0,0 +1,178 @@
# drawio-main — Maintenance Guide
This document is for **developers** maintaining or extending the `drawio-tools` CLI.
For agent usage instructions, see [SKILL.md](../SKILL.md).
The CLI lives under the skill's `scripts/` directory (`scripts/src/` → `scripts/dist/`),
per the skill-manager structure conventions. All commands below run from `scripts/`.
---
## Tech stack
| Layer | Library / Tool | Version |
|---|---|---|
| Language | TypeScript ESM (`NodeNext`) | — |
| Package manager | pnpm | v11.9+ |
| XML model | `@maxgraph/core` | v0.23 |
| DOM polyfill | `jsdom` | — |
| Deflate decode | `pako` | — |
| YAML output | `js-yaml` | — |
| Build | `tsc` | — |
| Dev runner | `tsx` | — |
`pnpm-workspace.yaml` must include:
```yaml
allowBuilds:
esbuild: true
```
---
## Install and deploy
The git repository is the source of truth. Install dependencies and build inside `scripts/`:
```bash
cd <skill>/scripts
pnpm install
task build # or: pnpm run build
```
Deploy with skill-manager (creates absolute-path symlinks in `$HOME/.agents/skills`
and `$HOME/.claude/skills`, so the repo working copy stays the single source of truth):
```bash
cd <skill-manager>/scripts
task deploy -- --skill-dir="/absolute/path/to/drawio-main"
```
Verify the CLI works after installation:
```bash
cd <skill>/scripts
node dist/cli/commands.js -f <diagram.drawio> -a summary
```
---
## Run the CLI
```bash
cd <skill>/scripts
task run -- --file="<diagram.drawio>" --action=<action>
# or directly:
node dist/cli/commands.js -f <diagram.drawio> -a <action>
# or build-and-run during development:
pnpm run cli -f <diagram.drawio> -a <action>
```
> Note: with `pnpm run cli`, pass arguments directly after `cli` — do **not** use `--` separator.
---
## Build (development only)
Build only (no run):
```bash
cd <skill>/scripts
task build # tsc → dist/
```
---
## Source structure
```
src/
├── cli/
│ └── commands.ts # parseArgs dispatcher → dynamic action imports
├── services/
│ ├── drawio-parser/
│ │ ├── parser.ts # parseAllPages() / parseDiagram() — Shape, Edge, ParsedPage
│ │ └── page-summary.ts # buildPageSummary() — shared per-page serialisation helper
│ └── hierarchy-builder/
│ └── hierarchy-builder.ts # buildHierarchy() — shared BFS depth map + containment tree
└── actions/
├── summary/ # all pages inventory
├── page-summary/ # single page inventory (uses --page)
├── page-hierarchy/ # containment tree from parentId
├── page-connectors-summary/ # connector stats
├── page-connectors-validation/ # overlap + crossing detection
├── page-labels-validation/ # label quality checks
├── page-shape-bbox-validation/ # bounding box overlap detection
├── page-orphans/ # isolated shapes + dangling connectors
├── page-recommendations/ # page size recommendation
├── page-hierarchy-full/ # nesting levels with full shape geometry (x, y, width, height)
└── validate/ # MANDATORY final gate — XML well-formedness + maxGraph compile + sanity check
```
Each action exports `run(filePath: string, pageIndex?: number): Record<string, unknown>`.
### Key modules
**`src/services/drawio-parser/parser.ts`**
- `parseAllPages(filePath)` — parses all `<diagram>` tabs in an mxfile, returns `ParsedPage[]`
- `parseDiagram(filePath)` — backward-compat wrapper, returns first page only
- Multi-page support: regex extracts all `<diagram>` blocks; each decoded separately (base64 + pako `inflateRaw`)
- Uses `@maxgraph/core` `ModelXmlSerializer` + `GraphDataModel` with a `jsdom` DOM polyfill
**`src/services/drawio-parser/page-summary.ts`**
- `buildPageSummary(page: ParsedPage): PageSummaryResult` — shared helper used by both `summary` and `page-summary` actions
**`src/services/hierarchy-builder/hierarchy-builder.ts`**
- `buildHierarchy(page: ParsedPage): HierarchyResult` — shared BFS depth map + containment tree
- Returns: `tree`, `allNodes`, `depthMap`, `childrenOf`, `maxDepth`, `totalLevels` (= maxDepth + 1), `depthCounts`
- Used by `page-hierarchy` (tree output) and `page-hierarchy-full` (geometry per nesting level)
**`src/cli/commands.ts`**
- `parseArgs` dispatcher → dynamic imports of action modules
- Supports `--file` / `-f`, `--action` / `-a`, `--page` / `-p` (0-based, default 0), `--help` / `-h`
- All output serialised to YAML on stdout; exit `0` success, `1` error
---
## Adding a new action
1. Create `src/actions/<name>/action.ts` exporting:
```ts
export async function run(filePath: string, pageIndex?: number): Promise<Record<string, unknown>>
```
2. Register it in `src/cli/commands.ts` under `ACTIONS`:
```ts
"my-action": () => import("../actions/my-action/action.js"),
```
3. Use `parseDiagram(filePath)` (first page) or `parseAllPages(filePath)` (all pages) from the parser
4. Optionally import `buildPageSummary(page)` from `page-summary.ts` for standard shape/edge serialisation
5. Return a plain object — the CLI serialises it to YAML automatically
6. Run `pnpm run build` to compile and verify no TypeScript errors
### Naming convention
Actions follow `{object}-{action}` naming:
- `page-*` — operates on a single diagram page (uses `--page`, default 0)
- `summary` — operates on all pages
---
## CLI action registration map
```typescript
const ACTIONS: Record<string, () => Promise<ActionModule>> = {
"summary": () => import("../actions/summary/action.js"),
"page-summary": () => import("../actions/page-summary/action.js"),
"page-hierarchy": () => import("../actions/page-hierarchy/action.js"),
"page-connectors-summary": () => import("../actions/page-connectors-summary/action.js"),
"page-connectors-validation": () => import("../actions/page-connectors-validation/action.js"),
"page-labels-validation": () => import("../actions/page-labels-validation/action.js"),
"page-shape-bbox-validation": () => import("../actions/page-shape-bbox-validation/action.js"),
"page-orphans": () => import("../actions/page-orphans/action.js"),
"page-recommendations": () => import("../actions/page-recommendations/action.js"),
"page-hierarchy-full": () => import("../actions/page-hierarchy-full/action.js"),
"page-negative-space-summary":() => import("../actions/page-negative-space-summary/action.js"),
"validate": () => import("../actions/validate/action.js"),
};
```
+96
View File
@@ -0,0 +1,96 @@
# Negative Space Diagram
A negative space diagram is a companion diagram generated from `page-negative-space-summary` CLI output. It visualises where free routing corridors exist on the canvas — dark areas show where connectors can travel; blank (grid-visible) areas show where shapes sit.
---
## Core rule
**Black rectangles only. Shape footprints are left completely empty.**
- Place **only solid black rectangles** (`fillColor=#1a1a1a;strokeColor=none`) where free space exists
- Where shapes are positioned, place **nothing** — leave those coordinates completely empty so the draw.io grid shows through
- Do **NOT** draw white rectangles, outlines, ghost shapes, or any visual marker at shape positions
- Do **NOT** add labels, annotations, or legend entries inside the main canvas area
- **One color only: `#1a1a1a`** — no distinctions between inter-row gap bands and within-row free corridors; all free space is the same black
The resulting diagram is a pure "ink = free space, blank = occupied" map.
---
## Construction steps
1. Run `page-negative-space-summary` on the source diagram to get the free corridor data
2. For each free corridor `{xMin, xMax, yMin, yMax}` from `freeCorridors` or `textAwareFreeCorridors`, place one black rectangle covering that exact area
3. For inter-row gaps (y bands between shape rows), place a full-width black rectangle covering the entire gap band — same `#1a1a1a` color, no special treatment
4. For shape footprint coordinates — place **nothing**; those cells remain blank (grid visible)
5. Add a **border frame** — 4 black rectangles forming a closed frame around the entire diagram canvas (see Border frame rule below)
6. A legend may appear **outside** the diagram canvas bounds (above or below) — it must not overlap any part of the canvas
### Border frame rule
Every negative space diagram **must** have a 4-rectangle black border frame surrounding the canvas area. The frame consists of:
| Side | Position | Formula |
|---|---|---|
| Top | above diagram | `x = diagramXMin - frameThickness`, `y = diagramYMin - frameThickness`, `width = diagramWidth + 2×frameThickness`, `height = frameThickness` |
| Bottom | below diagram | `x = diagramXMin - frameThickness`, `y = diagramYMax`, `width = diagramWidth + 2×frameThickness`, `height = frameThickness` |
| Left | left of diagram | `x = diagramXMin - frameThickness`, `y = diagramYMin - frameThickness`, `width = frameThickness`, `height = diagramHeight + 2×frameThickness` |
| Right | right of diagram | `x = diagramXMax`, `y = diagramYMin - frameThickness`, `width = frameThickness`, `height = diagramHeight + 2×frameThickness` |
Where:
- `frameThickness` = 40 pt (divisible by 40 — mandatory)
- `diagramXMin`, `diagramXMax`, `diagramYMin`, `diagramYMax` — from the `page-negative-space-summary` output fields
- `diagramWidth = diagramXMax - diagramXMin`
- `diagramHeight = diagramYMax - diagramYMin`
All four frame rectangles use `fillColor=#1a1a1a;strokeColor=none;` — same as all other free-space rectangles.
**Example** for `diagramXMin=80, diagramXMax=1600, diagramYMin=40, diagramYMax=720, frameThickness=40`:
```
Top: x=40, y=0, width=1600, height=40
Bottom: x=40, y=720, width=1600, height=40
Left: x=40, y=0, width=40, height=760
Right: x=1600, y=0, width=40, height=760
```
Note: the left and right bars span the full height including top and bottom bars (height = diagramHeight + 2×frameThickness = 680 + 80 = 760) so corners are fully covered with no gaps.
---
## XML pattern
All rectangles use the same style — no exceptions:
```xml
<mxCell id="free-r2-left" value="" style="shape=rectangle;fillColor=#1a1a1a;strokeColor=none;" vertex="1" parent="1">
<mxGeometry x="80" y="160" width="240" height="80" as="geometry"/>
</mxCell>
```
Use the `textAwareFreeCorridors` field from `page-negative-space-summary` — it gives the pre-computed black rectangle list per row, already accounting for text regions inside shape bounding boxes.
---
## File naming
Place the negative space diagram alongside the source diagram with a `-negative-space` suffix:
```
artifacts/
├── buyer-purchase-journey.drawio
└── buyer-purchase-journey-negative-space.drawio
```
---
## Validation
Validate with the standard `validate` action before finishing:
```bash
cd <skill>/scripts && task validate -- --file="<path-to-negative-space.drawio>"
```
Expected: `valid: true`. The diagram will have 0 edges (only vertex rectangles).
+389
View File
@@ -0,0 +1,389 @@
# drawio-main — Connector Routing Best Practices
## Connector Routing Best Practices (Zero-Overlap Guarantee)
Complex architecture diagrams with many connectors require deliberate routing. Follow this process to achieve zero connector-shape overlaps.
### 1. Plan corridors before drawing
Before placing any connectors, identify **clear corridors** — horizontal or vertical bands on the canvas that are free of all shapes. Route every connector through these corridors.
#### Vertical corridors (x-axis lanes between columns)
Between each column of shapes, choose a single x-coordinate that lies in the gap:
```
GAP = (right_edge_of_left_column + left_edge_of_right_column) / 2
```
Examples from a typical IBM Cloud deployment diagram:
| Corridor name | x value | Description |
|---------------|---------|-------------|
| GAP_AB | 370 | Between Internet zone and IBM Cloud boundary |
| GAP_BC | 720 | Between IBM edge services and VPC |
| GAP_NS | 1510 | Between namespace columns inside VPC |
| GAP_CD | 2450 | Between VPC right edge and external service group |
| GAP_DE | 2760 | Between two external service columns |
#### Horizontal corridors (y-axis lanes between rows)
Between each row of shapes, choose a y-coordinate in the clear gap:
| Corridor name | y value | Description |
|---------------|---------|-------------|
| Y_TOP | 110 | Above all shapes (highway for cross-diagram connectors) |
| Y_ROKS | 350 | Between ingress row and pod row |
| Y_GW_CORE | 640 | Between gateway namespace and core namespace |
| Y_CICD | 875 | Between ops pods and CI/CD row |
| Y_BETWEEN | 985 | Between CI/CD and database row |
| Y_BELOW | 1200 | Below all shapes |
**Rule:** When two rows are only 20–40 px apart, the corridor between them is still usable — just ensure the chosen y does not touch any shape's bounding box (see tolerance rule below).
### 2. Calculate absolute canvas coordinates
draw.io uses **relative coordinates** for nested containers: a child's `x`/`y` is relative to its parent container's top-left corner, *not* to the canvas. To verify that a connector waypoint (which uses canvas-absolute coordinates) clears a shape, compute:
```
abs_x = shape.x + parent.x + grandparent.x + ... (sum all ancestor x offsets)
abs_y = shape.y + parent.y + grandparent.y + ... (sum all ancestor y offsets)
```
For swimlane containers, child coordinates are relative to the swimlane's **top-left origin** (not to the content area below the header). `startSize` only affects the visual header height — ignore it when computing absolute coordinates.
Build a flat list of all shapes with absolute bounding boxes before routing:
```python
shapes = [
# (id, abs_x1, abs_y1, abs_x2, abs_y2)
("pod-api", 985, 416, 1145, 574),
("pod-svc", 810, 416, 967, 574),
...
]
```
### 3. Verify routes with Python before writing XML
Run an overlap-detection simulation against all shapes before finalising the XML. This prevents invisible bugs that only become apparent when the file is opened.
```python
TOL = 2 # pixels — allow connectors to touch but not overlap interiors
def segment_overlaps_shape(seg, shape):
sx1, sy1, sx2, sy2 = shape
if seg['type'] == 'H': # horizontal segment at y=Y from xA to xB
Y, xA, xB = seg['y'], min(seg['x1'], seg['x2']), max(seg['x1'], seg['x2'])
if sy1 + TOL < Y < sy2 - TOL:
if max(xA, sx1 + TOL) < min(xB, sx2 - TOL):
return True
elif seg['type'] == 'V': # vertical segment at x=X from yA to yB
X, yA, yB = seg['x'], min(seg['y1'], seg['y2']), max(seg['y1'], seg['y2'])
if sx1 + TOL < X < sx2 - TOL:
if max(yA, sy1 + TOL) < min(yB, sy2 - TOL):
return True
return False
def route_overlaps(segments, shapes):
for seg in segments:
for shape in shapes:
if segment_overlaps_shape(seg, shape[1:]): # skip id
return shape[0], seg
return None
```
Convert every connector's waypoint list into a series of H/V segments, then call `route_overlaps` for each connector. Fix any reported overlap before writing the XML.
**Endpoint-touch rule:** A connector that terminates *at* a target shape will appear to overlap that shape in the algorithm because the last segment enters the shape's bounding box. This is expected and correct — exclude the *terminal shape* (source or target) when checking a connector's first and last segments.
### 4. Common routing patterns
#### Pattern A — Top highway for long cross-diagram connectors
Route connectors that must span the full diagram width through `Y_TOP` (well above all shapes):
```
source_mid_y → vertical up to Y_TOP → horizontal across to target_col_x → vertical down to target_mid_y
```
Waypoints example (mxGraphModel format):
```xml
<Array as="points">
<mxPoint x="200" y="110"/>
<mxPoint x="2600" y="110"/>
</Array>
```
#### Pattern B — Stacked services (approach from the left)
When multiple services are stacked vertically in a column (e.g., Watson/AI services), never route a vertical connector *through* the column. Instead, approach each service individually from a horizontal corridor to its left:
```
source → vertical to Y_TOP → horizontal to GAP_CD (just left of the column) → horizontal at service_mid_y → connect to service left edge
```
Each service in the stack gets its own connector that stops at the gap corridor. draw.io completes the final short horizontal stub automatically.
```python
for svc_id, svc_abs_y in stacked_services:
svc_mid_y = svc_abs_y + svc_height / 2
waypoints = [
(source_mid_x, Y_TOP), # exit source upward
(GAP_CD, Y_TOP), # travel across at top highway
(GAP_CD, svc_mid_y), # descend to service's row
# last waypoint stops at corridor; draw.io connects to service edge
]
```
#### Pattern C — Narrow inter-pod corridors
When adjacent pods in a row leave only a small gap (e.g., pod_A right=967, pod_B left=985 → 18 px gap), that gap is still a usable vertical corridor:
```
corridor_x = (pod_A_right + pod_B_left) / 2 → e.g., 976
```
Use this narrow corridor to route a vertical segment that exits a pod row and connects to shapes above or below:
```
pod_interior → horizontal to corridor_x → vertical through gap to target_y → horizontal to target
```
#### Pattern D — Right bypass for connections below a dense pod grid
When many pods span horizontally across the diagram, route connectors that must reach shapes below by going around the right edge of the pod grid:
```
source_mid → horizontal right to RIGHT_BYPASS (just right of all pods) → vertical to target_y → horizontal left to target
```
Set `RIGHT_BYPASS` to `(rightmost_pod_right + left_edge_of_next_column) / 2`.
### 5. Waypoint XML format
Always use the `Array as="points"` form inside `mxGeometry`:
```xml
<mxCell id="conn-1" value="" style="edgeStyle=orthogonalEdgeStyle;html=1;rounded=1;endArrow=open;endFill=0;" edge="1" source="A" target="B" parent="1">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="450" y="110"/>
<mxPoint x="2450" y="110"/>
<mxPoint x="2450" y="520"/>
</Array>
</mxGeometry>
</mxCell>
```
Rules:
- All waypoint coordinates are **canvas-absolute** (not relative to any container).
- Edges/connectors must be children of the **root layer** (`parent="1"`), never children of a container shape.
- The first waypoint is where draw.io exits the source shape's auto-routing; the last waypoint is where it enters the target.
- Stop the last waypoint at the corridor boundary — do not pass a waypoint into the interior of the target shape. draw.io will complete the stub automatically.
### CRITICAL — Never use port pin constraints on edges
**DO NOT** add `exitX`, `exitY`, `exitDx`, `exitDy`, `entryX`, `entryY`, `entryDx`, `entryDy` attributes to edge `mxCell` elements.
| Indicator | Cause | Meaning |
|-----------|-------|---------|
| 🔵 Blue circle at connector endpoint | `source`/`target` IDs set, no port pins | **Correct** — properly connected to shape |
| 🟢 Green circle with white X at connector endpoint | Port pin constraints (`exitX/Y`, `entryX/Y`) present | **Wrong** — draw.io treats endpoint as floating/unlinked |
Port pin attributes force draw.io to attach the connector to a precise computed point on the shape boundary. When the waypoints don't exactly match that computed point, draw.io renders the endpoint as floating (green X). This breaks visual connectivity even though the `source`/`target` IDs are set.
**Correct pattern — source/target IDs + waypoints only, NO port pins:**
```xml
<!-- ✅ CORRECT — blue circle, properly connected -->
<mxCell id="edge-001" value="" style="edgeStyle=orthogonalEdgeStyle;html=1;rounded=1;endArrow=open;endFill=0;"
edge="1" source="shape-A" target="shape-B" parent="1">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="200" y="420"/>
<mxPoint x="200" y="200"/>
</Array>
</mxGeometry>
</mxCell>
<!-- ❌ WRONG — green X, floating endpoint -->
<mxCell id="edge-001" value="" style="edgeStyle=orthogonalEdgeStyle;html=1;rounded=1;endArrow=open;endFill=0;
exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.5;entryDx=0;entryDy=0;"
edge="1" source="shape-A" target="shape-B" parent="1">
...
</mxCell>
```
draw.io auto-computes the connection point from `source`/`target` shape IDs and the last waypoint direction. Waypoints guide the routing corridor; the actual attachment to the shape is handled automatically.
**For «include» / «extend» labels:** use real UTF-8 characters `«include»` / `«extend»` in the edge `value` attribute — not XML entities (`&#171;include&#187;`).
**Single-port rule:** When multiple edges enter the same target shape, all their last waypoints must approach from the **same axis direction** (all from left, all from right, all from below, etc.). Mixed directions cause `singlePortViolation` in `page-connectors-validation`.
### 6. Corridor-first layout checklist
Before placing shapes, plan the layout so corridors are naturally available:
- [ ] Leave ≥ 40 px horizontal gaps between columns of shapes
- [ ] Leave ≥ 30 px vertical gaps between rows of shapes
- [ ] Reserve at least one wide horizontal corridor above all shapes (`Y_TOP`)
- [ ] Reserve at least one wide horizontal corridor below all shapes (`Y_BELOW`)
- [ ] Do not place shapes in the corridor bands — treat corridors as sacred routing lanes
- [ ] For stacked service columns, leave a vertical corridor to their left at `GAP_CD`
- [ ] Run Python overlap verification before finalising; fix every reported overlap
- [ ] Apply endpoint-touch exclusion when the last segment enters the target shape
---
## Swimlane / Multi-Zone Diagram Routing
When a diagram uses **swimlane zones** (horizontal bands, each a `swimlane` container), apply the following rules in addition to the general patterns above.
### Zone layout reference
For a typical layered architecture with `startSize=40` swimlanes and 40pt spacing:
```
zone.y ← swimlane top edge
zone.y + 40 ← header bottom (label occupies y..y+40)
zone.y + 40 + 40 = zone.y+80 ← first child row top (rel y=80 inside container)
zone.y + 80 + child_h ← first child row bottom
...
zone.y + height ← swimlane bottom edge
```
Inter-zone gaps (between adjacent swimlanes) are clean horizontal corridors — use their midpoint as the H-travel y-coordinate for connectors crossing zone boundaries.
### Bypass corridors
Always reserve **two vertical bypass corridors** outside all zones:
| Corridor | x value | Rule |
|---|---|---|
| LEFT bypass | `zone.x - 20` (e.g. x=60 when zones start at x=80) | All leftward cross-zone connectors |
| RIGHT bypass | `zone.x + zone.width + 20` (e.g. x=1260 when zones end at x=1240) | All rightward cross-zone connectors |
These bypass corridors run the full canvas height and are free of all shapes. **Every connector that must travel between zones should route through one of these corridors.**
### Multi-row swimlane: horizontal segment placement
When a swimlane has **two rows of shapes** (row1 and row2), each row has a y-range. Never place a connector H segment at a y-value that falls inside a row's y-range — that will overlap sibling shapes.
Use only these safe H corridors inside a multi-row services swimlane:
| Corridor | y value | When to use |
|---|---|---|
| Inter-row gap | `row1_bottom + (row2_top - row1_bottom)/2` | H travel between row1 and row2 shapes |
| Services-bottom gap | `row2_bottom + (zone_bottom - row2_bottom)/2` | H travel below row2, still inside zone |
| Inter-zone gaps | midpoint of gap between adjacent zones | H travel outside zones |
**Example** — services-zone: startSize=40, zone.y=500, row1 abs y=580..620, row2 abs y=660..700, zone bottom=740:
- Inter-row gap corridor: **y=640** (midpoint of y=620..660)
- Services-bottom corridor: **y=720** (midpoint of y=700..740)
### Connector routing rules for multi-row swimlanes
**Rule 1 — Never route H segments through a row's y-range.**
If a connector must travel horizontally through the services zone, use y=640 (inter-row) or y=720 (services-bottom), never y=580..620 or y=660..700.
**Rule 2 — When exiting a shape in row2 that has sibling shapes to its right in the same row:**
Do NOT exit from the bottom of the shape and then travel H at y=720 (services-bottom) to the right — this H will cross the V stubs of right-side siblings that exit to the same corridor.
**Fix options:**
- a) Exit from the **right side** of the shape → immediately go to RIGHT bypass x=1260 → V down/up to target (no H inside zone)
- b) If right-side exit H would cross a sibling shape body: exit right → first waypoint in the **column gap** to the right (e.g. x=1060 for col5/col6 gap) → V down to services-bottom corridor y=720 → H right to RIGHT bypass → V to target
**Rule 3 — Left bypass for connectors going downward to lower zones.**
When a row2 shape must connect to a shape in a lower zone (messaging, data), route:
```
shape_bottom → inter-row corridor y=640 → H LEFT to x=LEFT_BYPASS → V down to target zone corridor → H right to target
```
This ensures the H segment travels in the clear inter-row gap corridor and never crosses sibling shapes.
**Rule 4 — connectorShapeOverlaps with zone containers are structural and unavoidable.**
Any connector crossing a swimlane zone boundary will be flagged as `connector_shape_overlap` with the zone container. This is expected and acceptable — focus on eliminating `connectorCrossings` (two connectors intersecting each other) and overlaps with **non-container leaf shapes**.
### Pattern F — Multi-row swimlane fan-out (api-gateway → many services)
When a shape in an upper zone connects to N shapes spread across multiple columns of a multi-row services swimlane:
```
api-gateway_bottom → H to LEFT_BYPASS at inter-zone gap y → V down LEFT_BYPASS →
branch per target:
- col1 (leftmost): H right from LEFT_BYPASS to target_center_x at inter-row gap y
- col2: same, longer H
- col3..colN: same pattern, extending H further right
- for row2 targets: V from inter-row corridor down to row2 top, enter from top
```
All H branches travel at the same y (inter-row gap) — they are **parallel**, not crossing.
### Pattern G — Event bus → services (right bypass fan-in)
When an event bus (bottom of diagram) connects back up to multiple services:
```
event-bus_right → H right to RIGHT_BYPASS → V up →
branch per target:
- service in row1: H left from RIGHT_BYPASS at row1_center_y to target
- service in row2: stop at services-bottom corridor y=720 → H left → V up 20pt to target bottom
- stagger y values slightly (e.g. y=720 for one, y=730 for another) to avoid parallel confusion
```
**Critical:** The H segments going LEFT from RIGHT_BYPASS at y=720/730 will cross V stubs of row2 services that exit their bottoms and route DOWN and RIGHT to the right bypass. To avoid these crossings:
- Route those downward connectors via the **LEFT bypass** instead (Pattern F inverse)
- OR ensure the rightward services exit via their **right side** (not bottom), so no V stub exists at y=720..730
### Validation workflow for swimlane diagrams
1. Run `page-connectors-validation` after every edit
2. Fix `connectorCrossings` first — these are always avoidable
3. Fix `connectorShapeOverlaps` with **leaf shapes** (non-containers) — these are overlaps with actual service boxes
4. Accept `connectorShapeOverlaps` with zone containers as structural (unavoidable)
5. Fix `cornerPortViolations`, `headerEdgeViolations`, `singlePortViolations` — all should reach 0
6. Target: `connectorCrossings=0`, `cornerPortViolations=0`, `headerEdgeViolations=0`, `singlePortViolations=0`
---
## Section 8 — Text-width estimation for negative space calculation
When computing negative space manually (e.g. generating a negative-space diagram), **shape bounding boxes alone overestimate occupied space**. Text labels only occupy a sub-region within the shape bbox. Use the following formula:
```
charWidth = fontSize × 0.6 // avg glyph width for proportional fonts
rawWidth = longestLineCharCount × charWidth
padding = fontSize × 1.0 // horizontal padding (~0.5em each side)
textWidth = rawWidth + padding
fontStyle modifiers (draw.io bitmask):
bit 0 (value 1) = bold → charWidth × 1.10
bit 1 (value 2) = italic → charWidth × 1.05
textXMin = clamp(shapeCenterX − textWidth/2, shape.xMin, shape.xMax)
textXMax = clamp(shapeCenterX + textWidth/2, shape.xMin, shape.xMax)
textFlankLeft = textXMin − shape.xMin // free space left of text inside bbox
textFlankRight = shape.xMax − textXMax // free space right of text inside bbox
```
**When to apply:**
- **Swimlane headers** (`startSize=40` band): header text is centered in the full zone width → use text region for occupied X, flanks are free negative space
- Large container shapes whose children don't fill the full width
- Any shape where `textWidth < shapeWidth` — the flanks inside the bbox are free
**Example — Marketplace diagram zone headers, fontSize=12 bold (fontStyle=1), center x=660, zone x=80..1240:**
| Label | longestLine chars | textWidth | textXMin | textXMax | flank each side |
|---|---|---|---|---|---|
| "Client Layer" | 12 | 107 | 607 | 713 | ~527pt |
| "API Gateway / Edge Layer" | 24 | 202 | 559 | 761 | ~479pt |
| "Core Microservices" | 18 | 155 | 583 | 737 | ~503pt |
| "Messaging / Event Bus" | 21 | 178 | 571 | 749 | ~491pt |
| "Data Layer" | 10 | 91 | 615 | 705 | ~535pt |
**`page-negative-space-summary` action outputs (per shape):**
- `textXMin`, `textXMax`, `textWidth` — estimated text rendering region
- `textFlankLeft`, `textFlankRight` — free flanks inside bbox
- `rows[].textAwareFreeCorridors` — corridors computed using text regions (wider than bbox-based)
**When drawing a negative-space diagram:** see [negative-space-diagram.md](./negative-space-diagram.md) for all rules, construction steps, XML pattern, file naming, and validation.
+492
View File
@@ -0,0 +1,492 @@
# drawio-main — Layout Rules
Connector placement and layout rules for draw.io diagrams generated by this skill.
These rules are **MANDATORY** — apply them when generating any diagram.
---
## General layout rules — MANDATORY
- Use a **10pt grid**; align all shapes to grid increments
- Leave ≥ 40px horizontal and ≥ 40px vertical gaps between shape columns/rows for connector corridors
- Keep connector labels short; place them in clear corridors, never overlapping shapes or other labels
- Before finalising, verify: no shape overlap, no connector-shape overlap, no label overlap, no page clipping
- **Universal 40pt spacing rule** — every shape must have at least 40pt of clear space on **all four sides**:
- **From parent header bottom**: child `y = startSize + 40` (measured from top of swimlane including header)
- **From parent sides**: child `x ≥ 40` from the left/right inner border of the swimlane
- **From parent bottom**: bottom of last child row + 40 = swimlane total height
- **Between siblings** (same nesting level): gap between any two adjacent shapes (horizontal or vertical) = 40pt exactly — all sibling gaps must be identical
Swimlane height formulas:
- Single row: `total_height = startSize + 40 + child_height + 40`
- Two rows: `total_height = startSize + 40 + row1_h + 40 + row2_h + 40`
- Round up total to the nearest multiple of 40 if needed; absorb any remainder into the bottom gap (≥ 40)
Examples:
- `startSize=40`, 1 row h=40: total = 40+40+40+40 = 160 (children at y=80, children w=160 with x-gap=40 between them)
- `startSize=40`, 1 row h=80: total = 40+40+80+40 = 200 (children at y=80)
- `startSize=40`, 2 rows h=40 each: total = 40+40+40+40+40+40 = 240 (row1 at y=80, row2 at y=160)
After generating or editing a diagram, run `page-spacing-audit` and `page-swimlane-audit` to verify.
---
## Diagram Layers and Connector Rules — MANDATORY
### Layer model
| Layer | Contents | Connector may overlap? |
|---|---|---|
| **0 — Background / containers** | Swimlanes, zone boundaries, grouping rectangles | **YES** — connectors may pass through containers |
| **1 — Primary shapes** | Core nodes: main system boxes, components, use cases | **NEVER** |
| **2 — Actor shapes** | Human actors (stick figures), external IT systems | **NEVER** |
| **3 — Connectors** | Edges, waypoints, routing corridors | **AVOID** — crossing other connectors is a last resort |
| **4 — Labels / annotations** | Edge labels, callouts, legend text, title blocks | **NEVER** |
> **Core rule: a connector may only overlap Layer 0. It must NEVER overlap Layers 1, 2, or 4.**
### Label-crossing prohibition — MANDATORY
**A connector must NEVER pass through the textual label of any shape — regardless of which layer the shape belongs to.**
- Container shapes (Layer 0 / swimlanes) have a header bar at the top that contains the label. Connectors must not pass through this header area
- For swimlanes with `startSize=40`, the header occupies `y` to `y+40`. Any connector that enters or exits vertically through the header is forbidden; route it through the side or bottom instead
- Leaf shapes (Layer 1/2) also carry labels — their entire bounding box is off-limits (existing rule), so this adds no extra constraint for those
- To check: identify every shape whose label bounding box (header bar for containers, full box for leaves) intersects a connector segment. Reroute any that does
### Corner-cutting prohibition — MANDATORY
**A connector must NEVER route across the corner of any shape — regardless of which layer the shape belongs to.**
A corner cut occurs when an orthogonal connector exits from one face of a shape and its first waypoint is positioned diagonally (same quadrant as the corner) relative to that exit point, causing the L-shaped segment to visually "clip" the corner region. This is forbidden even when the corner is technically outside the shape bounding box.
Rule: after choosing the exit face and direction of travel, the first waypoint must be placed such that the initial segment travels **parallel to or away from** the corner edge, not at an angle toward it.
| Exit face | First segment must go | Forbidden direction |
|---|---|---|
| Bottom | Down (↓) or laterally clear | Up (↑) toward corner |
| Top | Up (↑) or laterally clear | Down (↓) toward corner |
| Left | Left (←) or clear | Right (→) toward corner |
| Right | Right (→) or clear | Left (←) toward corner |
### Prefer-downward routing — MANDATORY
**When a connector can reach its target by routing either upward or downward, always prefer the downward route.**
Routing upward is only permitted when:
- The target is physically above the source (the upward direction is the natural one), OR
- Routing downward would create a connector-shape overlap that cannot otherwise be avoided
Violation example: a connector exits the bottom of a source shape, immediately routes **up** through the source's parent container header, travels horizontally, then comes back **down** — this is forbidden. The first segment after exiting the bottom face must go **down**, not up.
Decision rule:
1. Identify whether target `y_center` is above or below source `y_center`
2. If below (or same level): exit source bottom or side → route **downward** → enter target top or side
3. If above: exit source top or side → route **upward** → enter target bottom or side
4. If the natural downward path is blocked, use a side-exit (left or right) corridor to bypass, then continue downward — do NOT reverse direction to go upward
### Header-edge prohibition — MANDATORY
**A connector must NEVER run along (or within 1px of) the bottom edge of a swimlane/container header bar.**
The header bar of a swimlane occupies the band `[shape.y .. shape.y + startSize]`. Its **bottom edge** is the line `y = shape.y + startSize`. Connectors that travel horizontally across this line are visually indistinguishable from the header border and create a confusing, cluttered diagram.
- For a swimlane with `startSize=40`, the forbidden horizontal band is within 1px of `shape.y + 40`
- Connectors entering or exiting the swimlane via a **vertical segment that straddles** the header-bottom edge are also forbidden
- **Fix:** reroute the horizontal segment to travel either:
- **Inside** the swimlane body (below `shape.y + startSize + TOL`), or
- **Outside / above** the swimlane entirely (above `shape.y - TOL`), or
- Via a side corridor that avoids the header band altogether
**Detection:** `page-connectors-validation` action reports `headerEdgeViolations` — always run it before finishing any diagram that contains swimlanes or container shapes.
| Situation | Fix |
|---|---|
| Horizontal segment at `y ≈ container.y + startSize` | Move segment down into the swimlane body or up above the container |
| Vertical segment straddles header-bottom edge from inside | Re-enter the swimlane via left or right face instead |
| Multiple connectors fanning across the Data Layer header | Use a horizontal corridor at `y = container.y + startSize + 40` (center of the 40pt gap) or route via side bypass |
### Connector-crossing avoidance — MANDATORY
**Connectors must not cross each other.** Crossing another connector is a last resort — acceptable only when no feasible reroute exists. When a crossing is unavoidable, it must be a clean 90° crossing. Connectors crossing other connectors is always preferable to a connector crossing a shape label or shape corner.
| Cause | Fix |
|---|---|
| Multiple left-side sources fan into one target | Route through a shared left-side vertical corridor; stagger y-entry points |
| Sources on both sides of a central shape | Use separate left-corridor and right-corridor |
| Sources in different rows heading to the same column | Give each source its own horizontal lane in the corridor |
| Long connector crosses shorter ones | Route long connectors through Y_TOP (above all shapes) |
**Crossing-free strategy:**
1. Identify source groups and target groups
2. Assign each source group its own corridor lane
3. Route connectors in each group in parallel through their lane
4. Trace every connector pair — if any two intersect at a non-edge point, redesign
If a crossing truly cannot be avoided, prefer a right-angle (90°) crossing over an oblique one.
### Minimal waypoints rule — MANDATORY
**Add waypoints only when the direct path would clip a Layer 1/2/4 shape.**
| Situation | Waypoints? |
|---|---|
| Source and target at same horizontal level, path is clear | **NO** |
| Adjacent columns with clear gap between them | **NO** |
| Source mid_y falls within target's y-range, path is clear | **NO** |
| Path would clip an intermediate shape | **YES** — minimum waypoints to route around it |
| Fan-out from a central shape to a stacked column | **YES** — use Pattern E |
**Before adding a waypoint, ask:** *"Would the direct auto-routed path clip any Layer 1/2/4 shape?"* If no — no waypoints. If yes — first try repositioning shapes (layout-first principle).
**Keep all connectors the same edge style** (`edgeStyle=orthogonalEdgeStyle`). Never change edge style to work around a layout problem — fix the layout instead.
### Layout-first principle
**Redesign the layout to eliminate waypoints before adding them.**
| Problem | Layout fix |
|---|---|
| Actor above target's y-range | Move target up, or tighten actor spacing so target mid_y aligns |
| Actor below target's y-range | Move target down, or tighten actor spacing |
| Fan-out column spans much more than source | Centre source vertically on the column |
**Shape size is driven by content, not routing** — typically 80–160px tall. If only 1–2 actors fall outside the target's y-range, accept 2 minimal waypoints per connector rather than inflating the shape. Space actors 80–120px apart (centre-to-centre) to keep groups compact.
### When auto-routing is forbidden
Never rely on `edgeStyle=orthogonalEdgeStyle` without explicit waypoints when the path passes through intermediate shapes. Use waypoints only where needed — the goal is the minimum number that achieves zero overlaps and zero crossings.
---
## Connector Routing Patterns
### Corridors
Before placing connectors, identify clear **corridors** — bands free of all shapes.
**Vertical corridor** between two columns:
```
GAP_x = (right_edge_of_left_column + left_edge_of_right_column) / 2
```
**Horizontal corridor** between two rows:
```
GAP_y = (bottom_edge_of_upper_row + top_edge_of_lower_row) / 2
```
Reserve a **top corridor** (`Y_TOP`) above all shapes and a **bottom corridor** (`Y_BELOW`) below all shapes for cross-diagram connectors.
### Absolute coordinates
Connector waypoints are canvas-absolute. For nested containers, sum all ancestor offsets:
```
abs_x = shape.x + parent.x + grandparent.x + ...
abs_y = shape.y + parent.y + grandparent.y + ...
```
### Overlap verification (Python)
```python
TOL = 2
def segment_overlaps_shape(seg, shape):
sx1, sy1, sx2, sy2 = shape
if seg['type'] == 'H':
Y, xA, xB = seg['y'], min(seg['x1'],seg['x2']), max(seg['x1'],seg['x2'])
if sy1+TOL < Y < sy2-TOL and max(xA,sx1+TOL) < min(xB,sx2-TOL):
return True
elif seg['type'] == 'V':
X, yA, yB = seg['x'], min(seg['y1'],seg['y2']), max(seg['y1'],seg['y2'])
if sx1+TOL < X < sx2-TOL and max(yA,sy1+TOL) < min(yB,sy2-TOL):
return True
return False
```
Exclude the terminal shape (source/target) when checking first/last segments.
### Pattern A — Top highway
Long connectors that span the full diagram width:
```
source → V up to Y_TOP → H across → V down to target
```
### Pattern B — Stacked column approach
Multiple targets stacked vertically in a column — never route through the column. Approach each from a corridor to the side:
```
source → V to Y_TOP → H to GAP_x (beside column) → V to target_mid_y → H into target
```
### Pattern C — Narrow gap corridor
When two adjacent shapes leave a small gap (≥ 10px), that gap is a usable vertical corridor:
```
corridor_x = (shape_A_right + shape_B_left) / 2
```
### Pattern D — Bypass around a dense row
When a row of shapes blocks a path to shapes below, go around the right edge:
```
source → H right to RIGHT_BYPASS → V to target_y → H left to target
RIGHT_BYPASS = (rightmost_shape_right + next_column_left) / 2
```
### Pattern E — Fan-out from a central shape to a stacked column
The most common overlap scenario: one central shape connects to N stacked targets on one side.
**Solution — vertical fan-out corridor:**
1. `GAP = (central_right + column_left) / 2`
2. Exit central shape → H to GAP → V to target_mid_y → H into target
```xml
<Array as="points">
<mxPoint x="{GAP}" y="{source_mid_y}"/>
<mxPoint x="{GAP}" y="{target_mid_y}"/>
</Array>
```
**Example** — source mid_y=200, GAP=820, 5 stacked targets:
| Target | mid_y | Waypoints |
|---|---|---|
| Item A | 80 | (820, 200) → (820, 80) |
| Item B | 200 | direct (no waypoints needed) |
| Item C | 320 | (820, 200) → (820, 320) |
| Item D | 440 | (820, 200) → (820, 440) |
| Item E | 560 | (820, 200) → (820, 560) |
Constraint: `central_right < GAP < column_left`. If gap < 40px, move the column right.
### Waypoint XML format
```xml
<mxCell id="conn-1" value="label" style="edgeStyle=orthogonalEdgeStyle;html=1;" edge="1" source="A" target="B" parent="1">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="450" y="40"/>
<mxPoint x="820" y="40"/>
<mxPoint x="820" y="320"/>
</Array>
</mxGeometry>
</mxCell>
```
Rules:
- Waypoints are canvas-absolute
- Edges are children of root layer (`parent="1"`), never of a container
- Last waypoint stops at the corridor boundary — draw.io completes the final stub
### Layout checklist
- [ ] ≥ 40px gaps between columns and rows (universal 40pt spacing rule)
- [ ] Y_TOP corridor reserved above all shapes
- [ ] Y_BELOW corridor reserved below all shapes
- [ ] Corridor bands contain no shapes
- [ ] Python overlap verification run; all overlaps fixed
- [ ] Endpoint-touch exclusion applied for first/last segments
- [ ] Every connector pair traced — no path intersections at non-edge points
- [ ] All connector labels in clear corridors, not overlapping shapes or other labels
- [ ] No connector passes through any shape's text label (including swimlane header bars)
- [ ] No connector cuts across a shape corner (first segment after exit travels away from corners)
- [ ] No connector runs along (or within 1px of) the bottom edge of any swimlane/container header bar (`page-connectors-validation` reports `headerEdgeViolations`)
- [ ] All connectors route downward when target is below source; upward only when target is above source
---
## Swimlane / Multi-Zone Diagram Routing
When a diagram uses **swimlane zones** (horizontal bands, each a `swimlane` container), apply the following rules in addition to all rules above.
### Zone layout reference
For a typical layered architecture with `startSize=40` swimlanes and 40pt spacing:
```
zone.y ← swimlane top edge
zone.y + 40 ← header bottom (label occupies y..y+40)
zone.y + 40 + 40 = zone.y+80 ← first child row top (rel y=80 inside container)
zone.y + 80 + child_h ← first child row bottom
...
zone.y + height ← swimlane bottom edge
```
Inter-zone gaps (between adjacent swimlanes) are clean horizontal corridors — use their midpoint as the H-travel y-coordinate for connectors crossing zone boundaries.
### Bypass corridors
Always reserve **two vertical bypass corridors** outside all zones:
| Corridor | x value | Rule |
|---|---|---|
| LEFT bypass | `zone.x - 20` (e.g. x=60 when zones start at x=80) | All leftward cross-zone connectors |
| RIGHT bypass | `zone.x + zone.width + 20` (e.g. x=1260 when zones end at x=1240) | All rightward cross-zone connectors |
These bypass corridors run the full canvas height and are free of all shapes. **Every connector that must travel between zones should route through one of these corridors.**
### Multi-row swimlane: horizontal segment placement
When a swimlane has **two rows of shapes** (row1 and row2), each row has a y-range. Never place a connector H segment at a y-value that falls inside a row's y-range — that will overlap sibling shapes.
Use only these safe H corridors inside a multi-row services swimlane:
| Corridor | y value | When to use |
|---|---|---|
| Inter-row gap | `row1_bottom + (row2_top - row1_bottom)/2` | H travel between row1 and row2 shapes |
| Services-bottom gap | `row2_bottom + (zone_bottom - row2_bottom)/2` | H travel below row2, still inside zone |
| Inter-zone gaps | midpoint of gap between adjacent zones | H travel outside zones |
**Example** — services-zone: startSize=40, zone.y=500, row1 abs y=580..620, row2 abs y=660..700, zone bottom=740:
- Inter-row gap corridor: **y=640** (midpoint of y=620..660)
- Services-bottom corridor: **y=720** (midpoint of y=700..740)
### Connector routing rules for multi-row swimlanes
**Rule 1 — Never route H segments through a row's y-range.**
If a connector must travel horizontally through the services zone, use y=640 (inter-row) or y=720 (services-bottom), never y=580..620 or y=660..700.
**Rule 2 — When exiting a shape in row2 that has sibling shapes to its right in the same row:**
Do NOT exit from the bottom of the shape and then travel H at y=720 (services-bottom) to the right — this H will cross the V stubs of right-side siblings that exit to the same corridor.
**Fix options:**
- a) Exit from the **right side** of the shape → immediately go to RIGHT bypass x=1260 → V down/up to target (no H inside zone)
- b) If right-side exit H would cross a sibling shape body: exit right → first waypoint in the **column gap** to the right (e.g. x=1060 for col5/col6 gap) → V down to services-bottom corridor y=720 → H right to RIGHT bypass → V to target
**Rule 3 — Left bypass for connectors going downward to lower zones.**
When a row1 or row2 shape must connect to a shape in a lower zone (messaging, data), route:
```
shape_bottom → inter-row corridor y=640 → H LEFT to x=LEFT_BYPASS → V down to target zone corridor → H right to target
```
This ensures the H segment travels in the clear inter-row gap corridor and never crosses sibling shapes.
**Rule 4 — connectorShapeOverlaps with zone containers are structural and unavoidable.**
Any connector crossing a swimlane zone boundary will be flagged as `connector_shape_overlap` with the zone container. This is expected and acceptable — focus on eliminating `connectorCrossings` (two connectors intersecting each other) and overlaps with **non-container leaf shapes**.
### Pattern F — Multi-row swimlane fan-out (api-gateway → many services)
When a shape in an upper zone connects to N shapes spread across multiple columns of a multi-row services swimlane:
```
api-gateway_bottom → H to LEFT_BYPASS at inter-zone gap y → V down LEFT_BYPASS →
branch per target:
- col1 (leftmost): H right from LEFT_BYPASS to target_center_x at inter-row gap y
- col2..colN: same pattern, extending H further right
- for row2 targets: V from inter-row corridor down to row2 top, enter from top
```
All H branches travel at the same y (inter-row gap) — they are **parallel**, not crossing.
### Pattern G — Event bus → services (right bypass fan-in)
When an event bus (bottom of diagram) connects back up to multiple services:
```
event-bus_right → H right to RIGHT_BYPASS → V up →
branch per target:
- service in row1: H left from RIGHT_BYPASS at row1_center_y to target
- service in row2: stop at services-bottom corridor y=720 → H left → V up 20pt to target bottom
- stagger y values slightly (e.g. y=720 for one, y=730 for another) to avoid parallel confusion
```
**Critical:** The H segments going LEFT from RIGHT_BYPASS at y=720/730 will cross V stubs of row2 services that exit their bottoms and route DOWN and RIGHT to the right bypass. To avoid these crossings:
- Route those downward connectors via the **LEFT bypass** instead (Pattern F inverse)
- OR ensure the rightward services exit via their **right side** (not bottom), so no V stub exists at y=720..730
### Swimlane validation workflow
1. Run `page-connectors-validation` after every edit
2. Fix `connectorCrossings` first — these are always avoidable
3. Fix `connectorShapeOverlaps` with **leaf shapes** (non-containers) — these are overlaps with actual service boxes
4. Accept `connectorShapeOverlaps` with zone containers as structural (unavoidable)
5. Fix `cornerPortViolations`, `headerEdgeViolations`, `singlePortViolations` — all should reach 0
6. Target: `connectorCrossings=0`, `cornerPortViolations=0`, `headerEdgeViolations=0`, `singlePortViolations=0`
---
## Sequence Diagram Layout Rules — MANDATORY
Sequence diagrams have a fundamentally different structure to architecture diagrams. The rules below override or supplement the general connector rules **for sequence diagrams only**.
### Participants (lifeline headers)
- **Participant boxes** are rectangular shapes (`rounded=0`) placed in a single horizontal row at the top of the diagram
- **HUMAN_ACTOR participants** use `shape=actor`, `width=40`, `height=40` — same as all actor shapes
- **Service/system participants** use `rounded=0`, `width=120`, `height=80` (both divisible by 40)
- **Participant spacing**: gap between adjacent participant boxes must be ≥ 40pt and divisible by 40. Preferred gap = 80pt, giving a step of `width + 80` between participant x-origins
- **Participant x-origin**: must be on the 10pt grid; preferred to be on the 40pt grid
- **All participant boxes must have the same height** (uniform row)
### Lifelines
- Each participant has exactly one **lifeline** — a vertical dashed edge (`dashed=1; endArrow=none`) centered on the participant
- Lifeline x-coordinate = `participant.x + participant.width / 2` (center of participant)
- Lifeline starts at `y = participant.y + participant.height` (bottom edge of participant box) and ends above the legend/footer area. Stop lifelines at least 40pt above the legend box top edge
- Lifeline color matches the participant stroke color
- **Lifelines are Layer-0 elements** — they are background structural elements, equivalent to swimlane containers. Connectors (message arrows) may cross lifelines freely — this is the defining visual characteristic of a sequence diagram
### Message arrows
- Message arrows are horizontal edges (`endArrow=block; endFill=1`) drawn at exact y-coordinates, traveling between lifeline x-positions
- **Each message occupies its own y-row** — messages must never share the same y-coordinate
- **Vertical step between messages**: minimum 20pt, preferred 20–40pt to ensure labels don't overlap
- **Message arrow y-coordinates** must be on the 10pt grid
- **Label placement**: edge label is above the arrow line; keep it short (≤ 30 chars) to avoid overlap with lifelines it crosses
- **Return messages** (response arrows) travel in the opposite horizontal direction; they are drawn 20pt below the corresponding request arrow
### Step / phase labels
- Phase separator labels ("1. Search & Browse", etc.) are text shapes (`style=text`) positioned in a **left margin column** that must not overlap any lifeline
- Left margin column: `x = 20`, `width ≤ participant_leftmost_x - 20 - 4` (at least 4pt clear gap from the leftmost lifeline)
- Phase labels are placed at the y-coordinate of the first message in that phase, minus 20pt
### Lifeline × message crossing — STRUCTURAL EXEMPTION
**Lifeline × message arrow crossings are structural and expected in sequence diagrams.** They must NOT be treated as violations. The `page-connectors-validation` tool will report these as `connectorCrossings` — accept them without fix.
Specifically:
- A vertical lifeline edge crossing a horizontal message arrow edge = **structural, expected, acceptable**
- Only report as a true crossing violation: two message arrows crossing each other (both horizontal) or two lifelines crossing each other (impossible by construction)
This exemption applies only to lifeline edges (identified by: `dashed=1; endArrow=none; vertical segment spanning many messages`). All other crossing rules remain fully in force.
### Legend container — STRUCTURAL EXEMPTION
Legend sample arrows (short colored stubs showing connector styles) placed inside a plain container shape will be reported as `connectorShapeOverlaps` with the container. This is structural and expected — the legend connectors are intentionally drawn inside the container boundary.
Accept `connectorShapeOverlaps` where:
- The overlapping edge is a legend sample stub (short, non-connected edge with `parent=legend-box`)
- The overlapping shape is the legend container itself (`id=legend-box`)
All other `connectorShapeOverlaps` with non-container leaf shapes must still be fixed.
### Sequence diagram validation targets
| Metric | Target | Notes |
|---|---|---|
| `connectorCrossings` (lifeline × message) | **Accepted as structural** | Expected behavior of sequence diagrams |
| `connectorCrossings` (message × message) | **0** | Two horizontal messages must never cross |
| `connectorShapeOverlaps` (legend stubs × legend box) | **Accepted as structural** | Legend connectors inside their container |
| `connectorShapeOverlaps` (message × participant box) | **0** | Message arrows must not pass through participant boxes |
| `connectorShapeOverlaps` (lifeline × step-label shape) | **0** | Step labels must be in a clear left margin column |
| `cornerPortViolations` | **0** | |
| `headerEdgeViolations` | **0** | |
| `singlePortViolations` | **0** | |
| `overlappingPairs` (shape bbox) | **0** | No shape bounding boxes overlap |
### Sequence diagram layout checklist
- [ ] All participants in one horizontal row, uniform height, gaps divisible by 40
- [ ] HUMAN_ACTOR participants: `shape=actor`, width=40, height=40
- [ ] Service participants: `rounded=0`, width=120, height=80
- [ ] Lifelines centered on participants, stop 40pt above legend
- [ ] Lifelines use `dashed=1; endArrow=none`; color matches participant stroke
- [ ] Each message at a unique y-coordinate, on 10pt grid, min 20pt apart
- [ ] Step/phase labels in left margin column (x=20, clear of all lifelines)
- [ ] No message × message crossings (horizontal × horizontal)
- [ ] No message overlapping a participant box
- [ ] Legend items are children of a plain container (not swimlane)
- [ ] `page-shape-bbox-validation` reports `overlappingPairs=0`
- [ ] `page-connectors-validation` reports `cornerPortViolations=0`, `headerEdgeViolations=0`, `singlePortViolations=0`
+71
View File
@@ -0,0 +1,71 @@
# drawio-main — Style Rules
Visual appearance and sizing rules for draw.io diagrams generated by this skill.
These rules are **MANDATORY** — apply them when generating any diagram.
---
## General style rules — MANDATORY
- **All child shapes within the same swimlane must have the same height** — never mix different heights within one swimlane layer/row
- **Rectangles must never use rounding** — always set `rounded=0` on rectangle shapes
- Prefer dimensions divisible by 40; wrap non-divisible vendor icons in a grid-aligned container
- **The space between sibling shapes of the same level (same swimlane, same row) must be divisible by 40px** — use 40px as the minimum gap. If a swimlane row has shapes of width W and gap G, the step between shape origins = W + G where G ≥ 40 and G mod 40 = 0.
- **Swimlane `startSize` (header height) must be divisible by 40** — use `startSize=40`
- **Swimlane body height (total − startSize) must be divisible by 40** — so total height = 40 + N×40 = a multiple of 40
- Example: `startSize=40`, body=80 → total=120 ✓; body=160 → total=200 ✓
- Use ≤ 3 primary color families; create hierarchy with shades
- Use dashed connectors only for semantically distinct flows (async, backup, admin)
- Shape size is driven by **content**, not routing — typically 80–160px tall per label line
---
## Connector routing rules — MANDATORY
- **All outgoing connectors from the same shape must share a single exit point** — never let multiple connectors leave a shape at different X/Y coordinates. Pick one exit side (top/bottom/left/right) and one coordinate on that side; all outgoing connectors use it as their first waypoint.
- **All incoming connectors to the same shape must share a single entry point** — never let multiple connectors enter a shape at different X/Y coordinates. Pick one entry side and one coordinate; all incoming connectors use it as their last waypoint before the shape.
- **Connectors must never attach at a shape corner** — the exit/entry point must lie on the middle of a side: top-center, bottom-center, left-center, or right-center. A point that is simultaneously on both an X-edge (left or right) AND a Y-edge (top or bottom) of the shape bounding box is a corner and is forbidden. Use the midpoint of the chosen side: `x_mid = (x1+x2)/2` for top/bottom sides, `y_mid = (y1+y2)/2` for left/right sides.
- These rules ensure a clean "bus-bar" fan-out/fan-in pattern and prevent connectors from diverging at their source or converging at their target at different positions, which creates visual clutter and increases crossing risk.
- Exception: shapes with only a single outgoing or single incoming connector — the single-port rule trivially holds. The corner rule still applies.
- When computing waypoints: use `page-negative-space-summary` to find free X corridors per row, then pick an exit/entry coordinate that lies within a free corridor at the next traversed level. This minimises connector-shape overlaps and connector crossings.
- **Waypoints must never be closer than 20px to any shape** — the first waypoint after a shape exit must be at least 20px away from the shape's edge in the direction of travel (e.g., if exiting bottom at y=520, first waypoint y ≥ 540; if exiting right at x=1040, first waypoint x ≥ 1060). The last waypoint before a shape entry must likewise be at least 20px away from the shape's edge. This 20px clearance also applies to any waypoint relative to same-level sibling shapes the connector passes by — the waypoint must not come within 20px of any sibling shape's bounding box side it is adjacent to.
---
## Text-width estimation — negative space calculation
When computing negative space manually (e.g. for a negative-space diagram), **shape bounding boxes alone overestimate occupied space**. Text labels only occupy a sub-region within the shape bbox. Use the following formula to estimate the text rendering width:
```
charWidth = fontSize × 0.6 // avg glyph width for proportional fonts
rawWidth = longestLineChrCount × charWidth
padding = fontSize × 1.0 // horizontal padding (~0.5em each side)
textWidth = rawWidth + padding
fontStyle modifiers (draw.io flags):
bit 0 (value 1) = bold → charWidth × 1.10
bit 1 (value 2) = italic → charWidth × 1.05
textXMin = clamp(shapeCenterX − textWidth/2, shape.xMin, shape.xMax)
textXMax = clamp(shapeCenterX + textWidth/2, shape.xMin, shape.xMax)
```
**When to apply:**
- Swimlane headers (`startSize=40` band): the header text is centered in the full zone width. Use text region for occupied X, flanks are free negative space.
- Large container shapes whose children don't fill the full width.
- Any shape where `textWidth < shapeWidth` — the flanks inside the bbox are free.
**Example — zone headers at fontSize=12 bold (fontStyle=1), center x=660, zone x=80..1240:**
| Label | chars | charWidth | rawWidth | padding | textWidth | textXMin | textXMax | flank each side |
|---|---|---|---|---|---|---|---|---|
| "Client Layer" | 12 | 7.9 | 95 | 12 | 107 | 607 | 713 | ~527pt |
| "API Gateway / Edge Layer" | 24 | 7.9 | 190 | 12 | 202 | 559 | 761 | ~479pt |
| "Core Microservices" | 18 | 7.9 | 143 | 12 | 155 | 583 | 737 | ~503pt |
| "Messaging / Event Bus" | 21 | 7.9 | 166 | 12 | 178 | 571 | 749 | ~491pt |
| "Data Layer" | 10 | 7.9 | 79 | 12 | 91 | 615 | 705 | ~535pt |
**The `page-negative-space-summary` action now outputs these fields per shape:**
- `textXMin`, `textXMax`, `textWidth` — estimated text rendering region
- `textFlankLeft`, `textFlankRight` — free space flanking text inside bbox
- `rows[].textAwareFreeCorridors` — free corridors computed using text regions (wider than bbox-based corridors)
+485
View File
@@ -0,0 +1,485 @@
# draw.io XML Reference
Detailed reference for styles, edge routing, containers, layers, tags, metadata, and dark mode. Consult this when generating draw.io XML diagrams.
## Reasoning budget (read this first)
Your job is to declare the **logical structure** of the diagram — what nodes exist, what edges connect them, what labels they carry, what lane/container groups them. draw.io's edge router and (when available) a post-layout pass handle routing and placement; you do **not** need to do layout math.
**Do NOT** in your reasoning:
- Do NOT debate the topic. The user asked for a flowchart / architecture / sequence / etc. — pick one concrete scenario on your first impulse and commit. Never write "Actually, let me think of something else…" or pitch alternatives.
- Do NOT debate flat-lanes vs nested-pools, horizontal vs vertical orientation, one vs multiple variations. Pick the first reasonable option (almost always: flat swimlanes, top-down or left-right based on what fits the content). Do not flip-flop.
- Do NOT compute x/y coordinates in prose. No "column spacings of 160px totaling 1840px width — that's too wide, let me tighten to 1700…" loops. Use the rigid grid below; do the arithmetic in your head and write the XML.
- Do NOT re-derive drawio mechanics (`horizontal=0`, `startSize=110`, nested-lane coordinates). Use the templates below as-is.
- Do NOT enumerate columns ("customer lane columns 0-10, web app 1-7"). Place a node, move on.
- Do NOT add `<Array as="points">` waypoints. Edges are routed automatically.
- Do NOT set `exitX` / `exitY` / `entryX` / `entryY` connection-point overrides unless you have specific geometric intent.
- Do NOT verify, re-check, or adjust coordinates after placing a node.
- Do NOT narrate "building the diagram / finalizing the XML / now let me…". Just emit XML.
- Do NOT write out lists of node positions as planning text. Emit them as `<mxCell>` elements directly.
**Do** in your reasoning:
- Identify the diagram type + actors/stages (1-2 short sentences).
- Identify any grouping (swimlanes? containers? none?).
- Go straight to XML.
**Rigid grid — use for every XML diagram:**
- Column x = `col_index * 180 + 40` (col 0 = 40, col 1 = 220, col 2 = 400, …)
- Row y = `row_index * 120 + 40` (row 0 = 40, row 1 = 160, row 2 = 280, …)
- Node size: rectangles `140×60`, diamonds `140×80`, circles `60×60`, documents `120×80`, cylinders `100×70`
Pick a `(col, row)` for each node. Don't think about centers, gaps, or overlap — ELK handles routing between rough positions. Slight misalignment is invisible in the result.
## General principles
- **Use proper draw.io shapes and connectors** — choose the semantically correct shape for each element (e.g., `shape=cylinder3` for databases and tanks, `rhombus` for decisions, `shape=mxgraph.pid2valves.*` for valves in P&IDs). draw.io has extensive shape libraries; prefer domain-appropriate shapes over generic rectangles.
- **Decide whether to search for shapes** — before generating a diagram, decide if it needs domain-specific shapes from draw.io's extended libraries. **Skip `search_shapes`** for standard diagram types that use basic geometric shapes: flowcharts, UML (class, sequence, state, activity), ERD, org charts, mind maps, Venn diagrams, timelines, wireframes, and any diagram using only rectangles, diamonds, circles, cylinders, and arrows. Also skip if the user explicitly asks to use basic/simple shapes or says not to search. **Use `search_shapes`** when the diagram requires industry-specific or branded icons: cloud architecture (AWS, Azure, GCP), network topology (Cisco, rack equipment), P&ID (valves, instruments, vessels), electrical/circuit diagrams, Kubernetes, BPMN with specific task types, or any domain where the user expects realistic/standardized symbols rather than labeled boxes.
- **Match the language of labels to the user's language** — if the user writes in German, French, Japanese, etc., all diagram labels, titles, and annotations should be in that same language.
- **Group related nodes, and surface a hub when edges converge** — put nodes that belong together inside a container or swimlane, and keep external actors (users, files, third-party systems) outside implementation containers. When many edges converge on one area or cross several groups, route them through a single hub/gateway node (a registry, broker, event log, …) instead of drawing every low-level dependency across the canvas — fewer crossings, clearer contract.
- **Encode secondary detail in node text, not edges** — draw an edge only when the relationship itself carries meaning; push incidental detail into the node label so the connector layer stays readable.
## Common styles
**Rounded rectangle:**
```xml
<mxCell id="2" value="Label" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
</mxCell>
```
**Diamond (decision):**
```xml
<mxCell id="3" value="Condition?" style="rhombus;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="100" y="200" width="120" height="80" as="geometry"/>
</mxCell>
```
**Arrow (edge):**
```xml
<mxCell id="4" value="" style="edgeStyle=orthogonalEdgeStyle;html=1;" edge="1" source="2" target="3" parent="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
```
**Labeled arrow:**
```xml
<mxCell id="5" value="Yes" style="edgeStyle=orthogonalEdgeStyle;html=1;" edge="1" source="3" target="6" parent="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
```
## Style properties
| Property | Values | Use for |
|----------|--------|---------|
| `rounded=1` | 0 or 1 | Rounded corners |
| `whiteSpace=wrap` | wrap | Text wrapping |
| `fillColor=#dae8fc` | Hex color | Background color |
| `strokeColor=#6c8ebf` | Hex color | Border color |
| `fontColor=#333333` | Hex color | Text color |
| `shape=cylinder3` | shape name | Database cylinders |
| `shape=mxgraph.flowchart.document` | shape name | Document shapes |
| `ellipse` | style keyword | Circles/ovals |
| `rhombus` | style keyword | Diamonds |
| `edgeStyle=orthogonalEdgeStyle` | style keyword | Right-angle connectors |
| `edgeStyle=elbowEdgeStyle` | style keyword | Elbow connectors |
| `dashed=1` | 0 or 1 | Dashed lines |
| `swimlane` | style keyword | Swimlane containers |
| `group` | style keyword | Invisible container (pointerEvents=0) |
| `container=1` | 0 or 1 | Enable container behavior on any shape |
| `pointerEvents=0` | 0 or 1 | Prevent container from capturing child connections |
| `html=1` | 0 or 1 | Enable HTML rendering in labels (required for `<b>`, `<br>`, `<font>`, etc.) |
| `shape=umlLifeline;perimeter=lifelinePerimeter;size=16` | shape | UML sequence diagram lifeline (size = header height) |
## HTML labels
**Always include `html=1` in the style** when the `value` attribute contains any HTML tags (`<b>`, `<br>`, `<font>`, `<i>`, `<u>`, `<hr>`, `<p>`, `<table>`, etc.). Without `html=1`, HTML tags are displayed as literal text instead of being rendered.
HTML in attribute values must be **XML-escaped**: `<` → `&lt;`, `>` → `&gt;`, `&` → `&amp;`, `"` → `&quot;`
```xml
<mxCell value="&lt;b&gt;Title&lt;/b&gt;&lt;br&gt;Description"
style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
</mxCell>
```
**Line breaks:** Use `&#xa;` (works with both `html=1` and `html=0`) or `&lt;br&gt;` (requires `html=1`) for line breaks — never use `\n`, which renders as literal backslash-n text instead of a newline.
**Best practice:** Always include `html=1` in every cell style. This ensures labels render correctly whether they contain HTML or plain text — plain text is unaffected by the flag.
**Bold/italic/underline:** Use `fontStyle` in the style string when the entire label should be bold (`fontStyle=1`), italic (`fontStyle=2`), or underline (`fontStyle=4`). Values can be combined via bitwise OR (e.g., `fontStyle=3` = bold+italic). Use HTML tags (`<b>`, `<i>`, `<u>`) only when formatting part of the label (e.g., bold title with normal description). Never combine `fontStyle` with HTML tags for the same effect — this is redundant and causes visible raw tags if `html=1` is missing.
## Edges
**CRITICAL: Every edge `mxCell` must contain a `<mxGeometry relative="1" as="geometry" />` child element.** Self-closing edge cells (e.g. `<mxCell ... edge="1" ... />`) are invalid and will not render correctly. Always use the expanded form:
```xml
<mxCell id="e1" edge="1" parent="1" source="a" target="b" style="...">
<mxGeometry relative="1" as="geometry" />
</mxCell>
```
**Don't hand-route edges.** Just declare `source` and `target`. You do **not** need to:
- Add `<mxPoint>` waypoints
- Set `exitX` / `exitY` / `entryX` / `entryY`
- Route around obstacles
- Worry about edge-vertex collisions or parallel edge spacing
draw.io's built-in router is **basic**: it draws each edge as a straight line or a simple right-angle path between `source` and `target`, with **no awareness of other shapes** — a wire will run straight across any box that sits between its endpoints. That's fine when connected nodes have open space between them. When edges would otherwise cross over shapes, or you want consistently clean orthogonal wires that route *around* the boxes, set **`routing: "libavoid"`** on `create_diagram`; for a full re-layout use **`postLayout: "elk"`** (see **Edge routing & layout passes** below). Both compute the waypoints for you — you never add them by hand either way.
**What you still choose: the edge style.** The style determines the overall look (orthogonal angles, curves, straight lines) — the router honors the style family.
| Style | Syntax | Best for |
|-------|--------|---------|
| **Orthogonal** | `edgeStyle=orthogonalEdgeStyle` | Flowcharts, architecture, network diagrams, BPMN — any diagram with right-angle connectors |
| **Straight** | no `edgeStyle` | UML class/sequence diagrams, direct point-to-point connections. For sequence diagram messages use `endSize=6;startSize=6;` to keep arrowheads small |
| **Entity Relation** | `edgeStyle=entityRelationEdgeStyle` | ER diagrams — creates perpendicular stubs at both ends |
| **Curved** | `curved=1` | Mind maps, informal diagrams |
| **Elbow** | `edgeStyle=elbowEdgeStyle;elbow=vertical;` | Rarely needed — `orthogonalEdgeStyle` handles almost all cases; use this only for simple 1-bend linear flows |
**Use a consistent edge style within each diagram.** Pick one based on diagram type and apply it to all edges: ER → `entityRelationEdgeStyle`; UML class → straight; mind maps → curved; flowcharts/architecture/network → `orthogonalEdgeStyle`.
**Useful edge style attributes** that apply regardless of routing:
- `rounded=1` — rounded corners at bend points (recommended for orthogonal)
- `endArrow=classic` / `endArrow=none` — arrow heads
- `dashed=1` — dashed line
- `strokeColor=#...`, `strokeWidth=2` — color/width
- Edge labels: set `value` directly on the edge cell
**Keep edge labels short and meaningful** — one to three words (`Yes`, `async`, `reads`). Drop labels that merely restate an obvious action (`call`, `register`); move longer explanations into node text or a small legend node.
**Visual semantics — stay consistent, add a legend when mixing styles.** Within one diagram apply `dashed=1`, `strokeColor`, and `strokeWidth` consistently for one chosen meaning (e.g. dashed = optional / async / inferred relationship). Don't mix several dashed meanings without a small legend explaining them.
## Containers and groups
For architecture diagrams or any diagram with nested elements, use draw.io's proper parent-child containment — do **not** just place shapes on top of larger shapes.
### How containment works
Set `parent="containerId"` on child cells. Children use **relative coordinates** within the container.
### Container types
| Type | Style | When to use |
|------|-------|-------------|
| **Group** (invisible) | `group;` | No visual border needed, container has no connections. Includes `pointerEvents=0` so child connections are not captured |
| **Swimlane** (titled) | `swimlane;startSize=30;` | Container needs a visible title bar/header, or the container itself has connections |
| **Custom container** | Add `container=1;pointerEvents=0;` to any shape style | Any shape acting as a container without its own connections |
### Key rules
- **Edges to children inside containers naturally cross the container boundary** — this is correct and expected. Do not add extra waypoints or complex routing to avoid a parent container when connecting to shapes inside it.
- **Always add `pointerEvents=0;`** to container styles that should not capture connections being rewired between children
- Only omit `pointerEvents=0` when the container itself needs to be connectable — in that case, use `swimlane` style which handles this correctly (the client area is transparent for mouse events while the header remains connectable)
- Children must set `parent="containerId"` and use coordinates **relative to the container**
### Example: Architecture container with swimlane
```xml
<mxCell id="svc1" value="User Service" style="swimlane;startSize=30;fillColor=#dae8fc;strokeColor=#6c8ebf;html=1;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="300" height="200" as="geometry"/>
</mxCell>
<mxCell id="api1" value="REST API" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="svc1">
<mxGeometry x="20" y="40" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="db1" value="Database" style="shape=cylinder3;whiteSpace=wrap;html=1;" vertex="1" parent="svc1">
<mxGeometry x="160" y="40" width="120" height="60" as="geometry"/>
</mxCell>
```
### Example: Invisible group container
```xml
<mxCell id="grp1" value="" style="group;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="300" height="200" as="geometry"/>
</mxCell>
<mxCell id="c1" value="Component A" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="grp1">
<mxGeometry x="10" y="10" width="120" height="60" as="geometry"/>
</mxCell>
```
### Swimlanes for grouped actors (BPMN-style flowcharts)
Use **flat swimlanes** at `parent="1"`, stacked vertically. One row of nodes per lane.
**Fixed values — do not compute or debate:**
- Lane size: `x=0, y=lane_index*150, width=CANVAS_W, height=150`
- Lane style: `swimlane;horizontal=0;startSize=110;fillColor=<pastel>;html=1;`
- Child nodes inside a lane: `parent="<lane_id>"`, `x = 120 + col*180`, `y = 45` (always 45), size 140×60 (or 140×80 for diamonds)
- Cross-lane edges: `parent="1"` (not inside a lane)
Pick `CANVAS_W = max_col * 180 + 300`. Choose lane colors from `#f5f5f5, #e8f4f8, #fff0e6, #e8f5e9, #fff9e6, #fce4ec` in that order.
```xml
<mxCell id="lane1" value="Customer" style="swimlane;horizontal=0;startSize=110;fillColor=#f5f5f5;html=1;" vertex="1" parent="1">
<mxGeometry x="0" y="0" width="1800" height="150" as="geometry"/>
</mxCell>
<mxCell id="n1" value="Place Order" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="lane1">
<mxGeometry x="120" y="45" width="140" height="60" as="geometry"/>
</mxCell>
<mxCell id="lane2" value="System" style="swimlane;horizontal=0;startSize=110;fillColor=#e8f4f8;html=1;" vertex="1" parent="1">
<mxGeometry x="0" y="150" width="1800" height="150" as="geometry"/>
</mxCell>
<mxCell id="n2" value="Validate" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="lane2">
<mxGeometry x="300" y="45" width="140" height="60" as="geometry"/>
</mxCell>
<mxCell id="e1" edge="1" parent="1" source="n1" target="n2" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
```
Do NOT nest lanes inside a pool. Do NOT vary lane heights. Do NOT compute title-area offset — it is always 110, children start at x=120 to clear it.
### Nested architecture containers (cloud, infra, network topologies)
For diagrams with **nested groupings** — VPC → Availability Zone → EC2 instance, Datacenter → Rack → Server, Region → Environment → Service — use nested swimlanes. This is where the AI most often flattens hierarchy that should be nested. Treat each level as a swimlane container.
**Rules:**
- Every container is a `swimlane` with `startSize=24` (title area at the top).
- Child cells set `parent="<container_id>"` and use coordinates **relative to their parent** (origin 0,0 is the parent's top-left, below the title).
- Edges between cells in **different** containers must have `parent="1"` (not a container) — otherwise they render inside the container and get clipped.
- For industry-specific icons (AWS/Azure/GCP logos, Cisco equipment, etc.), call `search_shapes` to get the exact `style` string and substitute it into a regular vertex — the container structure stays the same.
```xml
<mxCell id="vpc" value="VPC" style="swimlane;startSize=24;fillColor=#dae8fc;strokeColor=#6c8ebf;html=1;" vertex="1" parent="1">
<mxGeometry x="0" y="0" width="720" height="360" as="geometry"/>
</mxCell>
<mxCell id="az1" value="AZ us-east-1a" style="swimlane;startSize=24;fillColor=#fff2cc;strokeColor=#d6b656;html=1;" vertex="1" parent="vpc">
<mxGeometry x="20" y="36" width="320" height="300" as="geometry"/>
</mxCell>
<mxCell id="web1" value="web-1" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="az1">
<mxGeometry x="30" y="40" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="db1" value="db-1" style="shape=cylinder3;whiteSpace=wrap;html=1;" vertex="1" parent="az1">
<mxGeometry x="180" y="40" width="100" height="70" as="geometry"/>
</mxCell>
<mxCell id="az2" value="AZ us-east-1b" style="swimlane;startSize=24;fillColor=#fff2cc;strokeColor=#d6b656;html=1;" vertex="1" parent="vpc">
<mxGeometry x="360" y="36" width="340" height="300" as="geometry"/>
</mxCell>
<mxCell id="web2" value="web-2" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="az2">
<mxGeometry x="30" y="40" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="e1" edge="1" parent="1" source="web1" target="web2" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
```
### Cross-functional flowcharts (actor × phase grid, as a table)
Cross-functional flowcharts show a process across **two axes at once** — actors (rows) and phases (columns). Use drawio's `table` shape, which auto-arranges cells into a grid via `childLayout=tableLayout`. This is the canonical draw.io pattern and is distinct from plain swimlanes (which only group on one axis).
**Structure:**
- Outer container: `shape=table;childLayout=tableLayout;startSize=0;collapsible=0;fillColor=none;`
- Rows are children of the table: `shape=tableRow;horizontal=0;startSize=0;collapsible=0;`
- Cells are children of rows — regular vertices, one per (actor, phase) intersection
- Row heights and cell widths are set via `mxGeometry`; they tile automatically
- First row = phase headers; first cell of every other row = actor label
- Process nodes go INSIDE the appropriate cell (parent = cell id) at coordinates relative to the cell
- Cross-cell edges must use `parent="1"` (same rule as containers)
```xml
<mxCell id="tbl" style="shape=table;childLayout=tableLayout;startSize=0;collapsible=0;fillColor=none;" vertex="1" parent="1">
<mxGeometry x="0" y="0" width="900" height="320" as="geometry"/>
</mxCell>
<mxCell id="r0" style="shape=tableRow;horizontal=0;startSize=0;collapsible=0;" vertex="1" parent="tbl">
<mxGeometry width="900" height="40" as="geometry"/>
</mxCell>
<mxCell id="h0" style="text;html=1;" vertex="1" parent="r0">
<mxGeometry width="140" height="40" as="geometry"/>
</mxCell>
<mxCell id="h1" value="Order" style="text;align=center;fontStyle=1;fillColor=#e8e8e8;" vertex="1" parent="r0">
<mxGeometry x="140" width="380" height="40" as="geometry"/>
</mxCell>
<mxCell id="h2" value="Fulfill" style="text;align=center;fontStyle=1;fillColor=#e8e8e8;" vertex="1" parent="r0">
<mxGeometry x="520" width="380" height="40" as="geometry"/>
</mxCell>
<mxCell id="r1" style="shape=tableRow;horizontal=0;startSize=0;collapsible=0;" vertex="1" parent="tbl">
<mxGeometry y="40" width="900" height="140" as="geometry"/>
</mxCell>
<mxCell id="a1" value="Customer" style="fillColor=#dae8fc;fontStyle=1;" vertex="1" parent="r1">
<mxGeometry width="140" height="140" as="geometry"/>
</mxCell>
<mxCell id="c_cust_order" style="fillColor=none;" vertex="1" parent="r1">
<mxGeometry x="140" width="380" height="140" as="geometry"/>
</mxCell>
<mxCell id="t_place" value="Place Order" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="c_cust_order">
<mxGeometry x="120" y="40" width="140" height="60" as="geometry"/>
</mxCell>
<mxCell id="c_cust_fulfill" style="fillColor=none;" vertex="1" parent="r1">
<mxGeometry x="520" width="380" height="140" as="geometry"/>
</mxCell>
<mxCell id="r2" style="shape=tableRow;horizontal=0;startSize=0;collapsible=0;" vertex="1" parent="tbl">
<mxGeometry y="180" width="900" height="140" as="geometry"/>
</mxCell>
<mxCell id="a2" value="System" style="fillColor=#d5e8d4;fontStyle=1;" vertex="1" parent="r2">
<mxGeometry width="140" height="140" as="geometry"/>
</mxCell>
<mxCell id="c_sys_order" style="fillColor=none;" vertex="1" parent="r2">
<mxGeometry x="140" width="380" height="140" as="geometry"/>
</mxCell>
<mxCell id="t_validate" value="Validate" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="c_sys_order">
<mxGeometry x="120" y="40" width="140" height="60" as="geometry"/>
</mxCell>
<mxCell id="c_sys_fulfill" style="fillColor=none;" vertex="1" parent="r2">
<mxGeometry x="520" width="380" height="140" as="geometry"/>
</mxCell>
<mxCell id="t_ship" value="Ship" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="c_sys_fulfill">
<mxGeometry x="120" y="40" width="140" height="60" as="geometry"/>
</mxCell>
<mxCell id="e1" edge="1" parent="1" source="t_place" target="t_validate" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="e2" edge="1" parent="1" source="t_validate" target="t_ship" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
```
**When to use cross-functional tables vs flat swimlanes:**
- Flat swimlanes — one-dimensional (actors only, or phases only). Simpler. Use this when you just need to show who does what in sequence.
- Cross-functional table — two-dimensional (actors AND phases). Use this when **both** the actor and the process stage matter, and every step belongs to a specific (actor, phase) cell.
**Do NOT** nest swimlanes inside a table row, do NOT set `startSize` on rows or cells (columns tile from `x=0`), and do NOT rely on the AI to produce exact widths that sum to the table width — close-enough totals are fine, the `tableLayout` normalizes them.
## Layers
Layers control visibility and z-order. Every cell belongs to exactly one layer. Use layers to manage diagram complexity — viewers can toggle layer visibility to show or hide groups of elements (e.g., "Physical Infrastructure" vs "Logical Network" vs "Security Zones").
Cell `id="0"` is the root and cell `id="1"` is the default layer — both always exist. Additional layers are `mxCell` elements with `parent="0"`:
```xml
<mxGraphModel>
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" value="Annotations" parent="0"/>
<mxCell id="10" value="Server" style="rounded=1;html=1;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="20" value="Note: deprecated" style="text;" vertex="1" parent="2">
<mxGeometry x="100" y="170" width="120" height="30" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
```
- A layer is an `mxCell` with `parent="0"` and no `vertex` or `edge` attribute
- Assign shapes to a layer by setting `parent` to the layer's id
- Later layers render on top of earlier layers (higher z-order)
- Add `visible="0"` as an attribute on the layer cell to hide it by default
- Use layers when the diagram has distinct conceptual groupings that viewers may want to toggle independently
## Tags
Tags are visual filters that let viewers show or hide elements by category. Unlike layers, a single element can have multiple tags, making tags ideal for cross-cutting concerns (e.g., tagging shapes as "critical", "v2", or "backend").
Tags require wrapping `mxCell` in an `<object>` element. Tags are assigned via the `tags` attribute as a space-separated string:
```xml
<mxGraphModel>
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<object id="2" label="Auth Service" tags="critical v2">
<mxCell style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
</mxCell>
</object>
<object id="3" label="Legacy API" tags="critical deprecated">
<mxCell style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="300" y="100" width="120" height="60" as="geometry"/>
</mxCell>
</object>
</root>
</mxGraphModel>
```
- Tags require the `<object>` wrapper — a plain `mxCell` cannot have tags
- The `label` attribute on `<object>` replaces `value` on `mxCell`
- Tags are space-separated in the `tags` attribute
- Viewers filter the diagram by selecting tags in the draw.io UI (Edit > Tags)
- Tags do not affect z-order or structural grouping — they are purely a visibility filter
## Metadata and placeholders
Metadata stores custom key-value properties on shapes as additional attributes on the `<object>` wrapper element. Combined with placeholders, metadata values can be displayed in labels — useful for data-driven diagrams showing status, owner, IP addresses, or versions on each shape.
Set `placeholders="1"` on the `<object>` to enable `%propertyName%` substitution in the `label`:
```xml
<mxGraphModel>
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<object id="2" label="&lt;b&gt;%component%&lt;/b&gt;&lt;br&gt;Owner: %owner%&lt;br&gt;Status: %status%"
placeholders="1" component="Auth Service" owner="Team Backend" status="Active">
<mxCell style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="100" y="100" width="160" height="80" as="geometry"/>
</mxCell>
</object>
</root>
</mxGraphModel>
```
- Custom properties are plain XML attributes on `<object>` (e.g., `component="Auth Service"`)
- Set `placeholders="1"` to enable `%key%` substitution in the label and tooltip
- The label must use `html=1` style when using HTML formatting with placeholders
- Placeholders resolve by walking up the containment hierarchy: shape attributes first, then parent container, then layer, then root — first match wins
- Predefined placeholders work without custom properties: `%id%`, `%width%`, `%height%`, `%date%`, `%time%`, `%timestamp%`, `%page%`, `%pagenumber%`, `%pagecount%`, `%filename%`
- Use `%%` for a literal percent sign in labels
- Tags, metadata, and placeholders can all be combined on the same `<object>` element
- Use metadata when shapes represent data records (servers, services, components) and you want to attach structured information beyond the visible label
## Dark mode colors
draw.io supports automatic dark mode rendering. How colors behave depends on the property:
- **`strokeColor`, `fillColor`, `fontColor`** default to `"default"`, which renders as black in light theme and white in dark theme. When no explicit color is set, colors adapt automatically.
- **Explicit colors** (e.g. `fillColor=#DAE8FC`) specify the light-mode color. The dark-mode color is computed automatically by inverting the RGB values (blending toward the inverse at 93%) and rotating the hue by 180° (via `mxUtils.getInverseColor`).
- **`light-dark()` function** — To specify both colors explicitly, use `light-dark(lightColor,darkColor)` in the style string, e.g. `fontColor=light-dark(#7EA6E0,#FF0000)`. The first argument is used in light mode, the second in dark mode.
To enable dark mode color adaptation, the `mxGraphModel` element must include `adaptiveColors="auto"`.
When generating diagrams, you generally do not need to specify dark-mode colors — the automatic inversion handles most cases. Use `light-dark()` only when the automatic inverse color is unsatisfactory.
## Edge routing & layout passes
By default, edges are drawn by draw.io's **built-in router**, which is intentionally basic: each edge is a straight line or a simple right-angle path between its endpoints, with **no obstacle avoidance** — a connector runs straight through any shape lying between its `source` and `target`. There is no server-side post-processing. Two **opt-in** passes on `create_diagram` upgrade this; they are independent and combine freely, run client-side after the diagram renders, and the exported XML (copy/clipboard, "Open in draw.io") reflects the final routed result.
- **`routing: "libavoid"`** (XML only) — obstacle-avoiding orthogonal **edge routing**. Vertices stay exactly where you placed them; only the connectors are recomputed, so they run in clean right-angle segments that route *around* the boxes (and spread apart when parallel) instead of cutting across them. Use it for diagrams you laid out deliberately — architecture, network topology, deployment, swimlanes, UML, floor plans — where you want tidy wires without disturbing your layout.
- **`postLayout: "elk"`** — a **full re-layout** (ELK `layered` flow). Vertices animate (morph) from your positions to canonical hierarchical positions, and the edges are routed as part of that. Best for flowcharts, process/state diagrams, decision flows, pipelines, and other directional/hierarchical diagrams. (You should rarely hand-write these as XML — prefer Mermaid.) Flow **direction**: on XML set the optional `direction` field (`"vertical"` (default) / `"horizontal"`); on Mermaid it is read from the flowchart code (`flowchart TD/TB` vs `LR/RL`) and `direction` is ignored.
The four combinations:
| `postLayout` | `routing` | Result |
|---|---|---|
| — | — | basic built-in router (straight / simple right-angle, no obstacle avoidance); your positions kept |
| — | `libavoid` | your positions kept; wires re-routed orthogonally *around* the shapes |
| `elk` | — | ELK places the vertices **and** routes the edges (decent routing built in) |
| `elk` | `libavoid` | rarely worth it — ELK already routes; only add `libavoid` if ELK's routing specifically comes out poor |
**Pick ONE — they are essentially alternatives, not a stack:**
- **Neither** — fine when connected nodes sit in clear rows/columns with open space between them, so the basic router's straight/right-angle lines won't cross another shape. Simplest and lightest; do this by default for sparse layouts.
- **`routing: "libavoid"`** — keep your hand-placed layout but clean up the wires: use whenever an edge would otherwise cut across a box, or you want consistently clean orthogonal wires routed around shapes (architecture, network topology, deployment, UML, floor plans — anything densely connected).
- **`postLayout: "elk"`** — when you want a canonical re-layout (vertices moved). ELK routes the edges itself as part of the layout, so **do not also set `routing`** — the combination is redundant in almost all cases. Add `direction: "horizontal"` for left-to-right flow.
**For Mermaid diagrams: see the `postLayout` parameter description for when to set it.** Complex Mermaid flowcharts (≥ ~20 nodes, ≥ 3 decision diamonds, feedback edges, or ≥ 3 endpoints) need `postLayout: "elk"` because the native parser's layout goes cramped or unbalanced past that threshold — the direction follows the flowchart code, so no `direction` is needed. Simple flowcharts and all non-flowchart Mermaid types (sequence, class, ER, sankey, …) need no `postLayout`.
**When NOT to use (XML):**
- The user has asked for specific positions (swim lanes with exact lanes, architecture diagrams with meaningful spatial arrangement).
- The diagram relies on containers/grouping where spatial layout encodes information.
## Style reference
Complete style reference (all shape types, style properties, color palettes, HTML labels, and more): https://github.com/jgraph/drawio-mcp/blob/main/shared/style-reference.md
XML Schema (XSD): https://github.com/jgraph/drawio-mcp/blob/main/shared/mxfile.xsd
## CRITICAL: XML well-formedness
When generating draw.io XML, the output **must** be well-formed XML:
- **NEVER include ANY XML comments (`<!-- -->`) in the output.** XML comments are strictly forbidden — they waste tokens, can cause parse errors, and serve no purpose in diagram XML.
- Escape special characters in attribute values: `&amp;`, `&lt;`, `&gt;`, `&quot;`
- Always use unique `id` values for each `mxCell`