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:
- The page is rendered and loaded in a headless browser
- Guardian inspects the DOM for overflow issues
- If issues are found, the SmartHealer applies a CSS fix strategy and rebuilds
- This loop repeats up to
max_retriestimes (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-generateand a trained model (trinity train) - Guardian: requires Playwright and browser binaries (
playwright install) - Neural Healer: requires the
--neuralflag and a pre-trained LSTM model inmodels/neural_healer.pth; the model is not included in the repository and must be trained separately (seesrc/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:
trinity mine-generate --count 1000 --guardianTrain model:
trinity trainThe model is saved to models/layout_risk_predictor.pkl.
Use in builds:
# 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-predictiveModel 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:
pip install playwright
playwright install chromiumDetection
Guardian loads the rendered HTML in a headless browser and inspects the DOM:
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 overflowsUsage
# 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 brutalistHealer
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.
# Use Neural Healer instead of SmartHealer
trinity build --input data/content.json --guardian --neuralThe Neural Healer falls back to the SmartHealer if the model is unavailable or confidence is below threshold.
Healing Loop
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 attemptConfiguration
Key settings (environment variables or config/settings.yaml via TRINITY_* prefix):
| Setting | Default | Description |
|---|---|---|
guardian_enabled | false | Enable Guardian validation |
predictive_enabled | true | Enable ML predictor (no-op if no model) |
max_retries | 3 | Max healing attempts |
truncate_length | 50 | Content truncation length for CONTENT_CUT |
Next Steps
- Retry Logic with Heuristics - Full pipeline details
- Centuria Theme Factory - Theme generation
- LLM Caching - Response caching