Skip to content

Self-Healing Layouts

Automatic layout repair with ML prediction and CSS fix strategies

Trinity's self-healing system combines an optional machine learning predictor with progressive CSS repair strategies to automatically fix layout issues detected by Guardian.


Overview

Without Guardian (--guardian flag), Trinity builds pages without any visual validation.

With Guardian enabled:

  1. The page is rendered and loaded in a headless browser
  2. Guardian inspects the DOM for overflow issues
  3. If issues are found, the SmartHealer applies a CSS fix strategy and rebuilds
  4. This loop repeats up to max_retries times (default: 3)

Optionally, the ML predictor can be used to suggest which CSS strategy to apply before Guardian runs, reducing the number of Guardian validation rounds needed.


Architecture

┌──────────────┐      ┌──────────────┐      ┌──────────────┐
│  PREDICTOR   │─────▶│   GUARDIAN   │─────▶│    HEALER    │
│  (optional)  │      │  (optional)  │      │  (required)  │
│              │      │              │      │              │
│ Random Forest│      │  Playwright  │      │  Rule-based  │
│  Multiclass  │      │  DOM inspect │      │  or LSTM     │
└──────────────┘      └──────────────┘      └──────────────┘

All three components require explicit setup:

  • Predictor: requires training data collected via trinity mine-generate and a trained model (trinity train)
  • Guardian: requires Playwright and browser binaries (playwright install)
  • Neural Healer: requires the --neural flag and a pre-trained LSTM model in models/neural_healer.pth; the model is not included in the repository and must be trained separately (see src/trinity/components/neural_healer.py)

Predictor

Purpose

Predict which CSS healing strategy is most likely to fix a layout issue, based on content and theme features. This allows the engine to apply a fix before Guardian runs, reducing iteration rounds.

Model

Random Forest Classifier (Multiclass):

  • 100 decision trees, max depth 10
  • Must be trained locally on data collected by trinity mine-generate
  • Features: content character count, word count, CSS density metrics, pathological score, theme, active strategy
  • Output: Strategy ID (0 = NONE, 1 = CSS_BREAK_WORD, 2 = FONT_SHRINK, 3 = CSS_TRUNCATE, 4 = CONTENT_CUT)
  • Confidence threshold: 0.6 (predictions below this threshold are ignored)

Setup

Collect training data:

bash
trinity mine-generate --count 1000 --guardian

Train model:

bash
trinity train

The model is saved to models/layout_risk_predictor.pkl.

Use in builds:

bash
# Predictive healing is enabled by default when a model exists
trinity build --input data/content.json --guardian --theme brutalist

# Disable predictive healing
trinity build --input data/content.json --guardian --no-predictive

Model performance depends on your training data. The predictor requires a minimum of 10 samples (1000+ recommended for reliable predictions). Training enforces quality gates (F1 >= 0.6, precision >= 0.5, recall >= 0.5).


Guardian

Purpose

Detect layout issues (overflow, element clipping) in the rendered HTML page using a headless browser.

Requirements

Guardian requires Playwright and browser binaries:

bash
pip install playwright
playwright install chromium

Detection

Guardian loads the rendered HTML in a headless browser and inspects the DOM:

python
async def detect_overflows(page: Page) -> List[OverflowError]:
    elements = await page.query_selector_all("h1, h2, h3, p, span")
    
    overflows = []
    for el in elements:
        box = await el.bounding_box()
        scroll_width = await el.evaluate("el => el.scrollWidth")
        client_width = await el.evaluate("el => el.clientWidth")
        
        # 5px tolerance
        if scroll_width > client_width + 5:
            overflows.append({
                "element": await el.evaluate("el => el.className"),
                "overflow_px": scroll_width - client_width,
                "text": await el.text_content(),
            })
    
    return overflows

Usage

bash
# Enable Guardian (disabled by default)
trinity build --input data/content.json --guardian --theme brutalist

# Chaos test: intentionally broken content to test Guardian
trinity chaos --theme brutalist

Healer

SmartHealer (default)

The SmartHealer applies rule-based CSS fix strategies in order when Guardian detects a layout issue.

Strategy 1: CSS_BREAK_WORD

Adds word-break and overflow-wrap to allow long unbreakable strings to wrap.

Strategy 2: FONT_SHRINK

Reduces font size on overflowing elements.

Strategy 3: CSS_TRUNCATE

Applies text truncation with ellipsis.

Strategy 4: CONTENT_CUT

Truncates the actual content string to a shorter length (nuclear option).

Neural Healer (optional)

An LSTM Seq2Seq model that generates CSS class fixes based on the error context.

bash
# Use Neural Healer instead of SmartHealer
trinity build --input data/content.json --guardian --neural

The Neural Healer falls back to the SmartHealer if the model is unavailable or confidence is below threshold.

Healing Loop

python
for attempt in range(1, max_retries + 1):
    html = build_page(content, theme)
    
    if not guardian_enabled:
        return html  # Skip validation
    
    audit = guardian.audit_layout(html)
    
    if audit["approved"]:
        return html
    
    fix = healer.heal_layout(report=audit, content=content, attempt=attempt)
    apply_fix(html, fix)

# Max retries exceeded
return html  # Return last attempt

Configuration

Key settings (environment variables or config/settings.yaml via TRINITY_* prefix):

SettingDefaultDescription
guardian_enabledfalseEnable Guardian validation
predictive_enabledtrueEnable ML predictor (no-op if no model)
max_retries3Max healing attempts
truncate_length50Content truncation length for CONTENT_CUT

Next Steps

Released under the MIT License.