# How self_check.py Verifies Generated Diagram Integrity

> Learn how self_check.py verifies generated diagram integrity. This script parses HTML for safety, validates references, enforces accessibility, and ensures motion controller compliance.

- Repository: [Cathryn Lavery/diagram-design](https://github.com/cathrynlavery/diagram-design)
- Tags: how-to-guide
- Published: 2026-08-15

---

**The [`self_check.py`](https://github.com/cathrynlavery/diagram-design/blob/main/self_check.py) validator ensures generated diagram HTML files obey strict safety and motion-contract rules by parsing markup through a custom `HTMLParser` subclass that detects unsafe constructs, validates external references, enforces SVG accessibility standards, and verifies compliance with the canonical motion controller.**

The [`self_check.py`](https://github.com/cathrynlavery/diagram-design/blob/main/self_check.py) script is a dependency-free integrity checker located in the `cathrynlavery/diagram-design` repository. According to the Diagram Design skill source code, this validator runs against generated HTML diagrams to guarantee they meet security, accessibility, and behavioral contracts before deployment.

## The Validation Pipeline Architecture

The validator processes diagram files through a sequential pipeline defined in [`skills/diagram-design/scripts/self_check.py`](https://github.com/cathrynlavery/diagram-design/blob/main/skills/diagram-design/scripts/self_check.py). Each stage aggregates violations into a shared `errors` list that the `verify()` function returns to callers.

### 1. Document Loading and Parsing

The validation begins by reading the target file as UTF-8 text and feeding it into a custom `HTMLParser` subclass named `DiagramParser`. This parser records elements, attributes, scripts, styles, SVGs, and references while tracking nesting depth.

```python
source = path.read_text(encoding="utf-8")
parser = parsed_document(source)  # Returns DiagramParser instance

```

The `DiagramParser` definition starts at line 34 and extends through line 55 in [`self_check.py`](https://github.com/cathrynlavery/diagram-design/blob/main/self_check.py). It maintains internal state to capture every tag and attribute for subsequent analysis.

### 2. Security and Unsafe Construct Detection

During the parse phase, the validator immediately flags prohibited elements and executable attributes. Any occurrence of tags such as `<base>`, `<embed>`, `<object>`, or `<iframe>` triggers an error. The parser also rejects executable event handlers (attributes starting with `on`) and `srcdoc` attributes that could inject unwanted content.

These checks occur at lines 61-66 in [`self_check.py`](https://github.com/cathrynlavery/diagram-design/blob/main/self_check.py), where violations are appended to `parser.unsafe` for later aggregation.

### 3. External Reference Validation

The `reference_error()` function (lines 79-98) examines every attribute capable of referencing external URLs, including `src` and `href`. This validator blocks JavaScript URLs outright and restricts remote stylesheets to Google Fonts exclusively. Any other remote resource references result in immediate validation failures.

### 4. SVG Accessibility Verification

The `check_svgs()` function enforces strict accessibility standards on vector graphics. It verifies that at least one non-`aria-hidden` SVG exists in the document, and that each SVG carries `role="img"` along with a `<title>` element as its first child. The function also checks for non-empty title and description text, correctly prefixed IDs, and proper `aria-labelledby` ordering.

These checks are implemented at lines 14-45 in [`self_check.py`](https://github.com/cathrynlavery/diagram-design/blob/main/self_check.py).

### 5. Canonical Controller Enforcement

To prevent arbitrary code execution, `check_scripts()` (lines 47-62) ensures the diagram contains exactly one `<script>` tag with the single attribute `data-diagram-controls=""`. The script body must match the canonical controller loaded from [`assets/template-motion.html`](https://github.com/cathrynlavery/diagram-design/blob/main/assets/template-motion.html) via the `canonical_controller()` function (lines 200-212). Any deviation from this canonical source results in a validation error.

### 6. Motion Contract Compliance

When the markup includes motion attributes, `check_motion()` validates the interactive behavior against the declared `data-motion-mode` value (`none`, `reveal`, `step`, or `loop`). This function checks step counts against item budgets, enforces semantic step continuity, detects duplicate steps, and verifies the presence of required controls, actions, and status elements. It also validates CSS fallbacks for `prefers-reduced-motion` and `@media print`, along with `<noscript>` support.

The motion validation logic spans lines 69-122 in the source file.

## Running the Validator

### Command Line Usage

Execute the validator directly against generated HTML files:

```bash
python3 skills/diagram-design/scripts/self_check.py path/to/generated-diagram.html

```

The CLI prints `FAIL` with specific errors for invalid diagrams and `OK` for passing files, exiting with a non-zero status if any check fails.

### Programmatic Integration

Import the `verify()` function to validate diagrams within Python applications:

```python
from pathlib import Path
from skills.diagram_design.scripts.self_check import verify

errors = verify(Path("path/to/generated-diagram.html"))
if errors:
    print("Diagram is invalid:")
    for err in errors:
        print(" -", err)
else:
    print("Diagram passed all checks!")

```

## Summary

- **[`self_check.py`](https://github.com/cathrynlavery/diagram-design/blob/main/self_check.py)** provides a dependency-free validation pipeline for generated diagram HTML.
- The **`DiagramParser`** class ingests documents at lines 34-55 and tracks unsafe constructs like prohibited tags and executable attributes.
- **`reference_error()`** blocks JavaScript URLs and restricts remote resources to Google Fonts (lines 79-98).
- **`check_svgs()`** enforces accessibility standards including `role="img"` and proper title elements (lines 14-45).
- **`check_scripts()`** ensures exactly one canonical controller script matches [`assets/template-motion.html`](https://github.com/cathrynlavery/diagram-design/blob/main/assets/template-motion.html) (lines 47-62).
- **`check_motion()`** verifies animation contracts based on `data-motion-mode` and requires CSS fallbacks (lines 69-122).
- The **`verify()`** function aggregates all errors and returns them as human-readable strings.

## Frequently Asked Questions

### What file paths does self_check.py validate?

The validator accepts any file path pointing to an HTML diagram generated by the Diagram Design skill. Internally, it uses `pathlib.Path.read_text(encoding="utf-8")` to load the file at line 54 of [`self_check.py`](https://github.com/cathrynlavery/diagram-design/blob/main/self_check.py). The script does not modify the original file; it performs read-only analysis.

### Why does the validator reject remote stylesheets except Google Fonts?

The `reference_error()` function implements a whitelist approach to prevent data exfiltration and script injection. Lines 79-98 explicitly block JavaScript URLs and only permit remote stylesheets from Google Fonts domains. This restriction ensures diagrams remain self-contained and cannot leak sensitive information or load unauthorized third-party code.

### How does the motion contract validation work?

The `check_motion()` function examines the `data-motion-mode` attribute to determine which animation rules apply. It validates that step counts match declared item budgets, prevents duplicate step identifiers, and requires specific CSS fallbacks including `prefers-reduced-motion` media queries and `<noscript>` blocks. These checks ensure diagrams remain accessible and functional when JavaScript is disabled or when users request reduced motion.

### What happens if the controller script does not match the canonical template?

The `check_scripts()` function compares the diagram's script content against the canonical controller loaded from [`skills/diagram-design/assets/template-motion.html`](https://github.com/cathrynlavery/diagram-design/blob/main/skills/diagram-design/assets/template-motion.html). If the content differs or if multiple scripts are present, the validator appends an error to the results list. This guarantees that every validated diagram runs identical, audited control logic rather than arbitrary JavaScript.