Skip to content

Editorial diagram design for Claude Code, Codex, GitHub Copilot, Cursor, Factory Droid, Qoder, and Pi. 45 diagram types. Self-contained HTML + SVG. No shadows. No Mermaid slop.

71.0 KB
Raw Blame
#!/usr/bin/env python3
"""Lint diagram examples as *rendered* — catches breakage the source can't show.

``lint-skin.py`` reads the HTML. This one renders it in headless Chromium and
asks the browser what actually got painted, so it catches content cut off by the
SVG viewport, collapsed SVGs, sideways page overflow and runtime errors.

How the clipping check works
---------------------------
Chromium's ``getBoundingClientRect()`` on an SVG child reports *geometry*, not
paint: it excludes stroke width, markers and filter bleed (so a 40px stroke
spilling past the viewport measures as inside), and it ignores ``clip-path``,
``opacity: 0`` ancestors and ``overflow: visible`` (so safe content measures as
outside). Both directions were reproduced in Chromium, so no geometry model is
used here.

Instead the browser is the oracle: screenshot the viewport as authored,
screenshot it again with ``overflow`` released, and diff the two. New ink means
paint was being cut off — ink is ink, so strokes, markers and filter bleed all
count, while clip-path, invisible and already-visible content produce no new ink.

Releases are **staged**, because a diagram can be clipped at more than one level
and each release repaints its own box:

- stage 0 releases the SVG alone, and looks for ink outside the SVG's box;
- stage *k* also releases the *k* nearest clipping ancestors, and looks for ink
  outside the outermost released box.

Without staging, releasing an ancestor masks spill just outside the SVG (its box
becomes part of the ignored area), and an SVG authored ``overflow: visible``
inside a clipping wrapper looks clean while the wrapper cuts it off.

What the diff ignores, and why:

- The outermost released box for that stage. A released element repaints itself —
  an ``overflow: hidden`` box with a ``border-radius`` loses its rounded corners —
  which is not spill.
- An ``EDGE_GUARD``-px band around it, and anything under ``MIN_DIFF_PIXELS``
  pixels past ``CHANNEL_THRESHOLD``. Releasing ``overflow`` re-antialiases
  boundary pixels by a channel step or two, which is not a clipped diagram.

Every stage runs at each of ``DIFF_SCALES``: 1x resolves spill of a few px, 0.25x
pulls spill up to four viewports wide back into frame. All geometry stays in one
coordinate system — viewport pixels, straight from ``getBoundingClientRect()``,
matching ``page.screenshot()`` — so an SVG below the fold measures the same as
one above it.

Known ceilings: spill of ~2px or less, spill past 0.25x framing, and SVGs inside
a *scrolling* ancestor, which report ``unmeasurable`` rather than passing quietly.

Every property this script mutates is snapshotted and restored verbatim in a
``finally``, and ``--self-test`` asserts the DOM is byte-identical afterwards.

Trust boundary
--------------
This renders contributor HTML in a real browser with JavaScript enabled, so treat
it like opening the file yourself. Network is cut at the resolver
(``--host-resolver-rules``), which also stops WebSockets and anything else that
does not go through Playwright's request routing, with request routing as a second
layer. ``--fonts`` excludes exactly the two Google Fonts hostnames from the
resolver block and allows them only over HTTPS on an exact hostname match.
``--self-test`` proves the isolation against a local listener.

One check sits outside that browser: ``--all`` and ``--self-test`` run the
packaged PNG renderer in a subprocess, the way the doc tells a user to, on local fixtures (the shipped templates re-drawn at a wide
preset, with every remote ``<link>`` removed). That subprocess's Chromium is not
under the resolver block, which is why the fixtures carry no remote references.

Because the oracle is pixels, CI must pin Playwright and its bundled Chromium
rather than taking whatever is newest; see ``.github/workflows/ci.yml``.

    python3 scripts/lint-render.py --all
    python3 scripts/lint-render.py skills/diagram-design/assets/example-venn.html
    python3 scripts/lint-render.py --self-test   # proves every check still fires

Requires Playwright (same dev dependency the PNG export uses):

    pip install playwright && playwright install chromium
"""

import argparse
import base64
import os
import re
import socket
import subprocess
import sys
import tempfile
import threading
from pathlib import Path
from urllib.parse import urlparse

ROOT = Path(__file__).resolve().parent.parent
ASSET_DIR = ROOT / "skills/diagram-design/assets"
EXPORT_PNG = ROOT / "skills/diagram-design/scripts/export_png.py"

VIEWPORT = {"width": 1600, "height": 1000}
TOLERANCE = 1.0  # px of slop before page overflow counts, absorbs subpixel layout
CHANNEL_THRESHOLD = 16  # per-channel delta that counts as new ink, not antialiasing
MIN_DIFF_PIXELS = 8  # new-ink pixels needed before a clip is reported
# ponytail: 2px guard band around a released box absorbs boundary re-antialiasing;
# the cost is that a spill of 2px or less goes unreported.
EDGE_GUARD = 2
# Two passes: 1x sees spills of a few px, 0.25x pulls a spill four viewports wide
# back into frame. ponytail: anything past that stays unseen, and says so above.
DIFF_SCALES = (1, 0.25)
# Deepest ancestor chain to stage. Diagram wrappers are shallow; this only bounds
# pathological nesting. ponytail: raise it if a real example needs more.
MAX_ANCESTOR_STAGES = 4

FONT_HOSTS = ("fonts.googleapis.com", "fonts.gstatic.com")
# Kill name resolution outright. Unlike request routing this also covers
# WebSockets, EventSource and anything else that opens its own connection.
RESOLVER_RULE = "MAP * ~NOTFOUND"

# Findings in these categories are reported but do not fail the run: they say
# "not checked", which is worth printing and wrong to treat as a defect.
NOTE_CATEGORIES = {"unmeasurable"}

# Per-svg facts that don't need paint: its box, whether the author already set
# overflow visible, and the chain of ancestors that clip it. A clipping ancestor
# that is currently scrolling cannot be released (its scrollbars would move and
# change the pixels), so the chain stops there and the rest is reported unchecked.
SURVEY_JS = """
() => {
  const label = (el) => {
    const id = el.id ? '#' + el.id : '';
    const cls = el.getAttribute('class') ? '.' + el.getAttribute('class').split(/\\s+/)[0] : '';
    return el.tagName.toLowerCase() + id + cls;
  };
  return [...document.querySelectorAll('svg')].map((svg, index) => {
    const box = svg.getBoundingClientRect();
    const chain = [];
    let blockedBy = null;
    for (let el = svg.parentElement; el; el = el.parentElement) {
      const overflow = getComputedStyle(el).overflow;
      if (overflow === 'visible') continue;
      const scrolls = el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 1;
      if (scrolls) { blockedBy = `${label(el)} (overflow: ${overflow})`; break; }
      chain.push(`${label(el)} (overflow: ${overflow})`);
    }
    return {
      index,
      label: label(svg),
      width: box.width,
      height: box.height,
      ownOverflowVisible: getComputedStyle(svg).overflow === 'visible',
      chain,
      blockedBy,
    };
  });
}
"""

# Mutations record the exact `style` attribute they replace, so RESTORE_JS can put
# it back verbatim — including an authored inline transform, which an earlier
# version clobbered by resetting the property to ''.
REMEMBER_JS = """
  window.__lintSnapshots = window.__lintSnapshots || [];
  const remember = (el) => window.__lintSnapshots.push([el, el.getAttribute('style')]);
"""

RESTORE_JS = """
() => {
  const snapshots = window.__lintSnapshots || [];
  // Reverse order, so an element mutated twice ends on its earliest snapshot.
  for (const [el, style] of snapshots.slice().reverse()) {
    if (style === null) el.removeAttribute('style');
    else el.setAttribute('style', style);
  }
  delete window.__lintSnapshots;
}
"""

# A paint-only scale on the svg. Transforms don't reflow, so the rest of the page
# stays put and both screenshots of a pass are directly comparable. Shrinking the
# svg pulls spill that would land off-screen back into the viewport.
SET_SCALE_JS = (
    """
([index, scale]) => {
"""
    + REMEMBER_JS
    + """
  const svg = document.querySelectorAll('svg')[index];
  remember(svg);
  svg.style.setProperty('transform-origin', 'top left', 'important');
  svg.style.setProperty('transform', `scale(${scale})`, 'important');
}
"""
)

# Release overflow on the svg plus the `depth` nearest clipping ancestors, and
# return every released box in viewport coordinates, innermost first. `important`
# so a class rule can't win; the exact prior style attribute is snapshotted.
RELEASE_JS = (
    """
([index, depth]) => {
"""
    + REMEMBER_JS
    + """
  const svg = document.querySelectorAll('svg')[index];
  const targets = [svg];
  let taken = 0;
  for (let el = svg.parentElement; el && taken < depth; el = el.parentElement) {
    if (getComputedStyle(el).overflow === 'visible') continue;
    targets.push(el);
    taken++;
  }
  const rects = [];
  for (const el of targets) {
    remember(el);
    const r = el.getBoundingClientRect();
    rects.push([r.left, r.top, r.right, r.bottom]);
    el.style.setProperty('overflow', 'visible', 'important');
  }
  return rects;
}
"""
)

DOM_STATE_JS = "() => document.documentElement.outerHTML"

PAGE_OVERFLOW_JS = """
() => {
  const doc = document.documentElement;
  return [doc.scrollWidth - doc.clientWidth, doc.clientWidth];
}
"""

# Diff two screenshots of the same viewport inside the browser: no image library
# on the Python side. Only ink OUTSIDE the released box counts, so an element
# repainting its own area can't masquerade as clipping.
DIFF_JS = """
async ({a, b, interior, threshold, minPixels, guard}) => {
  const load = async (src) => {
    const bitmap = await createImageBitmap(await (await fetch(src)).blob());
    const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
    canvas.getContext('2d').drawImage(bitmap, 0, 0);
    return canvas.getContext('2d').getImageData(0, 0, bitmap.width, bitmap.height);
  };
  const [before, after] = await Promise.all([load(a), load(b)]);
  if (before.width !== after.width || before.height !== after.height) {
    return {count: 0, resized: true, sides: {}};
  }
  const sides = {left: 0, top: 0, right: 0, bottom: 0};
  let count = 0;
  const g = guard;
  for (let y = 0; y < before.height; y++) {
    for (let x = 0; x < before.width; x++) {
      if (x >= interior.left - g && x < interior.right + g &&
          y >= interior.top - g && y < interior.bottom + g) continue;
      const i = (y * before.width + x) * 4;
      const delta = Math.max(
        Math.abs(before.data[i] - after.data[i]),
        Math.abs(before.data[i + 1] - after.data[i + 1]),
        Math.abs(before.data[i + 2] - after.data[i + 2]),
        Math.abs(before.data[i + 3] - after.data[i + 3]),
      );
      if (delta <= threshold) continue;
      count++;
      if (x < interior.left) sides.left = Math.max(sides.left, interior.left - x);
      if (x >= interior.right) sides.right = Math.max(sides.right, x - interior.right + 1);
      if (y < interior.top) sides.top = Math.max(sides.top, interior.top - y);
      if (y >= interior.bottom) sides.bottom = Math.max(sides.bottom, y - interior.bottom + 1);
    }
  }
  return {count, resized: false, sides, reported: count >= minPixels};
}
"""


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("files", nargs="*", type=Path, help="HTML files to render")
    parser.add_argument("--all", action="store_true", help="render every example")
    parser.add_argument("--quiet", action="store_true", help="summary only")
    parser.add_argument(
        "--fonts",
        action="store_true",
        help="allow exactly the Google Fonts hosts, over HTTPS, so text is measured "
        "with the real typefaces",
    )
    parser.add_argument(
        "--self-test",
        action="store_true",
        dest="self_test",
        help="check the checks: detection, false flags, network isolation, DOM restore",
    )
    return parser.parse_args()


def shipped_assets():
    """Every asset that ships and renders: examples *and* the templates they are
    scaffolded from. A broken template ships broken diagrams, so leaving templates
    out of --all was a hole (thanks @greptile). index.html and icons.html are
    galleries of the others, so they add no coverage.
    """
    patterns = ("example-*.html", "template*.html")
    return sorted({path for pattern in patterns for path in ASSET_DIR.glob(pattern)})


def display_path(path):
    try:
        return str(path.resolve().relative_to(ROOT))
    except ValueError:
        return str(path)


def resolver_rule(allow_fonts):
    """Block every hostname, minus the font hosts when they are opted in."""
    if not allow_fonts:
        return RESOLVER_RULE
    return ",".join([RESOLVER_RULE] + [f"EXCLUDE {host}" for host in FONT_HOSTS])


def launch(playwright, allow_fonts):
    """Bundled Chromium, or the channel named by DIAGRAM_LINT_BROWSER_CHANNEL.

    No silent fallback: in CI a missing bundled Chromium is a broken environment,
    and quietly using whatever browser is lying around hides that.
    """
    args = [f"--host-resolver-rules={resolver_rule(allow_fonts)}"]
    channel = os.environ.get("DIAGRAM_LINT_BROWSER_CHANNEL")
    if channel:
        print(f"Using browser channel {channel!r} (DIAGRAM_LINT_BROWSER_CHANNEL).", file=sys.stderr)
        return playwright.chromium.launch(channel=channel, args=args)
    return playwright.chromium.launch(args=args)


def block_network(context, allow_fonts):
    """Second layer behind the resolver block: local documents only.

    The font exception requires HTTPS and an exact hostname, so a URL merely
    containing "fonts.googleapis.com" (a path, a query, a lookalike host) is not
    enough to get through.
    """

    def handler(route):
        url = route.request.url
        if url.startswith(("file://", "data:", "blob:")):
            route.continue_()
            return
        parsed = urlparse(url)
        if allow_fonts and parsed.scheme == "https" and parsed.hostname in FONT_HOSTS:
            route.continue_()
            return
        route.abort()

    context.route("**/*", handler)


def watch(page, findings):
    """Runtime failures. Local assets are reported precisely, via requestfailed."""
    page.on("pageerror", lambda error: findings.append(("page-error", str(error))))
    page.on(
        "console",
        lambda message: message.type == "error"
        # Resource failures arrive on requestfailed with a URL, which is where they
        # get judged. This drops the duplicate, not the signal.
        and not message.text.startswith("Failed to load resource")
        and findings.append(("console-error", message.text)),
    )

    def on_request_failed(request):
        if request.url.startswith("file://"):
            findings.append(("missing-asset", f"{request.url} failed to load"))
        # Remote requests are blocked by policy (resolver + routing); that is this
        # linter's doing, not the diagram's.

    page.on("requestfailed", on_request_failed)


def shoot(page):
    """The viewport, not the page: fixed dimensions, so releasing overflow can't
    resize the image, and the whole visible area is available to spill into.
    Viewport pixels are also the coordinate system every rect here uses."""
    return page.screenshot(animations="disabled")


def data_url(png_bytes):
    return "data:image/png;base64," + base64.b64encode(png_bytes).decode("ascii")


def compare_release(page, index, depth, scale):
    """One authored-vs-released paint comparison. Returns (diff, released_label_depth).

    Restores every mutated property before returning, whatever happens.
    """
    try:
        if scale != 1:
            page.evaluate(SET_SCALE_JS, [index, scale])
        as_authored = shoot(page)
        rects = page.evaluate(RELEASE_JS, [index, depth])
        released = shoot(page)
    finally:
        page.evaluate(RESTORE_JS)

    if not rects:
        return None
    # Outermost released box: the only area whose own repaint is expected.
    left, top, right, bottom = rects[-1]
    interior = {
        "left": round(left),
        "top": round(top),
        "right": round(right),
        "bottom": round(bottom),
    }
    return page.evaluate(
        DIFF_JS,
        {
            "a": data_url(as_authored),
            "b": data_url(released),
            "interior": interior,
            "threshold": CHANNEL_THRESHOLD,
            "minPixels": MIN_DIFF_PIXELS,
            "guard": EDGE_GUARD,
        },
    )


def clipping_findings(page, survey):
    """Staged paint comparisons per svg: the svg alone, then each clipping ancestor."""
    findings = []
    handles = page.locator("svg")
    for entry in survey:
        if not entry["width"] or not entry["height"]:
            findings.append(
                ("svg-collapsed", f"{entry['label']} renders {entry['width']}x{entry['height']}")
            )
            continue
        if entry["blockedBy"]:
            findings.append(
                (
                    "unmeasurable",
                    f"{entry['label']} sits inside scrolling {entry['blockedBy']}; "
                    "clipping cannot be measured through it",
                )
            )
        chain = entry["chain"][:MAX_ANCESTOR_STAGES]
        # Stage 0 is the svg's own overflow — skipped only when the author already
        # set it visible. Ancestor stages run regardless, since a wrapper can clip
        # an svg that does not clip itself.
        stages = [] if entry["ownOverflowVisible"] else [0]
        stages += list(range(1, len(chain) + 1))
        if not stages:
            continue

        handles.nth(entry["index"]).scroll_into_view_if_needed()
        for depth in stages:
            where = entry["label"] if depth == 0 else f"{entry['label']} inside {chain[depth - 1]}"
            worst = None
            unmeasurable = False
            for scale in DIFF_SCALES:
                diff = compare_release(page, entry["index"], depth, scale)
                if diff is None:
                    continue
                if diff.get("resized"):
                    findings.append(
                        ("unmeasurable", f"{where} changed size when overflow was released")
                    )
                    unmeasurable = True
                    break
                if diff.get("reported") and (worst is None or diff["count"] > worst[0]["count"]):
                    worst = (diff, scale)
            if unmeasurable or not worst:
                continue
            diff, scale = worst
            spills = ", ".join(
                f"{side} by {int(distance / scale)}px"
                for side, distance in sorted(diff["sides"].items())
                if distance
            )
            findings.append(
                (
                    "clipped",
                    f"{where} paints outside its box: {spills} "
                    f"({diff['count']} px of ink cut off at {scale:g}x)",
                )
            )
            # One report per svg is enough; deeper stages describe the same spill.
            break
    return findings


def measure(page):
    findings = []
    # Playwright awaits a returned promise; no timeout kwarg exists on evaluate.
    page.evaluate("() => document.fonts.ready")
    survey = page.evaluate(SURVEY_JS)
    findings.extend(clipping_findings(page, survey))
    spill, client_width = page.evaluate(PAGE_OVERFLOW_JS)
    if spill > TOLERANCE:
        findings.append(
            ("page-overflow", f"page scrolls {spill:.0f}px horizontally at {client_width}px wide")
        )
    return findings


def check(page, path):
    findings = []
    watch(page, findings)
    # CSS animation disabling does not stop the controller's JavaScript timer.
    # Both overflow captures must observe the same complete diagram.
    page.goto(path.resolve().as_uri() + "?motion=static", wait_until="load")
    return measure(page) + findings


# --- self-test ---------------------------------------------------------------

SVG_CASES = [
    # (name, svg markup, svg inline style, wrapper html or None, should_be_flagged)
    ("plain-overflow", '<rect x="150" y="60" width="400" height="10" fill="#000"/>', "", None, True),
    (
        "thick-stroke-spill",
        '<rect x="150" y="20" width="45" height="40" fill="none" stroke="#000" stroke-width="40"/>',
        "",
        None,
        True,
    ),
    (
        "marker-spill",
        '<defs><marker id="a" markerWidth="30" markerHeight="30" refX="0" refY="5" overflow="visible">'
        '<path d="M0,0 L30,5 L0,10 Z" fill="#000"/></marker></defs>'
        '<line x1="100" y1="50" x2="199" y2="50" stroke="#000" marker-end="url(#a)"/>',
        "",
        None,
        True,
    ),
    (
        "filter-bleed",
        '<filter id="b" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="20"/></filter>'
        '<rect x="165" y="10" width="30" height="20" fill="#000" filter="url(#b)"/>',
        "",
        None,
        True,
    ),
    (
        "clip-path-keeps-it-safe",
        '<clipPath id="c"><rect x="0" y="0" width="200" height="100"/></clipPath>'
        '<rect x="150" y="10" width="400" height="30" fill="#000" clip-path="url(#c)"/>',
        "",
        None,
        False,
    ),
    (
        "opacity-0-ancestor",
        '<g opacity="0"><rect x="150" y="10" width="400" height="10" fill="#000"/></g>',
        "",
        None,
        False,
    ),
    (
        "display-none-ancestor",
        '<g style="display:none"><rect x="150" y="10" width="400" height="10" fill="#000"/></g>',
        "",
        None,
        False,
    ),
    ("all-inside", '<rect x="10" y="10" width="100" height="40" fill="#000"/>', "", None, False),
    # The author set overflow visible: the svg itself clips nothing.
    (
        "overflow-visible-svg",
        '<rect x="150" y="60" width="400" height="10" fill="#000"/>',
        "overflow:visible",
        None,
        False,
    ),
    # ... but a wrapper still clips it, and staging must catch that.
    (
        "overflow-visible-svg-in-clipping-wrapper",
        '<rect x="150" y="60" width="400" height="10" fill="#000"/>',
        "overflow:visible",
        '<div style="overflow:hidden;width:200px;height:100px">',
        True,
    ),
    # Wrapper clipping declared inline, and via a class — both must be released.
    (
        "inline-wrapper",
        '<rect x="150" y="60" width="400" height="10" fill="#000"/>',
        "",
        '<div style="overflow:hidden;width:200px;height:100px">',
        True,
    ),
    (
        "class-wrapper",
        '<rect x="150" y="60" width="400" height="10" fill="#000"/>',
        "",
        '<style>.wrap{overflow:hidden;width:200px;height:100px}</style><div class="wrap">',
        True,
    ),
    # A rounded clipping wrapper repaints its corners when released; not spill.
    (
        "rounded-wrapper",
        '<rect x="10" y="10" width="100" height="40" fill="#000"/>',
        "background:#eee",
        '<div style="overflow:hidden;border-radius:12px;padding:40px;background:#222;width:280px">',
        False,
    ),
    # An authored inline transform must survive the scale pass untouched.
    (
        "authored-transform",
        '<rect x="150" y="60" width="400" height="10" fill="#000"/>',
        "transform:rotate(2deg)",
        None,
        True,
    ),
]

FIXTURE_PAGE = """
<!DOCTYPE html><html><body style="margin:40px">%(filler)s%(open)s
<svg width="200" height="100" viewBox="0 0 200 100" style="display:block;%(svg_style)s">%(markup)s</svg>
%(close)s</body></html>
"""

# Enough filler to push the svg below a 1000px-tall viewport, so the paired
# above/below-fold cases exercise scrolled measurement.
BELOW_FOLD_FILLER = '<div style="height:1800px;background:#eee"></div>'


def fixture_html(markup, svg_style="", wrapper=None, filler=""):
    return FIXTURE_PAGE % {
        "filler": filler,
        "open": wrapper or "",
        "close": "</div>" if wrapper else "",
        "svg_style": svg_style,
        "markup": markup,
    }


def network_isolation_failures(context):
    """Point a page at a local listener four different ways; nothing may connect.

    Request routing alone does not stop a WebSocket — verified — which is why the
    resolver block exists. This asserts the boundary rather than documenting it.
    """
    connections = []
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    port = server.getsockname()[1]
    server.listen(8)

    def accept_loop():
        while True:
            try:
                connection, address = server.accept()
            except OSError:
                return
            connections.append(address)
            connection.close()

    thread = threading.Thread(target=accept_loop, daemon=True)
    thread.start()

    page = context.new_page()
    try:
        with tempfile.TemporaryDirectory() as directory:
            fixture = Path(directory) / "isolation.html"
            fixture.write_text(
                "<!DOCTYPE html><html><body><script>\n"
                f"  const target = '127.0.0.1:{port}';\n"
                "  try { new WebSocket('ws://' + target + '/ws'); } catch (e) {}\n"
                "  try { fetch('http://' + target + '/fetch').catch(() => {}); } catch (e) {}\n"
                "  try { new EventSource('http://' + target + '/sse'); } catch (e) {}\n"
                "  const img = new Image(); img.src = 'http://' + target + '/img.png';\n"
                "</script></body></html>",
                encoding="utf-8",
            )
            page.goto(fixture.as_uri(), wait_until="load")
            page.wait_for_timeout(1200)
    finally:
        page.close()
        server.close()

    if connections:
        return [f"network-isolation: {len(connections)} connection(s) reached a local listener"]
    return []


def gallery_mobile_failures(context, gallery_path=None):
    """Keep the wrapped gallery controls from collapsing its mobile preview."""
    gallery_path = gallery_path or ASSET_DIR / "index.html"
    failures = []
    page = context.new_page()
    page.set_viewport_size({"width": 390, "height": 844})
    try:
        page.goto(gallery_path.as_uri(), wait_until="load")
        page.locator('[data-type="polar"]').click()
        routed_source = page.locator("#preview").get_attribute("src")
        if routed_source != "example-polar.html":
            failures.append(
                "gallery-mobile-routing: Polar routed to "
                f"{routed_source!r}, expected 'example-polar.html'"
            )
        facts = page.evaluate(
            """
            () => {
              const doc = document.documentElement;
              const preview = document.querySelector('#preview');
              const rect = preview.getBoundingClientRect();
              return {
                previewHeight: rect.height,
                pageOverflow: doc.scrollWidth - doc.clientWidth,
              };
            }
            """
        )
        if facts["previewHeight"] < 400:
            failures.append(
                "gallery-mobile-preview: iframe height "
                f"{facts['previewHeight']:.1f}px is below the 400px minimum"
            )
        if facts["pageOverflow"] > TOLERANCE:
            failures.append(
                "gallery-mobile-overflow: page extends "
                f"{facts['pageOverflow']:.1f}px past the mobile viewport"
            )
    finally:
        page.close()
    return failures


def gallery_navigation_failures(context):
    """Exercise shipped gallery interactions over HTTP and opaque local-file origins."""
    from playwright.sync_api import expect

    failures = []
    for mode in ("http", "file"):
        for viewport in ({"width": 1600, "height": 1000}, {"width": 390, "height": 844}):
            page = context.new_page()
            page.set_viewport_size(viewport)
            phase = "initial-state"
            label = f"gallery-navigation-{mode}-{viewport['width']}"
            runtime_errors = []
            page.on("pageerror", lambda error: runtime_errors.append(str(error)))
            try:
                if mode == "http":
                    # Fulfill only committed HTML assets in memory. No listener or
                    # network exception is needed under the linter's isolation policy.
                    def serve_gallery(route):
                        name = urlparse(route.request.url).path.removeprefix("/")
                        asset = ASSET_DIR / name
                        if "/" in name or not name.endswith(".html") or not asset.is_file():
                            route.abort()
                            return
                        route.fulfill(content_type="text/html", body=asset.read_bytes())

                    page.route("http://gallery.test/*", serve_gallery)
                    url = "http://gallery.test/index.html"
                else:
                    url = (ASSET_DIR / "index.html").as_uri()
                page.goto(url, wait_until="load")
                nav = page.locator("#diagram-nav")
                toggle = page.locator("#nav-toggle")
                search = page.locator("#diagram-search")
                preview = page.locator("#preview")
                expect(nav).to_be_visible()
                expect(toggle).to_have_attribute("aria-expanded", "true")
                expanded_height = preview.bounding_box()["height"]
                # Confirm file:// actually exercises the inaccessible-document fallback.
                accessible = page.evaluate("document.querySelector('#preview').contentDocument !== null")
                assert accessible == (mode == "http"), "unexpected iframe origin accessibility"

                phase = "preview-collapse-and-reopen"
                for attempt in range(3):
                    page.frame_locator("#preview").locator("body").click(position={"x": 24, "y": 24})
                    expect(nav).to_be_hidden()
                    expect(toggle).to_have_attribute("aria-expanded", "false")
                    assert preview.bounding_box()["height"] > expanded_height, "collapse did not enlarge preview"
                    expect(page.locator("#current-diagram")).to_be_visible()
                    expect(page.locator("#variant-tabs")).to_be_visible()
                    if mode == "http" and attempt == 0:
                        # Retain iframe focus on reopen: the next click must be
                        # handled by its pointer listener, not another window blur.
                        toggle.evaluate("button => button.click()")
                        assert page.evaluate("document.activeElement === document.querySelector('#preview')")
                    else:
                        toggle.click()
                    expect(nav).to_be_visible()
                    expect(toggle).to_have_attribute("aria-expanded", "true")

                phase = "filtered-keyboard-navigation"
                search.fill("scatter")
                visible = page.locator("#type-tabs .tab:visible")
                names = visible.evaluate_all("tabs => tabs.map(tab => tab.dataset.type)")
                assert len(names) >= 3, "scatter filter did not expose related variants"
                expect(page.locator('#type-tabs .tab.active')).to_be_hidden()
                search.press("Tab")
                expect(visible.first).to_be_focused()
                for key, expected in (("ArrowRight", names[1]), ("ArrowLeft", names[0]),
                                      ("ArrowLeft", names[-1]), ("ArrowRight", names[0])):
                    page.keyboard.press(key)
                    selected = page.locator(f'#type-tabs [data-type="{expected}"]')
                    expect(selected).to_be_focused()
                    expect(selected).to_have_attribute("aria-checked", "true")
                    expect(preview).to_have_attribute("src", f"example-{expected}.html")

                phase = "empty-search-and-recovery"
                search.fill("no-matching-diagram-xyz")
                expect(visible).to_have_count(0)
                expect(page.locator("#empty-results")).to_be_visible()
                search.fill("polar")
                expect(page.locator("#empty-results")).to_be_hidden()
                expect(visible).to_have_count(1)
                with page.expect_event(
                    "framenavigated",
                    predicate=lambda frame: frame.parent_frame == page.main_frame
                    and frame.url.endswith("/example-polar.html"),
                ):
                    visible.first.click()
                expect(preview).to_have_attribute("src", "example-polar.html")
                search.fill("")
                expect(visible).to_have_count(page.locator("#type-tabs .tab").count())
                expect(page.locator('#type-tabs [data-type="polar"]')).to_have_attribute("aria-checked", "true")

                phase = "collapse-after-example-change"
                page.frame_locator("#preview").locator("body").click(position={"x": 24, "y": 24})
                expect(nav).to_be_hidden()
                toggle.click()
                search.focus()
                search.press("Escape")
                expect(nav).to_be_hidden()
                expect(toggle).to_be_focused()

                phase = "first-click-inside-preview"
                # Collapsing must not move the preview between press and release,
                # or the first click on a control inside the example is lost.
                # A tall window keeps the playback controls on screen without scrolling.
                page.set_viewport_size({"width": viewport["width"], "height": 1400})
                toggle.click()
                search.fill("fan-in")
                expect(visible).to_have_count(1)
                visible.first.click()
                expect(preview).to_have_attribute("src", "example-queue-animated.html")
                play = page.frame_locator("#preview").locator('[data-motion-action="play"]')
                expect(play).to_have_attribute("aria-pressed", "false")
                expect(play).to_be_in_viewport()
                expect(nav).to_be_visible()
                box = play.bounding_box()
                page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
                page.mouse.down()
                page.wait_for_timeout(120)
                page.mouse.up()
                expect(play).to_have_attribute("aria-pressed", "true")
                expect(nav).to_be_hidden()
                assert not runtime_errors, "; ".join(runtime_errors)
            except Exception as error:
                failures.append(f"{label}-{phase}: {str(error).splitlines()[0]}")
            finally:
                page.close()
    return failures


def waterfall_mobile_failures(context, waterfall_paths=None):
    """Keep waterfall labels readable while containing its wide plot locally."""
    paths = waterfall_paths or sorted(ASSET_DIR.glob("example-waterfall*.html"))
    failures = []
    for path in paths:
        page = context.new_page()
        page.set_viewport_size({"width": 390, "height": 844})
        try:
            page.goto(path.as_uri(), wait_until="load")
            facts = page.evaluate(
                """
                () => {
                  const doc = document.documentElement;
                  const svg = document.querySelector('svg');
                  if (!svg) return { missingSvg: true };
                  let ancestor = svg.parentElement;
                  let localScroller = false;
                  while (ancestor && ancestor !== document.body) {
                    const overflow = getComputedStyle(ancestor).overflowX;
                    if ((overflow === 'auto' || overflow === 'scroll') &&
                        ancestor.scrollWidth > ancestor.clientWidth + 1) {
                      localScroller = true;
                      break;
                    }
                    ancestor = ancestor.parentElement;
                  }
                  return {
                    missingSvg: false,
                    pageOverflow: doc.scrollWidth - doc.clientWidth,
                    svgWidth: svg.getBoundingClientRect().width,
                    localScroller,
                  };
                }
                """
            )
        finally:
            page.close()

        shown_path = display_path(path)
        if facts["missingSvg"]:
            failures.append(f"{shown_path}: waterfall-mobile-svg: no SVG found")
            continue
        if facts["pageOverflow"] > TOLERANCE:
            failures.append(
                f"{shown_path}: waterfall-mobile-page-overflow: page extends "
                f"{facts['pageOverflow']:.1f}px past the 390px viewport"
            )
        if facts["svgWidth"] < 720:
            failures.append(
                f"{shown_path}: waterfall-mobile-legibility: SVG shrinks to "
                f"{facts['svgWidth']:.1f}px; preserve at least 720px for its 8px labels"
            )
        if not facts["localScroller"]:
            failures.append(
                f"{shown_path}: waterfall-mobile-containment: wide SVG needs a local horizontal scroller"
            )
    return failures


def excalidraw_mobile_failures(context, example_path=None):
    """Keep the Excalidraw worked example readable without widening the page."""
    path = example_path or ASSET_DIR / "example-import-excalidraw.html"
    page = context.new_page()
    page.set_viewport_size({"width": 390, "height": 844})
    try:
        page.goto(path.as_uri(), wait_until="load")
        facts = page.evaluate(
            """
            () => {
              const doc = document.documentElement;
              const svg = document.querySelector('svg');
              if (!svg) return { missingSvg: true };
              const scroller = svg.parentElement;
              const overflow = scroller && getComputedStyle(scroller).overflowX;
              return {
                missingSvg: false,
                pageOverflow: doc.scrollWidth - doc.clientWidth,
                svgWidth: svg.getBoundingClientRect().width,
                localScroller: Boolean(scroller &&
                  (overflow === 'auto' || overflow === 'scroll') &&
                  scroller.scrollWidth > scroller.clientWidth + 1),
              };
            }
            """
        )
    finally:
        page.close()

    shown_path = display_path(path)
    failures = []
    if facts["missingSvg"]:
        return [f"{shown_path}: excalidraw-mobile-svg: no SVG found"]
    if facts["pageOverflow"] > TOLERANCE:
        failures.append(
            f"{shown_path}: excalidraw-mobile-page-overflow: page extends "
            f"{facts['pageOverflow']:.1f}px past the 390px viewport"
        )
    if facts["svgWidth"] < 900:
        failures.append(
            f"{shown_path}: excalidraw-mobile-legibility: SVG shrinks to "
            f"{facts['svgWidth']:.1f}px; preserve its 900px labeled canvas"
        )
    if not facts["localScroller"]:
        failures.append(
            f"{shown_path}: excalidraw-mobile-containment: wide SVG needs a local horizontal scroller"
        )
    return failures


def marimekko_mobile_failures(context, marimekko_paths=None):
    """Keep every marimekko at its readable 760px canvas, scrolled locally.

    Segment labels are 9-11px on a 1000-unit viewBox, so letting the SVG shrink
    to a phone width makes them unreadable, and letting its min-width widen the
    document scrolls the whole page sideways. The wide SVG must sit inside an
    ancestor that scrolls horizontally on its own.
    """
    paths = marimekko_paths or sorted(ASSET_DIR.glob("example-marimekko*.html"))
    failures = []
    for path in paths:
        page = context.new_page()
        page.set_viewport_size({"width": 390, "height": 844})
        try:
            page.goto(path.as_uri(), wait_until="load")
            facts = page.evaluate(
                """
                () => {
                  const doc = document.documentElement;
                  const svg = document.querySelector('svg');
                  if (!svg) return { missingSvg: true };
                  let ancestor = svg.parentElement;
                  let localScroller = false;
                  while (ancestor && ancestor !== document.body) {
                    const overflow = getComputedStyle(ancestor).overflowX;
                    if ((overflow === 'auto' || overflow === 'scroll') &&
                        ancestor.scrollWidth > ancestor.clientWidth + 1) {
                      localScroller = true;
                      break;
                    }
                    ancestor = ancestor.parentElement;
                  }
                  return {
                    missingSvg: false,
                    pageOverflow: doc.scrollWidth - doc.clientWidth,
                    svgWidth: svg.getBoundingClientRect().width,
                    localScroller,
                  };
                }
                """
            )
        finally:
            page.close()

        shown_path = display_path(path)
        if facts["missingSvg"]:
            failures.append(f"{shown_path}: marimekko-mobile-svg: no SVG found")
            continue
        if facts["pageOverflow"] > TOLERANCE:
            failures.append(
                f"{shown_path}: marimekko-mobile-page-overflow: page extends "
                f"{facts['pageOverflow']:.1f}px past the 390px viewport"
            )
        if facts["svgWidth"] < 760 - TOLERANCE:
            failures.append(
                f"{shown_path}: marimekko-mobile-legibility: SVG shrinks to "
                f"{facts['svgWidth']:.1f}px; preserve its 760px canvas for the segment labels"
            )
        if not facts["localScroller"]:
            failures.append(
                f"{shown_path}: marimekko-mobile-containment: wide SVG needs a local horizontal scroller"
            )
    return failures


def template_mobile_failures(context, template_paths=None):
    """Every template must survive a phone, because every diagram starts as one.

    Two defects, both invisible on a desktop:

    * An SVG whose ``min-width`` exceeds the viewport with no local scroller
      drags the whole document sideways, and the nodes on the right are simply
      gone unless the reader thinks to scroll the page.
    * When an ancestor is ``overflow: hidden`` (the terminal template's window
      chrome), the same SVG is clipped instead: no scrollbar, no page overflow,
      nothing for a page-overflow check to see. The content is unreachable and
      the linter reports the file clean.

    ``min-width`` must also equal the viewBox width. Anything smaller scales the
    whole drawing down and silently takes the type ramp with it - a 12px node
    name on a 1280 viewBox pinned at 900 draws at 8.4px, under every floor the
    style guide sets.
    """
    paths = template_paths or sorted(ASSET_DIR.glob("template*.html"))
    failures = []
    for path in paths:
        page = context.new_page()
        page.set_viewport_size({"width": 390, "height": 844})
        try:
            page.goto(path.as_uri(), wait_until="load")
            facts = page.evaluate(
                """
                () => {
                  const doc = document.documentElement;
                  const svg = document.querySelector('svg');
                  if (!svg) return { missingSvg: true };
                  let ancestor = svg.parentElement;
                  let localScroller = false, clipped = false;
                  while (ancestor && ancestor !== document.body) {
                    const overflow = getComputedStyle(ancestor).overflowX;
                    const overflows = ancestor.scrollWidth > ancestor.clientWidth + 1;
                    if ((overflow === 'auto' || overflow === 'scroll') && overflows) {
                      localScroller = true;
                      break;
                    }
                    if (overflow === 'hidden' && overflows) clipped = true;
                    ancestor = ancestor.parentElement;
                  }
                  const viewBox = (svg.getAttribute('viewBox') || '').trim().split(/[ ,]+/);
                  return {
                    missingSvg: false,
                    pageOverflow: doc.scrollWidth - doc.clientWidth,
                    svgWidth: svg.getBoundingClientRect().width,
                    minWidth: parseFloat(getComputedStyle(svg).minWidth) || 0,
                    viewBoxWidth: viewBox.length === 4 ? parseFloat(viewBox[2]) : 0,
                    localScroller,
                    clipped,
                  };
                }
                """
            )
        finally:
            page.close()

        shown_path = display_path(path)
        if facts["missingSvg"]:
            failures.append(f"{shown_path}: template-mobile-svg: no SVG found")
            continue
        if facts["pageOverflow"] > TOLERANCE:
            failures.append(
                f"{shown_path}: template-mobile-page-overflow: page extends "
                f"{facts['pageOverflow']:.1f}px past the 390px viewport"
            )
        if facts["clipped"] and not facts["localScroller"]:
            failures.append(
                f"{shown_path}: template-mobile-clipped: an overflow:hidden ancestor cuts the "
                f"{facts['svgWidth']:.0f}px SVG off with no scroller - the content is unreachable"
            )
        if facts["minWidth"] > TOLERANCE and not facts["localScroller"]:
            failures.append(
                f"{shown_path}: template-mobile-containment: wide SVG needs a local horizontal scroller"
            )
        if facts["minWidth"] <= TOLERANCE and facts["viewBoxWidth"] > TOLERANCE:
            # An absent min-width is not a pass: the SVG then shrinks into the
            # phone and the type ramp shrinks with it, which is the same defect
            # the type-ramp check below reports - it just reads as 0 instead of
            # a wrong number, and would otherwise skip both checks silently.
            drawn = facts["svgWidth"]
            failures.append(
                f"{shown_path}: template-mobile-type-ramp: no min-width, so the SVG shrinks to "
                f"{drawn:.0f}px against a {facts['viewBoxWidth']:.0f} viewBox and a 12px node name "
                f"lands at {12 * drawn / facts['viewBoxWidth']:.1f}px; pin min-width to the viewBox width"
            )
        if (
            facts["minWidth"] > TOLERANCE
            and facts["viewBoxWidth"] > TOLERANCE
            and abs(facts["minWidth"] - facts["viewBoxWidth"]) > TOLERANCE
        ):
            ratio = facts["minWidth"] / facts["viewBoxWidth"]
            failures.append(
                f"{shown_path}: template-mobile-type-ramp: min-width {facts['minWidth']:.0f}px "
                f"!= viewBox width {facts['viewBoxWidth']:.0f}px, so everything draws at "
                f"{ratio:.3f} scale and a 12px node name lands at {12 * ratio:.1f}px"
            )
    return failures


OUTPUT_SPEC_DOC = ROOT / "skills/diagram-design/references/output-spec.md"


def output_spec_widest_preset():
    """The widest fixed viewBox in the output-spec.md size table, or None."""
    text = OUTPUT_SPEC_DOC.read_text(encoding="utf-8")
    sizes = re.findall(r"^\| `[a-z0-9-]+` \| `0 0 (\d+) (\d+)`", text, re.M)
    return max((int(w), int(h)) for w, h in sizes) if sizes else None


# The export check re-draws each template at the widest fixed preset in
# output-spec.md (print-a3-landscape, 1584 wide, at the time of writing). With
# min-width pinned to the viewBox width, every preset from 1280 up is wider than
# the templates' 1200px frame; the widest is the hardest to capture whole. The
# self-test fails if this falls back or drifts from the table.
WIDE_PRESET = output_spec_widest_preset() or (1280, 720)
# A node in the rightmost 100 units of the wide preset; the PNG must paint it.
EXPORT_PROBE = {"x": WIDE_PRESET[0] - 100, "y": WIDE_PRESET[1] // 2 - 32, "width": 80, "height": 60}
EXPORT_PROBE_MARKUP = (
    '<rect id="export-probe" x="{x}" y="{y}" width="{width}" height="{height}" '
    'fill="#ff00ff"/>'.format(**EXPORT_PROBE)
)
EXPORT_TIMEOUT = 120  # seconds for one run of the recipe, browser launch included

PNG_PROBE_JS = """
async ([src, probe, viewBoxWidth]) => {
  const img = new Image();
  img.src = src;
  await img.decode();
  const canvas = document.createElement('canvas');
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);
  const k = img.naturalWidth / viewBoxWidth;
  const y = probe.y + probe.height / 2;
  const xs = [probe.x + 4, probe.x + probe.width / 2, probe.x + probe.width - 4];
  const pixels = xs.map((x) => Array.from(ctx.getImageData(Math.floor(x * k), Math.floor(y * k), 1, 1).data));
  return { width: img.naturalWidth, height: img.naturalHeight, pixels };
}
"""


def wide_preset_fixture(html):
    """Re-draw a template at the widest preset the way output-spec.md says:
    viewBox and min-width both at the preset width, plus a probe node at the
    right edge.
    Remote <link>s are dropped so the recipe runs without a network."""
    match = re.search(r'<svg\b[^>]*\bviewBox="0 0 (\d+) (\d+)"', html)
    if match is None:
        return None
    width = match.group(1)
    html = html[: match.start(1)] + f"{WIDE_PRESET[0]} {WIDE_PRESET[1]}" + html[match.end(2) :]
    html, pinned = re.subn(rf"min-width:\s*{width}px", f"min-width: {WIDE_PRESET[0]}px", html)
    if pinned != 1 or "</svg>" not in html:
        return None
    html = html.replace("</svg>", EXPORT_PROBE_MARKUP + "</svg>", 1)
    return re.sub(r"<link\b[^>]*\bhref=\"https?://[^>]*>", "", html)


def export_png_failures(context, label, html):
    """Run the packaged PNG renderer on ``html`` exactly as the doc says and
    report a PNG that is not the full viewBox width or does not paint the probe."""
    with tempfile.TemporaryDirectory() as directory:
        directory_path = Path(directory)
        source = directory_path / "wide-preset.html"
        out = directory_path / "wide-preset.png"
        source.write_text(html, encoding="utf-8")
        try:
            run = subprocess.run(
                [sys.executable, str(EXPORT_PNG), str(source), str(out), "1"],
                capture_output=True, text=True, timeout=EXPORT_TIMEOUT,
            )
        except subprocess.TimeoutExpired:
            return [f"{label}: template-export: the packaged renderer did not finish in {EXPORT_TIMEOUT}s"]
        if run.returncode != 0 or not out.is_file():
            tail = (run.stderr.strip().splitlines() or ["no output"])[-1]
            return [f"{label}: template-export: the packaged renderer failed: {tail}"]
        png = out.read_bytes()
    page = context.new_page()
    try:
        facts = page.evaluate(PNG_PROBE_JS, [data_url(png), EXPORT_PROBE, WIDE_PRESET[0]])
    finally:
        page.close()
    failures = []
    if facts["width"] != WIDE_PRESET[0]:
        failures.append(
            f"{label}: template-export: PNG is {facts['width']}px wide at scale 1, "
            f"expected the viewBox width {WIDE_PRESET[0]}px"
        )
    painted = [r > 200 and g < 60 and b > 200 and a > 200 for r, g, b, a in facts["pixels"]]
    if not all(painted):
        failures.append(
            f"{label}: template-export: the node at x={EXPORT_PROBE['x']}-"
            f"{EXPORT_PROBE['x'] + EXPORT_PROBE['width']} of a {WIDE_PRESET[0]}-wide preset is "
            f"missing from the PNG (sampled {facts['pixels']}); an ancestor clipped the SVG "
            f"during capture"
        )
    return failures


def template_export_failures(context, template_paths=None):
    """A template re-drawn at doc-wide or slide-16x9 must export to a whole PNG.

    min-width equal to the viewBox width makes a 1280 SVG wider than the 1200px
    frame, so the local scroller (and the terminal's overflow:hidden chrome)
    clips it on screen. The packaged renderer screenshots the SVG's box, and
    whatever an ancestor clipped is simply not in the PNG: full size, blank on
    the right, no error. This runs the packaged helper named by export.md.
    """
    if not EXPORT_PNG.is_file():
        return [f"{display_path(EXPORT_PNG)}: template-export: packaged renderer is missing"]
    paths = template_paths or sorted(ASSET_DIR.glob("template*.html"))
    failures = []
    for path in paths:
        shown_path = display_path(path)
        fixture = wide_preset_fixture(path.read_text(encoding="utf-8"))
        if fixture is None:
            failures.append(
                f"{shown_path}: template-export: could not re-draw at the {WIDE_PRESET[0]} preset "
                "(needs one viewBox=\"0 0 W H\" and one `min-width: Wpx`)"
            )
            continue
        failures += export_png_failures(context, shown_path, fixture)
    return failures


def self_test(context):
    page = context.new_page()
    failures = []
    checks = 0

    def flagged(html):
        page.set_content(html)
        return any(category == "clipped" for category, _ in measure(page))

    for name, markup, svg_style, wrapper, expected in SVG_CASES:
        checks += 1
        if flagged(fixture_html(markup, svg_style, wrapper)) != expected:
            failures.append(f"{name}: flagged={not expected}, expected={expected}")

    # Paired above/below-fold: identical spill, so a scrolled measurement that
    # mixed document and viewport coordinates would disagree with its twin.
    for label, filler in (("above-fold", ""), ("below-fold", BELOW_FOLD_FILLER)):
        checks += 1
        if not flagged(fixture_html(SVG_CASES[0][1], filler=filler)):
            failures.append(f"{label}-spill: not caught")
    checks += 1
    if flagged(fixture_html(SVG_CASES[7][1], filler=BELOW_FOLD_FILLER)):
        failures.append("below-fold-clean: false clipped finding")

    # The DOM must come back exactly as authored, including inline transforms.
    checks += 1
    page.set_content(fixture_html(SVG_CASES[0][1], svg_style="transform:rotate(2deg)"))
    before = page.evaluate(DOM_STATE_JS)
    measure(page)
    if page.evaluate(DOM_STATE_JS) != before:
        failures.append("dom-restore: markup changed after measuring")

    # A *scrolling* ancestor must be reported unmeasurable, not clean.
    checks += 1
    page.set_content(
        fixture_html(SVG_CASES[0][1], wrapper='<div style="overflow:auto;width:120px">')
    )
    if not any(category == "unmeasurable" for category, _ in measure(page)):
        failures.append("scrolling-ancestor: no unmeasurable finding")

    # Collapsed svg, and a page that scrolls sideways.
    checks += 2
    page.set_content(
        '<!DOCTYPE html><html><body style="margin:0"><div style="width:3000px">wide</div>'
        '<svg width="0" height="0" viewBox="0 0 200 100"><rect width="10" height="10"/></svg></body></html>'
    )
    categories = {category for category, _ in measure(page)}
    for expected_category in ("svg-collapsed", "page-overflow"):
        if expected_category not in categories:
            failures.append(f"{expected_category}: check did not fire")
    page.close()

    # A missing local asset must surface, not be swallowed with the remote noise.
    checks += 1
    asset_page = context.new_page()
    asset_findings = []
    watch(asset_page, asset_findings)
    with tempfile.TemporaryDirectory() as directory:
        fixture = Path(directory) / "missing-asset.html"
        fixture.write_text('<img src="does-not-exist-12345.png">', encoding="utf-8")
        asset_page.goto(fixture.as_uri(), wait_until="load")
        asset_page.wait_for_timeout(300)
    asset_page.close()
    if not any(category == "missing-asset" for category, _ in asset_findings):
        failures.append("missing-asset: check did not fire")

    checks += 1
    failures += network_isolation_failures(context)

    # Exercise the real reveal controller through the public file entry point.
    # Its timers must stay stopped throughout the paired clipping screenshots.
    for asset in ("example-exploded-phone-animated.html", "example-axonometric-plan-coffee-shop-animated.html"):
        checks += 1
        motion_page = context.new_page()
        try:
            findings = check(motion_page, ASSET_DIR / asset)
            state = motion_page.locator("[data-motion-root]").first.evaluate(
                "el => [el.dataset.frame, el.dataset.motionState, el.dataset.stepCurrent === el.dataset.stepCount]"
            )
            if findings or state != ["static", "static", True]:
                failures.append(f"{asset}: static capture failed: {state}, {findings}")
        finally:
            motion_page.close()

    checks += 1
    with tempfile.TemporaryDirectory() as directory:
        clipped_path = Path(directory) / "static-clipped.html"
        clipped_path.write_text(fixture_html(SVG_CASES[0][1]), encoding="utf-8")
        clipped_page = context.new_page()
        try:
            if not any(category == "clipped" for category, _ in check(clipped_page, clipped_path)):
                failures.append("static file entry point stopped detecting actual clipping")
        finally:
            clipped_page.close()

    checks += 1
    failures += gallery_mobile_failures(context)

    # Same-origin iframe clicks and file:// focus fallback, desktop and mobile.
    checks += 4
    failures += gallery_navigation_failures(context)

    # The waterfall uses 8px SVG labels, so shrinking its 1000-unit canvas to
    # a phone width is not a responsive layout. Keep it readable and scroll it
    # inside a local container without widening the document.
    checks += 2
    with tempfile.TemporaryDirectory() as directory:
        directory_path = Path(directory)
        broken = directory_path / "example-waterfall-broken.html"
        broken.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}svg{width:100%;min-width:760px;display:block}</style>'
            '<body><svg viewBox="0 0 1000 500"></svg></body></html>',
            encoding="utf-8",
        )
        if not waterfall_mobile_failures(context, [broken]):
            failures.append("waterfall-mobile-broken-fixture: page overflow was not reported")

        contained = directory_path / "example-waterfall-contained.html"
        contained.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}.wrap{width:100%;overflow-x:auto}'
            'svg{width:100%;min-width:760px;display:block}</style><body><div class="wrap">'
            '<svg viewBox="0 0 1000 500"></svg></div></body></html>',
            encoding="utf-8",
        )
        contained_failures = waterfall_mobile_failures(context, [contained])
        if contained_failures:
            failures.append(
                "waterfall-mobile-contained-fixture: false finding: "
                + "; ".join(contained_failures)
            )

    checks += 2
    with tempfile.TemporaryDirectory() as directory:
        directory_path = Path(directory)
        broken = directory_path / "example-import-excalidraw.html"
        broken.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}svg{width:100%;min-width:900px;display:block}</style>'
            '<body><svg viewBox="0 0 960 600"></svg></body></html>',
            encoding="utf-8",
        )
        if not excalidraw_mobile_failures(context, broken):
            failures.append("excalidraw-mobile-broken-fixture: page overflow was not reported")

        contained = directory_path / "example-import-excalidraw-contained.html"
        contained.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}.wrap{width:100%;overflow-x:auto}'
            'svg{width:100%;min-width:900px;display:block}</style><body><div class="wrap">'
            '<svg viewBox="0 0 960 600"></svg></div></body></html>',
            encoding="utf-8",
        )
        contained_failures = excalidraw_mobile_failures(context, contained)
        if contained_failures:
            failures.append(
                "excalidraw-mobile-contained-fixture: false finding: "
                + "; ".join(contained_failures)
            )

    # Marimekko: the same containment contract, pinned in both polarities -
    # an uncontained min-width widens the page, a local scroller does not.
    checks += 2
    with tempfile.TemporaryDirectory() as directory:
        directory_path = Path(directory)
        broken = directory_path / "example-marimekko-broken.html"
        broken.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}svg{width:100%;min-width:760px;display:block}</style>'
            '<body><div class="frame"><svg viewBox="0 0 1000 500"></svg></div></body></html>',
            encoding="utf-8",
        )
        broken_failures = marimekko_mobile_failures(context, [broken])
        if not any("marimekko-mobile-page-overflow" in f for f in broken_failures):
            failures.append("marimekko-mobile-broken-fixture: page overflow was not reported")
        if not any("marimekko-mobile-containment" in f for f in broken_failures):
            failures.append("marimekko-mobile-broken-fixture: missing local scroller was not reported")

        contained = directory_path / "example-marimekko-contained.html"
        contained.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}.diagram-container{width:100%;overflow-x:auto}'
            'svg{width:100%;min-width:760px;display:block}</style><body><div class="frame">'
            '<div class="diagram-container"><svg viewBox="0 0 1000 500"></svg></div></div></body></html>',
            encoding="utf-8",
        )
        contained_failures = marimekko_mobile_failures(context, [contained])
        if contained_failures:
            failures.append(
                "marimekko-mobile-contained-fixture: false finding: "
                + "; ".join(contained_failures)
            )

    # Templates: three polarities, because the clipped case is the one a
    # page-overflow check cannot see - it reports clean precisely because the
    # content was destroyed instead of overflowing.
    checks += 5
    with tempfile.TemporaryDirectory() as directory:
        directory_path = Path(directory)

        overflowing = directory_path / "template-overflow.html"
        overflowing.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}'
            'svg{width:100%;min-width:1000px;display:block}</style>'
            '<body><div class="frame"><svg viewBox="0 0 1000 600"></svg></div></body></html>',
            encoding="utf-8",
        )
        overflow_failures = template_mobile_failures(context, [overflowing])
        if not any("template-mobile-page-overflow" in f for f in overflow_failures):
            failures.append("template-overflow-fixture: page overflow was not reported")
        if not any("template-mobile-containment" in f for f in overflow_failures):
            failures.append("template-overflow-fixture: missing local scroller was not reported")

        clipped = directory_path / "template-clipped.html"
        clipped.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}.chrome{overflow:hidden}'
            'svg{width:100%;min-width:1000px;display:block}</style>'
            '<body><div class="chrome"><svg viewBox="0 0 1000 600"></svg></div></body></html>',
            encoding="utf-8",
        )
        clipped_failures = template_mobile_failures(context, [clipped])
        if not any("template-mobile-clipped" in f for f in clipped_failures):
            failures.append("template-clipped-fixture: unreachable clipped SVG was not reported")

        contained = directory_path / "template-contained.html"
        contained.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}.diagram-container{width:100%;overflow-x:auto}'
            'svg{width:100%;min-width:1000px;display:block}</style><body><div class="frame">'
            '<div class="diagram-container"><svg viewBox="0 0 1000 600"></svg></div>'
            '</div></body></html>',
            encoding="utf-8",
        )
        contained_failures = template_mobile_failures(context, [contained])
        if contained_failures:
            failures.append(
                "template-contained-fixture: false finding: " + "; ".join(contained_failures)
            )

        ramp = directory_path / "template-ramp.html"
        ramp.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}.diagram-container{width:100%;overflow-x:auto}'
            'svg{width:100%;min-width:900px;display:block}</style><body><div class="frame">'
            '<div class="diagram-container"><svg viewBox="0 0 1280 720"></svg></div>'
            '</div></body></html>',
            encoding="utf-8",
        )
        if not any("template-mobile-type-ramp" in f for f in template_mobile_failures(context, [ramp])):
            failures.append("template-ramp-fixture: min-width below the viewBox width was not reported")

        absent = directory_path / "template-no-min-width.html"
        absent.write_text(
            '<!DOCTYPE html><html><style>body{margin:0}.diagram-container{width:100%;overflow-x:auto}'
            'svg{width:100%;display:block}</style><body><div class="frame">'
            '<div class="diagram-container"><svg viewBox="0 0 1280 720"></svg></div>'
            '</div></body></html>',
            encoding="utf-8",
        )
        if not any("template-mobile-type-ramp" in f for f in template_mobile_failures(context, [absent])):
            failures.append("template-no-min-width-fixture: absent min-width was treated as a pass")

    # The export check must cover the widest preset output-spec.md offers, or
    # clipping that only a wider preset hits goes untested.
    checks += 1
    widest = output_spec_widest_preset()
    if widest is None:
        failures.append("template-export-widest-preset: no viewBox rows in the output-spec.md size table")
    elif WIDE_PRESET != widest:
        failures.append(
            f"template-export-widest-preset: the export check uses {WIDE_PRESET[0]}x{WIDE_PRESET[1]}, "
            f"but the widest output-spec.md preset is {widest[0]}x{widest[1]}"
        )

    # Export of the wide preset, both polarities: an SVG wider than the 1200px
    # frame, held in a local scroller, must come out whole, and a probe node that
    # really is cut off (clip-path, which export does not release) must be reported.
    checks += 2
    if not EXPORT_PNG.is_file():
        failures.append("template-export: packaged PNG renderer is missing")
    else:
        wide_page = (
            '<!DOCTYPE html><html><style>body{{margin:0;padding:32px;background:#f5f5f5}}'
            '.frame{{max-width:1200px;width:100%}}.diagram-container{{width:100%;overflow-x:auto}}'
            'svg{{width:100%;min-width:' + str(WIDE_PRESET[0]) + 'px;display:block}}</style>'
            '<body><div class="frame"><div class="diagram-container"{clip}>'
            '<svg viewBox="0 0 ' + f"{WIDE_PRESET[0]} {WIDE_PRESET[1]}" + '" '
            'xmlns="http://www.w3.org/2000/svg"><rect width="' + str(WIDE_PRESET[0])
            + '" height="' + str(WIDE_PRESET[1]) + '" fill="#f5f5f5"/>'
            + EXPORT_PROBE_MARKUP
            + "</svg></div></div></body></html>"
        )
        scroller_failures = export_png_failures(
            context, "template-export-scroller-fixture", wide_page.format(clip="")
        )
        if scroller_failures:
            failures.append(
                f"template-export-scroller-fixture: the renderer clipped a {WIDE_PRESET[0]}-wide SVG held in a "
                "local scroller: " + "; ".join(scroller_failures)
            )
        clipped_failures = export_png_failures(
            context,
            "template-export-clipped-fixture",
            wide_page.format(clip=' style="clip-path:inset(0 160px 0 0)"'),
        )
        if not any("is missing from the PNG" in f for f in clipped_failures):
            failures.append("template-export-clipped-fixture: a cut-off probe node was not reported")

    # A broken route should be a targeted failure, not a delayed Playwright
    # timeout or traceback that escapes the self-test report.
    checks += 1
    with tempfile.TemporaryDirectory() as directory:
        broken_gallery = Path(directory) / "index.html"
        gallery_source = (ASSET_DIR / "index.html").read_text(encoding="utf-8")
        route_line = "const src = `example-${state.type}${state.variant}.html`;"
        if gallery_source.count(route_line) != 1:
            failures.append("gallery-mobile-routing-fixture: route source changed unexpectedly")
        else:
            broken_gallery.write_text(
                gallery_source.replace(route_line, 'const src = "wrong-example.html";'),
                encoding="utf-8",
            )
            route_failures = gallery_mobile_failures(context, broken_gallery)
            if not any(
                failure.startswith("gallery-mobile-routing:") for failure in route_failures
            ):
                failures.append("gallery-mobile-routing: broken route was not reported")

    if failures:
        print("self-test FAILED:")
        for failure in failures:
            print(f"  {failure}")
        return 1
    print(f"self-test OK: {checks} cases, no false flags.")
    return 0


def main():
    args = parse_args()
    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        print(
            "Playwright is not installed. Install it with:\n"
            "  pip install playwright && playwright install chromium",
            file=sys.stderr,
        )
        return 2

    paths = shipped_assets() if args.all else args.files
    if not paths and not args.self_test:
        print("Nothing to check. Pass files, --all or --self-test.", file=sys.stderr)
        return 2

    total_findings = 0
    total_notes = 0
    with sync_playwright() as playwright:
        try:
            browser = launch(playwright, args.fonts)
        except Exception as error:
            print(
                f"Could not launch a browser: {error}\n"
                "  playwright install chromium\n"
                "  (or set DIAGRAM_LINT_BROWSER_CHANNEL=chrome to use a system Chrome)",
                file=sys.stderr,
            )
            return 2
        # The oracle is pixels, so record which browser produced them.
        print(f"Chromium {browser.version}, network: {resolver_rule(args.fonts)}", file=sys.stderr)
        context = browser.new_context(viewport=VIEWPORT)
        block_network(context, args.fonts)
        if args.self_test:
            status = self_test(context)
            if status or not paths:
                browser.close()
                return status
        for path in paths:
            page = context.new_page()
            try:
                findings = check(page, path)
            except Exception as error:
                findings = [("render-error", str(error).splitlines()[0])]
            finally:
                page.close()

            findings.sort()
            total_findings += sum(1 for category, _ in findings if category not in NOTE_CATEGORIES)
            total_notes += sum(1 for category, _ in findings if category in NOTE_CATEGORIES)
            if not args.quiet:
                shown_path = display_path(path)
                for category, message in findings:
                    print(f"{shown_path}: {category}: {message}")
        if args.all:
            mobile_failures = waterfall_mobile_failures(context)
            mobile_failures += excalidraw_mobile_failures(context)
            mobile_failures += marimekko_mobile_failures(context)
            mobile_failures += template_mobile_failures(context)
            mobile_failures += template_export_failures(context)
            total_findings += len(mobile_failures)
            if not args.quiet:
                for failure in mobile_failures:
                    print(failure)
        browser.close()

    print(
        f"Summary: {len(paths)} file(s) rendered, {total_findings} finding(s), "
        f"{total_notes} note(s) (not checked, not failed)."
    )
    return 1 if total_findings else 0


if __name__ == "__main__":
    sys.exit(main())