Beyond Components: Why MetaKit UI Is a Different Successor to Foldkit

Why MetaKit UI, our planned successor to Foldkit, treats an application as one inspectable transition system instead of a tree of stateful components, what that could buy, and how little of it is built so far.

Foldkit Plus20 min read

  • successor
  • metakit
  • metakit-ui
  • architecture
  • state-machines
  • incremental-computation
On this page

On explicit semantics, state machines that compose, provable correctness, and the possibility of doing less work than fine-grained reactivity.

The rules of a shopping cart do not depend on where you draw it on screen. Yet in most UI frameworks, a component boundary decides state ownership, re-rendering, and data fetching. Move a widget in the layout and its state moves with it.

The Elm Architecture (TEA) avoids that trap, which is why I like it. An app keeps one state object (the Model), events (Messages), a pure update function, and a view function.

Foldkit brought TEA to Effect (typed errors, dependency injection, managed effects). Foldkit has now become Effect UI, shifting to a component tree where each component runs its own TEA program—a direction I find less compelling.

We are taking a different path in three stages:

  1. MetaKit (source): business rules and state changes as inspectable data, not only executable code.
  2. MetaKit UI: our planned successor to Foldkit, with its own runtime and renderer on MetaKit and Effect.
  3. Foldkit Plus: our extension packages, rebuilt on MetaKit UI once it proves itself.

Our goal for you is an application that is faster than Solid and more correct than Effect UI. Solid sets the bar for fine-grained reactivity; Effect UI sets the bar for correctness. Transitions and proofs cover correctness; the sections on doing less work than fine-grained reactivity cover speed.

Upfront: all of this is work in progress. MetaKit is unreleased, MetaKit UI has no runtime yet, and the code samples below are API sketches. Track the release gates on the direction page.

The thesis is direct: if an app stores what each state change reads, writes, and guarantees as inspectable data, one description powers type checking, proofs, incremental updates, fetching, offline sync, resumable HTML, and devtools.

What component boundaries cost

In an online shop, products, inventory, pricing, sign-in, carts, and checkout depend on each other regardless of where they sit—a sidebar, a checkout page, or a terminal.

When every component owns state, layout dictates computation. An "Add to cart" button inside a card, inside a grid, inside a page forces props down, events up, and shared stores just to reconnect split state. The Elm guide makes a related point: organising code around the screen tempts you into stateful components where plain types and functions suffice.

An interactive app has four separate structures—data shape, change rules, derived-value dependencies, and layout—that should compose independently. Effect UI ties all four to the component: state ownership, re-rendering, queries, and server-to-client hand-off. That design has real strengths, which I return to below.

Our successor design separates them under four working names:

  • Block: a reusable slice of state, its transitions, and its external inputs.
  • Machine: combines Blocks into one state machine, running cross-Block changes as one atomic commit.
  • Surface: declares what a UI reads and which Messages it sends, without owning state.
  • Layer (from Effect): supplies services like an HTTP client or database.

You keep reusable Blocks and encapsulation without turning every widget into a mini-app, and splitting a file never changes update speed. Plain TEA stays available for a tiny counter; extra precision is opt-in.

An application is a transition system that composes

Every TEA app is already a state machine: update(model, message) returns the next state and side effects. A plain function hides key facts—which states accept a Message, which fields it reads or writes, what rules it preserves, and which services it needs.

Language research offers clear tools. Typestate (Strom and Yemini, 1986) ties allowed operations to a value's current state; Harel's statecharts compose nested and parallel regions; Atkey's parameterised notions of computation compose steps whose start and end types differ.

MetaKit UI brings these ideas to TEA. An auth flow becomes named states and transitions:

ts
const Auth = Machine.define({
  states: {
    Anonymous: {},
    Authenticating: { requestId: Schema.String },
    Authenticated: { user: User },
  },
})

const Login = Transition
  .from(Auth.Anonymous)
  .on(Msg.Login)
  .to(Auth.Authenticating)

Inside Login, TypeScript narrows the state to Auth.Anonymous and checks that you return Auth.Authenticating. A transition needing an authenticated user cannot follow one that only starts sign-in, making invalid states—like an active checkout with nobody signed in—unrepresentable.

An application combines domain machines (auth, inventory, cart, checkout, navigation) as parallel regions without listing every combination. One transition can coordinate across them:

ts
const Logout = App.transition(Msg.Logout).sequence(
  Auth.transitions.Logout,
  Cart.transitions.Clear,
  Checkout.transitions.Cancel,
  Navigation.transitions.GoHome,
)

Those four steps run as one atomic commit: no view sees a signed-out user with an open checkout, and no component tree sits in the way. One logical machine does not mean one giant update function—the runtime stays free to split and schedule the work.

More said about meaning, less about plumbing

"Make it explicit" sounds like boilerplate until you separate plumbing from meaning. Forwarding Messages through wrapper components, maintaining cache keys by hand, or writing effects to sync duplicate state is plumbing.

Compare that with domain facts your compiler, tests, runtime, and tools can reuse:

  • Move stock between two warehouses without changing total stock.
  • Require enough source stock and permission from an authorised user.
  • Write only to those two quantities.

MetaKit captures these facts with three primitives: a path points to a state field; an expression computes a value from paths as a typed tree over Effect Schema (Effect's validator); a transition pairs a guard (precondition) with its writes.

Because rules are data trees rather than opaque closures, multiple readers can interpret one declaration: a JavaScript evaluator, Postgres and SQLite SQL generators, a fast interval checker (tracking min/max bounds), and the Z3 solver. Every reader follows one contract: match the reference evaluator, or refuse and name why (MetaKit introduction).

Foldkit Plus tested the UI half on Foldkit: Surface separates reads and Messages from state ownership, while Bundles package reusable machines. MetaKit UI distils these into fewer primitives and drops the adapter layer.

From type safety to proofs

TypeScript checks that a function takes two numbers and returns a number, not that it obeys your rules. Write an inventory transfer as an inspectable transition instead:

ts
const Transfer = Transition.on(Msg.Transfer)
  .when(
    Num.gt(input.amount, 0),
    Num.gte(model.source, input.amount),
  )
  .set(model.source, Num.sub(model.source, input.amount))
  .set(model.destination, Num.add(model.destination, input.amount))

Both .set calls read pre-transition state and expose their arithmetic and modified fields. For distinct integer warehouses, two guarantees follow directly: source stock never drops below zero, and combined stock stays unchanged.

Application-wide invariants—rules that hold in every reachable state—are declared the same way:

ts
const Invariants = [
  Inventory.nonnegative,
  implies(Checkout.isActive, Auth.isAuthenticated),
]

For an invariant I, guard G, and transition T, the prover checks I(state) ∧ G(state, message) ⇒ I(T(state, message)). If I holds at startup and every guarded transition preserves it, no committed state can break it.

Each layer checks a different property: Schemas verify shape, typestate restricts states, guards check preconditions, and provers verify invariants across transitions.

MetaKit already runs the first piece: given a Schema, invariant, and transition, it runs the interval checker first, escalates to an SMT solver (Z3) when needed, and returns a proof or a counterexample (Proving transitions). MetaKit UI extends this to named states and cross-region invariants.

Proofs must match runtime behaviour. MetaKit refuses unsafe integers, NaN, and NUL bytes where JavaScript, Postgres, and SQLite disagree, and a generated test checks three evaluators across 2,000 random expressions. External inputs, authorisation, async Messages, and plain TypeScript handlers still need runtime validation, while formal proofs grow out of the definitions you already write.

Doing less work than fine-grained reactivity

What surprised me most is how much work a compiler can skip when it understands a transition—how MetaKit UI aims to beat Solid's speed.

SolidJS sets the bar for fine-grained reactivity: its graph routes changes only to readers, and memos stop unchanged results from propagating. Here is a balance transfer in Solid 1.x:

ts
const [a, setA] = createSignal(100n)
const [b, setB] = createSignal(200n)
const total = createMemo(() => a() + b())

function transfer(amount: bigint) {
  batch(() => {
    setA(a() - amount)
    setB(b() + amount)
  })
}

Solid sees a and b change, re-runs total, and finds 300n unchanged. Nothing downstream updates.

Yet the answer was knowable before total ran. Write the same transfer in MetaKit UI:

ts
const total = Num.add(model.a, model.b)
const transfer = Transition.on(Msg.Transfer)
  .set(model.a, Num.sub(model.a, input.amount))
  .set(model.b, Num.add(model.b, input.amount))

Because both trees are inspectable, the compiler checks (a - x) + (b + x) = a + b for in-range arithmetic. It neither invalidates nor re-evaluates total; the compiled plan for transfer leaves total untouched.

Scale that to Expr.sum(model.accounts) across 100,000 accounts. Transferring between two accounts updates those balances, while the grand total has three options:

StrategyWork to maintain the sum
Recompute the reductionO(n): 100,000 additions
Maintain incrementallyO(1): subtract one, add one
Prove preservationNone

You can hand-code the second or third strategy in Solid; MetaKit UI's compiler chooses it automatically from the transition.

I call this semantic invalidation: dependency graphs show what might have changed, while transition meaning proves what could not have changed. MetaKit already maintains sums and counts in O(1), and Foldkit Plus does so for some queries; compiler-proven preservation is next.

Profiling our own pages showed why: on two slow frames, DOM diffing took under half the time, while recomputing derived values took most of the rest.

Deriving incremental computation

Preservation is one case of a broader pattern. Given a projection P (a derived value like a cart subtotal or filtered list) and transition T, if the compiler proves P(T(state, message)) = P(state), the cache stands. Otherwise it derives a delta function D—P(T(state, message)) = D(P(state), change, message)—that updates the previous result from only what changed.

This builds on A Theory of Changes for Higher-Order Languages (Cai et al., PLDI 2014) and DBSP, which composes small operators for incremental view maintenance (keeping query results fresh as rows change).

MetaKit expressions compose from operations that each declare how to evaluate, differentiate (compute a delta), obey algebraic laws, and lower to a target. Any expression inherits those incremental rules alongside MetaKit's evaluators, SQL lowerings, and tested laws:

OperationDerived valuePossible strategy
Rename a productNumber of productsPreserve
Transfer inventoryTotal inventoryPreserve
Insert an itemCollection sizeAdd one
Remove an itemCollection sizeSubtract one
Change a line's quantityCart totalApply the difference
Reorder a collectionSumPreserve
Modify one productFiltered collectionRe-test that one product

Incremental algorithms are not always faster: indexes and caches cost memory and CPU, so a compiler chooses among preservation, deltas, reactivity, and plain recomputation (often faster on small lists). Edge cases matter too—a conditional (if (flag) a else b) can return the same value while switching its dependencies—so unproven shortcuts always fall back to recomputing.

One compiler for the application

Svelte showed how compiling templates into direct DOM updates cuts framework overhead. Qwik showed resumability: serialising server state so the browser continues without re-running setup code (hydration). MetaKit UI compiles the whole app—Schemas, operations, transitions, invariants, projections, services, and views—together.

Like MLIR, it would lower declarations in stages: semantic representation first, then dependency, transition, and incremental passes, then plain target code. In the browser, abstractions vanish—paths become property lookups, transitions become plain functions, projections become deltas, and views become direct DOM ops. A counter never ships a math engine.

Whole-transition compilation also collapses pure sequences like add(10); add(20); subtract(30): when arithmetic is exact and intermediate states are unobserved, the writes vanish while side effects stay.

Refinement types—types narrowed by a value rule—add further facts:

ts
const AdultAge = Schema.Int.pipe(
  Expr.refine($ => Expr.all(Num.gte($, 18), Num.lte($, 120))),
)
const IsAdult = Num.gte(model.age, 18)

When every input satisfies AdultAge, IsAdult folds to true with no reactive node. MetaKit already has partial evaluation and evidence-gated rewrites; richer descriptions should compile to more specialised code, with no runtime tax.

Data fetching and caching are questions of meaning too

Most apps work out what a screen needs, write queries with manual cache keys, and track which keys to invalidate per mutation. TanStack Query and Effect UI's Query refine that pattern, yet a screen's own declaration already knows what to fetch:

ts
const ProductSurface = App.surface("Products", {
  reads: {
    products: Products.matching(model.filters),
    inventory: Inventory.forProducts,
    cart: model.cart,
  },
  intents: [Msg.FilterChanged, Msg.AddToCart],
})

Foldkit Plus already does this over a normalised store (a local cache keyed by record ID): it batches only missing fields, returns updated fields with each write in one round trip, and refreshes affected reads without manual keys.

MetaKit UI goes further. Instead of checking a write's response afterward, inspectable transitions let the runtime compare a write's footprint (modified fields) against every query's dependencies before running. Renaming a product updates its name projection, leaves total-inventory queries cached, and re-tests just that product in name-filtered searches—sharing one dependency analysis across fetching, caching, and rendering.

Language-integrated queries like Links follow the same idea: a query as data runs in memory, compiles to SQL, or updates incrementally. Server revisions, freshness policies, authorisation, and live subscriptions still handle remote changes, driven by real dependencies instead of hand-synced keys.

Offline work and correctness across machines

Explicit transitions fit offline work directly: while disconnected, the client applies a local effect, journals the operation, and syncs on reconnect, with the server reply arriving as another typed Message.

Merging is the hard part. Two offline edits to a product description can often reconcile, but two reservations for the last item in stock look valid locally and break non-negative inventory together.

Research on invariant confluence (Bailis et al.) classifies when independent changes merge safely. With inspectable transitions and invariants, the framework separates operations that:

  • commute (same result in either order);
  • apply optimistically before server confirmation;
  • reconcile without coordination, versus requiring one authority.

MetaKit already checks whether two transitions commute—answering yes when footprints and write kinds prove it, and returning "unknown" with a two-order test otherwise. Foldkit Plus adds a reload-safe outbox (persistent pending-write queue) and typed refusals; MetaKit UI layers conflict policies on top, giving local-first sync engines explicit rules to protect.

Resuming an application instead of rebuilding it

A server-rendered catalogue may display thousands of items while only a sliver is interactive. Conventional hydration downloads and runs JavaScript to rebuild component trees for HTML already on screen; Qwik's resumability serialises enough server state for the client to pick up directly.

Because projections declare reads and transitions declare writes, MetaKit UI's compiler can compute the exact slice a page needs:

  • only the state this user may see;
  • markers for the HTML regions that can change;
  • interaction entry points, local transitions, and server-transition adapters.

Regions no permitted interaction can change ship zero rendering code, and typestate defers later stages—like checkout confirmation while browsing—until reachable. Live updates, client navigation, changing permissions, and plain JavaScript handlers mean static regions can turn dynamic, so the analysis stays conservative.

Our Foldkit Plus experiment showed why the runtime must change: its opt-in resume mode ships 54.6 kB of JavaScript before first interaction (target: 20 kB) and blocks the main thread for 1.4–1.5 s (target: 200 ms). Clearing those budgets on a real page is an early gate for MetaKit UI.

One rule, wherever it runs

A pricing rule easily gets written four times—UI, API, SQL query, and analytics job—until copies drift. Effect swaps service implementations via Layers; MetaKit stores the rule itself as portable data:

ts
const DiscountedPrice = Money.sub(
  Product.price,
  Money.percent(Product.price, Product.discount),
)

Define it once and each target interprets it. MetaKit already runs rules in JavaScript, compiles to SQL, and checks them with provers, with native Rust planned via Reffect.

Because SQL NULL, collations, floats, JavaScript equality, and native integers disagree, each target declares what it supports and returns a named refusal instead of a slightly different answer.

Rendering on more than one target

Effect UI is ahead here: it ships browser, terminal, and native hosts (platform backends behind one contract). MetaKit UI goes further by binding any renderer to a Surface:

ts
const WebCart = View.make(CartSurface, htmlTags, ...)
const TerminalCart = View.make(CartSurface, terminalTags, ...)
const PortableCart = View.make(CartSurface, portableTags, ...)

The cart's state machine stays identical across all three. Rendering vocabularies can also layer—from a design system down to HTML, terminal controls, or native widgets—keeping platform work like DOM measurement explicit.

Some targets render no pixels: an AI agent reads a Surface as structured observations and permitted actions, a CLI exposes commands, and tests invoke them directly.

Tools that know what the application means

A normal debugger tells you a function ran. A tool reading transitions explains why an action was allowed, what it writes, which invariants it preserves, and what depends on it:

  • Why is checkout disabled, and which transitions enable it?
  • Can this action run offline, or could a late response break an invariant?
  • What will this Surface fetch, what state must the page resume with, and why did the compiler skip a computation?

Answers come from static analysis, traces, tests, or a solver, reporting incomplete evidence rather than guessing. From one button you can trace its intention, transition, writes, projections, and invariants—deriving statecharts, dependency graphs, and model-based tests (generated from the machine's rules).

Effect UI ships message logs, time travel, and host-free test helpers; we want richer semantics underneath. MetaKit already reports allowed transitions from partial state, indexes definitions, and traces change impact.

Why this over Effect UI?

The choice is which abstraction sits at the bottom: Effect UI nests TEA inside stateful components; MetaKit UI enriches one transition system and derives reusable UI pieces from it.

ConcernEffect UIMetaKit UI (proposed)
Basic unitComponent (each a TEA program)One transition system of Blocks
State ownershipEach component's ModelOne logical Model per Machine
CommunicationProps down, events upTyped intentions and transitions
State changeFunction (runnable)Data (runnable and readable)
CorrectnessSchemas and component contractsNamed states, guards, invariants, proofs
Derived valuesView-computed or identity-cachedInspectable expressions, law-maintained
Data fetchingPer-component queriesSurface reads, route-planned
Re-renderingChanged componentBindings reading changed fields
Server hand-offHydrationResuming reachable transition state
TargetsThree working hostsDOM renderer; vocabularies designed
ToolingMessage log, time travel, host-free testsStatic and runtime semantic inspection

This compares emphasis, not hard limits. Effect UI has real strengths—Schema-backed components, Effect Layers, typed Commands, headless components, three working hosts, and independent boundaries that are easier to make fast locally than a general incremental compiler.

Aiming to be faster than Solid and more correct than Effect UI carries real risks: compiler correctness, analysis speed, graph memory, TypeScript inference speed, distributed consistency, and ergonomics.

Our codebase shows the ergonomics risk: the smallest MetaKit language takes five imports and nine statements, and rewriting one app's Messages as data fit 31 of 39 while 8 stayed plain TypeScript. Dropping to ordinary code must stay easy. Still, I prefer one composable transition system that keeps domain relationships together for the compiler, prover, fetcher, and renderer alike.

What happens next, in order

We plan to prove this in three gated stages:

  • MetaKit first. Core kernel defects are fixed with regression tests. Next: toolkit fixes, a simpler public API, two cast-free languages on MetaKit, content-derived definition IDs, and a pre-release audit.
  • MetaKit UI plan and one benchmarked app. Before writing runtime code, we will set targets for a keyed cart (items with stable IDs) with named states, single-binding DOM updates, an incremental subtotal, and cold SSR resume. We will benchmark against idiomatic Effect UI and Solid at 1,000, 10,000, and 100,000 rows on a throttled CPU (Effect UI's upstream benchmark reports 0.7–1.1 ms per update at 1,000 rows), reporting view calls, projection evaluations, and DOM mutations. Changing one quantity in a 1,000-row cart should make one text update, refresh affected totals, and do zero work for the other 999 rows. Every optimisation must match the reference interpreter, fall back safely, and pay for itself.
  • Full MetaKit UI, then Foldkit Plus. Since 28 of our 50 packages import Foldkit, Foldkit Plus stays on frozen Foldkit until MetaKit UI runs two real apps cleanly.

Keeping the meaning of software

Many hard problems in web development come from recovering facts you already knew: tests rediscover valid behaviours, reactive runtimes rediscover dependencies, caches guess what changed, compilers recover algebra, and sync engines deduce conflicts.

Keep those facts from the start and one description serves every layer. A law that proves correctness also skips work; a projection drives fetching; an invariant guides offline conflict resolution; one typed Message serves as UI event, test input, agent command, and offline journal entry.

That shared foundation is why this is worth building: stronger correctness than Effect UI, and less runtime work than Solid. I want TEA's simplicity at a scale component trees cannot reach—describing the application clearly enough that its views and machinery follow. That is MetaKit UI.

Where to go next

Follow the work or try what exists today:

Further reading

Architecture and type systems:

Compilation and incremental computation:

Distributed systems and data:

← All posts