Technical Specification

Inside the
Machine.

A deep dive into the 16-byte cell architecture, Bayesian rendering strategies, and the zero-unsafe kernel that powers FrankenTUI.

Data Flow

The Render Cycle

Every frame follows a deterministic, 5-stage pipeline. Pure state transitions, no hidden I/O.

Event

Input capture

01

Update

State transition

02

View

Virtual buffer

03

Diff

Bayesian selection

04

Present

ANSI emission

05
Binary Purity

16-Byte Cell Model

The atom of FrankenTUI. Cache-aligned, SIMD-ready, and designed for extreme performance.

cell.rs
Cell(16 bytes)
CellContent4 byteschar / gid
fg4 bytesPackedRgba
bg4 bytesPackedRgba
attrs2 bytesCellAttrs
link_id2 bytes

Cache Optimal

4 cells fit perfectly in a 64-byte L1 cache line.

SIMD Ready

Single 128-bit instruction for full cell equality.

Zero Leak

RAII-backed grapheme cleanup prevents memory growth.

Intelligence

Monster Math

Algorithms borrowed from statistical machine learning, not hand-tuned heuristics.

Rendering

Bayesian Diff Strategy

Beta posterior over change rates adaptively selects between full diff, dirty-row, and full redraw strategies.

p ~ Beta(α, β)
ImpactAvoids slow strategies as workload shifts
Runtime

BOCPD Resize Coalescing

Bayesian Online Change-Point Detection detects regime transitions between steady typing and burst resizing.

P(r_t | x₁:t) with hazard H(r) = 1/λ
ImpactFewer redundant renders during window drag
Budget Control

E-Process Monitoring

Wealth-based sequential tests for anytime-valid statistical decisions. No peeking penalty.

W_t = W_{t-1}(1 + λ_t(X_t - μ₀))
ImpactSafe budget decisions at every frame
Alerting

Conformal Prediction

Distribution-free risk bounds that learn 'normal' from recent residuals.

q = Quantile_{⌈(1-α)(n+1)⌉}(R₁,...,Rₙ)
ImpactStable alert thresholds without tuning
Data Structures

Fenwick Tree

Binary Indexed Tree for O(log n) prefix sums in virtualized lists.

update: j += j & -j | query: j -= j & -j
ImpactO(log n) scroll positioning
Input

CUSUM Hover Stabilizer

Cumulative sum change-point detector suppresses mouse jitter at hover boundaries.

S_t = max(0, S_{t-1} + d_t - k)
ImpactStable hover targets without lag
Animation

Damped Spring Physics

Critically-damped harmonic oscillator for natural motion without overshoot.

x'' + c·x' + k(x - x*) = 0
ImpactSmooth, deterministic animation
Input Guard

Jain's Fairness Index

Scale-independent fairness metric prevents rendering from starving input processing.

F = (Σxᵢ)² / (n·Σxᵢ²)
ImpactResponsive UI under heavy render load
Rendering

Porter-Duff Compositing

Full alpha-blending pipeline with opacity stacks for translucent overlays and layered widgets.

C_out = C_src·α_src + C_dst·α_dst·(1-α_src)
ImpactTrue transparency without hacks
Diagnostics

VOI Telemetry

Value-of-Information analysis that tracks which diagnostic measurements actually improve decisions.

VOI = E[max(a,b)|X] - max(E[a],E[b])
ImpactSelf-tuning diagnostic overhead
Frame Timing

Exponential Moving Average

Smoothed frame-time estimation for adaptive budget allocation across render cycles.

EMA_t = α·x_t + (1-α)·EMA_{t-1}
ImpactStable frame budgets despite jitter
Visual Effects

Gray-Scott Reaction-Diffusion

PDE-based pattern generator for organic visual effects rendered entirely in terminal cells.

∂u/∂t = Dᵤ∇²u - uv² + F(1-u)
ImpactMathematical art in the terminal
Command Palette

Bayesian Fuzzy Scoring

Posterior odds via Bayes factors for match scoring. Each clue (word boundary, position, tags) is a multiplier on confidence.

P(R|E)/P(¬R|E) = P(R)/P(¬R) × Π BFᵢ
ImpactBetter ranking with fewer re-sorts
UI Intelligence

Bayesian Hint Ranking

Keybinding hints ranked by expected utility minus display cost, with VOI exploration bonus and hysteresis for stability.

Vᵢ = E[Uᵢ] + w_voi·√Var(Uᵢ) - λ·Cᵢ
ImpactStable, utility-aware hint ordering
Terminal Probing

Bayesian Capability Detection

Log Bayes factors as evidence weights to combine noisy signals from env vars, DA1/DA2, and DECRPM probes.

logit P(feature|E) = logit P(feature) + Σ log BFᵢ
ImpactRobust detection from noisy probes
Rendering

Summed-Area Table

2D prefix sum enables O(1) tile density checks for skipping empty tiles on large screens.

SAT(x,y) = A(x,y) + SAT(x-1,y) + SAT(x,y-1) - SAT(x-1,y-1)
ImpactSkip empty tiles deterministically
Rendering

Dirty-Span Interval Union

Each row tracks dirty spans; diff scans only the union of changed intervals instead of full row width.

Sᵧ = ∪ₖ [x₀ₖ, x₁ₖ)
ImpactScan cost proportional to actual changes
Virtualized Lists

Bayesian Height Prediction

Normal-Normal conjugate update predicts unseen row heights to avoid scroll jumps, with conformal bounds.

μₙ = (κ₀·μ₀ + n·x̄) / (κ₀ + n)
ImpactFewer scroll jumps in long lists
Explainability

Bayes-Factor Evidence Ledger

Every probabilistic decision records its reasoning as a log10 Bayes factor ledger. Auditable, not black-box.

LBF = log₁₀(P(E|apply) / P(E|coalesce))
ImpactTransparent, debuggable decisions
Budget Control

GRAPA Adaptive Betting

General Random Adaptive Proportion Algorithm auto-tunes the e-process betting fraction for optimal sensitivity.

λ_{t+1} = λ_t + η·∇_λ log W_t
ImpactSelf-tuning statistical sensitivity
Frame Timing

Mondrian Conformal

Bucketed conformal prediction keyed by screen mode, diff strategy, and size for frame-time risk gating.

ŷ⁺ = ŷ + q_{1-α}(|r|) per bucket
ImpactSafe budget gating with sparse data
Data Structures

Count-Min Sketch

Probabilistic sketch for approximate frequency counts of hot items with PAC-Bayes error tightening.

f̂(x) = min_j C_{j,h_j(x)}
ImpactTiny memory for huge-scale counts
Caching

W-TinyLFU Admission

Width cache admission policy using Doorkeeper + Count-Min Sketch to maximize hit-rate.

admit if f̂(x) ≥ f̂(victim)
ImpactHigher cache hit-rate, fewer recomputes
Error Bounds

PAC-Bayes Calibration

Tightens sketch error bounds using PAC-Bayes theory. Bound shrinks as more data is observed.

E[err] ≤ ē + √(KL(q‖p) / 2n)
ImpactTighter bounds without distribution assumptions
Scheduling

Smith's Rule + Aging

Background work ordered by importance per remaining time, with aging to prevent starvation of long-waiting jobs.

priority = w/r + a·wait
ImpactFair throughput under load
Budget Control

CUSUM Budget Detection

Cumulative sum accumulates small deviations to catch sustained drift in allocation budgets quickly.

S_t = max(0, S_{t-1} + X_t - μ₀ - k)
ImpactFast drift detection with dual e-process confirmation
Frame Timing

PID Frame Pacing

Classic feedback control for frame-time regulation. PI is the default; MPC tested but PI proven sufficient.

u_t = Kp·e_t + Ki·Σe_t + Kd·Δe_t
ImpactSmooth frame-time stabilization
Command Palette

Conformal Rank Confidence

Gap-based p-values for deterministic tie-breaks and stable top-k ordering in search results.

pᵢ = (1/n) Σⱼ 1[gⱼ ≤ gᵢ]
ImpactDeterministic, stable search results
Animation

Easing + Stagger Cascades

Analytic easing curves distribute start offsets across list items. Optional xorshift jitter for organic feel.

offset_i = D · ease(i / (n-1))
ImpactCoordinated, non-uniform entrances
Animation

Sine Pulse Attention

Half-cycle sine for smooth attention cues. 0→1→0 emphasis without sharp edges or flicker.

p(t) = sin(πt), t ∈ [0,1]
ImpactSmooth emphasis without flicker
Terminal Probing

Perceived Luminance

RGB to perceived luminance for dark/light theme detection from terminal background probe.

Y = 0.299R + 0.587G + 0.114B
ImpactReliable theme defaults

See these algorithms running live in your browser.

Try the Live Demo

Requires Chrome or Edge (WebGPU)

Invariants

Architecture Rules

Core principles enforced at the type and crate level.

Concurrency_Safety

One-Writer Rule

All stdout goes through TerminalWriter. Single serialization point eliminates race conditions.

Kernel_Integrity

RAII Cleanup

State restored on drop—even on panic. Your terminal never stays broken.

Correctness_Protocol

Deterministic

Identical Model state + terminal size = bit-identical ANSI output. Always.

Memory_Security

Zero Unsafe

#![forbid(unsafe_code)] across all core rendering and layout crates.

Hardware Alignment

Efficiency Gains

Key architectural decisions that ensure FrankenTUI runs at 60 FPS even on legacy hardware.

0 allocs/frame

Zero-Alloc Diffing

The diff algorithm compares buffers without allocating new vectors, reusing `ChangeRun` structs.

1 cycle/cell

SIMD Cell Comparison

Cells are exactly 16 bytes, allowing single 128-bit SIMD comparison for equality checks.

O(1) layout

Cached Text Measurement

WidthCache memoizes text measurements, skipping expensive grapheme segmentation on repeated frames.

Sub-ms diffs

Dirty Row Tracking

Widgets mark specific rows as dirty, allowing the renderer to skip diffing static regions.

Runtime Invariants

Quality Guards

Hard performance targets enforced in CI. Violations are test failures, not warnings.

MetricTargetHard CapNotes
Resize → first stable present≤ 120ms (p95)≤ 250ms (p99)Drop intermediate sizes if over budget
Action resolution latency< 16ms< 16msAll keybinding actions complete within one frame
Conformal prediction alpha0.05Coverage: P(y_t ≤ U_t) ≥ 95% within each bucket
Dirty-span overhead (dense)< 2%< 5%Overhead of dirty-span tracking vs full scan
Dirty-span improvement (sparse)> 50%Scan cost reduction for ≤ 5% edit density

Ready to build?

Add FrankenTUI to your project and start building interfaces with correctness guarantees from day one.