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.
fix(screenshots): hash example sources as canonical text in the freshness gate (#253)
ANIRUDDHA ADAK147cbb2874a8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 86a8b07..9d114ba 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -237,6 +237,11 @@ jobs:id: screenshotsrun: python scripts/verify-screenshot-freshness.py+ - name: Verify screenshot freshness checker+ if: always()+ id: screenshots_tests+ run: python scripts/test-verify-screenshot-freshness.py+- name: Install Pillow for README thumbnail verificationif: always() && matrix.os == 'ubuntu-latest' && matrix.python-version == '3.12'env:@@ -467,6 +472,7 @@ jobs:echo "| Doctor Diagnostics Tests | ${{ steps.doctor_tests.outcome == 'success' && '✅ Passed' || (steps.doctor_tests.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| Docs & Routing Sync | ${{ steps.docs_sync.outcome == 'success' && '✅ Passed' || (steps.docs_sync.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| Canonical Screenshot Freshness | ${{ steps.screenshots.outcome == 'success' && '✅ Passed' || (steps.screenshots.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARY+ echo "| Screenshot Freshness Checker | ${{ steps.screenshots_tests.outcome == 'success' && '✅ Passed' || (steps.screenshots_tests.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| README Thumbnail Freshness | ${{ steps.readme_thumbs.outcome == 'success' && '✅ Passed' || (steps.readme_thumbs.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| Packaged Self-Check | ${{ steps.self_check.outcome == 'success' && '✅ Passed' || (steps.self_check.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYecho "| Label Geometry | ${{ steps.geometry.outcome == 'success' && '✅ Passed' || (steps.geometry.outcome == 'skipped' && '⏭️ Skipped' || '❌ Failed') }} |" >> $GITHUB_STEP_SUMMARYdiff --git a/.maintainer-policy.json b/.maintainer-policy.jsonindex eb59afb..f53c78d 100644--- a/.maintainer-policy.json+++ b/.maintainer-policy.json@@ -64,6 +64,7 @@"python3 scripts/verify-docs-sync.py","python3 scripts/test-verify-docs-sync.py","python3 scripts/verify-screenshot-freshness.py",+ "python3 scripts/test-verify-screenshot-freshness.py","python3 scripts/test-build-readme-thumbs.py","python3 scripts/build-readme-thumbs.py --check","python3 scripts/test-self-check.py",diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1e3dc9a..0615e13 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -55,6 +55,7 @@ Every validation gate below must pass before a PR is ready. They also run automa| Every shipped motion template/example | `python3 scripts/verify-motion.py --shipped` || Docs/routing sync (description hooks, gallery, README tree, reference links and style-guide anchors, strict-bundler support paths, command/prompt surfaces, font-link parity, template title fallback order, SKILL.md split routing) | `python3 scripts/verify-docs-sync.py && python3 scripts/test-verify-docs-sync.py` || Canonical README screenshots match their example HTML sources and recorded PNG digests | `python3 scripts/verify-screenshot-freshness.py` |+| Screenshot freshness checker behaves (CRLF checkout, real source drift, raw PNG digests) | `python3 scripts/test-verify-screenshot-freshness.py` || README WebP previews match their PNGs, manifest, dimensions, and full-size links | `python3 scripts/test-build-readme-thumbs.py && python3 scripts/build-readme-thumbs.py --check` (requires `Pillow==12.1.1`) || Packaged output self-check behaves (pass + adversarial cases) | `python3 scripts/test-self-check.py` || Label masks are never clipped by a node painted after them | `python3 scripts/verify-geometry.py --all` |@@ -127,6 +128,7 @@ python3 scripts/test-plugin-package.py \&& python3 scripts/verify-docs-sync.py \&& python3 scripts/test-verify-docs-sync.py \&& python3 scripts/verify-screenshot-freshness.py \+ && python3 scripts/test-verify-screenshot-freshness.py \&& python3 scripts/test-build-readme-thumbs.py \&& python3 scripts/build-readme-thumbs.py --check \&& python3 scripts/test-self-check.py \@@ -165,7 +167,7 @@ python3 scripts/test-plugin-package.py \- **`verify-plugin-package.py`:** if it reports a version change, drop the manifest edits from your branch — versions are bumped on `main` after merge, never in a PR. If packaging validation fails, keep all native marketplaces pointed at the repository root and keep the shared skill at `skills/diagram-design/SKILL.md`.- **`lint-skin.py`:** the failure message names the file, line, and category (`color`, `font-family`, `a11y`, `external-asset`, `pure-black`, `script`). Colors must come from the palette in `skills/diagram-design/references/style-guide.md`; fonts from the allowed list; diagrams must satisfy the accessible SVG contract (see below). The linter also requires the SHA-pinned controller from `template-motion.html` verbatim and rejects remote resources, CSS `@import`, non-fragment CSS `url()`, event handlers, `srcdoc`, executable URLs, and extra scripts.- **`verify-*.py`:** the extractor's real behavior no longer matches its fixture or the documentation, or the reference/command/prompt wiring drifted. Fix the source of truth — do not widen a test to avoid a failure.-- **`verify-screenshot-freshness.py`:** a canonical minimal-light example or its committed PNG changed without a synchronized catalog refresh. Before the first regeneration, install the renderer with `python3 -m pip install playwright && python3 -m playwright install chromium`. Then run `python3 scripts/render-canonical-screenshots.py`, inspect all 40 renders, and commit the updated PNGs plus `docs/screenshots/manifest.json`.+- **`verify-screenshot-freshness.py`:** a canonical minimal-light example or its committed PNG changed without a synchronized catalog refresh. Before the first regeneration, install the renderer with `python3 -m pip install playwright && python3 -m playwright install chromium`. Then run `python3 scripts/render-canonical-screenshots.py`, inspect all 40 renders, and commit the updated PNGs plus `docs/screenshots/manifest.json`. The gate hashes example sources in their canonical LF form, so a checkout that converts LF to CRLF still passes; `scripts/test-verify-screenshot-freshness.py` covers that case, real source drift, and raw PNG digests.- **`build-readme-thumbs.py --check`:** a README preview is missing, stale, corrupt, the wrong size, orphaned, or no longer links to its full PNG. Install the pinned renderer with `python3 -m pip install Pillow==12.1.1`, run `python3 scripts/build-readme-thumbs.py`, inspect the preview changes, and commit the WebPs plus `docs/screenshots/thumbs/manifest.json`.- **`verify-marimekko.py`:** a column is drawn off its category's share of the width, a segment off its series' share of the column, the columns do not share one plot height or one gutter, segments leave a gap or overlap, a series changes order between columns, a second segment wears the accent, anything positions a segment or a bound label from a `transform` attribute, an inline `style`, or a `<style>` rule, or a label, caption or key disagrees with the rect it binds. Fix the geometry or the declaration so they state one thing — never widen a column or pad a segment to fit a label, and never drop a category or a series to tidy the grid.- **`verify-slopegraph.py`:** the two axes disagree about scale or origin, or an endpoint is drawn somewhere other than where its own declared value belongs. Fix the coordinate, never the label — and never move a point to stop two endpoint labels colliding, because crowded labels mean the values really are close.diff --git a/scripts/render-canonical-screenshots.py b/scripts/render-canonical-screenshots.pyindex d1f26e2..feaff52 100644--- a/scripts/render-canonical-screenshots.py+++ b/scripts/render-canonical-screenshots.py@@ -15,6 +15,7 @@ from screenshot_catalog import (png_dimensions,screenshot_path,sha256,+ sha256_text,source_path,)@@ -50,7 +51,7 @@ def main() -> int:"slug": slug,"source": source.relative_to(ROOT).as_posix(),"screenshot": output.relative_to(ROOT).as_posix(),- "source_sha256": sha256(source),+ "source_sha256": sha256_text(source),"screenshot_sha256": sha256(output),"width": width,"height": height,diff --git a/scripts/screenshot_catalog.py b/scripts/screenshot_catalog.pyindex 5843486..ac51b09 100644--- a/scripts/screenshot_catalog.py+++ b/scripts/screenshot_catalog.py@@ -46,6 +46,21 @@ def sha256(path: Path) -> str:return digest.hexdigest()+def sha256_text(path: Path) -> str:+ """Hash a text source in its canonical LF form.++ Checkouts rewrite LF blobs to CRLF when `core.autocrlf=true`, so an+ unchanged file has different raw bytes per platform. Hashing the+ line-ending normalized bytes ties a digest to the committed content+ instead of to the contributor's checkout. Use `sha256` for binary files+ such as PNGs, where the bytes themselves are what is being verified.+ """++ data = path.read_bytes()+ normalized = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")+ return hashlib.sha256(normalized).hexdigest()++def png_dimensions(path: Path) -> tuple[int, int]:with path.open("rb") as handle:header = handle.read(24)diff --git a/scripts/test-verify-screenshot-freshness.py b/scripts/test-verify-screenshot-freshness.pynew file mode 100644index 0000000..33d7712--- /dev/null+++ b/scripts/test-verify-screenshot-freshness.py@@ -0,0 +1,286 @@+#!/usr/bin/env python3+"""Regression tests for the canonical screenshot freshness gate.++A checkout that rewrites LF blobs to CRLF (`core.autocrlf=true`) must not make+committed canonical examples look changed, and canonicalizing text sources must+not loosen the gate: a real source edit, or a recorded PNG digest that was+folded rather than taken from the bytes, still has to fail.+"""++from __future__ import annotations++import contextlib+import hashlib+import importlib.util+import io+import json+import struct+import sys+import tempfile+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+SCRIPTS = ROOT / "scripts"+VERIFIER = SCRIPTS / "verify-screenshot-freshness.py"+sys.path.insert(0, str(SCRIPTS))++import screenshot_catalog++PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"+IEND = bytes.fromhex("0000000049454e44ae426082")+WIDTH = 1440+HEIGHT = 1000+SCREENSHOT = (+ PNG_SIGNATURE+ + struct.pack(">I", 13)+ + b"IHDR"+ + struct.pack(">II", WIDTH, HEIGHT)+ + IEND+)+SCREENSHOT_CRLF = SCREENSHOT + b"\r\n"+++def load_verifier():+ spec = importlib.util.spec_from_file_location("verify_screenshot_freshness", VERIFIER)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++def source_text(slug: str) -> str:+ return (+ "<!DOCTYPE html>\n"+ '<html lang="en">\n'+ f"<body><h1>{slug}</h1></body>\n"+ "</html>\n"+ )+++class Checkout:+ """A throwaway copy of the canonical catalog layout for the gate to read."""++ def __init__(self, base: Path, slugs: list[str]) -> None:+ self.base = base+ self.slugs = list(slugs)+ self.assets = base / "skills/diagram-design/assets"+ self.shots = base / "docs/screenshots"+ self.assets.mkdir(parents=True)+ self.shots.mkdir(parents=True)+ self.manifest = self.shots / "manifest.json"++ def source(self, slug: str) -> Path:+ return self.assets / f"example-{slug}.html"++ def screenshot(self, slug: str) -> Path:+ return self.shots / f"{slug}.png"++ def write_sources(self, newline: str) -> None:+ for slug in self.slugs:+ self.source(slug).write_bytes(source_text(slug).replace("\n", newline).encode("utf-8"))++ def write_screenshots(self, blob: bytes) -> None:+ for slug in self.slugs:+ self.screenshot(slug).write_bytes(blob)++ def write_manifest(self, source_digest, screenshot_digest) -> None:+ entries = [+ {+ "slug": slug,+ "source": self.source(slug).relative_to(self.base).as_posix(),+ "screenshot": self.screenshot(slug).relative_to(self.base).as_posix(),+ "source_sha256": source_digest(slug),+ "screenshot_sha256": screenshot_digest(slug),+ "width": WIDTH,+ "height": HEIGHT,+ }+ for slug in self.slugs+ ]+ payload = {+ "schema_version": 1,+ "renderer": {+ "engine": "playwright-chromium",+ "scale": 2.0,+ "viewport": [WIDTH, HEIGHT],+ "capture": "first-svg",+ "font_gate": "document.fonts.ready",+ },+ "entries": entries,+ }+ self.manifest.write_bytes((json.dumps(payload, indent=2) + "\n").encode("utf-8"))+++def run_gate(checkout: Checkout) -> tuple[int, str]:+ """Point the gate at a synthetic checkout and capture its verdict."""++ verifier = load_verifier()+ verifier.canonical_slugs = lambda: list(checkout.slugs)+ verifier.source_path = checkout.source+ verifier.screenshot_path = checkout.screenshot+ verifier.MANIFEST = checkout.manifest+ verifier.ROOT = checkout.base+ stream = io.StringIO()+ with contextlib.redirect_stdout(stream):+ code = verifier.main()+ return code, stream.getvalue()+++def committed_manifest_check(manifest: dict, source_for) -> tuple[bool, str]:+ """Compare committed digests the way the gate does.++ Sources are hashed as canonical text and PNGs as raw bytes. A raw digest+ of a source would tie the check to the checkout's line endings.+ """++ sources: list[str] = []+ pngs: list[str] = []+ for entry in manifest["entries"]:+ slug = entry["slug"]+ if entry["source_sha256"] != screenshot_catalog.sha256_text(source_for(slug)):+ sources.append(slug)+ screenshot = screenshot_catalog.screenshot_path(slug)+ if entry["screenshot_sha256"] != screenshot_catalog.sha256(screenshot):+ pngs.append(slug)+ return not sources and not pngs, f"source_mismatch={sources} png_mismatch={pngs}"+++def main() -> int:+ slugs = screenshot_catalog.canonical_slugs()+ failures: list[str] = []+ passed = 0++ def record(label: str, ok: bool, detail: str) -> None:+ nonlocal passed+ if ok:+ passed += 1+ else:+ failures.append(f"{label}: {detail}")++ def digest(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()++ def source_bytes(slug: str, newline: str = "\n") -> bytes:+ return source_text(slug).replace("\n", newline).encode("utf-8")++ with tempfile.TemporaryDirectory() as scratch:+ root = Path(scratch)++ # Unchanged sources in a CRLF checkout: the manifest holds the digest of+ # the committed LF text, so the gate must pass.+ checkout = Checkout(root / "crlf", slugs)+ checkout.write_sources("\r\n")+ checkout.write_screenshots(SCREENSHOT)+ checkout.write_manifest(+ lambda slug: digest(source_bytes(slug)),+ lambda slug: digest(SCREENSHOT),+ )+ code, out = run_gate(checkout)+ record("a CRLF checkout of unchanged sources passes", code == 0, out.strip())++ # Canonicalizing must not hide a real edit: one CRLF source differs from+ # its committed text by a single character, and the manifest keeps the+ # digest of the unedited LF text.+ checkout = Checkout(root / "drift", slugs)+ checkout.write_sources("\r\n")+ edited = checkout.source(slugs[0])+ edited.write_bytes(edited.read_bytes().replace(b'lang="en"', b'lang="em"', 1))+ checkout.write_screenshots(SCREENSHOT)+ checkout.write_manifest(+ lambda slug: digest(source_bytes(slug)),+ lambda slug: digest(SCREENSHOT),+ )+ code, out = run_gate(checkout)+ record(+ "an edited source still fails on a CRLF checkout",+ code == 1+ and f"{slugs[0]}: source changed" in out+ and out.count("source changed") == 1,+ out.strip(),+ )++ # PNG digests stay raw, so a recorded raw digest is accepted even when+ # the PNG bytes themselves contain a CRLF pair.+ checkout = Checkout(root / "png-raw", slugs)+ checkout.write_sources("\n")+ checkout.write_screenshots(SCREENSHOT_CRLF)+ checkout.write_manifest(+ lambda slug: digest(source_bytes(slug)),+ lambda slug: digest(SCREENSHOT_CRLF),+ )+ code, out = run_gate(checkout)+ record("a PNG digest recorded from raw bytes passes", code == 0, out.strip())++ # A digest folded the way a text source is folded must be rejected.+ checkout = Checkout(root / "png-folded", slugs)+ checkout.write_sources("\n")+ checkout.write_screenshots(SCREENSHOT_CRLF)+ checkout.write_manifest(+ lambda slug: digest(source_bytes(slug)),+ lambda slug: screenshot_catalog.sha256_text(checkout.screenshot(slug)),+ )+ code, out = run_gate(checkout)+ record(+ "a folded PNG digest is rejected",+ code == 1 and "screenshot changed without a matching manifest refresh" in out,+ out.strip(),+ )++ # sha256_text folds CRLF and a lone CR, and leaves LF bytes untouched.+ probe = root / "probe.txt"+ probe.write_bytes(b"a\r\nb\rc\nd\n")+ folded = screenshot_catalog.sha256_text(probe)+ probe.write_bytes(b"a\nb\nc\nd\n")+ record(+ "sha256_text folds CRLF and lone CR",+ folded == screenshot_catalog.sha256_text(probe),+ folded,+ )+ record(+ "sha256_text agrees with the raw digest on LF content",+ folded == screenshot_catalog.sha256(probe),+ folded,+ )++ # The committed manifest already holds canonical digests, so normalizing+ # text sources changes no recorded value and needs no regeneration.+ manifest = json.loads(screenshot_catalog.MANIFEST.read_text(encoding="utf-8"))+ record(+ "committed manifest digests match this checkout",+ *committed_manifest_check(manifest, screenshot_catalog.source_path),+ )++ # The same check against CRLF copies of the committed sources, so this+ # test stays green on a core.autocrlf=true checkout even though CI+ # always checks out LF.+ crlf_dir = root / "committed-crlf"+ crlf_dir.mkdir()+ unconverted: list[str] = []+ for entry in manifest["entries"]:+ slug = entry["slug"]+ lf = screenshot_catalog.source_path(slug).read_bytes().replace(b"\r\n", b"\n")+ copy = crlf_dir / f"example-{slug}.html"+ copy.write_bytes(lf.replace(b"\n", b"\r\n"))+ if screenshot_catalog.sha256(copy) == entry["source_sha256"]:+ unconverted.append(slug)+ record(+ "CRLF copies of the committed sources differ from the committed bytes",+ not unconverted,+ f"unchanged_by_crlf={unconverted}",+ )+ record(+ "committed manifest digests match CRLF copies of the sources",+ *committed_manifest_check(manifest, lambda slug: crlf_dir / f"example-{slug}.html"),+ )++ if failures:+ print("FAIL screenshot freshness regression tests")+ for failure in failures:+ print(f" - {failure}")+ return 1+ print(f"OK screenshot freshness regression tests: {passed} checks")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/verify-screenshot-freshness.py b/scripts/verify-screenshot-freshness.pyindex e474953..09f28dd 100644--- a/scripts/verify-screenshot-freshness.py+++ b/scripts/verify-screenshot-freshness.py@@ -13,6 +13,7 @@ from screenshot_catalog import (png_dimensions,screenshot_path,sha256,+ sha256_text,source_path,)@@ -79,7 +80,7 @@ def main() -> int:errors.append(f"{slug}: manifest source must be {expected_source}")if entry.get("screenshot") != expected_screenshot:errors.append(f"{slug}: manifest screenshot must be {expected_screenshot}")- if entry.get("source_sha256") != sha256(source):+ if entry.get("source_sha256") != sha256_text(source):errors.append(f"{slug}: source changed; rerun scripts/render-canonical-screenshots.py")if entry.get("screenshot_sha256") != sha256(screenshot):errors.append(f"{slug}: screenshot changed without a matching manifest refresh")