Spec and roadmap · draft 5 · 30 Nov 2026

Cairn language specifications

Cairn is a general-purpose language for building AI software that other developers can pick up quickly. It has C#-style syntax and Rust-style types, every function declares what it's allowed to touch, and it compiles to WebAssembly so the same code runs in the browser, on servers and at the edge.

NameCairn · .crn · cairn-lang Repogithub.com/sanjay-bhat/cairn NowPhase 2 · milestones 1 and 2 of 5 done SyntaxC#-style TypesRust-style enums, match, no null MemoryWasm GC, no borrow checker CompilerRust, incremental Runs onBrowser · Node/Deno/Bun · edge FocusAI apps, code AI can write safely

What changed

  • Draft 5, updated: generics and interfaces now compile too (Phase 2, milestone 2).
  • Draft 5: Phase 2 has started. Records, classes, enums with data and tuples now compile and run; values print as code and compare by value (decision 0015), and a constructor must set every field before using the object (decision 0017).
  • Draft 4: Phase 1 is done and released. New AI-first features from decision 0016: typed holes and an MCP server for coding agents (Phase 3), and budgets and record-and-replay on capabilities (Phases 5 and 6).
  • The focus moved from a browser notebook to a general language for AI development. The notebook is now Phase 9, after the v0.1 release, and the C# and Python kernels are dropped.
  • Fourteen phases: 0–8 lead to v0.1, and 9–13 (notebook, UI, WebGPU and Rust interop, data tables, native mobile apps) follow it.
  • New phases for running on servers and edge platforms, declared permissions, an AI standard library, and evals.
  • The independent review's points are folded in: the spec for generics across modules comes first, the incremental compiler and error messages start in Phase 1, there's a size budget enforced in CI, and MoonBit is named as the closest competitor.

The language at a glance

Five pillars

A sketch of the target syntax. Nothing here compiles yet.

enum Sentiment { Positive, Negative, Mixed(string reason) }
record Review(int Stars, Sentiment Sentiment, string Summary);

[Tool("Look up an order by its id")]
async Result<Order, NotFound> GetOrder(string id) uses Net { ... }

async Result<Review, ModelError> Triage(string text) uses Llm {
    // JSON Schema generated from Review; the reply is
    // parsed into a Review or returns a typed error
    return await Llm.Ask<Review>($"Classify: {text}", tools: [GetOrder]);
}

[Replay("cassettes/angry.jsonl")]
test "angry review is negative" {
    let r = (await Triage("Broken on arrival.")).Unwrap();
    Assert.Equal(r.Sentiment, Sentiment.Negative);
}
  1. 1
    Typed AI building blocksOutput schemas come from your types, a function marked [Tool] becomes a tool definition, and model output streams as async streams. The compiler checks all of it.
  2. 2
    Declared permissionsuses Net, uses Llm, uses Fs. The host grants them, and the WebAssembly sandbox enforces them, so agent-written or third-party code can't reach the network unless you allow it. That includes your dependencies.
  3. 3
    Easy for AI to writeOne way to do things, a formatter with no options, compiler errors as JSON with suggested fixes, and docs an LLM can read as context.
  4. 4
    Tests and evals built intest and eval blocks, plus record-and-replay for model calls, so tests are fast, free and repeatable.
  5. 5
    Runs wherever WebAssembly runsBrowser, Node, Deno, Bun and edge workers, with typed bindings to JavaScript libraries.

Positioning

Where Cairn fits

Good for

  • AI apps and agents that need typed, validated model output and tools
  • Running agent-written or third-party code with tight permissions
  • Libraries and services that ship to both browser and server from one codebase
  • Parsers, DSLs and state machines, where enums and match shine

Not for

  • Training models or heavy number-crunching (use Python, or call existing inference libraries)
  • Native systems work
  • Content sites that need search ranking
  • Apps that need the whole npm ecosystem on day one
  • Safari versions before 18.2, which lack Wasm GC
AlternativeWhy pick Cairn insteadWhy people stay
TypeScriptReal enums with data, exhaustive match, no undefined, typed AI calls without extra librariesNo friction with the DOM and npm; a huge ecosystem
Rust + WasmNo borrow checker; graphs and trees without Rc<RefCell>; compiles in the browserRaw speed, SIMD, crates
BlazorSmall downloads instead of a shipped .NET runtimeReal C#, NuGet, Microsoft support
Kotlin/WasmLighter toolchain; AI building blocks in the languageCompose UI, multiplatform, JetBrains
MoonBit (closest)Familiar C#-style syntax; AI calls, tools and schemas in the language; declared permissionsAlready does Rust-style types on Wasm GC with tiny binaries, and also pitches itself as built for AI

Platforms

Where Cairn apps run

Cairn compiles to WebAssembly, so it runs wherever a browser engine or JavaScript runtime supports Wasm GC (decision 0010).

PlatformWhenHow
Browserv0.1The main target: Chrome and Edge 119+, Firefox 120+, Safari 18.2+
Linux, macOS, Windowsv0.1Node, Deno or Bun, including single executables; desktop windows through a Tauri or Electron shell
iOS, Android (web view)v0.1A web app, or an app store app that wraps a web view (Capacitor)
iOS, Android (native)Phase 13Cairn logic inside SwiftUI and Jetpack Compose apps, run by an embedded Wasm runtime
Smart TVsv0.1Web apps on Samsung (Tizen), LG (webOS) and Android TV, where the TV's browser engine is new enough
Apple TVNot plannedtvOS has no web view
Smart watchesNot plannedNo watch platform gives apps a Wasm GC engine

Figure 1

What each phase needs

Read top to bottom. Arrows point from a phase to the phases that depend on it, labeled with what gets handed over. Phases 9–13 sit below the v0.1 release.

COMPILER + TOOLS RUNTIME + SAFETY AI AFTER v0.1 · EACH NEEDS ONLY THE PHASE NAMED typed AST full language GC types · Buffer hosts uses Llm, Net typed calls evals fmt · LSP · tests test blocks v0.1 shipped PHASE 0 Spec and decisions ✓ spec v0 with 10 sample programs PHASE 8 Packages, docs and v0.1 release ✓ cairn-lang v0.1 published PHASE 1 Language core ✓ errors as JSON PHASE 2 Heap data on Wasm GC ✓ BFS on a grid PHASE 3 Tooling + playground ✓ 9 editors supported PHASE 4 Runs everywhere ✓ same code, 3 hosts PHASE 5 Permissions ✓ no Net, no fetch PHASE 6 AI standard library ✓ agent in 50 lines PHASE 7 Evals + replay ✓ evals run offline PHASE 9 Notebooks needs P3 PHASE 10 UI with signals needs P4 PHASE 11 WebGPU + Rust needs P2, P4 PHASE 12 Typed data tables needs P6 PHASE 13 Native mobile apps needs P4
The critical path to v0.1 runs 0 → 1 → 2 → 4 → 5 → 6 → 7 → 8. Phase 3 can run alongside 4 to 6, and its tests feed the evals in Phase 7. After the release, phases 9–13 can go in any order: each one only needs the earlier phase named in its box.

All points, merged

Phases 0–8: to v0.1

Draft 1's language phases, the review's additions and the AI focus, sorted into phases. Each phase ends on a test you can run. Items marked NEW weren't in draft 1.

Phase 0All tracks

Spec and decisions

  • NEW Generics across separately compiled modules: compiled once per type everywhere, with rules that make duplicates harmless (decision 0004)
  • NEW Permission model: which capabilities exist, and how a host grants them
  • NEW String representation: JS String Builtins where supported, with a fallback
  • NEW Size budget: 20 KB compressed for hello world, 3 MB for the compiler (decision 0007)
  • Syntax, types and memory model as decided; .crn files
  • Status: done. The spec is in spec/, with its decision records and sample programs.
Needs
Nothing
Done when
A spec v0 exists with 10 sample programs, including 3 AI programs
Phase 1Compiler

Language core

  • NEW Incremental, query-based compiler from day one, so the editor, playground and CLI share it
  • Lexer and parser to an AST with source positions
  • Type checker for numbers, functions, records, enums, match
  • NEW Errors that list missing enum cases and suggest fixes, also as JSON
  • Codegen to Wasm; tests run in Node
  • NEW Binaryen's wasm-opt on every build, with its Wasm GC passes (decision 0011)
Needs
Phase 0
Done when
FizzBuzz and Fibonacci compile and run, and a missing match case gives a JSON error with a fix (two-sum moved to Phase 2: it needs lists and maps)
Status
Done, released as v0.0.7. Details in docs/phase-1.md
Phase 2Compiler

Heap data on Wasm GC

  • Records, arrays and strings as garbage-collected objects
  • Generics using the Phase 0 strategy, traits, closures
  • Option and Result in a small standard library
  • NEW A narrow Buffer<T>/Bytes type in linear memory for zero-copy handoff to JS, WebGPU and Rust
Needs
Phase 1
Done when
Two-sum, BFS on a grid and a linked list run, and bytes reach JS without a copy
Status
In progress. Milestones 1 (records, classes, enums, tuples) and 2 (generics and interfaces) are done, so the linked list and a generic Largest run; next is the standard library core: Option, Result and List. Details in docs/phase-2.md on the phase-2 branch
Phase 3Tools

Tooling and playground

  • NEW cairn fmt: one style, no options
  • NEW test blocks, Assert.Equal with readable diffs, doc tests
  • NEW TextMate and tree-sitter grammars for highlighting (decision 0012)
  • NEW cairn lsp, one language server for every editor: errors with quick fixes, hover types, completion, go to definition, rename, outline, formatting
  • NEW Editor packages: VS Code (and Cursor), JetBrains IDEs, Visual Studio, Neovim, Vim, Emacs, Helix, Zed, Sublime Text
  • Compiler compiled to Wasm; a playground page
  • NEW Size budget checked in CI
  • NEW Benchmarks in CI against TypeScript, Kotlin/Wasm and Rust: BFS, JSON parsing, string-heavy AI work, start-up. A 10% slowdown fails CI (decision 0011)
  • NEW Typed holes: todo() fits anywhere, and cairn check says the type it needs and which names in scope have it, so an agent can outline first and fill in after (decision 0016)
  • NEW cairn mcp: an MCP server that lets coding agents ask the compiler for errors, types, definitions, references, docs and test results (decision 0016)
Needs
Phase 2
Done when
All nine editors show highlighting, errors with fixes and hover types; the playground is live; benchmarks run in CI; an agent fills a todo() using cairn mcp
Phase 4Runtime

Runs everywhere

  • NEW Hosts: browser, Node, Deno, Bun and edge workers. Check Wasmtime's GC support before promising it.
  • Hand-written bindings for the DOM, fetch and canvas, plus a JsValue escape hatch
  • async/await mapped onto JS promises
  • A .d.ts importer for a subset of TypeScript, after the hand-written bindings work
Needs
Phase 2
Done when
The same program runs in a browser, in Node and on an edge worker
Phase 5Safety

Permissions

  • NEW uses Net, uses Llm, uses Fs on functions, checked by the compiler
  • NEW The host grants capabilities when it loads a module; anything not granted is refused at run time
  • NEW Workers as actors, with a Transferable marker for data that can cross threads
  • NEW Budgets on capability grants: number of calls and total time; going over returns a typed BudgetExceeded error (decision 0016)
  • NEW Record and replay: cairn run --record saves every capability call's result, and cairn replay reruns the program exactly, with no network or model calls (decision 0016)
Needs
Phase 4
Done when
Code without uses Net can't fetch: a compile error, and a refusal if it's loaded anyway. A recorded run replays identically
Phase 6AI

AI standard library

  • NEW JSON Schema generated from any record or enum
  • NEW Llm.Ask<T>: typed structured output, or a typed ModelError
  • NEW [Tool] turns a function into a tool definition; tool calls run under the function's permissions
  • NEW Streaming as async streams; an agent-loop helper; adapters for several model providers
  • NEW Token and money budgets on Llm grants, so a runaway agent loop stops (decision 0016)
Needs
Phase 5
Done when
A tool-using agent with typed output fits in 50 lines
Phase 7AI

Evals and replay

  • NEW eval blocks: run a prompt over a dataset and score the results
  • NEW Record-and-replay for model calls, so tests need no network or API cost
  • NEW Token and cost report per run
  • NEW Docs generated as llms.txt for coding agents
Needs
Phases 3 and 6
Done when
CI runs the evals offline from recordings
Phase 8All tracks

Packages, docs and release

  • NEW cairn add github.com/you/lib@v1.2: packages come straight from git as source, Go-style. No registry to run for v0.1.
  • NEW The lockfile records each dependency's permissions; an upgrade that asks for new ones, such as Net, fails until you approve it
  • NEW cairn publish --npm: compiled Wasm, JS glue and .d.ts types, so TypeScript projects can use Cairn libraries
  • Builds cached by content hash; a static index or caching proxy only if usage justifies it
  • Docs site and examples; dogfood on your own projects
  • Publish cairn-lang on crates.io and npm; logo and brand already locked
Needs
Phases 3 and 7
Done when
cairn-lang v0.1 is published, a Cairn library installs from npm into a TypeScript project, and someone else builds something with it

After v0.1

Phases 9–13

These come after the v0.1 release. None of them blocks it, and each one only needs the earlier phase it names, so they can run in any order or in parallel.

Phase 9After v0.1

Notebook front end

  • A Display trait: types render as tables, grids, trees and graphs, sent as MIME type plus JSON to TypeScript renderers
  • Each cell compiles to its own module, using the Phase 0 generics strategy
  • Cells re-run when their inputs change, using a dependency graph between cells
  • A stop button that works through loop checks
  • Starts as a JupyterLite plugin; its own shell later, if ever
Needs
Phase 3
Done when
A LeetCode walkthrough runs as a Cairn notebook on GitHub Pages
Phase 10After v0.1

UI with signals

  • Signals and view blocks compiled to direct DOM updates, in the style of Solid or Leptos
  • Components with typed props and events
  • Has to stay a library, not a runtime, and stay inside the size budget
Needs
Phase 4
Done when
A todo app ships in under 100 KB
Phase 11After v0.1

WebGPU and Rust interop

  • Typed GPU buffers through Buffer<T>; WGSL shaders as strings first, a shader DSL maybe later
  • Load Rust libraries compiled to Wasm with wasm-bindgen, passing buffers and handles
  • WebGPU where the browser has it, with a clear error where it doesn't
Needs
Phases 2 and 4
Done when
chunkfetti's mesher is called from Cairn and its output drawn with WebGPU
Phase 12After v0.1

Typed data tables

  • A small columnar Table<Row> with a schema read from CSV or Arrow
  • Typed filter, group and join
  • Eval datasets from Phase 7 load as tables
  • Deliberately small: it shouldn't try to be pandas
Needs
Phase 6
Done when
An eval dataset loads from CSV, and a bad column is a type error
Phase 13After v0.1

Native iOS and Android apps

  • Cairn modules packaged as a Swift package and an Android library, each with a small embedded Wasm runtime
  • Generated Swift and Kotlin bindings: records become structs and data classes, enums become enums and sealed classes, async becomes Swift async and coroutines
  • Capabilities provided by the app: Net through the platform's HTTP stack, Fs inside the app's sandbox, Llm through the app's provider settings
  • The UI stays native: SwiftUI and Jetpack Compose
  • First, check which embeddable runtime fully supports Wasm GC, and how to run it on iOS, which doesn't allow apps to generate machine code at run time (decision 0010)
Needs
Phase 4
Done when
A SwiftUI app and a Compose app call the same Cairn function

Figure 2

How a typed model call runs

The finished system from Phases 5 to 7: what happens when Triage calls Llm.Ask<Review>.

COMPILE TIME RUN TIME · WASM SANDBOX HOST · GRANTS PERMISSIONS types schema prompt + schema ok in tests JSON stream tool call result uses Net? record Review your type Compiler derives JSON Schema GetOrder [Tool] · uses Net Llm.Ask<Review> in Triage · uses Llm Typed parser JSON → Review Triage returns Review | ModelError Permission check is Llm granted? Model provider streams JSON Replay cassette recorded replies
Nothing leaves the sandbox without passing the host's permission check: the model call needs Llm, and the tool needs Net. In tests the dashed replay cassette answers instead of the provider, so evals run offline.

From the independent review

The five additions to do first

  1. Spec how generics behave across separately compiled modules. It decides the compiler's architecture (Phase 0).
  2. An incremental compiler with good error messages. The language server, playground and CLI all depend on it (Phases 1–3).
  3. The typed AI building blocks: schemas from types, Llm.Ask<T> and [Tool]. This is the clearest difference from MoonBit (Phase 6). The review's own third pick was the notebook's display system; with the new focus, this takes its place.
  4. Test blocks, doc tests and a formatter. Cheap, and evals build on them (Phase 3).
  5. Hand-written DOM and fetch bindings with a JsValue escape hatch, plus Buffer<T>. These unblock real apps without waiting on the .d.ts importer (Phases 2 and 4).

Hard parts

Risks and what to do about them

RiskPhasePlan
Generics across modules0, 2Calling a generic function with a new type from another module means generating code there, and changing a type can force dependent modules to rebuild. Decide the strategy in the spec before writing the compiler.
MoonBit got there firstallDon't compete on the language core alone. Lead with typed AI calls, declared permissions and C#-familiar syntax.
"No runtime" is only half true3The standard library, JS glue and the compiler itself still ship. Enforce the size budget in CI.
Browser support gaps0, 4Safari support for JS String Builtins is disputed, and for JSPI (WebAssembly that can wait on JS promises) it's unconfirmed. Detect features at load time and keep fallbacks.
TypeScript types don't map cleanly4Unions, overloads and structural types will defeat a naive .d.ts importer. Hand-written bindings come first, and the importer handles a subset.
Compromised dependencies8The lockfile records every dependency's permissions, and new permissions need your approval. Packages come from git, so there's no registry of our own to secure.
Model providers keep changing6Keep provider adapters thin and behind one interface; test them against recorded replies.
Slower than native1, 3WebAssembly is somewhat slower than native code, most on heavy allocation. wasm-opt runs on every build, and benchmarks against TypeScript, Kotlin/Wasm and Rust catch regressions (decision 0011).
Wasm GC outside browsers4, 13Standalone and embeddable runtimes are still adding Wasm GC, and iOS forbids generating machine code at run time. Check before Phase 13 starts; the fallback is a hidden web view.
Scope creepallThe language server, package manager and AI library can each take months. Ship v0.1 with the five pillars, and keep phases 9–13 after the release.

Decisions

Settled and still open

Settled

Name and brand

Cairn: .crn files, a cairn command, packages as cairn-lang. The logo is locked as v1.

Settled

Focus

A general-purpose language for AI development that other developers can use. The notebook is optional.

Settled · decision 0004

Generics strategy

Compiled once per type everywhere, including across modules. No mutable statics in generic code, and function values can't be compared, so duplicate copies are harmless.

Open · Phase 0

Which AI use comes first

Building AI apps + code AI writes safely (recommended)Also ML number-crunching
Open · Phase 4

Standalone runtimes

Whether Wasmtime is a v0.1 target depends on how mature its GC support is. Check before promising it.

Open · Phase 6

First model providers

Which providers ship adapters in v0.1, and whether local models are in scope.